2

我正在使用LoaderforRecyclerView.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,nullselectionselectionArgs在这里,我列出了带有特定的项目IDs。当新项目添加到表中并且我想列出它时会出现问题。cursor我返回的人不知道新项目,因为我给了 3 个特定项目,所以它只是检测这 3 个项目何时发生变化。

当添加了一些新项目ID并且我也想列出它时如何列出?我应该将所有项目从数据库投影到并RecyclerView.Adapter过滤吗?IDsonBindViewHolder()

4

1 回答 1

2

由于我已限制IDsin cursor,因此仅在特定项目发生更改时才更改,而不是在添加新项目时更改。我做了一个技巧onLoadFinished()来创建新的cursor并交换那个新的光标。因此,当有变化时,我会再次获得新的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;
      }
}
于 2015-03-21T10:43:45.137 回答