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

如果您使用的是列表,您可以再次填充适配器并将其设置为您的列表。或尝试通知数据集更改。

相关问题