本文轉自:http://yaku2688.iteye.com/blog/1185364
ContentProvider數據共享
1.首先在AndroidManifest.xml文件中添加對外暴露的數據共享接口Content
- <provider android:name=".UserProvider" android:authorities="com.yaku.ContentProvider.userprovider"/>
ContentProvider采用了authorities(主機名/域名)對它進行唯一標識,authorities 就是他的域名
2.Url解析
content://com.yaku.ContentProvider.userprovider/user/2
【content://】 Android定義的內容提供都的Schema
【com.yaku.ContentProvider.userprovider】 主機名或者authorities
【user】 路徑
【2】 ID
示例代碼:
數據結構User.java:
- package com.yaku.pojo;
- public class User {
- private int id;
- private String name;
- private int age;
- public User(int id, String name, int age) {
- super();
- this.id = id;
- this.name = name;
- this.age = age;
- }
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- @Override
- public String toString() {
- return "User [age=" + age + ", id=" + id + ", name=" + name + "]";
- }
- }
數據庫操作DBOpenHelper.java:
- package com.yaku.db;
- import android.content.Context;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteOpenHelper;
- public class DBOpenHelper extends SQLiteOpenHelper {
- private static final String DBNAME = "yaku.db"; //數據庫名稱
- private static final int DBVER = 1;//數據庫版本
- public DBOpenHelper(Context context) {
- super(context, DBNAME, null, DBVER);
- }
- @Override
- public void onCreate(SQLiteDatabase db) {
- String sql = "CREATE TABLE user (userid integer primary key autoincrement, name varchar(20), age integer)";
- db.execSQL(sql);//執行有更改的sql語句
- }
- @Override
- public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
- db.execSQL("DROP TABLE IF EXISTS user");
- onCreate(db);
- }
- }
對外共享處理類ContentProviderUser.java:
- package com.yaku.ContentProvider;
- import com.yaku.db.DBOpenHelper;
- 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;
- public class ContentProviderUser extends ContentProvider {
- private DBOpenHelper dbOpenHelper;
- //常量UriMatcher.NO_MATCH表示不匹配任何路徑的返回碼
- private static final UriMatcher MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
- private static final int USERS = 1;
- private static final int USER = 2;
- static{
- //如果match()方法匹配content://com.yaku.ContentProvider.userprovider/user路徑,返回匹配碼為1
- MATCHER.addURI("com.yaku.ContentProvider.userprovider", "user", USERS);
- //如果match()方法匹配content://com.yaku.ContentProvider.userprovider/user/123路徑,返回匹配碼為2
- MATCHER.addURI("com.yaku.ContentProvider.userprovider", "user/#", USER);//#號為通配符
- }
- @Override
- public int delete(Uri uri, String selection, String[] selectionArgs) {
- SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
- int count = 0;
- switch (MATCHER.match(uri)) {
- case USERS:
- count = db.delete("user", selection, selectionArgs);
- return count;
- case USER:
- //ContentUris類用於獲取Uri路徑后面的ID部分
- long id = ContentUris.parseId(uri);
- String where = "userid = "+ id;
- if(selection!=null && !"".equals(selection)){
- where = selection + " and " + where;
- }
- count = db.delete("user", where, selectionArgs);
- return count;
- default:
- throw new IllegalArgumentException("Unkwon Uri:"+ uri.toString());
- }
- }
- /**
- * 該方法用於返回當前Url所代表數據的MIME類型。
- * 如果操作的數據屬於集合類型,那么MIME類型字符串應該以vnd.android.cursor.dir/開頭
- * 如果要操作的數據屬於非集合類型數據,那么MIME類型字符串應該以vnd.android.cursor.item/開頭
- */
- @Override
- public String getType(Uri uri) {
- switch (MATCHER.match(uri)) {
- case USERS:
- return "vnd.android.cursor.dir/user";
- case USER:
- return "vnd.android.cursor.item/user";
- default:
- throw new IllegalArgumentException("Unkwon Uri:"+ uri.toString());
- }
- }
- @Override
- public Uri insert(Uri uri, ContentValues values) {
- SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
- switch (MATCHER.match(uri)) {
- case USERS:
- long rowid = db.insert("user", "name", values);
- Uri insertUri = ContentUris.withAppendedId(uri, rowid);//得到代表新增記錄的Uri
- this.getContext().getContentResolver().notifyChange(uri, null);
- return insertUri;
- default:
- throw new IllegalArgumentException("Unkwon Uri:"+ uri.toString());
- }
- }
- @Override
- public boolean onCreate() {
- this.dbOpenHelper = new DBOpenHelper(this.getContext());
- return false;
- }
- @Override
- public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
- String sortOrder) {
- SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
- switch (MATCHER.match(uri)) {
- case USERS:
- return db.query("user", projection, selection, selectionArgs, null, null, sortOrder);
- case USER:
- long id = ContentUris.parseId(uri);
- String where = "userid = "+ id;
- if(selection!=null && !"".equals(selection)){
- where = selection + " and " + where;
- }
- return db.query("user", projection, where, selectionArgs, null, null, sortOrder);
- default:
- throw new IllegalArgumentException("Unkwon Uri:"+ uri.toString());
- }
- }
- @Override
- public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
- SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
- int count = 0;
- switch (MATCHER.match(uri)) {
- case USERS:
- count = db.update("person", values, selection, selectionArgs);
- return count;
- case USER:
- long id = ContentUris.parseId(uri);
- String where = "userid = "+ id;
- if(selection!=null && !"".equals(selection)){
- where = selection + " and " + where;
- }
- count = db.update("user", values, where, selectionArgs);
- return count;
- default:
- throw new IllegalArgumentException("Unkwon Uri:"+ uri.toString());
- }
- }
- }
單元測試類(在另一個應用中):
- package com.yaku.ContentProvider;
- import android.content.ContentResolver;
- import android.content.ContentValues;
- import android.database.Cursor;
- import android.net.Uri;
- import android.test.AndroidTestCase;
- import android.util.Log;
- /**
- * 對ContentProvider工程中的ContentProviderActivity進行單元測試
- */
- public class ContentProviderActivityTest extends AndroidTestCase {
- private static final String TAG = "ContentProvider";
- //往內容提供者添加數據
- public void testInsert() throws Throwable{
- ContentResolver contentResolver = this.getContext().getContentResolver();
- Uri insertUri = Uri.parse("content://com.yaku.ContentProvider.userprovider/user");
- ContentValues values = new ContentValues();
- values.put("name", "道長");
- values.put("age", 86);
- 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.yaku.ContentProvider.userprovider/user/1");
- ContentValues values = new ContentValues();
- values.put("name", "青眉道長");
- contentResolver.update(updateUri, values, null, null);
- }
- //從內容提供者中刪除數據
- public void testDelete() throws Throwable{
- ContentResolver contentResolver = this.getContext().getContentResolver();
- Uri deleteUri = Uri.parse("content://com.yaku.ContentProvider.userprovider/user/1");
- contentResolver.delete(deleteUri, null, null);
- }
- //獲取內容提供者中的數據
- public void testFind() throws Throwable{
- ContentResolver contentResolver = this.getContext().getContentResolver();
- Uri selectUri = Uri.parse("content://com.yaku.ContentProvider.userprovider/user");
- Cursor cursor = contentResolver.query(selectUri, null, null, null, "userid desc");
- while(cursor.moveToNext()){
- int id = cursor.getInt(cursor.getColumnIndex("userid"));
- String name = cursor.getString(cursor.getColumnIndex("name"));
- int age = cursor.getInt(cursor.getColumnIndex("age"));
- Log.i(TAG, "id="+ id + ",name="+ name+ ",age="+ age);
- }
- }
- }
監聽數據的變化:
- <SPAN style="FONT-SIZE: medium">package com.yaku.ContentProvider;
- import android.content.ContentResolver;
- import android.content.ContentValues;
- import android.database.Cursor;
- import android.net.Uri;
- import android.test.AndroidTestCase;
- import android.util.Log;
- /**
- * 監聽數據變化
- */
- public class OtherContentProviderTest extends AndroidTestCase {
- private static final String TAG = "OtherContentProvider";
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- Uri insertUri = Uri.parse("content://com.yaku.ContentProvider.userprovider/user");
- ContentResolver contentResolver = this.getContentResolver();
- //對指定uri進行監聽,如果該uri代表的數據發生變化,就會調用PersonObserver中的onChange()
- contentResolver.registerContentObserver(insertUri, true, new PersonObserver(new Handler()));
- }
- private final class PersonObserver extends ContentObserver{
- public PersonObserver(Handler handler) {
- super(handler);
- }
- @Override
- public void onChange(boolean selfChange) {
- ContentResolver contentResolver = getContentResolver();
- Uri selectUri = Uri.parse("content://com.yaku.ContentProvider.userprovider/user");
- Cursor cursor = contentResolver.query(selectUri, null, null, null, "userid desc");
- while(cursor.moveToNext()){
- int id = cursor.getInt(cursor.getColumnIndex("userid"));
- String name = cursor.getString(cursor.getColumnIndex("name"));
- int age = cursor.getInt(cursor.getColumnIndex("age"));
- Log.i(TAG, "id="+ id + ",name="+ name+ ",age="+ age);
- }
- }
- }
- }
- </SPAN>