監聽內容提供者的資料變化

來源:互聯網
上載者:User
//在DB應用的基礎上實現監聽內容提供者的資料變化//1 在DB應用的主介面添加一個按鈕,當點擊按鈕的時候,往內容提供者中添加一條資料  button =(Button) findViewById(R.id.button);        button.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View view) {ContentResolver resolver=getContentResolver();ContentValues values=new ContentValues();values.put("name", "rew");values.put("phone", "888");values.put("amount", 5454);Uri uri=Uri.parse("content://cn.companyname.contentproviders.personcontentprovider/person");resolver.insert(uri, values);    }});   //2 在內容提供者的insert()和update()和delete()方法的return語句前中都添加一條語句//getContext().getContentResolver().notifyChange(uri, null)用於向外通知數據已發生變化//如insert()方法:public Uri insert(Uri uri, ContentValues values) {SQLiteDatabase db=dbOpenHelper.getWritableDatabase();switch (URI_MATCHER.match(uri)) {case PERSONS:           long rowid=db.insert("person", "name", values);           getContext().getContentResolver().notifyChange(uri, null);//向外通知數據已發生變化           return ContentUris.withAppendedId(uri, rowid);default:throw new IllegalArgumentException("unknown uri"+uri.toString());}}//3 建立立一個應用ListenDB,實現監聽public class ListenDBActivity extends Activity {private final static String TAG="TTT";@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);Uri uri = Uri.parse("content://cn.companyname.contentproviders.personcontentprovider/person");this.getContentResolver().registerContentObserver(uri, true,new DBContentObserver(new Handler()));}private final class DBContentObserver extends ContentObserver {public DBContentObserver(Handler handler) {super(handler);}@Overridepublic void onChange(boolean selfChange) {//監聽內容提供者的資料變化ContentResolver resolver=getContentResolver();Uri uri=Uri.parse("content://cn.companyname.contentproviders.personcontentprovider/person");//即可擷取最新的一條資料.小技巧Cursor cursor= resolver.query(uri, null, null, null, "personid desc limit 1");while(cursor.moveToNext()){int personid=cursor.getInt(cursor.getColumnIndex("personid"));Log.i(TAG, ""+personid);}cursor.close();}}}//(1)this.getContentResolver().registerContentObserver(uri, true,new DBContentObserver(new Handler()));註冊監聽器//(2)重寫public void onChange(boolean selfChange)方法,當資料發生變化時便及時知道.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.