ContentProvider小结

时间:2024-10-13 20:34:14

1、什么情况下需要使用ContentProvider

  跨进程提供数据访问的接口,如果在同一个App下,没有必要使用此种方式

2、自定义ContentProvider

public class MyContentProvider extends ContentProvider {
private MyDbHelper helper; //Sqlite帮助类
private SQLiteDatabase db;
private static UriMatcher matcher;
private static final String AUTHORITY="com.loo.person";
static {
matcher=new UriMatcher(UriMatcher.NO_MATCH);
matcher.addURI(AUTHORITY,"person",1);
matcher.addURI(AUTHORITY,"person/#",2);
}
@Override
public boolean onCreate() {
helper=new MyDbHelper(getContext());
db=helper.getReadableDatabase();
return false;
} @Nullable
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { if( matcher.match(uri)==1){
return db.query("person",null,null,null,null,null,null);
}else if(matcher.match(uri)==2){
long id= ContentUris.parseId(uri);
return db.rawQuery("select * from person where id="+id,null);
} return null;
} @Nullable
@Override
public String getType(Uri uri) { return null;
} @Nullable
@Override
public Uri insert(Uri uri, ContentValues values) {
if(matcher.match(uri)==1){
long flag= db.insert("person",null,values);
if(flag>0){
getContext().getContentResolver().notifyChange(uri,null);
return uri;
}
}
return null;
} @Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0;
} @Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
}

AndroidManifest中注册

   <provider
android:authorities="com.loo.person" //主机名
android:name=".MyContentProvider"></provider>

3、如何访问?

  访问需要一个Uri content://com.loo.person/person

  getContentResolver()即可调用一些相关的增删改查的方法

4、当数据发生更改后如何响应?

  当数据发生更改时,调用getContext().getContentResolver().notifyChange(uri,null);

  并在获取数据的地方

   getContentResolver().registerContentObserver(uri, false, new ContentObserver(handler) {
@Override
public void onChange(boolean selfChange) {
List<Person> list= getData();
adapter=new MyAdapter(MainActivity.this,list);
listview.setAdapter(adapter);
}
});