Android contentprovider Summary

Source: Internet
Author: User

Transferred from: http://www.cnblogs.com/devinzhang/archive/2012/01/20/2327863.

1. Applicable scenarios

1) contentprovider provides a unified interface for data storage and reading.

2) using contentprovider, applications can share data

3) Many of the android built-in data is in the contentprovider format for developers to call (such as video, audio, image, Address Book, etc)

2. Introduction to related concepts

1) contentprovider Introduction
When an application inherits the contentprovider class and overwrites the class to provide and store data, it can share its data with other applications. Although data can be shared externally by using other methods, the data access method varies depending on the data storage method. For example, if data is shared externally by using the file method, you need to perform file operations to read and write data; to use sharedpreferences to share data, you must use the sharedpreferences API to read and write data. The advantage of using contentprovider to share data is to unify the data access mode.

2) URI class Introduction

Uri uri = URI. parse ("content: // com. Changcheng. provider. contactprovider/contact ")

The query strings used in content providers are different from standard SQL queries. We use a special URI for many operations such as select, add, delete, and modify. This URI consists of three parts: "content ://", indicates the data path and an optional ID. The following is an example URI:

 Content: // media/Internal/Images ThisUriReturns all images stored on the device.
Content: // contacts/people/
ThisUriAll contacts on the device will be returned.
Content: // contacts/people/45
ThisUriReturns a single result (in the contact informationIDIs45Contact Records)

Although this query string format is common, it looks a bit confusing. Therefore, Android provides a series of help classes (in Android. under the provider package), which contains a lot of query strings in the form of class variables, this method is easier for us to understand, so, as shown in the above content: // The contacts/people/45 URI can be written as follows:

Uri person = contenturis. withappendedid (people. content_uri, 45 );

Then execute the Data Query:

Cursor cur = managedquery (person, null );

This query returns a cursor containing all data fields. We can use this cursor to retrieve all data:

Package COM. wissen. testapp; public class contentproviderdemo extends activity {@ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); displayrecords ();} private void displayrecords () {// This array contains all the fields to return: String columns [] = new string [] {people. name, people. number}; Uri mcontacts = people. content_uri; cursor cur = managedquery (mcontacts, columns, // NULL data field to be returned, // null in the WHERE clause, and null in the WHERE clause // order-by clause ); if (cur. movetofirst () {string name = NULL; string phoneno = NULL; do {// obtain the field value name = 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 preceding example shows how to read the specified data column name and number in the contact information table in sequence.

Modification record:
We can use the contentresolver. Update () method to modify the data. Let's write a method to modify the data:

private void updateRecord(int recNo, String name) {    Uri uri = ContentUris.withAppendedId(People.CONTENT_URI, recNo);    ContentValues values = new ContentValues();    values.put(People.NAME, name);    getContentResolver().update(uri, values, null, null);}

  

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

UpdateRecord (10, "xyz"); // change the name field value of the first record to "xyz"

Add record:
To add records, we can call contentresolver. insert () method. This method accepts the target URI of the record to be added and a map object containing the value of the new record. The returned value after the call is the URI of the new record, including the record number.
In the above example, we are all based on the standard content provider of the contact information book. Now we will create an insertrecord () method to add data to the contact information book:

private void insertRecords(String name, String phoneNo) {    ContentValues values = new ContentValues();    values.put(People.NAME, name);    Uri uri = getContentResolver().insert(People.CONTENT_URI, values);    Log.d(”ANDROID”, uri.toString());    Uri numberUri = 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);}

In this way, you can call insertrecords (name, phoneno) to add the contact name and phone number to the contact information book.

Delete record:
The getcontextresolver. Delete () method in content provider can be used to delete records. The following records are used to delete all contact information on the device:

private void deleteRecords() {    Uri uri = People.CONTENT_URI;    getContentResolver().delete(uri, null, null);}

You can also specify the where Condition Statement to delete a specific record:

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

This will delete the record whose name is 'xyz xyz.

3. Create contentprovider

To create our own content provider, follow these steps:
A. Create a class that inherits the contentprovider parent class

B. define a class variable named content_uri and public static final URI. You must specify a unique string value for it. The best solution is to use the full name of the class, such:
Public static final URI content_uri = URI. parse ("content: // com. Google. Android. mycontentprovider ");

C. Define the data column name you want to return to the client. If you are using the android database, you must define a column named _ id for it to indicate the uniqueness of each record.

D. Create your data storage system. Most content providers use the android file system or SQLite database to maintain data, but you can store the data in any way you want.

E. If you want to store byte data, such as bitmap files, the data column is actually a URI string that represents the actually saved file and uses it to read the corresponding file data. To process this data type, the content provider needs to implement a field named _ data, And the _ data field lists the precise paths of the file on the android file system. This field is not only used by the client, but also for contentresolver. The client can call contentresolver. the openoutputstream () method is used to process the file Resources pointed to by the URI. If it is contentresolver itself, it can directly access the data file because it has higher permissions than the client.

F. Declare a public static string variable to specify the data column to be returned from the cursor.

G. The query returns a cursor type object. All write operations, such as insert (), update (), and delete (), will be monitored. We can use the contentresover (). policychange () method to notify the listener about data updates.

H. Use the <provider> label in androidmenifest. XML to set the content provider.

I. If the data type you want to process is a relatively new type, you must first define a new MIME type for contentprovider. getype (URL) to return. The MIME type can be either specified for a single record or multiple records. A common format is provided here:

Vnd. Android. cursor. Item/vnd. yourcompanyname. contenttype (MIME type of a single record)
For example, a request for train information URI such as content: // COM. example. transportationprovider/TRAINS/122 may return typevnd. android. cursor. item/vnd. example. a mime type such as rail.

Vnd. Android. cursor. DIR/vnd. yourcompanyname. contenttype (MIME type of multiple Records)
For example, a URI that requests all train information, such as content: // COM. example. transportationprovider/trains may return vnd. android. cursor. DIR/vnd. example. a mime type such as rail.

The following code creates a content provider that only stores the user name and displays all the user names (using the sqllite database to store the data ):

Public class myusers {public static final string authority = "com. wissen. mycontentprovider "; // The basecolumn class already contains the _ id field public static final class user implements basecolumns {public static final URI content_uri = Uri. parse ("content: // COM. wissen. mycontentprovider "); // table data column public static final string user_name =" user_name ";}}

The class above defines the content provider's content_uri and data columns. The following defines the actual content provider class based on the above class:

Public class mycontentprovider extends contentprovider {private sqlitedatabase sqldb; private databasehelper dbhelper; Private Static final string database_name = "users. DB "; Private Static final int database_version = 1; Private Static final string table_name =" user "; Private Static final string tag =" mycontentprovider "; Private Static class databasehelper extends sqliteopenhelper {databasehelpe R (context) {super (context, database_name, null, database_version) ;}@ override public void oncreate (sqlitedatabase dB) {// create the table db.exe csql ("create table" + table_name + "(_ id integer primary key autoincrement, user_name text);") used to store data );");} @ override public void onupgrade (sqlitedatabase dB, int oldversion, int newversion) {db.exe csql ("Drop table if exists" + table_name); oncreate (db );}} @ Override public int Delete (URI Uri, string S, string [] as) {return 0 ;}@ override Public String GetType (URI) {return NULL ;} @ override public URI insert (URI Uri, contentvalues) {sqldb = dbhelper. getwritabledatabase (); long rowid = sqldb. insert (table_name, "", contentvalues); If (rowid> 0) {URI rowuri = contenturis. appendid (myusers. user. content_uri.buildupon (), rowid ). buil D (); getcontext (). getcontentresolver (). notifychange (rowuri, null); Return rowuri;} Throw new sqlexception ("failed to insert row into" + URI);} @ override public Boolean oncreate () {dbhelper = new databasehelper (getcontext (); Return (dbhelper = NULL )? False: true;} @ override public cursor query (URI Uri, string [] projection, string selection, string [] selectionargs, string sortorder) {sqlitequerybuilder QB = new sqlitequerybuilder (); sqlitedatabase DB = dbhelper. getreadabledatabase (); QB. settables (table_name); cursor c = QB. query (dB, projection, selection, null, sortorder); C. setnotificationuri (getcontext (). getcontentresolver (), Uri); Return C ;}@ override public int Update (URI Uri, contentvalues, string S, string [] as) {return 0 ;}}

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

The content provider entry must be configured in androidmanifest. xml:

<provider android:name=”MyContentProvider” android:authorities=”com.wissen.MyContentProvider” />

Then, let's use the defined content provider:

1) Add the contentprovider access permission to the application.

2) use the getcontentresolver () method to obtain the contentresolver object.

3) Call the contentresolver class query () method to query data. This method returns a cursor object.

4) analyze the obtained cursor object to obtain the required data.

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

public class MyContentDemo extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        insertRecord(”MyUser”);        displayRecords();    }       private void insertRecord(String userName) {        ContentValues values = new ContentValues();        values.put(MyUsers.User.USER_NAME, userName);        getContentResolver().insert(MyUsers.User.CONTENT_URI, values);    }    private void displayRecords() {        String columns[] = new String[] { 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());       }    }}

 

 

 

Related Article

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.