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

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://CONTACTS/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:

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 () {
The array contains all the fields to be returned
String columns[] = new string[] {people.name, people.number};
Uri mcontacts = People.content_uri;
Cursor cur = managedquery (
Mcontacts,
columns,//data field to return
NULL,//WHERE clause
NULL,//parameter of the WHERE clause
NULL//ORDER-BY clause
);
if (Cur.movetofirst ()) {
String name = NULL;
String Phoneno = null;
do {
Get the value of a field
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 example above demonstrates how to read the specified data column name and number in the contact information table in turn.

To modify a record:
We can use the Contentresolver.update () method to modify the data, and we'll write a way 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 ("XYZ"); Change the Name field value of the 10th record to "XYZ"

To add a record:
To add a 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, including 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) {
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);
}

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:

private void Deleterecords () {
Uri uri = People.content_uri;
Getcontentresolver (). Delete (URI, NULL, 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. Creating 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. Declares 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 individual records)
For example, a URI that requests train information, such as content://com.example.transportationprovider/trains/122, might return typevnd.android.cursor.item/ Vnd.example.rail such a MIME type.

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, might return vnd.android.cursor.dir/ Vnd.example.rail such a MIME type.

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 class Myusers {
public static final String authority = "Com.wissen.MyContentProvider";

The _id field is already included in the Basecolumn class
public static final class User implements Basecolumns {
public static final Uri Content_uri = Uri.parse ("Content://com.wissen.mycontentprovider");
Table Data Columns
public static final String 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 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 {
Databasehelper (Context context) {
Super (context, database_name, NULL, database_version);
}

@Override
public void OnCreate (Sqlitedatabase db) {
Create a table for storing data
Db.execsql ("Create table" + table_name + "(_id INTEGER PRIMARY KEY autoincrement, user_name TEXT);");
}

@Override
public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {
Db.execsql ("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 uri) {
return null;
}

@Override
Public URI insert (URI Uri, contentvalues contentvalues) {
SqlDB = Dbhelper.getwritabledatabase ();
Long rowId = Sqldb.insert (table_name, "", contentvalues);
if (RowId > 0) {
Uri Rowuri = Contenturis.appendid (MyUsers.User.CONTENT_URI.buildUpon (), rowId). Build ();
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, NULL, NULL, sortOrder);
C.setnotificationuri (GetContext (). Getcontentresolver (), URI);
return C;
}

@Override
public int update (URI Uri, Contentvalues contentvalues, String S, string[] as) {
return 0;
}
}

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:

<provider android:name= "Mycontentprovider" android:authorities= "Com.wissen.MyContentProvider"/>

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 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 ());
}
}
}

ContentProvider Summary of Android

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.