Android CursorLoader with selection and selectionArgs[]

孤街浪徒 提交于 2019-12-14 02:17:47

问题


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()?


回答1:


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


来源:https://stackoverflow.com/questions/29181308/android-cursorloader-with-selection-and-selectionargs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!