Android 带有选择和 selectionArgs[] 的 CursorLoader

Android CursorLoader with selection and selectionArgs[]

我正在为 RecyclerView.Adapter 使用 Loader 来列出项目。我想列出数据库 table 中的特定项目。所以我做了:

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 分配给 selectionselectionArgs,但在这里,我列出了具有特定 IDs 的项目。当新项目添加到 table 并且我想列出它时出现问题。我返回的 cursor 不知道新项目,因为我提供了 3 个特定项目,所以它只是检测这 3 个项目何时发生变化。

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

由于我在 cursor 中限制了 IDs,因此只有特定项目发生变化时才会发生变化,而不是在添加新项目时发生变化。我在 onLoadFinished() 上做了一个技巧来创建新的 cursor 并交换新的光标。因此,当有变化时,我再次使用 selectionselectionArgs 获得新光标:

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;
      }
}