Android content Provider ContentProvider Usage Example Analysis _android

Source: Internet
Author: User
Tags throwable

This example describes the ContentProvider usage of the Android content provider. Share to everyone for your reference, specific as follows:

Personcontentprovider content provider Class

Package com.ljq.db;
Import Android.content.ContentProvider;
Import Android.content.ContentUris;
Import android.content.ContentValues;
Import Android.content.UriMatcher;
Import Android.database.Cursor;
Import Android.database.sqlite.SQLiteDatabase;
Import Android.net.Uri;
Import Android.text.TextUtils; /** * Content Provider * Role: Unified data access mode, easy external call * * @author Jiqinlin */public class Personcontentprovider extends CONTENTP The MIME type string for the Rovider {//dataset should be vnd.android.cursor.dir/with the opening public static final string persons_type = "Vnd.android.cursor.
  Dir/person "; The MIME type string for a single data should start with vnd.android.cursor.item/public static final String persons_item_type = "Vnd.android.cursor.item
  /person "; public static final String authority = "com.ljq.provider.personprovider";//Host name/* Custom MATCH code * * public static final int P
  Ersons = 1;
  /* Custom Match Code */public static final int person = 2;
  public static final Uri Persons_uri = Uri.parse ("content://" + Authority + "/person"); Private Dbopenhelper dbopenHelper = null;
  The Urimatcher class is used to match the URI and returns the matching code when matching the path using the match () method private static final Urimatcher Urimatcher;
    The static {//constant Urimatcher.no_match represents a return code that does not match any path urimatcher = new Urimatcher (urimatcher.no_match); If the match () method matches the Content://com.ljq.provider.personprovider/person path, the matching code is returned persons Urimatcher.adduri (authority, "
    Person ", PERSONS); If the match () method matches the content://com.ljq.provider.personprovider/person/230 path, the matching code is returned as the person Urimatcher.adduri (authority,
  "person/#", person);
    @Override public boolean onCreate () {dbopenhelper = new Dbopenhelper (This.getcontext ());
  return true; @Override public Uri Insert (URI uri, contentvalues values) {sqlitedatabase db = Dbopenhelper.getwritabledatabase
    ();
    Long id = 0; Switch (Urimatcher.match (URI)) {Case persons:id = db.insert (' person ', ' name ', values);//Returns the row number of the record, the primary key is int, and actually
    Is the primary key value return Contenturis.withappendedid (URI, id); Case person:id = db.insert (' person ', ' name ', values);
      String path = uri.tostring (); Return Uri.parse (path.substring (0, Path.lastindexof ("/")) +id);
    Replace the ID default:throw new IllegalArgumentException ("Unknown uri" + uri); @Override public int Delete (URI Uri, String selection, string[] selectionargs) {Sqlitedatabase db = Dbopenh
    Elper.getwritabledatabase ();
    int count = 0;
      Switch (Urimatcher.match (URI)) {Case persons:count = db.delete (' person ', selection, Selectionargs);
    Break
      Case PERSON://The following method is used to parse out the ID from the URI, CONTENT://COM.LJQ.PROVIDER.PERSONPROVIDER/PERSON/10//parsing the path, the return value is 10
      Long PersonID = Contenturis.parseid (URI); The String where = "id=" + personid;//deletes the record of the specified ID where + =! Textutils.isempty (selection)?
      "and (" + Selection + ")": "";//Append other conditions to count = Db.delete ("Person", where, Selectionargs);
    Break
    Default:throw new IllegalArgumentException ("Unknown uri" + uri);
    } db.close ();
  return count;@Override public int update (URI uri, contentvalues values, String selection, string[] selectionargs) {SQL
    Itedatabase db = Dbopenhelper.getwritabledatabase ();
    int count = 0;
      Switch (Urimatcher.match (URI)) {Case persons:count = db.update (' person ', values, selection, Selectionargs);
    Break
      Case PERSON://The following method is used to parse out the ID from the URI, CONTENT://COM.LJQ.PROVIDER.PERSONPROVIDER/PERSON/10//parsing the path, the return value is 10
      Long PersonID = Contenturis.parseid (URI); The String where = "id=" + personid;//gets the record of the specified ID where + =! Textutils.isempty (selection)?
      "and (" + Selection + ")": "";//Append other conditions to count = Db.update ("Person", values, where, Selectionargs);
    Break
    Default:throw new IllegalArgumentException ("Unknown uri" + uri);
    } db.close ();
  return count; @Override public String getType (URI uri) {switch (Urimatcher.match (URI)) {case Persons:return Perso
    Ns_type; Case Person:return Persons_item_type;
    Default:throw new IllegalArgumentException ("Unknown uri" + uri); @Override public Cursor query (URI uri, string[] projection, String selection, string[] Selectionargs, Stri
    ng SortOrder) {sqlitedatabase db = Dbopenhelper.getreadabledatabase (); Switch (Urimatcher.match (URI)) {case Persons:return db.query (' person ', projection, selection, Selectionargs, n
    Ull, NULL, sortOrder);
      Case PERSON://The following method is used to parse out the ID from the URI, CONTENT://COM.LJQ.PROVIDER.PERSONPROVIDER/PERSON/10//parsing the path, the return value is 10
      Long PersonID = Contenturis.parseid (URI); The String where = "id=" + personid;//gets the record of the specified ID where + =! Textutils.isempty (selection)? "and (" + Selection + ")": "";//Attach other conditions to return db.query ("person", projection, where, Selectionargs, NULL, NULL,
    SortOrder);
    Default:throw new IllegalArgumentException ("Unknown uri" + uri);

 }
  }
}

File list

<?xml version= "1.0" encoding= "Utf-8"?> <manifest xmlns:android= "http://schemas.android.com/apk/res/" Android "package=" Com.ljq.sql "android:versioncode=" 1 "android:versionname=" 1.0 "> <application android:icon="
    @drawable/icon "android:label=" @string/app_name "> <uses-library android:name=" Android.test.runner "/> <activity android:name= ". Sqlactivity "android:label=" @string/app_name "> <intent-filter> <action android:name=" Andro Id.intent.action.MAIN "/> <category android:name=" Android.intent.category.LAUNCHER "/> &L t;/intent-filter> </activity> <provider android:name= "Com.ljq.db.PersonContentProvider" Androi d:authorities= "Com.ljq.provider.personprovider"/> </application> <uses-sdk android:minsdkversion= "7"/ > <instrumentation android:name= "Android.test.InstrumentationTestRunner" android:targetpackage= "com.ljq.sq L "Android:lAbel= "Tests for my App"/> </manifest>

 

Personcontentprovidertest content Provider test class

Package com.ljq.test;
Import Android.content.ContentResolver;
Import android.content.ContentValues;
Import Android.database.Cursor;
Import Android.net.Uri;
Import Android.test.AndroidTestCase;
Import Android.util.Log; /** * External Access content provider * * @author Jiqinlin * */public class Personcontentprovidertest extends androidtestcase{private
  Static final String TAG = "Personcontentprovidertest";
    public void Testsave () throws throwable{contentresolver Contentresolver = This.getcontext (). Getcontentresolver ();
    Uri Inserturi = Uri.parse ("Content://com.ljq.provider.personprovider/person");
    Contentvalues values = new Contentvalues ();
    Values.put ("name", "LJQ");
    Values.put ("Phone", "1350000009");
    Uri uri = Contentresolver.insert (Inserturi, values);
  LOG.I (TAG, uri.tostring ()); The public void Testupdate () throws throwable{contentresolver Contentresolver = This.getcontext (). Getcontentresolver (
    ); Uri Updateuri = Uri.parse ("CONTENT://COM.LJQ.PROVIDER.PERSONPROVIDER/PERSON/1 ");
    Contentvalues values = new Contentvalues ();
    Values.put ("name", "Linjiqin");
  Contentresolver.update (Updateuri, values, NULL, NULL); 
    The public void Testfind () throws throwable{contentresolver Contentresolver = This.getcontext (). Getcontentresolver ();
    Uri uri = uri.parse ("Content://com.ljq.provider.personprovider/person");
    Uri uri = uri.parse ("Content://com.ljq.provider.personprovider/person");
    Cursor Cursor = contentresolver.query (URI, NULL, NULL, NULL, "ID ASC");
      while (Cursor.movetonext ()) {int PersonID = Cursor.getint (Cursor.getcolumnindex ("id"));
      String name = cursor.getstring (Cursor.getcolumnindex ("name"));
      String phone = cursor.getstring (Cursor.getcolumnindex ("Phone"));
    LOG.I (TAG, "personid=" + PersonID + ", name=" + name+ ", phone=" + phone);
  } cursor.close (); The public void Testdelete () throws throwable{contentresolver Contentresolver = This.getcontext (). Getcontentresolver (
    ); Uri uri = URi.parse ("CONTENT://COM.LJQ.PROVIDER.PERSONPROVIDER/PERSON/1");
  Contentresolver.delete (URI, NULL, NULL);

 }
}

For more information on Android-related content readers can view the site topics: "Android Debugging techniques and common problems solution summary", "Android Development introduction and Advanced Course", "Android Multimedia operating skills Summary (audio, video, recording, etc.)", " Android Basic Components Usage Summary, Android View tips Summary, Android layout layout tips and Android Control usage summary

I hope this article will help you with the Android program.

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.