Android Learning (12) ContentProvider

Source: Internet
Author: User

I. Introduction of ContentProvider
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 the use of other methods can also share data, but the way data access will vary depending on how the data is stored, such as: the use of file-based data sharing, the need for file operations to read and write data, the use of sharedpreferences shared data, You need to read and write data using the Sharedpreferences API. The benefit of using ContentProvider to share data is to unify the way data is accessed.

Second, how to realize ContentProvider

1, inheriting abstract class ContentProvider realization of a series of data on the deletion and modification of the method;

Test code:

 PackageCom.example.contentproviderdemo1;ImportAndroid.content.ContentProvider;Importandroid.content.ContentValues;ImportAndroid.database.Cursor;ImportAndroid.net.Uri; Public classMycontentproviderextendscontentprovider{@Override//is triggered after creation     Public BooleanonCreate () {//TODO auto-generated Method Stub        return false; } @Override//queries the selection for the records that match the specified criteria according to the URI, you can specify the columns, and the Sort method     PublicCursor query (Uri uri, string[] projection, string selection, string[] Selectionargs, string sortOrder) {//TODO auto-generated Method Stub        return NULL; } @Override//returns the MIME type of the current URI, if the data for the URI might include more than one record,//then the MIME-type string begins with vnd.android.dir/. //if the URI corresponds to only one record, then the MIME type string begins with vnd.android.cursor.item/.      PublicString getType (Uri uri) {//TODO auto-generated Method Stub        return NULL; } @Override//Insert values corresponding to the data from a URI     Publicuri insert (URI uri, contentvalues values) {//TODO auto-generated Method Stub        return NULL; } @Override//deletes a record that matches the criteria specified by the selection, based on the URI     Public intDelete (Uri Uri, String selection, string[] selectionargs) {//TODO auto-generated Method Stub        return0; } @Override//Modify selection to match the specified criteria according to the URI     Public intupdate (URI Uri, contentvalues values, String selection, string[] selectionargs) {//TODO auto-generated Method Stub        return0; }}

2, need to complete the registration of ContentProvider in Androidmainfest.xml;  

<ApplicationAndroid:allowbackup= "true"Android:icon= "@drawable/ic_launcher"Android:label= "@string/app_name"Android:theme= "@style/apptheme" >        <ActivityAndroid:name= "Com.example.contentproviderdemo1.MainActivity"Android:label= "@string/app_name" >            <Intent-filter>                <ActionAndroid:name= "Android.intent.action.MAIN" />                <categoryAndroid:name= "Android.intent.category.LAUNCHER" />            </Intent-filter>        </Activity>        <!--Name:contentprovider Name, authorities: Global package name, no Duplicates allowed -        <providerAndroid:name= "MyProvider"android:authorities= "Com.example.contentproviderdemo1"></provider>    </Application>

Iii. Introduction to the URI class

  The URI represents the data to be manipulated, and the URI mainly contains two pieces of information: 1. ContentProvider to operate, 2. Manipulate what data is in ContentProvider . A URI consists of the following parts:

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

2. Hostname (or authority): used to uniquely identify this contentprovider, external callers can find it based on this identity and must match the android:authorities name in the configuration file .

3. Path: can be used to represent the data we want to manipulate, the path should be built according to the business, as follows:
1) to manipulate the record with ID 10 in the Contact table, you can build such a path:/CONTACT/10
2) to manipulate the name field of the record with ID 10 in the Contact table, Contact/10/name
3) to manipulate all records in the Contact table, you can build such a path:/contact


The data you want to manipulate does not necessarily come from a database, or it can be stored as a file, as follows:
To manipulate the name node under the contact node in the XML file, you can build such a path:/contact/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.changcheng.provider.contactprovider/contact")

   

Iv. Introduction to Urimatcher, Contenturist and Contentresolver
Because the URI represents the data to manipulate, we often need to parse the URI and from the URIGet the data. AndroidThe system provides two tool classes for manipulating URIs, Urimatcher and Contenturis, respectively. Mastering their use will facilitate ourDevelopment work.

Urimatcher: Used to match the URI, it uses the following:
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.changcheng.sqlite.provider.contactprovider/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.changcheng.sqlite.provider.contactprovider/contact/230 path, a match code of 2 is returned
Urimatcher.adduri ("Com.changcheng.sqlite.provider.contactprovider", "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.changcheng.sqlite.provider.contactprovider/contact path, the matching code returned is 1.

Contenturis: Used to get the ID part after the URI path, it 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

Contentresolver: 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, You can use the Getcontentresolver () method provided by the activity. Contentresolver uses the INSERT, delete, update, and query methods to manipulate the data.
Iv. Examples of ContentProviderProgram
Code in Manifest.xml :

Android Learning (12) ContentProvider

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.