Android Learning Notes ContentProvider and URI detailed _android

Source: Internet
Author: User

This article describes the content of the custom content provider and fully resolves the usage of the contents provider. Content Provider, the contents of the provider, I believe that the name of this component are not unfamiliar, may be their usual to do are some simple app, so for the content Provider use is not a lot, nor is it particularly familiar. But here is a simple summary of the content provider, not very in-depth, but I hope to be able to help beginners, including me, read this article can have a general understanding of this component.

Sharing data using ContentProvider (content provider)

ContentProvider's role in Android is to share data externally, meaning that you can share the data in your application to other applications via ContentProvider. Other applications can be contentprovider the data in your application by adding a check. As for data sharing, we used to learn about file manipulation patterns, knowing that you can share data externally by specifying the operation mode of a file as Context.mode_world_readable or context.mode_world_writeable. So why use ContentProvider to share data externally? Is this, if the use of file operating mode to share data, data access will be different from the way the data is stored, resulting in access to data can not be unified, such as: the use of XML files to share data externally, the need for XML parsing to read data ; Share data with sharedpreferences, and you need to read data using the Sharedpreferences API. The benefit of using ContentProvider to share data externally is to unify the way data is accessed. When an application needs to share data externally through ContentProvider, the first step is to inherit ContentProvider and rewrite the following methods:

public class Personcontentprovider extends contentprovider{public 
  boolean onCreate () public 
  uri insert (URI uri , contentvalues values) public 
  int Delete (URI Uri, String selection, string[] selectionargs) public 
  int update (UR I URI, contentvalues values, String selection, string[] selectionargs) public 
  Cursor query (Uri URI, string[) projectio N, string selection, string[] Selectionargs, string sortOrder) public 
  string GetType (Uri uri) 
} 

The second step is to configure the ContentProvider in Androidmanifest.xml using <provider>, in order for other applications to find the ContentProvider, ContentProvider used authorities (hostname/domain name) to its unique identification, you can take ContentProvider as a website (think, the site is also providing data), authorities is his domain name:

  <manifest > 
 <application android:icon= "@drawable/icon" android:label= "@string/app_name" > 
   <provider android:name= ". Personcontentprovider "  
   android:authorities=" Com.ljq.providers.personprovider "/> 
 </application > 
</manifest> 

Ii. description of the URI
The URI represents the data to be manipulated, and the URI contains two pieces of information: 1 ContentProvider, 2, which operates on what data in ContentProvider, a URI consists of the following parts:

ContentProvider (content Provider) scheme has been set by Android, and scheme is: content://

The host name (or authority) is used to uniquely identify this contentprovider, and the external caller can find it based on the identity.

Path can be used to represent the data we want to manipulate, and 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 a record with ID 10 in the person table, Person/10/name

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

To manipulate the records in the XXX table, you can build such a path:/xxx

Of course, the data to be manipulated does not necessarily come from the database, or other storage methods such as file, XML, or network, as follows:

To manipulate the name node under the person node in the XML file, you can build such a path:/person/name

If you want to convert a string to a URI, you can use the parse () method in the Uri class, as follows:

 
 

Introduction to the use of Urimatcher class

Because the URI represents the data to be manipulated, 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 the use of them will facilitate our development work.
The Urimatcher class is used to match the URI, and its usage is as follows:

First step, you need to match the URI path to all the registration, as follows:

A constant Urimatcher.no_match represents a return code that does not match any path 
urimatcher smatcher = new Urimatcher (urimatcher.no_match); 
If the match () method matches the Content://com.ljq.provider.personprovider/person path, the return match code is 1 
smatcher.adduri (" Com.ljq.provider.personprovider ", person, 1);//Add need to match URI, if match will return match code 
//If Match () method matches content:// com.ljq.provider.personprovider/person/230 path, returns a match code of 2 
Smatcher.adduri ("Com.ljq.provider.personprovider", " person/# ", 2);//#号为通配符 
switch (smatcher.match uri.parse (" CONTENT://COM.LJQ.PROVIDER.PERSONPROVIDER/PERSON/10 ) {Case 1 break 
   ; 
  Case 2 break 
   ; 
  DEFAULT://does not match the break 
   ; 
} 

After registering for a matching URI, you can use the Smatcher.match (URI) method to match the input URI, and if the match returns a matching code, the match code is the third argument passed in by the call to the Adduri () method, assuming that the match content:// Com.ljq.provider.personprovider/person path, the return match code is 1

Iv. Introduction to the use of Contenturis class

The Contenturis class is used to manipulate the ID portion following the URI path, which has two more practical methods:

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

Uri uri = uri.parse ("Content://com.ljq.provider.personprovider/person") 
uri Resulturi = Contenturis.withappendedid (URI, 10);  

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

Uri uri = uri.parse ("CONTENT://COM.LJQ.PROVIDER.PERSONPROVIDER/PERSON/10") 

V. Sharing data using ContentProvider

The role of the main methods of the ContentProvider class:

public boolean onCreate ()
This method is invoked after ContentProvider is created, and when Android is powered on, ContentProvider is created the first time another application accesses it.

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 obtain data from 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 operation's data belongs to the collection type, then the MIME type string should start with vnd.android.cursor.dir/,

For example, to get the URI for all person records to be Content://com.ljq.provider.personprovider/person, the MIME type string returned should be: " Vnd.android.cursor.dir/person ".

If the data to be manipulated belongs to a vnd.android.cursor.item/type of data, then the MIME type string should start with the

For example: Get a person record with ID 10, URI is CONTENT://COM.LJQ.PROVIDER.PERSONPROVIDER/PERSON/10, then the MIME type string returned is: " Vnd.android.cursor.item/person ".

Vi. using Contentresolver to manipulate data in ContentProvider

When an external application needs to add, delete, modify, and query the data in the ContentProvider, you can use the Contentresolver class to get the Contentresolver object. You can use the Getcontentresolver () method provided by the activity. The Contentresolver class provides four methods that have the same signature as the ContentProvider class:

Public URI insert (URI uri, contentvalues values)
This method is used to add data to the 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)
This method is used to get the data from the ContentProvider.

The first parameter of these methods is a Uri that represents the contentprovider to manipulate and what data is being manipulated,
assuming that the given is: Uri.parse ("content:// COM.LJQ.PROVIDERS.PERSONPROVIDER/PERSON/10 "), Then the ContentProvider with host name Com.ljq.providers.personprovider is manipulated, and the data for the operation is the record with ID 10 in the person table.
Use Contentresolver to add, delete, modify, and query the data in ContentProvider:

Contentresolver resolver = Getcontentresolver (); 
Uri uri = uri.parse ("Content://com.ljq.provider.personprovider/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 Zhangsan 
contentvalues updatevalues = new Contentvalues (); 
Updatevalues.put ("name", "Zhangsan"); 
Uri Updateiduri = Contenturis.withappendedid (URI, 2); 
Resolver.update (Updateiduri, updatevalues, NULL, NULL); 
Deletes the record URI with ID 2 
Deleteiduri = Contenturis.withappendedid (URI, 2); 
Resolver.delete (Deleteiduri, NULL, NULL); 

Seven, monitor the data change in the ContentProvider

If a contentprovider visitor needs to know that the data in the ContentProvider changes, you can call Getcontentresolver () when the data changes ContentProvider. Notifychange ( URI, NULL) to notify visitors registered on this URI, as follows:

public class Personcontentprovider extends ContentProvider {public 
uri insert (URI uri, contentvalues values) { 
D B.insert ("Person", "PersonID", values); 
GetContext (). Getcontentresolver (). Notifychange (URI, NULL); 
} 
 

If a contentprovider visitor needs to be notified of changes to the data, it must be monitored using the contentobserver data (data using a URI description), and when the data change notification is heard, The system invokes the Contentobserver onchange () method:

Getcontentresolver (). Registercontentobserver (Uri.parse ("Content://com.ljq.providers.personprovider/person"), 
    true, new Personobserver (New Handler ()); 
public class Personobserver extends contentobserver{public 
  personobserver (Handler Handler) { 
   super (Handler); 
  } 
  public void OnChange (Boolean selfchange) { 
   //here is the appropriate business process 
  } 
} 

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.