Based on the Android ContentProvider summary of the detailed _android

Source: Internet
Author: User
Tags sqlite sqlite database static class string format
1. Applicable scene
1) ContentProvider provides a unified interface for storing and reading data
2 using ContentProvider, applications can realize data sharing
3 Android Built-in many of the data are used in the form of ContentProvider, for developers to call (such as video, audio, pictures, contacts, etc.)
2. Introduction to Relevant Concepts
1) ContentProvider Introduction
When you apply an inherited ContentProvider class and override the class's methods for providing data and storing data, you can share its data with other applications. Although other methods can also be used to share data, but the way data access will be different from the way the data is stored, such as: the use of file mode to share data externally, the need for file operations to read and write data, the use of sharedpreferences share 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 the URI class
Uri uri = uri.parse ("Content://com.changcheng.provider.contactprovider/contact")
The query string used in the content provider differs from the standard SQL query. Many operations, such as SELECT, add, delete, modify, are performed using a special URI that consists of 3 parts, "content://", a path to the data, and an optional ID for identifying data. Here are some sample URIs:
Copy Code code as follows:

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 looks a bit confusing. To do this, Android offers a series of helper classes (under the Android.provider package) that contain a lot of query strings in the form of class variables, which makes it easier for us to understand, 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:
Copy Code code as follows:

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 fields to be returned
NULL,//WHERE clause
NULL,//The 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 sequentially read the specified data column name and number in the contact information table.
To modify a record:
We can use the Contentresolver.update () method to modify the data, we write a method to modify the data:
Copy Code code as follows:

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 (Ten, "XYZ"); Change the Name field value of the 10th record to "XYZ"
To add a record:
To add records, we can call the Contentresolver.insert () method, which takes a target URI of the record to be added, and a map object that contains the new record value, and the return value after the call is the URI of the new record, containing 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 the data to the contact information book:
Copy Code code as follows:

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 contact names and phone numbers to the contact information book.
To delete a record:
The Getcontextresolver.delete () method in the Content provider can be used to delete records, and the following records are used to delete all contact information on the device:
Copy Code code as follows:

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. Create a class that inherits the ContentProvider parent class
B. To define a class variable named Content_uri and a URI type that is public static final, you must specify a unique string value for it, and the best scenario is 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 the Android database, you must define a column called _id, which is used to indicate the uniqueness of each record.
D. Create your data storage system. Most content provider use the Android file system or the SQLite database to keep the data, but you can also store it in any way you want.
E. If you want to store byte-type data, such as bitmap files, the data column is actually a URI string representing the actual saved file, through which you can read the corresponding file data. The content provider that handles this data type needs to implement a field called _data, which lists the exact path to the file on the Android file System _data field. This field is not only for client use, but also for contentresolver use. 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 holds more permissions than the client.
F. Declare a variable of public static string that specifies the data column to be returned from the cursor.
G. 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 <provider> tags in androidmenifest.xml to set content provider.
I. If the data type you are dealing with is a newer type, you must first define a new MIME type for 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:
Copy Code code as follows:

Vnd.android.cursor.item/vnd.yourcompanyname.contenttype (MIME type of a single record)
For example, a URI requesting train information, such as content://com.example.transportationprovider/trains/122, might return to typevnd.android.cursor.item/ Vnd.example.rail such a MIME type.
Vnd.android.cursor.dir/vnd.yourcompanyname.contenttype (MIME type of multiple records)
For example, a URI requesting all train information, such as Content://com.example.transportationprovider/trains, might return to 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 the user names (the data is stored using the Sqllite database):
Copy Code code as follows:

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 class above defines the Content_uri of the content provider and the data columns. Here we define the actual content provider class based on the above class:
Copy Code code as follows:

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, which is used to add and read records from the SQLite database.
The entry for the Content provider needs to be configured in Androidmanifest.xml:
Copy Code code as follows:

<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 invokes the query () method of the Contentresolver class for querying the data, which returns a cursor object.
4) The Cursor object is analyzed and the needed data is obtained.
5) Call the Close () method of the cursor class to turn the cursor object off.
Copy Code code as follows:

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.