我正在使用 Loader
为 RecyclerView.Adapter
列出项目。我想列出数据库表中的特定项目。所以我这样做了:
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String selectionArgs1[]={"1","13","14"};
String selection1 = DatabaseOpenHelper.COLUMN_ID + " in (";
for (int i = 0; i < selectionArgs1.length; i++) {
selection1 += "?, ";
}
selection1 = selection1.substring(0, selection1.length() - 2) + ")";
String[] projection1 =...
return new CursorLoader(getActivity(),StudentContentProvider.CONTENT_URI1, projection1, selection1,selectionArgs1, null);
}
通常情况下,我将 null,null
赋予 selection
和 selectionArgs
,但在这里,我列出了具有特定 ID
的项目。当新项目添加到表中并且我想列出它时,就会出现问题。我返回的光标不知道新项目,因为我提供了 3 个特定项目,因此它仅检测这 3 个项目何时发生更改。
当添加了带有一些 ID
的新项目并且我也想列出它时,如何列出它?我应该将数据库中的所有项目投影到 RecyclerView.Adapter
并在 onBindViewHolder()
中过滤 ID
吗?
最佳答案
由于我在 cursor
中限制了 ID
,因此只要特定项目发生变化,它就会发生变化,而不是在添加新项目时发生变化。我在 onLoadFinished() 上做了一个技巧来创建新的光标并交换该新光标。因此,当发生更改时,我会再次使用 selection
和 selectionArgs
获得新光标:
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
switch (loader.getId()) {
case LOADER_ID:{
String selectionArgs1[]={...};
String selection1 = DatabaseOpenHelper.COLUMN_ID + " in (";
for (int i = 0; i < selectionArgs1.length; i++) {
selection1 += "?, ";
}
selection1 = selection1.substring(0, selection1.length() - 2) + ")";
String[] projection1 =...
mDataset1 = getActivity().getContentResolver().query(StudentContentProvider.CONTENT_URI1, projection1, selection1, selectionArgs1, null);
mAdapter.swapCursor(mDataset1);
break;
}
}
关于Android CursorLoader 带有选择和selectionArgs[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29181308/