天天看點

巧用CursorLoader實時更新界面上顯示的資料

其實也沒什麼,當在不離開目前頁面時,界面上顯示了從資料庫中讀取的資料,而資料庫中内容改變了,要實時更新界面。比如來了一條短信,短信資料庫改變了的這種情況。以前的做法多是通過ContentResolver.registerContentObserver(),或Cursor.setNotificationUri()。而CursorLoader利用了基類的ForceLoadContentObserver監聽所查詢的uri對應的資料庫的變化。做法很簡單,寫個擴充自CursorLoader的類并重寫onContentChanged()方法:

@Override

public void onContentChanged() {

    if (!mCursor.isClosed()) {

        deliverResult(mCursor);

    }

    forceLoad();

}
           

而CursorLoader預設的onContentChanged的實作是不立即更新:

public void onContentChanged() {
    if (mStarted) {
        forceLoad();
    } else {
        // This loader has been stopped, so we don't want to load
        // new data right now...  but keep track of it changing to
        // refresh later if we start again.
        mContentChanged = true;
    }
}
           

一旦一次load完成,在onLoadFinished時就會更新界面了。

給出一個例子代碼

實驗很簡單,開兩個模拟器,在第一個模拟器(5554)上運作例子,不要離開頁面,讓後從5556向5554發短信,就能看到實時更新界面上顯示的資料了。