Objective
Content Provider--android One of the four components.
This article highlights
1.Content Provider Introduction
2.URI Introduction
3. How to access data in content provider
I. Introduction of Content Provider
Content Provider,android One of the four components. It is a mechanism provided by the Android system to share data among multiple applications. A content provider class implements a standard set of method interfaces that enable other applications to save or read the various data types of this content provider. There are a few notes:
(1) Each contentprovider will provide a public URI (wrapped as a URI object), if the application has data to share, you need to use ContentProvider to define a URI for the data, Other applications can then pass the URI through ContentProvider to manipulate the data.
(2) Our app can expose its own data by implementing a content Provider abstraction interface, or access the data provided by the content Provider through the contentresolver interface ;
(3)Contentresolver supports CRUD (create, retrieve, update, and delete) operations;
(4) The Android system provides content Provider such as audio, video, images, contacts and other key data types. We can also create our own content Provider.
First, Android is a system that attaches great importance to security (seemingly the most vulnerabilities in Android), and one app's data is private to other applications unless you store the data on an SD card. But many times we need to share data between programs, such as the information we want to get contacts. At this point, the content provider provides a good solution to the data storage, read the details hidden, provide a unified interface for other applications to access, and can also do the rights control to a certain extent to ensure the security of the data.
The second is the issue of interprocess communication (inter-process communication IPC), which is undoubtedly more difficult to develop if the developers themselves handle the details. The content provider provides a pattern similar to the B/s structure, in which way we do not care, as we do most of the time, without caring about how the network is connected. Developers should be concerned with how to implement a content Provider or to invoke a content Provider.
Ii. introduction of URIs
The URI uniquely identifies the data in the provider, and when the application accesses the data in the content provider, the URI is one of the important parameters. The URI contains two parts: (1) The type of the data in the content provider to be manipulated by the content provider object (2).
The URI consists of the following parts:
(1) Scheme: The scheme of URI in Android is constant, namely:content://
(2) Authority: Used to identify ContentProvider (API original: A string that identifies the entire content provider.);
(3) Path: Used to identify the data we want to manipulate. 0 or more segments, separated by a forward slash ( / );
(4) ID: After specifying the ID, the operation specifies the ID of the data (ID can also be considered as part of path), the ID is optional in the URI (API original: A unique numeric identifier for a single row in the subset of D ATA identified by the preceding path part.).
URI Example:
(1) content://media/internal/images return all pictures stored on the device;
(2) CONTENT://MEDIA/INTERNAL/IMAGES/10 returns a picture with ID 10 stored on the device
The operation URI is often used to two classes of Urimatcher and Contenturis.
Urimatcher: Used to match URIs;
Contenturis: Used to manipulate the ID portion after the URI path, as provided by the methodwithAppendedId()向URI中追加ID。
Iii. accessing data in content provider
Applications accessing content provider need to use the Contentresolver object, which is an example of how to access the data in content provider by manipulating the contents provider provided by the Android Address Book.
1. Create a project:hellocontentprovider,mainactivity layout file named Main.xml;
<?XML version= "1.0" encoding= "Utf-8"?><Manifestxmlns:android= "Http://schemas.android.com/apk/res/android" Package= "Com.example.helloandroid"Android:versioncode= "1"Android:versionname= "1.0" > <USES-SDKandroid:minsdkversion= "8"android:targetsdkversion= "+" /> <ApplicationAndroid:allowbackup= "true"Android:icon= "@drawable/ic_launcher"Android:label= "@string/app_name"Android:theme= "@style/apptheme" > <ActivityAndroid:name=". Mainactivity "Android:label= "@string/app_name" > <Intent-filter> <ActionAndroid:name= "Android.intent.action.MAIN" /> <categoryAndroid:name= "Android.intent.category.LAUNCHER" /> </Intent-filter> </Activity> <ActivityAndroid:name=". Secondactivity "Android:label= "@string/title_activity_second" > </Activity> <ActivityAndroid:name=". Serviceactivity "Android:label= "@string/title_activity_service" > </Activity> <ServiceAndroid:name=". MyService " > <Intent-filter> <ActionAndroid:name= "Android.guo.service.playmusic.MyService" /> </Intent-filter> </Service> <ActivityAndroid:name=". Contentprovideractivity "Android:label= "@string/title_activity_content_provider" > </Activity> </Application> <uses-permissionAndroid:name= "Android.permission.READ_CONTACTS" /> <uses-permissionAndroid:name= "Android.permission.WRITE_CONTACTS" /> </Manifest>
View Code
2. Add the Read and write access to the contact in the file: Androidmanifest.xml;
3. Add several button:insert,query,update,delete in Main.xml and bind the onclick event:
<LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Fill_parent"Android:layout_height= "Fill_parent"android:orientation= "vertical" > <TextViewAndroid:id= "@+id/text"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "Hello Content Provider" /> <ButtonAndroid:id= "@+id/btninsert"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:width= "100DP"Android:text= "Insert"Android:onclick= "Insertcontact"/> <ButtonAndroid:id= "@+id/btnquery"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:width= "100DP"Android:text= "Query"Android:onclick= "Querycontacts"/> <ButtonAndroid:id= "@+id/btnupdate"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:width= "100DP"Android:text= "Update"Android:onclick= "Updatecontact"/> <ButtonAndroid:id= "@+id/btndelete"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:width= "100DP"Android:text= "Delete"Android:onclick= "DeleteContact"/></LinearLayout>
View Code
To add a record:
To add a record, we can call the Contentresolver.insert () method, which takes a target URI for the record to be added, and a map object containing the new record value, which is the URI of the new record, including 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 data to the contact information book:
Private void insertrecords (string name, String Phoneno) { new contentvalues (); Values.put (People.name, NAME); = getcontentresolver (). Insert (People.content_uri, values); LOG.D ("ANDROID", uri.tostring ()); = 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);}
View Code
To delete a record:
The Getcontextresolver.delete () method in Content provider can be used to delete records, and the following record is used to delete all contact information on the device:
Private void deleterecords () { = People.content_uri; NULL NULL );}
View Code
To modify a record:
We can use the Contentresolver.update () method to modify the data, and we'll write a way to modify the data:
Private void updaterecord (int recNo, String name) { = Contenturis.withappendedid ( People.content_uri, recNo); New contentvalues (); Values.put (People.name, NAME); NULL NULL );}
View Code
Query Record :
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:
Packagecom.wissen.testApp; Public classContentproviderdemoextendsActivity {@Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.main); Displayrecords (); } Private voiddisplayrecords () {//The array contains all the fields to be returnedString columns[] =Newstring[] {people.name, people.number}; Uri mcontacts=People.content_uri; Cursor cur=managedquery (mcontacts, columns,//the data field to return NULL,//WHERE clause NULL,//arguments to the WHERE clause NULL //order-by clause ); if(Cur.movetofirst ()) {String name=NULL; String Phoneno=NULL; Do { //get the value of a fieldName =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 ()); } }}View Code
From the above example we can get the following points:
(1) Access to content provider requires certain operating rights;
(2) Access to content Prvider requires the use of Contentresolver objects;
(3) Contentresolver support query,insert,delete,update operation;
(4) Determine the specific data to be manipulated in the content provider by the URI;
(5) When insert, the data to be added can be encapsulated using the contentvalues.
The eighth chapter: content Provider of four components