Android ContentProvider implementing resource sharing instances

Source: Internet
Author: User

ContentProvider provides a unified interface for storing and reading data, using ContentProvider, applications can share data, and many of the data built into Android are used in contentprovider form for developers to invoke (such as video , audio, pictures, contacts, etc.).

This example takes SQLite as a way to store data.


Activity code:

protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_content_provider) Insertbutton = (Button) Findviewbyid (R.id.insertbutton); UpdateButton = (Button) Findviewbyid (R.id.updatebutton);d Eletebutton = (button) Findviewbyid (R.id.deletebutton); Querybutton = (Button) Findviewbyid (R.id.querybutton); Insertbutton.setonclicklistener (new Insertlistener ()); Updatebutton.setonclicklistener (New Updatelistener ());d Eletebutton.setonclicklistener (New DeleteListener ()); Querybutton.setonclicklistener (New Querylistener ());} Class Insertlistener implements Onclicklistener {@Overridepublic void OnClick (View v) {contentvalues[] values = new Conten TVALUES[2]; Contentvalues value = new Contentvalues (); Value.put (CPMetadata.users.NAME, "Zhang San"); Value.put (CPMetadata.users.AGE, 12) ; Values[0] = Value;value = new Contentvalues (); Value.put (CPMetadata.users.NAME, "John Doe"); Value.put (CPMetadata.users.AGE , values[1] = value;//multiple insertions, calls to the Demoprovider insert (), each call to atimes, the result returns the number of successful rows int count = Getcontentresolver (). Bulkinsert (CPMetadata.users.CONTENT_URI, values);//Insert a single data//URI URI =// Getcontentresolver (). Insert (CPMetadata.users.CONTENT_URI, values);//LOG.D ("ContentProvider", "uri:" + uri); LOG.D ("ContentProvider", "Count:" + count);}}  Class Updatelistener implements Onclicklistener {@Overridepublic void OnClick (View v) {//data to be updated contentvalues values = new Contentvalues (); Values.put (CPMetadata.users.NAME, "Zhao Liu"); Values.put (CPMetadata.users.AGE, 22);//update by ID, The Contenturis.withappendedid () method appends a 1Uri URI to the end of the URI = Contenturis.withappendedid (CPMetadata.users.CONTENT_URI, 1); int count = Getcontentresolver (). Update (URI, values, NULL, NULL); LOG.D ("ContentProvider", "Update rows:" + count);}} Class Deletelistener implements Onclicklistener {@Overridepublic void OnClick (View v) {//deleted by ID, The Contenturis.withappendedid () method appends a 2Uri URI to the end of the URI = Contenturis.withappendedid (CPMetadata.users.CONTENT_URI, 2); int count = Getcontentresolver (). Delete (URI, NULL, NULL); LOG.D ("ContentProvider", "Delete rows:" + count);}} Class Querylistener implements Onclicklistener {@Overridepublic void OnClick (View v) {////By ID query using this URI, The Contenturis.withappendedid () method appends a 1//uri URI to the end of the URI = Contenturis.withappendedid (CPMetadata.users.CONTENT_URI, 1) ;//update and delete data using the WHERE clause method in the same way cursor cursor = getcontentresolver (). query (CPMetadata.users.CONTENT_URI, NULL, CPMetadata.users.NAME + "=?", New string[]{"Zhang San"}, cpmetadata.users._id + "desc");//print query results based on cursor while (Cursor.movetonext ( ) {String id = cursor.getstring (cursor.getcolumnindex (cpmetadata.users._id)); String name = cursor.getstring (Cursor.getcolumnindex (CPMetadata.users.NAME)); String age = cursor.getstring (Cursor.getcolumnindex (CPMetadata.users.AGE)); LOG.D ("ContentProvider", "ID:" + ID + "Name:" + name + "Age:" + age); Cursor.close ();}}

Cpmetadata Code:

public class Cpmetadata {public static final String authority = "Com.example.olds1_contentprovider. Demoprovider ";p ublic static final String database_name =" DEMOPROVIDERDB ";p ublic static final int database_version = 1;pub LIC static final int CONTENT = 1;public static final int content_item = 2;public Static Final class users implements Basec olumns {public static final String table_name = "users";p ublic static final Uri Content_uri = Uri.parse ("content://" + AUT Hority + "/users");p ublic static final String content_type = "Vnd.android.cursor.dir/vnd.demoprovider.user";p ublic Static final String content_type_item = "Vnd.android.cursor.item/vnd.demoprovider.user";p ublic static final string NAME = "name";p ublic static final String age = ' age ';}}

DBHelper Code:

public class DBHelper extends Sqliteopenhelper{public dbhelper (context context) {Super (context, Cpmetadata.database_ NAME, NULL, cpmetadata.database_version);//TODO auto-generated constructor stub} @Overridepublic void OnCreate ( Sqlitedatabase db) {StringBuffer sql = new StringBuffer (); Sql.append ("CREATE TABLE" + CPMetadata.users.TABLE_NAME + "("); Sql.append (cpmetadata.users._id + "Integer primary key AutoIncrement,"); Sql.append (CPMetadata.users.NAME + "varchar" ( "), Sql.append (CPMetadata.users.AGE +" integer); "); Db.execsql (Sql.tostring ());} @Overridepublic void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {//TODO auto-generated method stub}}


public class Demoprovider extends ContentProvider {private dbhelper helper;private sqlitedatabase db;private static final Urimatcher urimatcher;static {urimatcher = new Urimatcher (urimatcher.no_match); Urimatcher.adduri ( Cpmetadata.authority, CPMetadata.users.TABLE_NAME, cpmetadata.content); Urimatcher.adduri (Cpmetadata.authority, CPMetadata.users.TABLE_NAME + "/#", Cpmetadata.content_item);} @Overridepublic Boolean onCreate () {helper = new DBHelper (GetContext ());d B = helper.getwritabledatabase (); return true;} @Overridepublic String getType (Uri uri) {switch (Urimatcher.match (URI)) {case CPMetadata.CONTENT:return Cpmetadata.users.content_type;case CPMetadata.CONTENT_ITEM:return Cpmetadata.users.content_type_item;default: throw new IllegalArgumentException ("Unknown URI:" + uri);}} /** * Collation WHERE clause * conditions are divided into ID and no ID Two, ID primary key is unique, without adding other conditions * No ID is used to process the incoming condition * @param uri * @param selection * @return */public Str ing getwherestr (Uri uri, string selection) {string Wherestr;switch (Urimatcher.match (URI)) {caseCPMETADATA.CONTENT:WHERESTR = Selection;break;case CPMetadata.CONTENT_ITEM:whereStr = cpmetadata.users._id + "=" + Uri.getpathsegments (). get (1); Break;default:throw new IllegalArgumentException ("Unknown URI:" + uri);} return WHERESTR;} @Overridepublic uri insert (URI uri, contentvalues values) {Long rowid = Db.insert (CPMetadata.users.TABLE_NAME, NULL, Valu ES); if (rowID > 0) {Uri Inserturi = Contenturis.withappendedid (CPMetadata.users.CONTENT_URI, ROWID); GetContext (). Getcontentresolver (). Notifychange (Inserturi, NULL); LOG.D ("ContentProvider", "Insert Success:" + Inserturi); return Inserturi;} throw new IllegalArgumentException ("Unknown URI:" + uri);} @Overridepublic int Delete (URI Uri, String selection, string[] selectionargs) {int count = 0; String wherestr = Getwherestr (URI, selection); LOG.D ("ContentProvider", "Delete Where:" + wherestr); count = Db.delete (CPMetadata.users.TABLE_NAME, Wherestr, Selectionargs); GetContext (). Getcontentresolver (). Notifychange (URI, NULL); return count;} @Overridepublic int update (URI uri, contentvalues values, String selection, string[] selectionargs) {int count = 0; String wherestr = Getwherestr (URI, selection); LOG.D ("ContentProvider", "Update Where:" + wherestr); count = Db.update (CPMetadata.users.TABLE_NAME, values, WHERESTR, s Electionargs); GetContext (). Getcontentresolver (). Notifychange (URI, NULL); return count;} @Overridepublic Cursor query (Uri uri, string[] projection, String selection, string[] selectionargs,string sortOrder) {Cu Rsor cursor; String wherestr = Getwherestr (URI, selection); LOG.D ("ContentProvider", "Query Where:" + wherestr); cursor = Db.query (CPMetadata.users.TABLE_NAME, projection, WHERESTR, Selectionargs, NULL, NULL, SortOrder), Cursor.setnotificationuri (GetContext (). Getcontentresolver (), URI); return cursor;}

Register ContentProvider, the red part indicates whether external app access is allowed, you must set

<span style= "color: #4b4b4b;" ><provider            android:name= "Demoprovider"            android:authorities= "Com.example.olds1_contentprovider. Demoprovider "             </span><span style=" color: #ff0000; " >android:exported= "true" </span><span style= "color: #4b4b4b;" >>        </provider></span>

Create a new test project,

Effect:


The activity code is as follows:

Private Button button;private TextView TextView;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Button = (button) Findviewbyid (R.id.button);        TextView = (TextView) Findviewbyid (R.id.textview); Button.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {String uristr = "content:// Com.example.olds1_contentprovider. Demoprovider/users "; Uri uri = Uri.parse (URISTR); cursor cursor = getcontentresolver (). Query (URI, NULL, "Name=?", New string[]{"Zhang San"}, NULL); StringBuffer show = new StringBuffer ();//print query results based on cursor while (Cursor.movetonext ()) {String id = cursor.getstring ( Cursor.getcolumnindex ("_id")); String name = cursor.getstring (Cursor.getcolumnindex ("name")); String age = cursor.getstring (Cursor.getcolumnindex (' age ')); Show.append ("ID:" + ID + "Name:" + name + "Age:" + A GE + "\ n");}   Cursor.close (); Textview.settext (show.tostring ());}); } 


Full code:

Click I download instance

Android ContentProvider implementing resource sharing instances

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.