Android Study Notes 19. Using ContentProvider for data sharing (1), androidprovider

Source: Internet
Author: User

Android Study Notes 19. Using ContentProvider for data sharing (1), androidprovider
1. How does Android achieve data sharing?To exchange data between applications, Android provides ContentProvider, which is a standard API for data exchange between different applications, when an application needs to expose its own data to other programs for use, the application can be implemented by providing ContentProvider, other applications can use ContentResolver to manipulate the data exposed by ContentProvider. Once an application exposes its own data operation interface through ContentProvider, other applications can use this interface to operate internal data of the application no matter whether the application is started or not, this includes adding, deleting, modifying, and querying data. Summary: application A exposes its own data through ContentProvider, and application B uses ContentResolver to manipulate the data exposed by ContentProvider. Application A provides external data in the form of A certain Uri. Application B uses ContentResolver to obtain the authority attribute of application A Based on the Uri provided by application A to access the specified data.2. ContentProvider andContentResolver Introduction
1. functions:(1) ContentProvider is a standard API for data exchange between different applications. ContentProvider provides external data in a certain Uri and runs other applications to access or modify data, that is, other applications use ContentResolver to access specified data based on the Uri. The UriMatcher class is used to help parse the URI. In practical applications, in addition to inheriting ContentProvider, the custom ContentProvider class also needs to implement the following methods (both abstract methods):-abstract boolean onCreate () -abstract Cursor query (Uri uri, String [] projection, String selection, String [] selectionArgs, String sortOrder)-abstract Uri insert (Uri uri, ContentValues values) -abstract int update (Uri uri, ContentValues values, String selection, String [] selectionArgs)-abstract int delete (Uri uri, String Selection, String [] selectionArgs)-abstract String getType (Uri uri) (2) Contentprovider is equivalent to a "website", which is used to expose data that can be operated. Other applications use ContentResolver to manipulate the data exposed by ContentProvider, that is, ContentResolver is equivalent to HttpClient. In general, ContentProvider is a single-instance mode. When multiple applications use ContentResolver to operate the data provided by ContentProvider, the Data Operations called by ContentResolver will be delegated to the same ContentProvider for processing.

Sublimation Note 1: How does ContentResolver access and modify the data in the ContentProvider corresponding to the Uri? From the relationship between ContentResolver, ContentProvider, and Uri, Uri is the identifier for data exchange between ContentResolver and ContentProvider. ContentResolver performs CRUD and other data operations on the specified Uri, but the Uri is not a real data center. Therefore, these CRUD operations will be delegated to the ContentProvider corresponding to the Uri. For example, if application B executes CUUD operations through ContentResolver, all these CRUD operations need to specify the Uri parameter, and the Android system will find the corresponding ContentProvider Based on the Uri (the ContentProvider belongs to application ), contentProvider implements the CRUD method in A complex way to add, delete, modify, and query the underlying data, which enables application B to access the data of application. Note: here the CRUD operation refers to the insert () method that B calls ContentResolver. It is actually equivalent to calling the insert () method of ContentProvider (which belongs to application A) corresponding to this Uri () method. 2. API ContentProvider
(1) inheritance relationship public abstract classjava. lang. Object construct android. content. ContentProvider (2) constructor
ContentProvider () Construct a ContentProvider instance.
(3) Common method abstract boolean onCreate (): This method is called after ContentProvider is created. When other applications access ContentProvider for the first time, the ContentProvider is created, and immediately calls back the onCreate () method. abstract Cursor query (Uri uri, String [] projection, String selection, String [] selectionArgs, String sortOrder ): query all records matched by the select condition according to the Uri. projection is a column name list, indicating that only the specified data column is selected. abstract Uri insert (Uri uri, ContentValues values ): insert the Data abstract int update (Uri ur I, ContentValues values, String selection, String [] selectionArgs): abstract int delete (Uri, String selection, String [] selectionArgs ): delete all records matching the select condition according to the Uri. abstract String getType (Uri uri): This method is used to return the MIME type of the data represented by the current Uri. If the Uri data may contain multiple records, the MIME-type string starts with vnd. android. cursor. dir. If the data corresponding to this Uri contains only one record, the returned MIME-type string should start with vnd. android. cursor. item.
ContentResolver
(1) inheritance relationship public abstract classjava. lang. Object construct android. content. ContentProvider (2) constructor (create ContentResolver Object)
ContentResolver (Context context)
In addition, Content provides the getContentResolver () method to obtain a ContentResolver object. That is to say, components such as Activity and Service can obtain the ContentResolver object through the getContentResolver () method, so that we can call the following ContenResolver method to operate on the exposed data. ContentResolver contentResolver = getContentResolver (); (3) Common Methods Final int delete (Uri url, String where, String [] selectionArgs): delete the matched data submitted by where in the ContentProvider corresponding to the Uri; final String getType (Uri url ): get the MIME type of the given Content URL; final Uri insert (Uri url, ContentValues values): insert the values data to the ContentProvider corresponding to the Uri;
Parameters:
Url The URL of the table to insert.
Values The initial values for the newly inserted row. The key is the column name for the field. Passing an empty ContentValues will create an empty row.
Returns:
The URL of the newly created row.
Final Cursor query (Uri uri, String [] projection, String selection, String [] selectionArgs, String sortOrder): queries the data submitted by where in the ContentProvider corresponding to the Uri. Parameters:
Uri The URI, using the content: // scheme, for the content to retrieve.
Projection A list of which columns to return. Passing null will return all columns, which is inefficient.
Selection A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given URI.
SelectionArgs You may include? S in selection, which will be replaced by the values from selectionArgs, in the order that they appear in the selection. The values will be bound as Strings.
SortOrder How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.
Returns:
A Cursor object, which is positioned before the first entry, or null
Final void registerContentObserver (Uri uri, boolean policyfordescendents, ContentObserver observer): registers an observation class, when the data in the ContentProvider corresponding to the exposed URI changes, call this method final int update (Uri uri, ContentValues values, String where, String [] selectionArgs ): update where in the ContentProvider corresponding to the Uri to submit matched data;
ContentValuesThis class is used to store a set of values that the ContentResolver can process. (1) Inheritance relation java. lang. Object contains android. content. ContentValues (2) constructor
ContentValues () Creates an empty set of values using the default initial size
ContentValues (int size) Creates an empty set of values using the given initial size
ContentValues (ContentValues from) Creates a set of values copied from the given set
(3) Common method void put (String key, Byte value): Add key-value pairs to the set Set set <Entry <String, Object> valueSet (): returns all key objects and value objects in the set int size (): returns the number of values in the set.
Cursor Interface(1) function Overview: this interface is mainly used to randomly read and write the results in the form of a set returned by a database query. The implementation of Cursor does not need to be synchronized. When we use the Cursor interface, we only need to pay attention to its own synchronization when multithreading uses Cursor. (2) Common method: abstract void close (): close Cursor and release all resources abstract void copyStringToBuffer (int columnIndex, CharArrayBuffer buffer ): obtain the required column text and store it in the provided buffer array abstract int getPosition (): returns the current row position of the cursor in the set abstract boolean isNull (int columnIndex ): if the specified column is null, return trueabstract boolean move (int offset): move the current cursor forward or backward offset count abstract boolean moveToNext (): move the cursor to the next row
3. ContentProvider and ContentResolver development ideas 1. ContentProvider development ideas (application A provides the ContentResolver Interface)(1) define a ContentProvider subclass. This subclass must inherit the ContentProvider base class provided by Android and implement methods such as query (), insert (), update (), and delete () (abstract method). (2) configure ContentProvider. Before the ContentProvider is called by other applications, you must register the ContentProvider with the Android system, that is, the AndroidManifest project file of application. register the ContentProvider (similar to registering an Activity) in the xml file, and bind a Uri to the ContentProvider when registering it; <provider android: name = ". firsttProvider "// specifies the Class Name of the ContentProvider implementation class android: authorities =" com. example. android. contentProvider_1 "// specify the Uri corresponding to the ContentProvider (equivalent to assigning a domain name to the ContentProvider) android: exported = "true"/> // specify whether the ContentProvider allows other applications to call ("true" indicates allow) NOTE 2: Note 1: the query (), insert (), update (), and delete () methods implemented by the ContentProvider subclass are not called by application A itself, it is provided to other applications for calling. NOTE 2: Since multiple applications can expose their data through ContentProvider, android: authorities is used to facilitate other applications to access and delete specified application data.
Note 3: The parameters passed when ContentResolver calls the method will be passed to the query (), insert (), update (), and delete () Methods of the ContentProvider corresponding to the Uri; returned value-The returned value when ContentResolver calls a method, that is, the returned values of the ContentProvider's query (), insert (), update (), and delete () methods corresponding to the Uri; 2. ContentResolver development ideas (B Application accesses and modifies data of A application) (1) obtain the ContentResolver instance object. (2) Call the query (), insert (), update (), and delete () Methods of ContentResolver through the instance object. That is, the functions to be completed by specifying the query (), insert (), update (), and delete () methods corresponding to the ContentProvider Uri. Iv. Actual source code 1. Develop ContentProvider(1) FirstProvider. java
Package com. example. android_contentprovider_1; import android. content. contentProvider; import android. content. contentValues; import android. database. cursor; import android.net. uri; public class FirstProvider extends ContentProvider {// 1. the method @ Override public boolean onCreate () {System. out. println ("==== onCreate method called ===="); return false;} // 2. implement the query method. This method should return the obtained Cursor @ Override public Cursor query (Uri uri, String [] projection, String where, String [] selectionArgs, String sortOrder) {System. out. println ("=== query method called ===="); System. out. println ("where parameter:" + where); return null;} // 3. the returned value of this method represents the MIME type of the data provided by the ContentProvider @ Override public String getType (Uri uri) {return null;} // 4. insert method. This method should return the Uri @ Override public Uri insert (Uri uri, ContentValues values) {System. out. println (uri + "==== insert called ===="); System. out. println ("values parameter:" + values); return null;} // 5. implements the delete method. This method should return the number of deleted records @ Override public int delete (Uri uri, String where, String [] selectionArgs) {System. out. println (uri + "==== delete method called ===="); System. out. println ("where parameter:" + where); return 0;} // 6. update method. This method should return the number of updated records @ Override public int update (Uri uri, ContentValues values, String selection, String [] selectionArgs) {System. out. println (uri + "==== update method called ===="); System. out. println ("values parameter:" + values); return 0 ;}}
(2) AndroidManifest. xml (partial) <application
Android: icon = "@ drawable/ic_launcher">
<! -- Register a ContentProvider -->
<Provider
Android: name = ". FirstProvider"
Android: authorities = "com. example. android_contentprovider_1"
Android: exported = "true"/>
</Application>
</Manifest>
2. Use ContentResolver to call the MethodFirstResolver. java
Package com. example. android_contentresolver_2; import android. app. activity; import android. content. contentResolver; import android. content. contentValues; import android. database. cursor; import android.net. uri; import android. OS. bundle; import android. view. view; import android. widget. toast; public class FirstResolver extends Activity {ContentResolver contentResolver; Uri uri = Uri. parse ("content: // com. example. android_contentprovider_1 "); // parse a uri to obtain the corresponding ContentProvider @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); // 1. obtain the system's ContentResolver object contentResolver = getContentResolver ();} // 2. call the ContentResolver's query () method public void query (View source) {Cursor c = contentResolver. query (uri, null, "query_where", null, null); // actually returns the return value Toast of the query () of the ContentProvider corresponding to the Uri. makeText (this, "the Cursor returned by the remote ContentProvider is" + c, Toast. LENGTH_SHORT ). show ();} // 3. call ContentResolver's insert () method public void insert (View source) {ContentValues values = new ContentValues (); values. put ("name", "jiangdongguo"); Uri newUri = contentResolver. insert (uri, values); // insert the key-value pair to the ContentProvider shared data of the uri. makeText (this, "The Uri of the new remote ContentProvider inserted record is:" + newUri, Toast. LENGTH_SHORT ). show ();} // 4. call the ContentResolver () update () method public void update (View source) {ContentValues values = new ContentValues (); values. put ("name", "zhongxian"); int count = contentResolver. update (uri, values, "update_where", null); Toast. makeText (this, "the number of remote ContentProvider update records is:" + count, Toast. LENGTH_SHORT ). show ();} // 5. call ContentResoler's delete () method public void delete (View source) {int count = contentResolver. delete (uri, "delete_where", null); // the return value of delete () of the ContentProvider is Toast. makeText (this, "the number of records deleted by the remote ContentProvider is:" + count, Toast. LENGTH_SHORT ). show ();}}

Note: The layout interface has four buttons. Each button must define the android: onClick = "delete" attribute. (1) ContentProvider is different from the complex declaration cycle of the Activity. ContentProvider has only one onCreate () Life Cycle method. When other applications access this ContentProvider through ContentResolver for the first time, onCreate () the onCreate method is called only once. (2) Other applications call the query (), insert (), delete (), and update () methods through ContentResolver. In fact, they call the query () and insert () methods provided by ContentProvider (), delete (), update () method to operate the data exposed by ContentProvider; (3) query (), insert (), delete (), update () implemented during ContentProvider Development () the first parameter of the method is the Uri parameter, which is passed in when ContentResolver calls these methods. Demo:

Reference: http://wear.techbrood.com/reference/android/content/ContentProvider.html

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.