Android four components of the ContentProvider

Source: Internet
Author: User

This article will comprehensively introduce ContentProvider, from the most basic knowledge of the most important, the core of knowledge, we can read according to the catalogue, God forgive me. The following design SQLite operation, no detailed explanation, as long as the introduction of ContentProvider in cross-process use.

preliminary discussion on URI

The URI represents the data to be manipulated, which consists of two parts: 1. ContentProvider to operate, 2. To manipulate what data is in ContentProvider, a URI consists of the following parts:

Content://com.gdut.yummylau/person/10

Scheme

ContentProvider (content Provider) scheme has been defined by Android as: content://.

Host name (or authority)

Used to uniquely identify this contentprovider, an external caller can find it based on this identity.

Paths (PATH)

Can be used to represent the data we want to manipulate, the path should be built according to the business, as follows:

? To manipulate records with ID 10 in the person table, you can build such a path:/PERSON/10

? To manipulate the name field of the record with ID 10 in the person table, Person/10/name

? To manipulate all the records in the person table, you can build such a path:/person

If you want to convert a string to a URI, you can use the parse () method in the URI class, such as: uri uri = Uri.parse ("content://com.gdut.yummylau/Contact")

Because the URI represents the data to manipulate, we often need to parse the URI and fetch the data from the URI. The Android system provides two tool classes for manipulating URIs, Urimatcher and Contenturis, respectively. Mastering their use will facilitate our development efforts.


Urimatcher: (see Code first)

The constant Urimatcher.no_match represents a return code that does not match any path urimatcher  smatcher = new Urimatcher (urimatcher.no_match);//If Match () Methods matching Content://<span style= "font-family:arial, Helvetica, Sans-serif; font-size:12px; " >com.gdut.yummylau</span>/person path, return match code of 1, match URI registration as follows: Smatcher.adduri ("Com.gdut.yummylau", Person ", 1); /Add need to match URI, if match will return match code//If Match () method matches Content://<span style= "font-family:arial, Helvetica, Sans-serif; font-size:12px; " >com.gdut.yummylau</span>/person/230 path, return match code of 2, with URI registration as follows: Smatcher.adduri ("Com.gdut.yummylau", "person/# ", 2);//#号为通配符//incoming Uri, matching switch (Smatcher.match (Uri.parse (" CONTENT://COM.GDUT.YUMMYLAU/PERSON/10 ")) {case     1 Break      ;    Case 2 break      ;    default://does not match break      ;}
As you can see from the code above, the steps are roughly:

1. First put the URI path you need to match all to the registration, as follows:

The constant Urimatcher.no_match represents a return code (-1) that does not match any path.

Urimatcher urimatcher = new Urimatcher (urimatcher.no_match);

If the match () method matches the Content://com.gdut.yummylau/contact path, a match code of 1 is returned

Urimatcher.adduri ("Com.changcheng.sqlite.provider.contactprovider", "Contact", 1);//Add need to match URI, if match will return match code

If the match () method matches the content://com.gdut.yummylau/contact/230 path, a match code of 2 is returned

Urimatcher.adduri ("Com.gdut.yummylau", "contact/#", 2);//#号为通配符

2. After registering a URI that needs to be matched, you can use the Urimatcher.match (URI) method to match the input URI, and if the match returns a matching code, the match code is the third parameter passed in by calling the Adduri () method, assuming that the match

Content://com.gdut.yummylau/contact path, the matching code returned is 1.


Contenturis (see Code first)

Uri uri = uri.parse ("Content://com.gdut.yummylau/person") uri Resulturi = Contenturis.withappendedid (URI, 10);  
The code above is used to get the ID part after the URI path, which has two more practical methods:

? Withappendedid (URI, id) is used to add the ID portion of the path

? The Parseid (URI) method is used to get the ID part from the path


Explore ContentProvider againSome friends may not even know what the URI class described above is intended to do. In fact, in the Android system, to store and get data to provide a unified interface, you can share data between different applications. Android was bornContentProvider. When an app inherits the ContentProvider class and overrides the method used to provide data and store data, it can share its data with other apps. While other methods can be used to share data externally, data access isdata storage methods, such as: the use of file-sharing data, the need for file operations to read and write data, the use of sharedpreferences shared data, you need to use the Sharedpreferences API to read and write data. The benefit of using ContentProvider to share data is to unify the way data is accessed. first recognize what basic methods you need to inherit from your custom ContentProvider (code)
import Android.content.contentprovider;import Android.content.contentvalues;import Android.database.cursor;import Android.net.uri;public class MyContentProvider Extends contentprovider{@Overridepublic boolean onCreate () {//TODO auto-generated method Stubreturn false;}  @Overridepublic Cursor query (Uri uri, string[] projection, string selection,string[] Selectionargs, string sortOrder) {// TODO auto-generated method Stubreturn null;} @Overridepublic String getType (Uri uri) {//TODO auto-generated method Stubreturn null;} @Overridepublic uri insert (URI uri, contentvalues values) {//TODO auto-generated method Stubreturn null;} @Overridepublic int Delete (URI Uri, String selection, string[] Selectionargs) {//TODO auto-generated method Stubreturn 0; } @Overridepublic int update (URI uri, contentvalues values, String selection,string[] selectionargs) {//TODO Auto-generat Ed method Stubreturn 0;}} 
Public Boolean onCreate (): This method is called after ContentProvider is created, and ContentProvider is created when the other app accesses it for the first time after Android is powered on. Public uri Insert (URI uri, contentvalues values): This method is used for external applications to add data to ContentProvider.
public int Delete (URI Uri, String selection, string[] Selectionargs): This method is used for external applications to delete data from ContentProvider.
public int update (URI uri, contentvalues values, String selection, string[] Selectionargs): This method is used for external applications to update data in ContentProvider.
Public Cursor query (Uri uri, string[] projection, string selection, string[] Selectionargs, string sortOrder): This method is used for external applications to fetch data from the ContentProvider.
Public String GetType (URI uri): This method is used to return the MIME type of the data represented by the current URL.
If the data for the operation belongs to the collection type, the MIME type string should bevnd.android.cursor.dir/Beginning
For example: To get the URI for all person Records is Content://com.gdut.yummylau/person, the MIME type string returned should be: "Vnd.android.cursor.dir/person".
If the data to be manipulated belongs to non-collection type data, the MIME type string should bevnd.android.cursor.item/Beginning
For example, if you get a person record with ID 10 and the URI is CONTENT://COM.GUDT.YUMMYLAU/PERSON/10, the MIME type string returned is: "Vnd.android.cursor.item/person".

after overriding the above method (involving the addition and deletion of data and its feedback data type), you also need to use <provider> to configure the ContentProvider in Androidmanifest.xml. In order for other apps to find the ContentProvider, ContentProvider uses authorities (hostname/domain) to uniquely identify it, and you can think of ContentProvider as a website, Authorities is his domain name:
<manifest >   <application android:icon= "@drawable/icon" android:label= "@string/app_name" >      <provider android:name= ". Mycontentprovider "            android:authorities=" Com.gdut.yummylau "/>   </application></manifest>

Content Recipient ContentresolverWith content providers, it is necessary for external applications to have content recipients. When external applications need to add, delete, modify, and query the data in ContentProvider, you can use the Contentresolver class to getContentresolver object, you can use the Getcontentresolver () method provided by the activity.
The Contentresolver class provides four methods for the same signature as the ContentProvider class:Public uri insert (URI uri, contentvalues values): This method is used to add data to ContentProvider.
public int Delete (URI Uri, String selection, string[] Selectionargs): This method is used to delete data from ContentProvider.
public int update (URI uri, contentvalues values, String selection, string[] Selectionargs) : This method is used to update the data in the ContentProvider.
Public Cursor query (Uri uri, string[] projection, string selection, string[] Selectionargs, String sortOrder): the party method is used to obtain data from the ContentProvider.
The first parameter of these methods is the Uri, which represents the contentprovider to manipulate and what data to manipulate, assuming that the given is: Uri.parse ("CONTENT://COM.GDUT.YUMMYLAU/PERSON/10"), Then the contentprovider with the hostname Com.gdut.yummylau will be manipulated, and the data is the record with ID 10 in the person table.
Use Contentresolver to add, delete, modify, and query the data in ContentProvider: (see Code)
Contentresolver resolver =  getcontentresolver (); Uri uri = Uri.parse ("Content://<span style=" FONT-SIZE:14PX; " >com.gdut.yummylau</span>/person ");//Add a record contentvalues values = new Contentvalues (); Values.put (" Name "," Linjiqin "); Values.put (" Age ", +); Resolver.insert (URI, values)  ; Gets all records in the person table cursor cursor = resolver.query (URI, NULL, NULL, NULL, "PersonID desc"), while (Cursor.movetonext ()) {   log.i ("Contenttest", "personid=" + cursor.getint (0) + ", name=" + cursor.getstring (1));} Change the Name field value of the record with ID 1 to zhangsancontentvalues updatevalues = new Contentvalues (), Updatevalues.put ("name", "Zhangsan") ; Uri Updateiduri = Contenturis.withappendedid (URI, 1); Resolver.update (Updateiduri, updatevalues, NULL, NULL);// Delete the record URI with ID 2 Deleteiduri = Contenturis.withappendedid (URI, 2); Resolver.delete (Deleteiduri, NULL, NULL);

If a contentprovider visitor needs to know that the data in the ContentProvider changes, Getcontentresolver () can be called when data changes occur in ContentProvider. Notifychange ( URI, NULL) to notify the visitor registered on this URI
public class Personcontentprovider extends ContentProvider {public   uri insert (URI uri, contentvalues values) {      D B.insert ("Person", "PersonID", values);      GetContext (). Getcontentresolver (). Notifychange (URI, null);}   }

If ContentProvider visitors need to be notified of changes to the data, they must use Contentobserver to listen to the data (the data is described by URI), and when the monitor hears the data change notification, The system calls Contentobserver's OnChange () method:
Getcontentresolver (). Registercontentobserver (Uri.parse ("Content://<span style=" FONT-SIZE:14PX; " >com.gdut.yummylau</span>/person "),       True, new Personobserver (New Handler ()));p Ublic class Personobserver extends contentobserver{public   personobserver (Handler Handler) {      super (Handler);   }   public void OnChange (Boolean selfchange) {      ///here can be handled accordingly   }}

Summarythe advantage of using ContentProvider is that the system shields all the data that you want to expose, and uses a unified interface for exposing the data for developers to use. Developers can use ContentProvider to achieve cross-process sharing of data across different storage modes on Android. andContentresolver accepted content is borrowedContentProvider's hands ensure the uniqueness of data processing.





Android four components of the ContentProvider

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.