ContentProvider is one of the four components of Android.
First of all, I understand this thing, ContentProvider is used to save data, used to share data, such as: The contact information of mobile phone contacts and the mobile phone on the storage of photos, videos and so on.
Compare the official explanation:
The content provider mechanism in Android enables the storage and reading of data in multiple applications. This is also a way of sharing data across applications, as well as files, sharepreference,sqlite databases and other ways to store shared databases, but ContentProvider better provide the unity of the data sharing interface. In an Android system, there is no public memory area for multiple apps to share storage data.
Let's write a simple and practical example!
Get a list of communication contacts
1. Need to allow reading of contact information in the Androidmanifest.xml file
<uses-permission android:name= "Android.permission.READ_CONTACTS"/>
2. Then create an activity to read the information directly on the line.
Package Zf.ui;import Java.util.arraylist;import Java.util.list;import zf.adapter.contactitemlistadapter;import Zf.entity.contactentity;import Zf.ui.r;import Android.app.activity;import Android.database.cursor;import Android.os.bundle;import Android.provider.contactscontract;import Android.util.log;import Android.widget.ListView ;p ublic class Contactsactivity extends Activity {private ListView contactslist;p rivate list<contactentity> List = n EW arraylist<contactentity> (); @Overrideprotected void OnCreate (Bundle savedinstancestate) {//TODO Auto-generated method Stubsuper.oncreate (savedinstancestate); Setcontentview (r.layout.contacts_activity); Contactslist = (ListView) Findviewbyid (r.id.contacts_list);//The list of information that needs to be read (including the ID of the address Book, the name of the address book, and the phone number) String [] Projecttion = {Contactscontract.commondatakinds.phone.contact_id,contactscontract.commondatakinds.phone.display_ name,contactscontract.commondatakinds.phone.number};//gets the Contentresolver object, The Contentresolver object is primarily used to obtain the contents of the ContentProvider and to modify the COntentprovider inside the contents of//Gets the information that is saved in the cursor cursor cursor = getcontentresolver (). Query ( Contactscontract.commondatakinds.phone.content_uri,projecttion, NULL, NULL, n ULL); LOG.D ("ZF", "+cursor.getcount ()"); String name= "";//judging the existence of the data displayed out of the while (Cursor.movetonext ()) {contactentity contact = new Contactentity (); Contact.setname (cursor.getstring (1)); Contact.setphonenum (Cursor.getstring (2)); List.add (contact);} Contactslist.setadapter (New Contactitemlistadapter (Contactsactivity.this,list));}}
3. There is also a adapter that populates the data
Package Zf.adapter;import Java.util.arraylist;import java.util.list;import zf.entity.contactentity;import Zf.ui.R; Import Android.content.context;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.baseadapter;import Android.widget.textview;public Class Contactitemlistadapter extends Baseadapter {//Contact list private list<contactentity> contactlist = new arraylist< Contactentity> ();p rivate Context mcontext;private layoutinflater mlayout;public contactitemlistadapter (context Context,list<contactentity> List) {this.mcontext = Context;mlayout = Layoutinflater.from (context); this.contactlist = list;} @Overridepublic int GetCount () {//TODO auto-generated method Stubreturn contactlist.size ();} @Overridepublic Object getItem (int position) {//TODO auto-generated method Stubreturn contactlist.get (position);} @Overridepublic long Getitemid (int position) {//TODO auto-generated method Stubreturn position;} @Overridepublic View GetView (int position, view Convertview, ViewGroup parent) {//TODO auto-generated method stubcontactentity contact = Contactl Ist.get (position); Viewholder holder = null;if (null = = Convertview) {Convertview = mlayout.inflate (R.layout.contact_item, null); holder = new Viewholder (); holder.name = (TextView) Convertview.findviewbyid (r.id.name); holder.phonenum = (TextView) Convertview.findviewbyid (R.id.num); Convertview.settag (holder);} Else{holder = (Viewholder) Convertview.gettag ();} Holder.name.setText (Contact.getname ()); Holder.phonenum.setText (Contact.getphonenum ()); return Convertview;} public class Viewholder{public TextView imei;public TextView name;public TextView phonenum;}}
One of the questions here is why only the contact's name and phone number are filled out, otherwise it won't show up.
Example 2: Write yourself a contentprovider that can be used by other applications to call the data inside
1. Create your own contentprovider (self-understanding, the system will automatically open after the boot), need to inherit contentprovider, than the overloaded inside several methods
Package Zf.provider;import Android.content.contentprovider;import Android.content.contentvalues;import Android.database.cursor;import Android.database.sqlite.sqlitedatabase;import Android.database.sqlite.sqliteopenhelper;import Android.net.uri;public class MyProvider extends contentprovider{ private static final String Sqlcreatinfo = "CREATE TABLE IF not EXISTS myinfo (ID integer PRIMARY key,name text,age Integer );"; Private Sqliteopenhelper Databaseopenhelper; @Overridepublic boolean onCreate () {//TODO auto-generated method stub// Create a database table to store data Databaseopenhelper = new Sqliteopenhelper (This.getcontext (), NULL, NULL, 1, null) {@Overridepublic void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {//TODO auto-generated method stub} @Overridepublic void Oncr Eate (Sqlitedatabase db) {//TODO auto-generated method Stubdb.execsql (Sqlcreatinfo);}}; return false;} @Overridepublic Cursor query (Uri uri, string[] projection, string selection,string[] Selectionargs, string sortOrder) {// TODO auto-generated method Stubsqlitedatabase database = Databaseopenhelper.getreadabledatabase (); return Database.query ( "MyInfo", projection, selection, Selectionargs, NULL, NULL, SortOrder);} @Overridepublic String getType (Uri uri) {//TODO auto-generated method Stubreturn null;} @Overridepublic uri insert (URI uri, contentvalues values) {//TODO auto-generated method stubsqlitedatabase database = Dat Abaseopenhelper.getwritabledatabase (); String str = Database.getpath ();d Atabase.insert ("MyInfo", "name", values); return 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-generat Ed method Stubreturn 0;}}
2. Register inside Androidmanifest (under Application), as if only the exported property is true, other apps can call
<provider android:name= "Zf.provider.MyProvider" android:authorities= "Zf.provider.MyProvider " Android:exported= "true" > </provider>
3. Create another application, and then you can call it (called method or same as above)
Package Zf.ui;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.util.log;public class Mainactivity extends Activity {@Overrideprotected void OnCreate (Bundle Savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate (savedinstancestate); Contentresolver resolver = getcontentresolver (); Uri uri = uri.parse ("Content://zf.provider.myprovider/myinfo");//Add a record contentvalues values = new Contentvalues (); Values.put ("ID", 1001); Values.put ("NAME", "ZF"); Values.put ("Age"); Resolver.insert (URI, values); cursor cursor = resolver.query (URI, new string[]{"ID", "NAME", "age"}, NULL, NULL, NULL), and while (Cursor.movetonext ()) { LOG.D ("ZF", "" "+ cursor.getstring (1));}}}
ContentProvider there should be more applications, welcome to add.
Android's ContentProvider