ContentProvider of Android data storage

Source: Internet
Author: User

ContentProvider

ContentProvider is a mechanism for data sharing among different applications in the Android platform. An application can use this mechanism if it needs to allow other programs to manipulate its own data.
And this approach ignores the underlying data storage implementations, ContentProvider provides a uniform way to implement data manipulation through URIs. The steps are:

1. Define a ContentProvider in the current application.

2. Register this contentprovider in the androidmanifest.xml of the current application

3. Other applications obtain this ContentProvider data through Contentresolver and URIs.

Contentresolver provides methods such as insert (), delete (), query (), and update (). Used to implement access to data in the ContentProvider.

A, URI is a generic resource identifier, which is divided into 4 parts of a,b,c,d:

A: Standard prefixes that cannot be changed, including; "content://", "tel://" and so on. When the current prefix is "content://", the description controls the data through a content provider

The identity of the B:uri, which is declared by the authorities property, which defines which ContentProvider provides the data. For third-party applications, in order to guarantee the uniqueness of the URI identity,
It must be a complete, lowercase class name. For example, " Content://com.test.data.myprovider "

C: The path, which can be approximated as the name of the table in the database that needs to be manipulated, such as: "Content://hx.android.text.myprovider/name"

D: If the URI contains an ID that represents the record that needs to be fetched, then the data corresponding to that ID is returned, and if there is no ID, it returns all;

Uri uri = uri.parse ("Content://com.changcheng.provider.contactprovider/contact")

The query strings used in content provider are different from standard SQL queries. Many operations such as SELECT, add, delete, modify, etc. we use a special URI that consists of 3 parts, "content://", a path representing the data, and an optional ID for the identity data. Here are some sample URIs:

Content://media/internal/images This URI will return all pictures stored on the device
content://contacts/people/This URI will return all contact information on the device
Content://contacts/people/45 This URI returns a single result (contact record with ID 45 in the contact information)

Although this query string format is common, it still seems a bit confusing. To do this, Android offers a range of helper classes (under the Android.provider package),
It contains a lot of query strings in the form of class variables, which is easier for us to understand, so as above content://contacts/people/45 this URI can be written as follows:

Uri person = Contenturis.withappendedid (People.content_uri, 45);

B, Contentvalues is used to store contentresolver processing content, which needs to be noted is put (String key, byte[] value), when an object is converted to byte[], It can be stored in the ContentProvider.
See API Doc for details


Here's a sample code that shows how to get data from one application to another.

In application A, inherit the Contprovider class and override the method.

 Public classMyProviderextendscontentprovider{@Override publicint Delete (Uri Uri, String selection, string[] selectionargs) {//TODO auto-generated Method StubReturn0; } @Override PublicString getType (Uri uri) {//TODO auto-generated Method Stub    return NULL; } @Override Publicuri insert (URI uri, contentvalues values) {return NULL; }    //initializing a database in Create@Override Public BooleanonCreate () {Sqlitedatabase db= This. GetContext (). Openorcreatedatabase ("Test_db.db3", Context.mode_private,NULL); Db.execsql ("CREATE Table tab (_id INTEGER PRIMARY KEY autoincrement, name TEXT not NULL)"); Contentvalues Values=Newcontentvalues (); Values.put ("Name", "Test"); Db.insert ("tab", "_id", values);        Db.close (); return true; }    //implementing the Query method@Override PublicCursor query (Uri uri, string[] projection, string selection, string[] Selectionargs, string sortOrder) { Sqlitedatabase DB= This. GetContext (). Openorcreatedatabase ("Test_db.db3", Context.mode_private,NULL); Cursor C= Db.query ("tab",NULL,NULL,NULL,NULL,NULL,NULL); returnC;        } @Override publicint update (URI Uri, contentvalues values, String selection, string[] Selectionargs) { //TODO auto-generated Method Stub        return0; }}

This contentprovider is declared in its androidmanifest.xml, where the authorities property defines the URI identity of this contentprovider:
<provider android:name= ". MyProvider "android:authorities=" Com.test.MyProvider "/>

In application B, get the data in program A's ContentProvider by Contentresolver.

Publicclass mainactivityextendsActivity {@Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);                Setcontentview (R.layout.main); //Get ContextContext CTX = mainactivity. This; //Get Contentresolver ObjectContentresolver resolver =Ctx.getcontentresolver (); //get URI ObjectUri uri = uri.parse ("Content://com.test.myprovider"); //Get DataCursor C = resolver.query (URI,NULL,NULL,NULL,NULL);        C.movetofirst ();  for(inti=0; I<c.getcount (); i++){            intindex = C.getcolumnindexorthrow ("name"); String src=c.getstring (index); LOG.D ("", SRC);        C.movetonext (); }    }}

The results of application B are as follows, and we can see that we have successfully obtained the data in program a in program B.

The above is the use of ContentProvider, this storage method compared to SQLite and sharedpreferences, its complexity is obvious,
But today, with the "cloud" everywhere, the need for data interaction between programs makes the ContentProvider storage mechanism an essential part.


ContentProvider of Android data storage

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.