Details about ContentProvider components in Android
I. Four Android Components
The four main components of Android are Activity, Service, Content Provider, and Broadcast Receiver.
Activity acts as a program interface and interacts directly with users
The Service runs in the background and has no interface to complete specific functions.
ContentProvider maintains application data to facilitate access by the application itself or other applications
Broadcast Receiver provides an asynchronous Broadcast message receiving mechanism to facilitate interaction between applications and components.
2. What is ContentProvider
ContentProvider is one of the four main components in Android. It is mainly used for external data sharing, that is, using ContentProvider to share the data in the application to other applications for access. Other applications can use ContentProvider to operate on the data in the specified application. ContentProvider is divided into system and custom data, such as contacts and images.
1. ContentProvider
Android provides some main data types of ContentProvider, such as audio, video, images, and private address book. You can find some ContentProvider provided by android in the Android. provider package. By obtaining these contentproviders, You can query the data they contain, provided that you have obtained the appropriate read permission.
Main Methods:
Public boolean onCreate () call public Cursor query (Uri, String [], String, String [], String) when creating ContentProvider to query the ContentProvider of a specified Uri, returns a Cursorpublic Uri insert (Uri, ContentValues) used to add data to the specified Uri's ContentProvider public int update (Uri, ContentValues, String, String []). used to update the data public int delete (Uri, String, String []) in the ContentProvider of the specified Uri to delete the data public String getType (Uri) from the ContentProvider of the specified Uri to return the specified U MIME type of data in ri * If the operated data belongs to the set type, the MIME type string should start with vnd. android. cursor. dir. For example, if the Uri of all person records is content: // contacts/person, the returned MIME-type string is "vnd. android. cursor. dir/person ". * If the data to be operated belongs to a non-set type, the MIME-type string should start with vnd. android. cursor. item. For example, if the Uri of the person record whose id is 10 is content: // contacts/person/10, the returned MIME-type string should be "vnd. android. cursor. item/person ".
2. ContentResolver
When an external application needs to add, delete, modify, and query data in ContentProvider, you can use the ContentResolver class to complete the operation. To obtain the ContentResolver object, you can use the getContentResolver () provided by Context () method.
ContentResolver cr = getContentResolver();
The methods provided by ContentResolver and the methods provided by ContentProvider correspond to the following methods.
Public Uri insert (Uri uri, ContentValues values) is used to add data to the ContentProvider of the specified Uri. Public int delete (Uri uri, String selection, String [] selectionArgs) is used to delete data from the specified Uri's ContentProvider. Public int update (Uri uri, ContentValues values, String selection, String [] selectionArgs) is used to update data in the ContentProvider of the specified Uri. Public Cursor query (Uri uri, String [] projection, String selection, String [] selectionArgs, String sortOrder) is used to query the ContentProvider of a specified Uri.
3. Uri
Uri indicates the data to be operated. Uri mainly contains two parts: 1.
ContentProvider; 2. operate on the data in ContentProvider. A Uri is composed
The following components:
The scheme of ContentProvider is defined by Android, and the scheme is content ://.
The hostname (authorities) is used to uniquely identify the ContentProvider.
It finds the corresponding content provider (ContentProvider ).
Path can be used to indicate the data we want to operate on. The Path construction should be based on the business,
As follows:
To operate records with the ID of 10 in the Person table, you can build the path:/person/id/10, or
It can be/prson/10. The URL to be constructed must match the Uri registered in UriMatcher.
To. For example:/person/id/10, the Uri must be matched with/preson/id/#. Otherwise
It can be written as/person/10.
To operate on all records in the person table, you can build the path as follows:/person
To convert a string to a Uri, you can use the parse () method in the Uri class. As follows:
Uri uri = Uri. parse ("content: // com. ljq. provider. personprovider/person ")
Iii. Introduction to the UriMatcher class
Because Uri represents the data to be operated, we often need to parse the Uri and obtain data from the Uri. The Android system provides two tool classes for Uri operations: UriMatcher and ContentUris. Understanding their usage will facilitate our development work.
The UriMatcher class is used to match a Uri. Its usage is as follows:
The first step is to register all the Uri paths you need, as shown below:
// Constant UriMatcher. NO_MATCH indicates that the response code UriMatcher sMatcher = new UriMatcher (UriMatcher. NO_MATCH); // If the match () method matches content: // com. ljq. provider. personprovider/person path. The returned matching code is 1. The matched Uri is registered as follows: sMatcher. addURI ("com. ljq. provider. personprovider ", person", 1); // Add the uri to be matched. If the uri matches, a matching code is returned. // If the match () method matches content: // com. ljq. provider. personprovider/person/230 path, returns a matching code of 2, with Uri registration as follows: sMatcher. addURI ("com. ljq. provider. personprovider "," person/# ", 2); // # It is a wildcard character. // enter the Uri and perform a match switch (sMatcher. match (Uri. parse ("content: // com. ljq. provider. personprovider/person/10 ") {case 1 break; case 2 break; default: // does not match break ;}
After registering the Uri to be matched, you can use sMatcher. match (uri)
If the matching is correct, the matching code is returned. The matching code is the third one passed in by the addUri () method.
Number. If the content: // com. ljq. provider. personprovider/person path is matched
The matching code is 1.
4. ContentUris describes how to use ContentUris to operate the ID section behind the Uri. It has two practical methods:
WithAppendedId (uri, id) is used to add the id part to the uri path, as follows:
Uri uri = Uri. parse ("content: // com. ljq. provider. personprovider/person ") Uri resultUri = ContentUris. withAppendedId (uri, 10); // The generated Uri is: content: // com. ljq. provider. personprovider/person/10 parseId (uri) is used to obtain the Id from the path, as follows: Uri uri = Uri. parse ("content: // com. ljq. provider. personprovider/person/10 ") long personid = ContentUris. parseId (uri); // The result is 10.
5. Listen for data changes in ContentProvider if the visitor of ContentProvider needs to know that the data in ContentProvider has changed, call getContentResovler () when the data in ContentProvider has changed (). notifyChange (uri, null) to notify the visitor registered on this uri, as follows:
public class PersonContentProvider extends ContentProvider { public Uri insert(Uri uri, ContentValues values) { db.insert("person", "personid", values); getContext().getContentResolver().notifyChange(uri, null); } }
If the visitor of ContentProvider needs to be notified of data changes, you must use ContentObserver to listen to the data (the data is described in the Uri). When the notification of data changes is received, the system will call the onChange () method of ContentObserver, as follows:
GetContentResolver (). registerContentObserver (Uri. parse ("content: // com. ljq. providers. personprovider/person "), true, new PersonObserver (new Handler (); public class PersonObserver extends ContentObserver {public PersonObserver (Handler handler) {super (handler );} public void onChange (boolean selfChange) {// you can perform corresponding business processing here }}
Vi. Specific instances
Public class FirstContentProvider extends ContentProvider {// The UriMatcher class is mainly used to match Uri private static final UriMatcher uriMatcher = new UriMatcher (UriMatcher. NO_MATCH); private MySqlite mysqlite; static {// register the Uri uriMatcher provided to the external program. addURI (UserInfo. AUTOR, "userinfo", 1); uriMatcher. addURI (UserInfo. AUTOR, "userinfoall", 2);} // delete data @ Override public int delete (Uri uri, String selection, String [] selec TionArgs) {int number = 0; if (uriMatcher. match (uri) = 1) {// Delete the data according to the condition and obtain the number of lines deleted = mysqlite. getReadableDatabase (). delete ("user_info", selection, selectionArgs);} // The Notification data has changed getContext (). getContentResolver (). policychange (uri, null); return number ;}@ Override public String getType (Uri uri) {return null ;}// insert data @ Override public Uri insert (Uri uri, contentValues values) {String name = Values. getAsString (UserInfo. user. NAME ). toString (); String age = values. getAsInteger (UserInfo. user. AGE ). toString (); String maxId = "select max (id) id from user_info"; Cursor cursor = mysqlite. getReadableDatabase (). rawQuery (maxId, null); cursor. moveToFirst (); int userid = cursor. getInt (0) + 1; if (uriMatcher. match (uri) = 1) {mysqlite.getwritabledatabase(cmd.exe cSQL ("insert into user_info values (?,? ,?) ", New String [] {String. valueOf (userid), name, age});} return uri;} // connect to the Database @ Override public boolean onCreate () {mysqlite = new MySqlite (getContext (), "userinfo. db ", null, 1); return true;} // query data @ Override public Cursor query (Uri uri, String [] projection, String selection, String [] selectionArgs, string sortOrder) {SQLiteDatabase sqlite = mysqlite. getReadableDatabase (); String str = "select name, age from user_info"; if (uriMatcher. match (uri) = 1) {str + = "where" + selection;} Cursor cursor = sqlite. rawQuery (str, selectionArgs); return cursor;} // modify data @ Override public int update (Uri uri, ContentValues values, String selection, String [] selectionArgs) {SQLiteDatabase sqlite = mysqlite. getReadableDatabase (); int number = 0; if (uriMatcher. match (uri) = 1) {number = sqlite. update ("user_info", values, selection, selectionArgs) ;}return number ;}}