如果ContentProvider的访问者需要知道ContentProvider中的数据的变化情况,可以在ContentProvider发生数据变化时调用getContentResolver().notifyChange(uri,null)来通知注册在此URI上的访问者。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Uri uri = Uri.parse("content://cn.wordtech.providers.personprovider/person");
this.getContentResolver().registerContentObserver(uri, true, new PersonContentdObserver(new Handler()));
// 第三个对象为监听对象,当数据发生改变的时候通知此对象做相应的改变
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class PersonContentdObserver extends ContentObserver {
public PersonContentdObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
Uri uri = Uri.parse("content://cn.wordtech.providers.personprovider/person");
Cursor cursor = getContentResolver().query(uri, null, null, null,"personid desc limit 1");
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex("name"));
Log.i("Name", name);
}
super.onChange(selfChange);
} }
}
新闻热点
疑难解答
图片精选