1.Xml注册ContentProvider
<provider android:name="com.cgh.activity.chapter05_save.Ch05Ex07ContentProvider"
android:authorities="com.cgh.myContentProvider" />
2.写一个类继承ContentProvider
public class Ch05Ex07ContentProvider extends ContentProvider {
private static final String tag = "Ch05Ex07ContentProvider";
private static final UriMatcher matcher = new UriMatcher(
UriMatcher.NO_MATCH);// 如果URI都不匹配 则用这个匹配码(-1)
private static final int one = 1;//更新单个
private static final int all = 2;//更新多个
static {
matcher.addURI("com.cgh.myContentProvider", "person", all);
matcher.addURI("com.cgh.myContentProvider", "person/#", one);
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
Log.e(tag, "delete");
return 0;
}
@Override
public String getType(Uri uri) {
int num = matcher.match(uri);
switch (num) {
case one:
return "vnd.android.cursor.dir/person";
case all:
return "vnd.android.cursor.item/person";
default:
throw new IllegalArgumentException("Unknown URL");
}
}
@Override
public Uri insert(Uri uri, ContentValues values) {
Log.e(tag, "insert");
//这个方法可以获得插入数据后的URI id就是插入数据成功返回的Id
//Uri insertUri = ContentUris.withAppendedId(uri, id);
return null;
}
@Override
public boolean onCreate() {
//进行SQLite数据库实例化
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
Log.e(tag, "query");
return null;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
Log.e(tag, "update");
return 0;
}
}
3.activity使用ContentProvider
public void onClick(View v) {
ContentResolver cr = this.getContentResolver();
Uri uri = Uri.parse("content://com.cgh.myContentProvider/person");
switch (v.getId()) {
case R.id.save:
cr.insert(uri , null);
break;
case R.id.delete:
cr.delete(uri, null, null);
break;
case R.id.update:
cr.update(uri, null, null, null);
break;
case R.id.find:
cr.query(uri, null, null, null, null);
break;
}
Toast.makeText(this, "操作完成", Toast.LENGTH_SHORT).show();
}
4.监听数据改变:
在insert或update或query或delete时注册一个类似监听器的
//注册监听
this.getContext().getContentResolver().notifyChange(uri, null);
在Activity中接受一个监听器用来接收数据的改变
//监听数据改变 ContentResolver resolver = this.getContentResolver(); Uri uri = Uri.parse("content://com.cgh.myContentProvider/person"); resolver.registerContentObserver(uri, true, new MyContentObserver(null));
写一个继承ContentObserver类的实例 重写onChange改变方法public class MyContentObserver extends ContentObserver{ private static final String tag = "MyContentObserver"; public MyContentObserver(Handler handler) { super(handler); } @Override public boolean deliverSelfNotifications() { Log.e(tag,"deliverSelfNotifications"); return super.deliverSelfNotifications(); } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); Log.e(tag,"onChange"); } }