Android Development ContentProvider (content Provider)

Source: Internet
Author: User

1, ContentProvider Introduction

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. Although other methods can be used to share data externally, the way data is accessed varies depending on how the data is stored.

Such as: the use of file-sharing data, the need for file operations to read and write data, the use of sharedpreferences shared data, need to use the Sharedpreferences API read and write data.

The benefit of using ContentProvider to share data is to unify the way data is accessed

2. Steps to share data via ContentProvider:

The first step is to create a class that inherits ContentProvider and overrides the following methods (not all of the following methods are implemented):

public class Pe Rsoncontentprovider extends contentprovider{

   public boolean  OnCreate ()

   public uri  insert (URI Uri, Contentvalues values)

   public int  Delete (Uri Uri, String Selection, string[] selectionargs)

   public int  Update ( Uri Uri, contentvalues values, String selection, string[] selectionargs)

   public cursor  query (URI Uri, string[] projection, string selection, string[] Selectionargs, string SortOrder)

   public string  getType (Uri uri)

Step Two this contentprovider needs to be configured in Androidmanifest.xml using <provider> , in order for other applications to find the ContentProvider, ContentProvider uses a authorities (hostname/domain name) to uniquely identify it.

<manifest. >

<application android:icon= "@drawable/icon" android:label= "@string/app_name" >

<provider android:name= ". Personcontentprovider "android:authorities=" Cn.itcast.provider.personprovider "/>

</application>

</manifest>

Note: Once the app inherits the ContentProvider class, we'll refer to this app as the ContentProvider (content provider) later.

3. URI

Each URI represents the data to be manipulated, and the URI mainly contains two pieces of information:

1> need to operate the ContentProvider

2> what data in the ContentProvider is being manipulated

A URI consists of the following parts:

content:// com.< Company name >.provider. Application name/PERSON/10

The hostname (or authority) is used to uniquely identify the contentprovider, and the external caller can find it based on the identity. android:authority takes a similar website domain name to assign it a value. In general, this defines authority:

com.< company name >.provider. Application Name

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 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

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

Of course, the data to be manipulated does not necessarily come from a database , or it can be a file and other storage methods , 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:

URI Uri =uri.parse ("content:// com.< Company name >.provider. Application name /data path")

Convert a string to a URI

4, Urimatcher class use Introduction (Public Classurimatcher)

Because the URI represents the data to be manipulated, we often need to parse the URI and get the data from the URI, and the Android system provides two tool classes for manipulating URIs :

A, public class Urimatcher

B, Publicclass Contenturis

The first step is to take the URI path you need to match all to the registration, as follows:

constant Urimatcher.no_match indicates a return code that does not match any path

Urimatcher Smatcher = Newurimatcher (Urimatcher.no_match);

If the match () method matches the Content://cn.itcast.provider.personprovider/person path, a match code of 1 is returned

Smatcher.adduri ("Cn.itcast.provider.personprovider", "person", 1);

Add need to match URI, if match will return match code (match code can fetch arbitrarily)

If the match () method matches the content://cn.itcast.provider.personprovider/person/230 path, a match code of 2 is returned

Smatcher.adduri ("Cn.itcast.provider.personprovider", "person/#", 2);//#号为通配符

Switch (smatcher.match (Uri.parse ("CONTENT://CN.ITCAST.PROVIDER.PERSONPROVIDER/PERSON/10"))) {

Case1

Break

Case 2

Break

DEFAULT://does not match

Break

}

After registering a URI that needs to be matched, you can use the Smatcher.match (URI) method to match the input URI, and if the match returns a match, the match code is the third parameter passed in by calling the Adduri () method, assuming that the match content:// Cn.itcast.provider.personprovider/person path, the matching code returned is 1

The code is as follows:

private static final Urimatcher Urimatcher;

static{

Urimatcher = new Urimatcher (urimatcher.no_match);

Urimatcher.adduri ("com.< company name >.provider. Application name ", "items", 1);

Urimatcher.adduri ("com.< company name >.provider. Application name ", "items/#", 2);

}

5, Contenturis class use Introduction

The Contenturis class 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:

URI Uri =uri.parse ("Content://cn.itcast.provider.personprovider/person")

Uri Resulturi =contenturis.withappendedid (URI, 10);

The resulting URI is: CONTENT://CN.ITCAST.PROVIDER.PERSONPROVIDER/PERSON/10

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

URI Uri =uri.parse ("CONTENT://CN.ITCAST.PROVIDER.PERSONPROVIDER/PERSON/10")

Long PersonID = Contenturis.parseid (URI);//The result obtained is: 10

6, Public abstract class ContentProvider

The role of the main methods of the ContentProvider class:

public boolean onCreate ()

This method is called after ContentProvider is created, and Android creates contentprovider when the system is started.

Public URI insert (URI Uri, contentvaluesvalues)

This method is used for external applications to add data to ContentProvider.

public int Delete (URI uri, StringSelection, string[] selectionargs)

This method is used for external applications to delete data from ContentProvider.

public int update (URI uri, contentvaluesvalues, 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 of the operation 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 is Content://cn.itcast.provider.personprovider/person, then the MIME type string returned should be: " Vnd.android.cursor.dir/person ". If the data to be manipulated belongs to a single data, then the MIME type string should start with vnd.android.cursor.item/ , for example: Get a person record with ID 10, URI content:// CN.ITCAST.PROVIDER.PERSONPROVIDER/PERSON/10, the MIME type string returned should be: "Vnd.android.cursor.item/person".

7. Use Contentresolver to manipulate data in ContentProvider

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

Public URI insert (URI Uri, contentvaluesvalues)

This method is used to add data to ContentProvider.

public int Delete (URI uri, StringSelection, string[] selectionargs)

This method is used to delete data from ContentProvider.

public int update (URI uri, contentvaluesvalues, 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 fetch data from the ContentProvider.

The first parameter of these methods is a Uri, which represents which contentprovider to manipulate and what data to manipulate, assuming that the given is: Uri.parse ("content:// CN.ITCAST.PROVIDER.PERSONPROVIDER/PERSON/10 "), Then the contentprovider with the hostname Cn.itcast.provider.personprovider will be manipulated, and the data is the record with ID 10 in the person table.

How to use:

1> get Contentresolver object.

2> defines a Uri,contentvalues object.

3> the method that invokes the Contentresolver object.

Use Contentresolver to add, delete, modify, and query the data in ContentProvider:

Contentresolver resolver = Getcontentresolver ();

Uri uri = uri.parse ("Content://cn.itcast.provider.personprovider/person");

Add a record

Contentvalues values = new Contentvalues ();

Values.put ("name", "Itcast");

Values.put ("Age", 25);

Resolver.insert (URI, values);

Get 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 the new liming

Contentvalues updatevalues = new Contentvalues ();

Updatevalues.put ("name", "Liming");

Uri Updateiduri = Contenturis.withappendedid (URI, 2);

Resolver.update (Updateiduri, updatevalues, NULL, NULL);

Delete a record with an ID of 2

Uri Deleteiduri = Contenturis.withappendedid (URI, 2);

Resolver.delete (Deleteiduri, NULL, NULL);

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.