Content provider belongs to Android applicationsProgramAs the only way to share data between applications, the main function of content provider is to store and retrieve data and provide data access excuses for other applications.
The Android system provides a series of content providers for some common data types (such as music, video, images, and mobile phone contacts), all of which are in the Android. provider package. With a specific license, you can access these content providers in your own developed applications.
There are two ways to share your data with other applications: Create your own content provier (that is, inherit from the subclass of contentprovider) or add your own data to the existing content provider. The latter must ensure that the existing content provider has the same data type and the write permission of the content provider. For content providers, the most important thing is the data model and Uri.
1. Data Model
Content providers provide the data they store to visitors in the form of data tables. Each row in the data table is a record, and each column is data of a specific type and meaning. Each data record contains a "_ id" value field, which uniquely identifies a data record.
2. Uri
Uri. Each content provider provides a public URI that uniquely identifies a data set. If a content provider manages multiple datasets, it will assign an independent URI for each dataset. The Uris of all content providers start with "content: //". "content:" indicates the schema managed by the content provider.
The following describes how to write an instance by inheriting content provier.
First, create an SQLite instance. For more information, see the SQLite instance in the previous section.Code:
The first step is to create a contentproviderdemo:
Step 2: Create the dbopenhelper class:
Public class dbopenhelper extends sqliteopenhelper {Private Static final string database_name = "person. DB "; // database name Private Static final int database_version = 1; // database version public dbopenhelper (context) {super (context, database_name, null, database_version ); // todo auto-generated constructor stub} @ overridepublic void oncreate (sqlitedatabase dB) {db.exe csql ("create table person (_ id integer primary key autoincrement, name varchar (20 ), age varchar (10) ") ;}@ overridepublic void onupgrade (sqlitedatabase dB, int oldversion, int newversion) {// todo auto-generated method stubdb.exe csql ("Drop table if exists person"); oncreate (db );}}
A person table is created above,
Public class personservice {private dbopenhelper; Public personservice (context) {// todo auto-generated constructor stub dbopenhelper = new dbopenhelper (context);} public void save (person) {sqlitedatabase DB = dbopenhelper. getwritabledatabase (); db.exe csql ("insert into person (name, age) values (?,?) ", New object [] {person. getname (), person. getage ()});} public void Delete (integer _ id) {sqlitedatabase DB = dbopenhelper. getwritabledatabase (); db.exe csql ("delete from person where _ id =? ", New object [] {_ id});} public person find (integer _ id) {sqlitedatabase DB = dbopenhelper. getreadabledatabase (); cursor = dB. rawquery ("select * From person where _ id =? ", New string [] {_ id. tostring ()}); If (cursor. movetofirst () {int id = cursor. getint (cursor. getcolumnindex ("_ id"); string name = cursor. getstring (cursor. getcolumnindex ("name"); string age = cursor. getstring (cursor. getcolumnindex ("Age"); person = new person (); person. set_id (ID); person. setname (name); person. setage (AGE); return person;} return NULL;} public list <person> findall () {sqlitedatabase DB = dbopenhelper. getreadabledatabase (); List <person> Persons = new arraylist <person> (); cursor = dB. rawquery ("select * From person", null); While (cursor. movetonext () {person = new person (); int id = cursor. getint (cursor. getcolumnindex ("_ id"); string name = cursor. getstring (cursor. getcolumnindex ("name"); string age = cursor. getstring (cursor. getcolumnindex ("Age"); person. set_id (ID); person. setname (name); person. setage (AGE); persons. add (person) ;}return persons ;}}
Add, delete, modify, and query persons,
Public class person {private integer _ id; private string name; private string age; Public integer get_id () {return _ id;} public void set_id (integer _ id) {This. _ id = _ id;} Public String getname () {return name;} public void setname (string name) {This. name = Name;} Public String getage () {return age;} public void setage (string age) {This. age = age ;}}
OK! The database has been created. The following is how to implement contentprovider to provide a unified access interface:
Public class personprovider extends contentprovider {private dbopenhelper; Private Static final urimatcher matcher = new urimatcher (urimatcher. no_match); Private Static final int persons = 1; Private Static final int person = 2; static {matcher. adduri ("cn.com. karl. personprovider "," person ", persons); matcher. adduri ("cn.com. karl. personprovider "," person/# ", person) ;}@ overridepublic Boolean o Ncreate () {// todo auto-generated method stubthis. dbopenhelper = new dbopenhelper (this. getcontext (); Return false ;}@ overridepublic cursor query (URI Uri, string [] projection, string selection, string [] selectionargs, string sortorder) {// todo auto-generated method stubsqlitedatabase DB = dbopenhelper. getreadabledatabase (); Switch (matcher. match (URI) {Case persons: Return dB. query ("person", projectio N, selection, selectionargs, null, null, sortorder); Case person: Long id = contenturis. parseid (URI); string where = "_ id =" + ID; If (selection! = NULL &&! "". Equals (selection) {where = Selection + "and" + where;} return dB. query ("person", projection, where, selectionargs, null, null, sortorder); default: Throw new illegalargumentexception ("unkwon URI:" + Uri. tostring () ;}// MIME type of the returned data. @ Overridepublic string GetType (URI) {// todo auto-generated method stubswitch (matcher. match (URI) {Case persons: Return "Vnd. android. cursor. DIR/person "; Case person: Return" Vnd. android. cursor. item/person "; default: Throw new illegalargumentexception (" unkwon URI: "+ Uri. tostring () ;}/// insert all records in the person table/person // insert records with the specified ID in the person table/person/10 @ overridepublic URI insert (URI Uri, contentvalues values ){ // Todo auto-generated method stubsqlitedatabase DB = dbopenhelper. getwritabledatabase (); Switch (matcher. match (URI) {Case persons: // specifically, when the name field is empty, a null value is automatically inserted. Long rowid = dB. insert ("person", "name", values); Uri inserturi = contenturis. withappendedid (Uri, rowid); // obtain the urithis that indicates the new record. getcontext (). getcontentresolver (). policychange (Uri, null); Return inserturi; default: Throw new illegalargumentexception ("unkwon URI:" + Uri. tostring () ;}@ overridepublic int Delete (URI Uri, string selection, string [] selectionargs) {// todo auto-generated method stubsqlitedataba Se DB = dbopenhelper. getwritabledatabase (); int COUNT = 0; Switch (matcher. match (URI) {Case persons: Count = dB. delete ("person", selection, selectionargs); Return count; Case person: Long id = contenturis. parseid (URI); string where = "_ id =" + ID; If (selection! = NULL &&! "". Equals (selection) {where = Selection + "and" + where;} COUNT = dB. delete ("person", where, selectionargs); Return count; default: Throw new illegalargumentexception ("unkwon URI:" + Uri. tostring () ;}@ overridepublic int Update (URI Uri, contentvalues values, string selection, string [] selectionargs) {// todo auto-generated method stubsqlitedatabase DB = dbopenhelper. getwritabledatabase (); int COUNT = 0; Switch (matcher. match (URI) {Case persons: Count = dB. update ("person", values, selection, selectionargs); Return count; Case person: Long id = contenturis. parseid (URI); string where = "_ id =" + ID; If (selection! = NULL &&! "". Equals (selection) {where = Selection + "and" + where;} COUNT = dB. update ("person", values, where, selectionargs); Return count; default: Throw new illegalargumentexception ("unkwon URI:" + Uri. tostring ());}}}
Do not forget to register in manifest
<Provider Android: Name = ". personprovider" Android: Authorities = "cn.com. Karl. personprovider"/>
This is basically done. Let's write another project to access and create a resolverdemo project:
To demonstrate the effect, we use listview to create item. xml under Res.
<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: Orientation = "horizontal" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content"> <textview Android: layout_width = "80dip" Android: layout_height = "wrap_content" Android: text = "435" Android: Id = "@ + ID/ID"/> <textview Android: layout_width = "100dip" Android: layout_height = "wrap_content" Android: text = "liming" Android: Id = "@ + ID/Name"/> <textview Android: layout_width = "fill_parent" Android: layout_height = "wrap_content" Android: text = "45" Android: Id = "@ + ID/age"/> </linearlayout>
Public class resolverdemoactivity extends activity {/** called when the activity is first created. */private simplecursoradapter adapter; private listview; @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); listview = (listview) This. findviewbyid (R. id. listview); contentresolver = getcontentresolver (); Uri selecturi = Uri. parse ("content: // cn.com. karl. personprovider/person "); cursor = contentresolver. query (selecturi, null, null); adapter = new simplecursoradapter (this, R. layout. item, cursor, new string [] {"_ id", "name", "Age"}, new int [] {R. id. ID, R. id. name, R. id. age}); listview. setadapter (adapter); listview. setonitemclicklistener (New onitemclicklistener () {@ overridepublic void onit Emclick (adapterview <?> Parent, view, int position, long ID) {listview lview = (listview) parent; cursor DATA = (cursor) lview. getitematposition (position); int _ id = data. getint (data. getcolumnindex ("_ id"); toast. maketext (resolverdemoactivity. this, _ ID + "", 1 ). show () ;}}); button = (button) This. findviewbyid (R. id. insertbutton); button. setonclicklistener (new view. onclicklistener () {@ overridepublic void onclick (view v) {contentresolver = getcontentresolver (); Uri inserturi = Uri. parse ("content: // cn.com. karl. personprovider/person "); contentvalues values = new contentvalues (); values. put ("name", "wangkuifeng"); values. put ("Age", 23); Uri uri = contentresolver. insert (inserturi, values); toast. maketext (resolverdemoactivity. this, "added", 1 ). show ();}});}}
Contentresolver is used for access. In fact, this class has been used in the section "get contact information by using content provider", but that section is the contentprovider provided by the access system, this section is our own contentprovider.
Finally, let's take a look at the running effect!