带有selection和selectionArgs []的Android CursorLoader

时间:2015-03-21 09:48:05

标签: android android-cursorloader android-loader android-recyclerview android-database

我使用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,nullselectionselectionArgs,但在这里,我会列出具有特定IDs的项目。将新项目添加到表格并且我想列出它时会出现问题。我正在返回的cursor不知道新项目,因为我提供了3个特定项目,因此它只检测这3个项目何时发生变化。

如何列出新项目添加了一些ID并且我想列出它?我应该将数据库中的所有项目投射到RecyclerView.Adapter并过滤IDs中的onBindViewHolder()吗?

1 个答案:

答案 0 :(得分:2)

由于我在IDs中限制了cursor,如果仅更改了特定项目,则会更改,而不是在添加新项目时。我在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;
      }
}