7

我正在使用第一種方法開發基於Google IO presentation體系結構的應用程序。基本上我有一個Service,ContentProvider支持SQLite DB,我也使用Loader s。發生數據庫更改後更新用戶界面的方式

當我的數據庫發生更改時,我需要一種更新UI的方法。例如,用戶可能想要將物品添加到他的購物籃中。將物品ID插入購物籃表後,我想更新UI。我應該使用什麼方法?到目前爲止,我看到關於ContentObserver的信息很少。這是要走的路嗎?

+0

籃子中的項目與數據庫中的* insert *操作組合在一起? – Blackbelt 2014-12-05 09:03:30

+0

不太清楚你的意思,但基本上在http請求完成後,我更新數據庫表中的相應行,哪種狀態應該以某種方式由UI進行鏡像。我的問題是,我似乎無法找到一種方法來告訴用戶界面更新後,數據庫數據已被更改。 – midnight 2014-12-05 09:09:07

+0

是否在更新該行後調用了notifyChange? – Blackbelt 2014-12-05 09:10:37

回答

6

在的query方法您ContentProvider附加一個偵聽返回光標:

Cursor cursor = queryBuilder.query(dbConnection, projection, selection, selectionArgs, null, null, sortOrder); 
cursor.setNotificationUri(getContext().getContentResolver(), uri); 

然後在你的insert/update/delete方法使用這樣的代碼:

final long objectId = dbConnection.insertOrThrow(ObjectTable.TABLE_NAME, null, values); 
final Uri newObjectUri = ContentUris.withAppendedId(OBJECT_CONTENT_URI, objectId); 
getContext().getContentResolver().notifyChange(newObjectUri , null); 

CursorLoader會將被通知並且OnLoadFinished(Loader, Cursor)將被再次呼叫。

如果你不使用Loader,該ContentObserver是去,你是在DB的變化通知的幾行代碼的方式(但你需要手動重新查詢)。

private ContentObserver objectObserver = new ContentObserver(new Handler()) { 
    @Override 
    public void onChange(boolean selfChange) { 
     super.onChange(selfChange); 
     restartObjectLoader(); 
    } 
}; 

記得onResume()致電:

getContentResolver().registerContentObserver(ObjectProvider.OBJECT_CONTENT_URI, false, objectObserver); 

onPause()

getContentResolver().unregisterContentObserver(objectObserver); 

更新:UI變化 這是一個大的話題,因爲它取決於Adapter你用來填寫ListViewRecyclerView

的CursorAdapteronLoadFinished(Loader loader, Cursor data)

mAdapter.swapCursor(data); 

ArrayAdapteronLoadFinished(Loader loader, Cursor data)

Object[] objects = transformCursorToArray(data); //you need to write this method 
mAdapter.setObjects(objects); //You need to wrie this method in your implementation on the adapter 
mAdapter.notifyDataSetChange(); 

RecyclerView.AdapteronLoadFinished(Loader loader, Cursor data)

Object[] objects = transformCursorToArray(data); //you need to write this method 
//Here you have more mAdapter.notify....() 

閱讀from here以不同方式通知RecyclerView.Adapter

2

如果您使用的是列表,您可以再次填充適配器並將其設置爲您的列表。或嘗試通知數據集更改。

相關問題