首页 > 代码库 > ContentProvider实现数据共享

ContentProvider实现数据共享

主要类有两个:ContentProviderContentResolver

ContentProvider实现步骤:

1.定义ContentProvider类,继承ContentProProvider基类

2.在AndroidManifest.xml文件中注册,在<application.../>下添加

      <provider            android:name=".providers.PersonContentProvider"            android:authorities="com.itheima28.sqlitedemo.providers.PersonContentProvider"
       android:exported="true"是否允许其他应用程序调用 android:readPermission="aa.bb.cc.read" android:writePermission="aa.bb.cc.write" > </provider>

继承ContentProvider需要实现以下方法

        @Override	public int delete(Uri arg0, String arg1, String[] arg2) {		// TODO Auto-generated method stub		return 0;	}	@Override	public String getType(Uri arg0) {		// TODO Auto-generated method stub		return null;	}	@Override	public Uri insert(Uri arg0, ContentValues arg1) {		// 根据Uri插入values对应数据		return null;	}	@Override	public boolean onCreate() {		// 其他应用程序第一次访问ContentProvider时,被创建,并立即调用onCreate方法
         mOpenHelper = new PersonSQLiteOpenHelper(getContext());
         return true;
}
	@Override	public Cursor query(Uri arg0, String[] arg1, String arg2, String[] arg3,			String arg4) {		// TODO Auto-generated method stub		return null;	}	@Override	public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) {		// TODO Auto-generated method stub		return 0;	}
public class PersonContentProvider extends ContentProvider {		private static final String AUTHORITY = "com.itheima28.sqlitedemo.providers.PersonContentProvider";	private static final int PRESON_INSERT_CODE = 0;	// 操作person表添加的操作的uri匹配码	private static final int PERSON_DELETE_CODE = 1;	private static final int PERSON_UPDATE_CODE = 2;	private static final int PERSON_QUERY_ALL_CODE = 3;	private static final int PERSON_QUERY_ITEM_CODE = 4;		private static UriMatcher uriMatcher;	private PersonSQLiteOpenHelper mOpenHelper;		// person表的数据库帮助对象		static {		uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);				// 添加一些uri(分机号)				// content://com.itheima28.sqlitedemo.providers.PersonContentProvider/person/insert		uriMatcher.addURI(AUTHORITY, "person/insert", PRESON_INSERT_CODE);				// content://com.itheima28.sqlitedemo.providers.PersonContentProvider/person/delete		uriMatcher.addURI(AUTHORITY, "person/delete", PERSON_DELETE_CODE);		// content://com.itheima28.sqlitedemo.providers.PersonContentProvider/person/update		uriMatcher.addURI(AUTHORITY, "person/update", PERSON_UPDATE_CODE);				// content://com.itheima28.sqlitedemo.providers.PersonContentProvider/person/queryAll		uriMatcher.addURI(AUTHORITY, "person/queryAll", PERSON_QUERY_ALL_CODE);				// content://com.itheima28.sqlitedemo.providers.PersonContentProvider/person/query/#		uriMatcher.addURI(AUTHORITY, "person/query/#", PERSON_QUERY_ITEM_CODE);	}	@Override	public boolean onCreate() {		mOpenHelper = new PersonSQLiteOpenHelper(getContext());		return true;	}	@Override	public Cursor query(Uri uri, String[] projection, String selection,			String[] selectionArgs, String sortOrder) {		SQLiteDatabase db = mOpenHelper.getReadableDatabase();		switch (uriMatcher.match(uri)) {		case PERSON_QUERY_ALL_CODE:  // 查询所有人的uri			if(db.isOpen()) {				Cursor cursor = db.query("person", projection, selection, selectionArgs, null, null, sortOrder);				return cursor;				// db.close(); 返回cursor结果集时, 不可以关闭数据库			}			break;		case PERSON_QUERY_ITEM_CODE:		// 查询的是单条数据, uri末尾出有一个id			if(db.isOpen()) {								long id = ContentUris.parseId(uri);								Cursor cursor = db.query("person", projection, "_id = ?", new String[]{id + ""}, null, null, sortOrder);				return cursor;			}			break;		default:			throw new IllegalArgumentException("uri不匹配: " + uri);		}		return null;	}	@Override	public String getType(Uri uri) {		switch (uriMatcher.match(uri)) {		case PERSON_QUERY_ALL_CODE: // 返回多条的MIME-type			return "vnd.android.cursor.dir/person";		case PERSON_QUERY_ITEM_CODE: // 返回单条的MIME-TYPE			return "vnd.android.cursor.item/person";		default:			break;		}		return null;	}	@Override	public Uri insert(Uri uri, ContentValues values) {				switch (uriMatcher.match(uri)) {		case PRESON_INSERT_CODE:	// 添加人到person表中			SQLiteDatabase db = mOpenHelper.getWritableDatabase();						if(db.isOpen()) {								long id = db.insert("person", null, values);								db.close();								return ContentUris.withAppendedId(uri, id);			}			break;		default:			throw new IllegalArgumentException("uri不匹配: " + uri);		}		return null;	}	@Override	public int delete(Uri uri, String selection, String[] selectionArgs) {		switch (uriMatcher.match(uri)) {		case PERSON_DELETE_CODE:	// 在person表中删除数据的操作			SQLiteDatabase db = mOpenHelper.getWritableDatabase();			if(db.isOpen()) {				int count = db.delete("person", selection, selectionArgs);				db.close();				return count;			}			break;		default:			throw new IllegalArgumentException("uri不匹配: " + uri);		}		return 0;	}	@Override	public int update(Uri uri, ContentValues values, String selection,			String[] selectionArgs) {		switch (uriMatcher.match(uri)) {		case PERSON_UPDATE_CODE: // 更新person表的操作			SQLiteDatabase db = mOpenHelper.getWritableDatabase();			if(db.isOpen()) {				int count = db.update("person", values, selection, selectionArgs);				db.close();				return count;			}			break;		default:			throw new IllegalArgumentException("uri不匹配: " + uri);		}		return 0;	}}

ContentPesolver  

public class TextCase extends AndroidTestCase {    private static final String TAG = "TextCase";    public void testInsert() {        Uri uri = Uri.parse("content://com.itheima28.sqlitedemo.providers.PersonContentProvider/person/insert");                // 内容提供者访问对象        ContentResolver resolver = getContext().getContentResolver();                ContentValues values = new ContentValues();        values.put("name", "fengjie");        values.put("age", 90);                uri = resolver.insert(uri, values);        Log.i(TAG, "uri: " + uri);        long id = ContentUris.parseId(uri);        Log.i(TAG, "添加到: " + id);    }        public void testDelete() {        Uri uri = Uri.parse("content://com.itheima28.sqlitedemo.providers.PersonContentProvider/person/delete");                // 内容提供者访问对象        ContentResolver resolver = getContext().getContentResolver();                String where = "_id = ?";        String[] selectionArgs = {"21"};        int count = resolver.delete(uri, where, selectionArgs);        Log.i(TAG, "删除行: " + count);    }        public void testUpdate() {        Uri uri = Uri.parse("content://com.itheima28.sqlitedemo.providers.PersonContentProvider/person/update");                // 内容提供者访问对象        ContentResolver resolver = getContext().getContentResolver();                ContentValues values = new ContentValues();        values.put("name", "lisi");                int count = resolver.update(uri, values, "_id = ?", new String[]{"20"});        Log.i(TAG, "更新行: " + count);    }        public void testQueryAll() {        Uri uri = Uri.parse("content://com.itheima28.sqlitedemo.providers.PersonContentProvider/person/queryAll");                // 内容提供者访问对象        ContentResolver resolver = getContext().getContentResolver();                Cursor cursor = resolver.query(uri, new String[]{"_id", "name", "age"}, null, null, "_id desc");                if(cursor != null && cursor.getCount() > 0) {                        int id;            String name;            int age;            while(cursor.moveToNext()) {                id = cursor.getInt(0);                name = cursor.getString(1);                age = cursor.getInt(2);                Log.i(TAG, "id: " + id + ", name: " + name + ", age: " + age);            }            cursor.close();        }    }        public void testQuerySingleItem() {        Uri uri = Uri.parse("content://com.itheima28.sqlitedemo.providers.PersonContentProvider/person/query/#");                // 在uri的末尾添加一个id content://com.itheima28.sqlitedemo.providers.PersonContentProvider/person/query/20        uri = ContentUris.withAppendedId(uri, 20);                // 内容提供者访问对象        ContentResolver resolver = getContext().getContentResolver();                Cursor cursor = resolver.query(uri, new String[]{"_id", "name", "age"}, null, null, null);                if(cursor != null && cursor.moveToFirst()) {            int id = cursor.getInt(0);            String name = cursor.getString(1);            int age = cursor.getInt(2);            cursor.close();            Log.i(TAG, "id: " + id + ", name: " + name + ", age: " + age);        }    }}
监听ContentProvider数据改变

ContentProvider的方法导致了数据库数据发生改变,就会调用getContext().getContentResolver().notifyChange(uri,null)被调用。
1.注册监听器
  getContentResolver().registerContentObserver(uri,true/false,new xxxContentObserver(new Handler()));
uri:待监听ContentProvider的Uri
true/false:true:监听uri目录及子目录;false:监听uri目
new xxxContentObserver(new Handler()):监听器实例
2.监听ContentProvider数据改变,需要继承ContentObserver基类,重写OnChange(boolean selfChange)方法,当数据发生改变此方法将被回调。

ContentProvider实现数据共享