Four components of android: ContentProvider and four components of android

Source: Internet
Author: User

Four components of android: ContentProvider and four components of android

This article will introduce ContentProvider in a comprehensive manner, from the basic knowledge to the most important and core knowledge. You can read the content according to the directory. The SQLite Operation is designed below, which is not described in detail, as long as ContentProvider is used across processes.

Uri

Uri indicates the data to be operated. It mainly contains two parts: 1. The ContentProvider to be operated, 2. What data in ContentProvider is operated. A Uri consists of the following parts:

Content: // com. gdut. yummylau/person/10

Scheme

The content provider's scheme has been defined by Android as: content ://.

Host Name (or Authority)

It is used to uniquely identify the ContentProvider, which can be found by external callers.

Path)

It can be used to represent the data we want to operate on. The path construction should be based 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.

• The name field of the record with the id of 10 in the person table, person/10/name

• To operate all records in the person table, you can build the path:/person

To convert a string to a Uri, you can use the parse () method in the Uri class, such as Uri uri = Uri. parse ("content: // com. gdut. yummylau/contact ")

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.


UriMatcher: (check the code first)

// Constant UriMatcher. NO_MATCH indicates that the response code UriMatcher sMatcher = new UriMatcher (UriMatcher. NO_MATCH); // If the match () method matches content: // <span style = "font-family: Arial, Helvetica, sans-serif; font-size: 12px; "> com. gdut. yummylau </span>/person path. The returned matching code is 1. The matched Uri is registered as follows: sMatcher. addURI ("com. gdut. yummylau ", person", 1); // Add the uri to be matched. If the uri matches, the matching code is returned. // If the match () method matches the content: // <span style = "font-family: Arial, Helvetica, sans-serif; font-size: 12px;"> com. gdut. yummylau </span>/person/230 path. The returned matching code is 2. The Uri registration is as follows: sMatcher. addURI ("com. gdut. yummylau "," person/# ", 2); // # It is a wildcard character. // input a Uri to match the switch (sMatcher. match (Uri. parse ("content: // com. gdut. yummylau/person/10 ") {case 1 break; case 2 break; default: // does not match break ;}
From the code above, we can see that the steps are roughly as follows:

1. First, you need to match all the Uri paths to the registration, as shown below:

// Constant UriMatcher. NO_MATCH indicates the return code (-1) that does not match any path ).

UriMatcher uriMatcher = new UriMatcher (UriMatcher. NO_MATCH );

// If the match () method matches the content: // com. gdut. yummylau/contact path, the return matching code is 1.

UriMatcher. addURI ("com. changcheng. sqlite. provider. contactprovider", "contact", 1); // Add a uri that needs to be matched. If yes, a matching code is returned.

// If the match () method matches the content: // com. gdut. yummylau/contact/230 path, the matching code is 2.

UriMatcher. addURI ("com. gdut. yummylau", "contact/#", 2); // # It is a wildcard

2. after registering the Uri to be matched, you can use uriMatcher. 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.

Content: // com. gdut. yummylau/contact path. The returned matching code is 1.


ContentUris (check the code first)

Uri uri = Uri. parse ("content: // com. gdut. yummylau/person ") Uri resultUri = ContentUris. withAppendedId (uri, 10); // The generated Uri is: content: // com. gdut. yummylau/person/10 parseId (uri) is used to obtain the Id from the path, as follows: Uri uri Uri = uri. parse ("content: // com. gdut. yummylau/person/10 ") long personid = ContentUris. parseId (uri); // The result is 10.
The above code is used to obtain 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.

• The parseId (uri) method is used to obtain the ID part from the path.


Then let's look at ContentProvider. Some friends may not know what the Uri class is used. In fact, the android system provides a unified interface for data storage and acquisition, and data can be shared between different applications. Android gave birth to ContentProvider. 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. First, we need to know which basic methods (Code-based) the custom ContentProvider must inherit)
import android.content.ContentProvider;import android.content.ContentValues;import android.database.Cursor;import android.net.Uri;public class MyContentProvider extends ContentProvider{@Overridepublic boolean onCreate() {// TODO Auto-generated method stubreturn false;}@Overridepublic Cursor query(Uri uri, String[] projection, String selection,String[] selectionArgs, String sortOrder) {// TODO Auto-generated method stubreturn null;}@Overridepublic String getType(Uri uri) {// TODO Auto-generated method stubreturn null;}@Overridepublic Uri insert(Uri uri, ContentValues values) {// TODO Auto-generated method stubreturn null;}@Overridepublic int delete(Uri uri, String selection, String[] selectionArgs) {// TODO Auto-generated method stubreturn 0;}@Overridepublic int update(Uri uri, ContentValues values, String selection,String[] selectionArgs) {// TODO Auto-generated method stubreturn 0;}}
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. gdut. yummylau/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. gudt. yummylau/person/10, the returned MIME type string is: "vnd. android. cursor. item/person ".

After rewriting the above method (involving adding, deleting, querying, and feedback data types of data), you also need to go to 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, and authorities is its domain name:
<manifest.... >   <application android:icon="@drawable/icon" android:label="@string/app_name">      <provider android:name=".MyContentProvider"            android:authorities="com.gdut.yummylau"/>   </application></manifest>

The content recipient ContentResolver has the content provider. For external applications, the content receiver is required. 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 the given parameter is Uri. parse ("content: // com. gdut. yummylau/person/10 "), the host name is com. gdut. the ContentProvider of yummylau 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: (See Code)
ContentResolver resolver = getContentResolver (); Uri uri = Uri. parse ("content: // <span style =" font-size: 14px; "> com. gdut. yummylau </span>/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, 1); resolver. update (updateIdUri, updateValues, null, null); // Delete the record Uri deleteIdUri = ContentUris with id 2. withAppendedId (uri, 2); resolver. delete (deleteIdUri, null, null );

If the visitor of ContentProvider needs to know that the data in ContentProvider has changed, you can call getContentResolver (). policychange (uri, null) when the data in ContentProvider changes to notify the visitor registered on this URI
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: // <span style =" font-size: 14px; "> com. gdut. yummylau </span>/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 }}

Summary the advantage of using ContentProvider is that the system shields all storage methods of data to be exposed and provides uniform data exposure interfaces for developers to use, developers can use ContentProvider to achieve cross-process data sharing in Different Storage Methods on android. The content accepted by ContentResolver is handled by ContentProvider, ensuring the uniqueness of data processing.





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.