ContentProvider Summary of Android

Source: Internet
Author: User
Tags sqlite database

1. Applicable scenarios

1) ContentProvider provides a unified interface for storing and reading data

2) using ContentProvider, applications can share data

3) Many of the data built into Android are used in the form of ContentProvider for developers to call (such as video, audio, images, contacts, etc.)

2. Introduction to Related concepts

1) ContentProvider Introduction When an application 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.

2) Introduction to URI classes

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://conta CTS/PEOPLE/45 This URI Returns a single result (the contact information has an ID of 's contact records)

Although this query string format is common, it still seems a bit confusing. To do this, Android provides a series of helper classes (under the Android.provider package) that contain many query strings given in the form of class variables, which makes it easier for us to understand a bit, so as above content://contacts/people/ 45 This URI can be written in the following form:

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

Then execute the data query:

Cursor cur = managedquery (person, NULL, NULL, NULL);

This query returns a cursor that contains all the data fields, and we can iterate over the cursor to get all the data:

 Packagecom.wissen.testApp; Public classContentproviderdemoextendsActivity {@Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);       Setcontentview (R.layout.main);    Displayrecords (); }    Private voiddisplayrecords () {//The array contains all the fields to be returnedString columns[] =Newstring[] {people.name, people.number}; Uri mcontacts=People.content_uri; Cursor cur=managedquery (mcontacts, columns,//the data field to return           NULL,//WHERE clause           NULL,//arguments to the WHERE clause           NULL         //order-by clause     ); if(Cur.movetofirst ()) {String name=NULL; String Phoneno=NULL;  Do {              //get the value of a fieldName =cur.getstring (Cur.getcolumnindex (people.name)); Phoneno=cur.getstring (Cur.getcolumnindex (People.number)); Toast.maketext ( This, name + "" +Phoneno, Toast.length_long). Show (); }  while(Cur.movetonext ()); }    }}

The example above demonstrates how to read the specified data column name and number in the contact information table in turn.

Modify the Record: we can use the Contentresolver.update () method to modify the data, we write a method to modify the data:

void UpdateRecord (int recNo, String name) {     uri uri = Contenturis.withappendedid (People.content_uri, recNo);     new Contentvalues ();     Values.put (People.name, NAME);     null); }

Now you can call the above method to update the specified record:

UpdateRecord ("XYZ"); Change the Name field value of the 10th record to "XYZ"

Add record: to increase the record, we can call the Contentresolver.insert () method, which takes a target URI for the record to be added, and a map object containing the new record value, which is the URI of the new record. Contains the record number. In the example above we are all based on the standard content Provider of the contact information book, and now we continue to create a Insertrecord () method to add data to the contact information book:

Private void insertrecords (string name, String Phoneno) {    new  contentvalues ();    Values.put (People.name, NAME);     = getcontentresolver (). Insert (People.content_uri, values);    LOG.D ("ANDROID", uri.tostring ());     = Uri.withappendedpath (Uri, People.Phones.CONTENT_DIRECTORY);    Values.clear ();    Values.put (Contacts.Phones.TYPE, People.Phones.TYPE_MOBILE);    Values.put (People.number, Phoneno);    Getcontentresolver (). Insert (Numberuri, values);}

This way we can call Insertrecords (name, Phoneno) to add the contact name and phone number to the contact information book.

To delete a record: The Getcontextresolver.delete () method in Content provider can be used to delete records, and the following record is used to delete all contact information on the device:

void Deleterecords () {     uri uri = People.content_uri;      null);}

You can also specify a WHERE condition statement to delete a specific record:

Getcontentresolver (). Delete (URI, "name=" + "' xyz xyz '", null);

This will delete the record with name ' XYZ XYZ '.

3. Create ContentProvider

To create our own content provider, we need to follow these steps: A. Create a class that inherits the ContentProvider parent class
B. Define a class variable named Content_uri, which is a public static final URI type, and you must specify a unique string value for it, the best scenario is to use the full name of the class, such as: public static final URI CONTENT _uri = Uri.parse ("Content://com.google.android.mycontentprovider");

C. Define the name of the data column you want to return to the client. If you are using an Android database, you must define a column called _id, which is used to represent the uniqueness of each record.

D. Create your data storage system. Most content provider use an android file system or SQLite database to keep data, but you can also store it in any way you want.
E. If you want to store byte data, such as a bitmap file, the data column is actually a URI string representing the actual saved file, through which to read the corresponding file data. The content provider that handles this data type needs to implement a field named _data, and the _data field lists the exact path to the file on the Android file system. This field is not only intended for use by clients, but is also available to contentresolver. The client can call the Contentresolver.openoutputstream () method to handle the file resource that the URI points to, and if it is contentresolver itself, it can access the data file directly because it has higher permissions than the client.
F. Declare a variable of public static string that specifies the data column to be returned from the cursor.
G. The query returns an object of type cursor. All methods that perform write operations, such as insert (), update (), and delete (), are monitored. We can notify listeners about data updates by using the Contentresover (). Notifychange () method.
H. Use the <provider> tag in Androidmenifest.xml to set the content provider.
I. If the type of data you are dealing with is a newer type, you must first define a new MIME type for the Contentprovider.getype (URL) to return. There are two forms of mime types: one for the specified single record, and one for multiple records. A common format is given here:

Vnd.android.cursor.item/vnd.yourcompanyname.contenttype (MIME type for a single record) For example, a URI that requests train information such as content:// COM.EXAMPLE.TRANSPORTATIONPROVIDER/TRAINS/122 may return a MIME type such as Typevnd.android.cursor.item/vnd.example.rail.

Vnd.android.cursor.dir/vnd.yourcompanyname.contenttype (MIME type for multiple records) For example, a URI that requests all train information, such as content:// Com.example.transportationprovider/trains may return a MIME type such as Vnd.android.cursor.dir/vnd.example.rail.

The following code creates a content Provider that simply stores the user name and displays all user names (which are stored using the Sqllite database):

 Public classMyusers { Public Static FinalString authority ="Com.wissen.MyContentProvider"; //the _id field is already included in the Basecolumn class    Public Static Final classUserImplementsBasecolumns { Public Static FinalUri Content_uri = Uri.parse ("CONTENT://Com.wissen.MyContentProvider "); //Table Data Columns         Public Static FinalString user_name ="user_name"; }}

The above class defines the Content_uri of the content provider, as well as the data columns. Below we will define the actual content provider class based on the class above:

 Public classMycontentproviderextendsContentProvider {Privatesqlitedatabase SqlDB; PrivateDatabasehelper DBHelper; Private Static FinalString database_name ="Users.db"; Private Static Final intDatabase_version= 1; Private Static FinalString table_name="User"; Private Static FinalString TAG ="Mycontentprovider"; Private Static classDatabasehelperextendsSqliteopenhelper {databasehelper (context context) {Super(Context, database_name,NULL, database_version); } @Override Public voidonCreate (Sqlitedatabase db) {//Create a table for storing dataDb.execsql ("Create table" + table_name +"(_id INTEGER PRIMARY KEY autoincrement, user_name TEXT);"); } @Override Public voidOnupgrade (Sqlitedatabase db,intOldversion,intnewversion) {Db.execsql ("DROP TABLE IF EXISTS"+table_name);        OnCreate (DB); }} @Override Public intDelete (Uri Uri, String s, string[] as) {return0; } @Override PublicString getType (Uri uri) {return NULL; } @Override Publicuri insert (Uri Uri, contentvalues contentvalues) {SqlDB=dbhelper.getwritabledatabase (); LongRowId =Sqldb.insert (table_name, "", contentvalues); if(RowId > 0) {Uri Rowuri=Contenturis.appendid (MyUsers.User.CONTENT_URI.buildUpon (), rowId). Build (); GetContext (). Getcontentresolver (). Notifychange (Rowuri,NULL); returnRowuri; }        Throw NewSQLException ("Failed to insert row into" +URI); } @Override Public BooleanonCreate () {DBHelper=NewDatabasehelper (GetContext ()); return(DBHelper = =NULL) ?false:true; } @Override PublicCursor query (Uri uri, string[] projection, string selection, string[] Selectionargs, string sortOrder) {Sqlit Equerybuilder QB=NewSqlitequerybuilder (); Sqlitedatabase DB=dbhelper.getreadabledatabase ();        Qb.settables (table_name); Cursor C= Qb.query (db, Projection, selection,NULL,NULL,NULL, SortOrder);        C.setnotificationuri (GetContext (). Getcontentresolver (), URI); returnC; } @Override Public intupdate (URI Uri, Contentvalues contentvalues, String S, string[] as) {return0; }}

A content provider named Mycontentprovider is created to add and read records from the SQLite database.

The portal for Content provider needs to be configured in Androidmanifest.xml:

<android:nameandroid:authorities/>  

After that, let's use this well-defined content Provider:

1) Add ContentProvider access rights to the application.

2) The Contentresolver object is obtained by Getcontentresolver () method.

3) Call the query () method of the Contentresolver class for querying the data, and the method returns a Cursor object.

4) The resulting cursor object is analyzed to obtain the required data.

5) Call the cursor class's close () method to close the cursor object.

 Public classMycontentdemoextendsActivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Insertrecord ("MyUser");    Displayrecords (); }       Private voidInsertrecord (String userName) {contentvalues values=Newcontentvalues ();        Values.put (MyUsers.User.USER_NAME, userName);    Getcontentresolver (). Insert (MyUsers.User.CONTENT_URI, values); }    Private voiddisplayrecords () {String columns[]=Newstring[] {myusers.user._id, MyUsers.User.USER_NAME}; Uri Myuri=MyUsers.User.CONTENT_URI; Cursor cur= Managedquery (Myuri, columns,NULL,NULL,NULL ); if(Cur.movetofirst ()) {String ID=NULL; String UserName=NULL;  Do{ID=cur.getstring (Cur.getcolumnindex (myusers.user._id)); UserName=cur.getstring (Cur.getcolumnindex (MyUsers.User.USER_NAME)); Toast.maketext ( This, id + "" +UserName, Toast.length_long). Show (); }  while(Cur.movetonext ()); }    }}

ContentProvider Summary of Android

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.