Search code examples
androidandroid-cursorloaderandroid-loaderandroid-recyclerviewandroid-database

Android CursorLoader with selection and selectionArgs[]


I am using Loader for RecyclerView.Adapter to list items. I want to list specific items from database table. So i did:

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

Normally i give null,null to selection and selectionArgs but here, i list items with specific IDs. Problem arises when new item is added to table and i want to list it. The cursor i am returning is not aware of new item since i gave 3 specific items, so it just detects when there is change on those 3 items.

How to list when there is new item added with some ID and i want to list it too ? Should i project all items from database to RecyclerView.Adapter and filter IDs in onBindViewHolder()?


Solution

  • Since I have restricted IDs in cursor, it is changed if only that specific items change, not when new item is added. I did a trick on onLoadFinished() to create new cursor and swap that new cursor. So when there is change, I get new cursor with my selection and selectionArgs again:

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