本文實(shí)例講述了Android內(nèi)容提供者ContentProvider用法。分享給大家供大家參考,具體如下:
PersonContentProvider內(nèi)容提供者類
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;/** * 內(nèi)容提供者 *  * 作用:統(tǒng)一數(shù)據(jù)訪問方式,方便外部調(diào)用 *  * @author jiqinlin *  */public class PersonContentProvider extends ContentProvider {  // 數(shù)據(jù)集的MIME類型字符串則應(yīng)該以vnd.android.cursor.dir/開頭  public static final String PERSONS_TYPE = "vnd.android.cursor.dir/person";  // 單一數(shù)據(jù)的MIME類型字符串應(yīng)該以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";// 主機(jī)名  /* 自定義匹配碼 */  public static final int PERSONS = 1;  /* 自定義匹配碼 */  public static final int PERSON = 2;  public static final Uri PERSONS_URI = Uri.parse("content://" + AUTHORITY + "/person");  private DBOpenHelper dbOpenHelper = null;  // UriMatcher類用來匹配Uri,使用match()方法匹配路徑時返回匹配碼  private static final UriMatcher uriMatcher;  static {    // 常量UriMatcher.NO_MATCH表示不匹配任何路徑的返回碼    uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);    // 如果match()方法匹配content://com.ljq.provider.personprovider/person路徑,返回匹配碼為PERSONS    uriMatcher.addURI(AUTHORITY, "person", PERSONS);    // 如果match()方法匹配content://com.ljq.provider.personprovider/person/230路徑,返回匹配碼為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);// 返回的是記錄的行號,主鍵為int,實(shí)際上就是主鍵值      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); // 替換掉id    default:      throw new IllegalArgumentException("Unknown URI " + uri);    }  }  @Override  public int delete(Uri uri, String selection, String[] selectionArgs) {    SQLiteDatabase db = dbOpenHelper.getWritableDatabase();    int count = 0;    switch (uriMatcher.match(uri)) {    case PERSONS:      count = db.delete("person", selection, selectionArgs);      break;    case PERSON:      // 下面的方法用于從URI中解析出id,對這樣的路徑content://com.ljq.provider.personprovider/person/10      // 進(jìn)行解析,返回值為10      long personid = ContentUris.parseId(uri);      String where = "id=" + personid;// 刪除指定id的記錄      where += !TextUtils.isEmpty(selection) ? " and (" + selection + ")" : "";// 把其它條件附加上      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) {    SQLiteDatabase db = dbOpenHelper.getWritableDatabase();    int count = 0;    switch (uriMatcher.match(uri)) {    case PERSONS:      count = db.update("person", values, selection, selectionArgs);      break;    case PERSON:      // 下面的方法用于從URI中解析出id,對這樣的路徑content://com.ljq.provider.personprovider/person/10      // 進(jìn)行解析,返回值為10      long personid = ContentUris.parseId(uri);      String where = "id=" + personid;// 獲取指定id的記錄      where += !TextUtils.isEmpty(selection) ? " and (" + selection + ")" : "";// 把其它條件附加上      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 PERSONS_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, String sortOrder) {    SQLiteDatabase db = dbOpenHelper.getReadableDatabase();    switch (uriMatcher.match(uri)) {    case PERSONS:      return db.query("person", projection, selection, selectionArgs, null, null, sortOrder);    case PERSON:      // 下面的方法用于從URI中解析出id,對這樣的路徑content://com.ljq.provider.personprovider/person/10      // 進(jìn)行解析,返回值為10      long personid = ContentUris.parseId(uri);      String where = "id=" + personid;// 獲取指定id的記錄      where += !TextUtils.isEmpty(selection) ? " and (" + selection + ")" : "";// 把其它條件附加上      return db.query("person", projection, where, selectionArgs, null, null, sortOrder);    default:      throw new IllegalArgumentException("Unknown URI " + uri);    }  }}文件清單
<?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="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <provider android:name="com.ljq.db.PersonContentProvider" android:authorities="com.ljq.provider.personprovider" /> </application> <uses-sdk android:minSdkVersion="7" /> <instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="com.ljq.sql" android:label="Tests for My App" /></manifest>
PersonContentProviderTest內(nèi)容提供者測試類
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;/** * 外部訪問內(nèi)容提供者 *  * @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());  }  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);  }  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();  }  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);  }}更多關(guān)于Android相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Android調(diào)試技巧與常見問題解決方法匯總》、《Android開發(fā)入門與進(jìn)階教程》、《Android多媒體操作技巧匯總(音頻,視頻,錄音等)》、《Android基本組件用法總結(jié)》、《Android視圖View技巧總結(jié)》、《Android布局layout技巧總結(jié)》及《Android控件用法總結(jié)》
希望本文所述對大家Android程序設(shè)計有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選