For details about ContentProvider and Uri, contentprovideruri

Source: Internet
Author: User

For details about ContentProvider and Uri, contentprovideruri
1. Use ContentProvider to share data
The role of ContentProvider in android is to share data externally, that is, you can share the data in the application to other applications through ContentProvider for access. Other applications can use ContentProvider to add, delete, modify, and query data in your application. For data sharing, we have learned the file operation mode before. We know that the operation mode of a specified file is Context. MODE_WORLD_READABLE or Context. MODE_WORLD_WRITEABLE. So why use ContentProvider to share data externally? If the file operation mode is used to share data externally, the Data Access Mode varies depending on the data storage mode, resulting in inconsistent data access methods, such: if an xml file is used to share data, xml parsing is required to read data. If sharedpreferences is used to share data, the sharedpreferences API must be used to read data.
The advantage of using ContentProvider to share data externally is to unify the data access mode.
When an application needs to share data externally through ContentProvider, the first step is to inherit ContentProvider and override the following method:

public class PersonContentProvider extends ContentProvider{   public boolean onCreate()   public Uri insert(Uri uri, ContentValues values)   public int delete(Uri uri, String selection, String[] selectionArgs)   public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)   public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)   public String getType(Uri uri)}
The second step must be in AndroidManifest. xml uses <provider> to configure the ContentProvider. To allow other applications to find the ContentProvider, The ContentProvider uses authorities (host name/Domain Name) to uniquely identify it, you can regard ContentProvider as a website (think about it, the website also provides data), and authorities is its domain name:
<manifest.... >   <application android:icon="@drawable/icon" android:label="@string/app_name">      <provider android:name=".PersonContentProvider"            android:authorities="com.ljq.providers.personprovider"/>   </application></manifest>
II. Introduction to Uri
Uri indicates the data to be operated. Uri mainly contains two parts: 1. ContentProvider to be operated; 2. what data is operated on in ContentProvider, a Uri consists of the following parts:


ContentProvider (content provider)'s scheme has been specified by Android, and scheme is: content ://
The Host Name (or Authority) is used to uniquely identify the ContentProvider. External callers can find it based on this identifier.
The path can be used to indicate the data to be operated. The path construction depends on the business, as shown below:
To operate records with the id of 10 in the person table, you can build the path:/person/10.
Name field of the record whose id is 10 in the person table to be operated, person/10/name
To operate on all records in the person table, you can create a path like this:/person
To operate records in the xxx table, you can build the path:/xxx
Of course, the data to be operated may not come from the database, but also from other storage methods such as files, xml, or networks, as follows:
To operate on the name node under the person node in the xml file, you can build the path:/person/name
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, returns the matching code 1sMatcher. 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 the matching code 2sMatcher. addURI ("com. ljq. provider. personprovider "," person/# ", 2); // # It is the wildcard 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. the match (uri) method matches the input Uri. If it matches, the matching code is returned. The matching code is the third parameter passed in by calling the addURI () method. Assume that it matches the content: // com. ljq. provider. personprovider/person path. The returned matching code is 1.

Iv. usage of the ContentUris class
The ContentUris class is used to operate the ID part after the Uri path. It has two practical methods:
WithAppendedId (uri, id) is used to add the ID part to the path:
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
The parseId (uri) method is used to obtain the ID part from the path:
Uri uri = Uri. parse ("content: // com. ljq. provider. personprovider/person/10 ") long personid = ContentUris. parseId (uri); // The result is 10.

5. Use ContentProvider to share data


Main Methods of the ContentProvider class:
Public boolean onCreate (): This method is called after ContentProvider is created. After Android is started, ContentProvider is created only when other applications access it for the first time.
Public Uri insert (Uri uri, ContentValues values): This method is used by external applications to add data to ContentProvider.
Public int delete (Uri uri, String selection, String [] selectionArgs): This method is used by external applications to delete data from ContentProvider.
Public int update (Uri uri, ContentValues values, String selection, String [] selectionArgs): This method is used by external applications to update data in ContentProvider.
Public Cursor query (Uri uri, String [] projection, String selection, String [] selectionArgs, String sortOrder): This method is used by external applications to obtain data from ContentProvider.
Public String getType (Uri uri): This method is used to return the MIME type of the data represented by the current Url.

If the operated data belongs to the set type, the MIME-type string should start with vnd. android. cursor. dir,
For example, to obtain all the person records, the Uri is content: // com. ljq. provider. personprovider/person, the returned MIME-type string should be: "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, obtain the person record with the id of 10. The Uri is content: // com. ljq. provider. personprovider/person/10, the returned MIME type string is: "vnd. android. cursor. item/person ".


6. Use ContentResolver to operate data in ContentProvider

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 getContentResolver () provided by Activity () method. The ContentResolver class provides four methods for the same signature as the ContentProvider class:
Public Uri insert (Uri uri, ContentValues values): This method is used to add data to ContentProvider.
Public int delete (Uri uri, String selection, String [] selectionArgs): This method is used to delete data from ContentProvider.
Public int update (Uri uri, ContentValues values, String selection, String [] selectionArgs): This method is used to update data in ContentProvider.
Public Cursor query (Uri uri, String [] projection, String selection, String [] selectionArgs, String sortOrder): This method is used to obtain data from ContentProvider.

The first parameter of these methods is Uri, which indicates the ContentProvider to be operated and the data to be operated on,
Assume that Uri. parse ("content: // com. ljq. providers. personprovider/person/10 "), the host name is com. ljq. providers. the ContentProvider of personprovider performs operations. The operation data is the record with the id of 10 in the person table.
Use ContentResolver to add, delete, modify, and query data in ContentProvider:
ContentResolver resolver = getContentResolver (); Uri uri = Uri. parse ("content: // com. ljq. provider. personprovider/person "); // Add a record ContentValues values = new ContentValues (); values. put ("name", "linjiqin"); values. put ("age", 25); resolver. insert (uri, values); // obtain all records in the person table. Cursor cursor = resolver. query (uri, null, "personid desc"); while (cursor. moveToNext () {Log. I ("ContentTest", "personid =" + cursor. getInt (0) + ", name =" + cursor. getString (1);} // change the name field value of the record whose id is 1 to zhangsanContentValues updateValues = new ContentValues (); updateValues. put ("name", "zhangsan"); Uri updateIdUri = ContentUris. withAppendedId (uri, 2); resolver. update (updateIdUri, updateValues, null, null); // Delete the record Uri deleteIdUri = ContentUris with id 2. withAppendedId (uri, 2); resolver. delete (deleteIdUri, null, null );


7. Monitor Data changes in ContentProvider
If the visitor of ContentProvider needs to know that the data in ContentProvider has changed, call getContentResolver () when the data in ContentProvider changes (). notifyChange (uri, null) to notify visitors registered on this URI, for example:
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:
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 }}





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.