@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);
} }
}
测试应用:
代码如下:
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Uri uri = Uri.parse("content://cn.wordtech.providers.personprovider/person");// 根据标识名得到内容提供者
ContentResolver cr = MainActivity.this.getContentResolver();
ContentValues values = new ContentValues();
values.put("name", "Livingstone");
values.put("phone", "1101");
values.put("amount", "1111111111");
cr.insert(uri, values);
}
});