Android Learning Experience (4)--content Provider (content Provider)

Source: Internet
Author: User

————————————————————————————————————————

|wangkuifeng0118
| Address: http://blog.csdn.net/wangkuifeng0118/article/details/7028953

————————————————————————————————————————

Content Provider belongs to one of the components of an Android application, and as the only way to share data between applications, content Provider's primary function is to store and retrieve data and provide access to data to other applications.

The Android system contains a series of Content Provider for some common data types, such as music, video, images, mobile phone contact information, etc., which are located under the Android.provider package. With a specific license, you can access these content Provider in your own application development.

There are two ways to share your data with other applications: Create your own content provier (that is, subclasses that inherit from ContentProvider) or add your own data to an existing content provider, The latter needs to ensure that the existing content provider is the same as its own data type and has write access to the content provider. For content Provider, the most important thing is the data model and the URI.

1. Data Model
Content Provider provides its stored data as a data table to visitors, each of which behaves in a data table, each of which has a specific type of data and meaning. Each data record includes a "_id" numeric field that uniquely identifies a single piece of data.

2.URI
URI, each content Provider provides a public URI that uniquely identifies its own dataset (data set), and if a content Provider manages multiple datasets, it assigns a separate URI to each dataset. All content Provider URIs begin with "content://", where "content:" is used to identify the schema that the data is managed by content Provider.

This is done by inheriting the content Provier to write an instance.

First set up a SQLite instance, the details see the previous section of the SQLite instance, here is only the code:

The first step is to create a contentproviderdemo:

The second step is to establish the Dbopenhelper class:

public class Dbopenhelper extends Sqliteopenhelper {    private static final String database_name = "person.db";//Database name P rivate static final int database_version = 1;//database Version public Dbopenhelper (context context) {Super (context, database_name, n Ull, database_version);//TODO auto-generated constructor stub} @Overridepublic void OnCreate (Sqlitedatabase db) {  Db.execsql ("CREATE TABLE person" (_id integer primary key autoincrement, name varchar (a), age varchar (10)) "); @Overridepublic void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {//TODO auto-generated method Stubdb.ex Ecsql ("DROP TABLE IF EXISTS person"); onCreate (db);}}

A person table was created above,

public class Personservice {private Dbopenhelper dbopenhelper;  Public Personservice (Context context) {//TODO auto-generated constructor stub dbopenhelper=new dbopenhelper (context);}  public void Save (person person) {sqlitedatabase db=dbopenhelper.getwritabledatabase ();  Db.execsql ("INSERT into person (name,age) VALUES (?,?)", New Object[]{person.getname (), Person.getage ()});  } public void Delete (Integer _id) {sqlitedatabase db=dbopenhelper.getwritabledatabase ();  Db.execsql ("Delete from person where _id=?", New object[]{_id});  } public person find (Integer _id) {sqlitedatabase db=dbopenhelper.getreadabledatabase ();  Cursor 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 person = new person ();p erson.set_id (ID);p erson.setname (name);p ERson.setage (age), return person;  } return null;  } public list<person> FindAll () {sqlitedatabase db=dbopenhelper.getreadabledatabase ();  list<person> persons = new arraylist<person> ();  Cursor cursor=db.rawquery ("SELECT * from person", NULL); while (Cursor.movetonext ()) {person person=new person (); int Id=cursor.getint (Cursor.getcolumnindex ("_id")); String name=cursor.getstring (Cursor.getcolumnindex ("name")); String age=cursor.getstring (Cursor.getcolumnindex ("Age"));p erson.set_id (ID);p erson.setname (name);p Erson.setage (  Age);p the ersons.add (person);  } return persons; }}

To achieve the person's additions and deletions to change,

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 is built, and the next step is to implement ContentProvider to provide a unified access interface:

public class Personprovider extends ContentProvider {private dbopenhelper dbopenhelper;private static final Urimatcher MA Tcher = new Urimatcher (urimatcher.no_match);p rivate static final int PERSONS = 1;private static final int person = 2;stati C {Matcher.adduri ("Cn.com.karl.personProvider", "person", PERSONS); Matcher.adduri ("Cn.com.karl.personProvider", "person/#", person);} @Overridepublic Boolean onCreate () {//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 ', projection, 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);d Efault:throw New    IllegalArgumentException ("Unkwon Uri:" + uri.tostring ());}} Returns the MIME type of the data. @Overridepublic String getType (Uri uri) {//TODO auto-generated method Stubswitch (Matcher.match (URI)) {case Persons:retu RN "Vnd.android.cursor.dir/person"; case Person:return "Vnd.android.cursor.item/person";d efault:throw New IllegalArgumentException ("Unkwon Uri:" + uri.tostring ());}} Insert all records in the person table/person//insert a record of the specified ID in the person table/person/10@overridepublic uri insert (URI uri, contentvalues values) {//To Do auto-generated method Stubsqlitedatabase db = Dbopenhelper.getwritabledatabase (), switch (Matcher.match (URI)) {case persons://Specifically, the second argument is that when the Name field is empty, a null is inserted automatically. Long rowID = Db.insert ("person", "name", values); Uri Inserturi = Contenturis.withappendedid (URI, ROWID);//Get Urithis.getcontext () that represents the new record. Getcontentresolver (). Notifychange (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 Stubsqlitedat Abase 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-generate D method Stubsqlitedatabase db = Dbopenhelper.getwritabledatabase (); int count = 0;switch (Matcher.match (URI)) {case Perso Ns: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 ());}}}

Finally, don't forget to register in manifest.

<provider android:name= ". Personprovider "          android:authorities=" Cn.com.karl.personProvider "/>

This is basically done, let's write a project to visit and build the Resolverdemo project:

To show the effect, we used the ListView to build the 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=" android:id= "  @+id/age"  />    </LinearLayout>


public class Resolverdemoactivity extends activity {/** Called when the activity is first created. */private SimpleC    Ursoradapter adapter;private ListView ListView;        @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                 Setcontentview (R.layout.main);    listview= (ListView) This.findviewbyid (R.id.listview); Contentresolver contentresolver = Getcontentresolver (); Uri Selecturi = Uri.parse ("Content://cn.com.karl.personprovider/person"); Cursor cursor=contentresolver.query (Selecturi, NULL, NULL, NULL, NULL); adapter = new Simplecursoradapter (this, r.layout.item, cursor, new string[]{"_id", "name", "Age"}, new INT[]{R.ID.I        D, R.id.name, r.id.age});        Listview.setadapter (adapter); Listview.setonitemclicklistener (New Onitemclicklistener () {@Overridepublic void Onitemclick (adapterview<?> Parent, view 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 = (button) This.findviewbyid (R.id.insertbutton); Button.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View v) {Contentresolver 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, "Add Complete", 1). Show ();}); }}

Use Contentresolver to access, in fact, the use of content provider get contact information This section has been used this class, but that section is to access the system provides ContentProvider, This section is the ContentProvider of our own realization.

Android Learning Experience (4)--content Provider (content Provider)

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.