如何更新RecyclerView适配器中的光标

时间:2017-10-29 15:19:21

标签: android sqlite

我构建了一个RecyclerView Adapter,它从SQLite数据库中读取数据。 编辑数据库后,我无法更新适配器。

我知道有一些例子展示了如何将swapCursor方法实现到RecyclerView适配器中,但是它们都包含很多额外的代码,我真的不知道如何适应。我觉得信息太少了关于这个。

在以下方法中,我根据其在适配器中的位置删除数据库行。当我之后调用adapter.notifyItemRemoved(position)时,它会在底部重新添加项目。当我关闭并重新打开Activity时,数据库是正确的。问题是,我不交换光标,我不知道如何。

@Override
public void onDeleteClick(int position) {
    SQLiteDatabase database = new ExampleSQLiteHelper(this).getWritableDatabase();
    Cursor cursor = database.rawQuery("select * from " + ExampleContract.ExampleEntry.TABLE_NAME, null);
    cursor.moveToPosition(position);
    database.delete(ExampleContract.ExampleEntry.TABLE_NAME, ExampleContract.ExampleEntry._ID + "=?", new String[] {cursor.getString(cursor.getColumnIndexOrThrow(ExampleContract.ExampleEntry._ID))});
    //Here i have to swap the Cursor and notify the Adapter
}
  1. 如何正确交换光标并关闭旧光标?
  2. 我必须提供什么光标?查询数据库以进行删除的那个不是最新的。所以我必须在删除行后创建第二个光标。这似乎是很多Cursor创建和关闭我。
  3. 根据其在适配器中的位置删除行是否可以,就像我在上面的示例中所做的那样?由于我的ViewHolder类是静态的,我无法访问那里的Adapter的光标,只能将适配器位置放入onClick方法。
  4. 编辑:

    这是我更改Cursor的方法。它确实有效,但我不知道它是否正确。任何人都可以证实这一点并且游标是否正常关闭?

    @Override
    public void onDeleteClick(int position) {
        SQLiteDatabase database = new ExampleSQLiteHelper(this).getWritableDatabase();
        Cursor cursor = database.rawQuery("select * from " + ExampleContract.ExampleEntry.TABLE_NAME, null);
        cursor.moveToPosition(position);
        database.delete(ExampleContract.ExampleEntry.TABLE_NAME, ExampleContract.ExampleEntry._ID + "=?", new String[] {cursor.getString(cursor.getColumnIndexOrThrow(ExampleContract.ExampleEntry._ID))});
        cursor.close();
    
        Cursor newCursor = database.rawQuery("select * from " + ExampleContract.ExampleEntry.TABLE_NAME, null);
        mAdapter.changeCursor(newCursor);
        mAdapter.notifyItemRemoved(position);
    }
    

    适配器:

    public void changeCursor(Cursor newCursor) {
        Cursor oldCursor = mCursor;
        mCursor = newCursor;
        oldCursor.close();
    }
    

1 个答案:

答案 0 :(得分:0)

  

这似乎很多Cursor创建并关闭了我。

好吧,如果没有存储与您在ViewHolder或适配器中删除的项目相关联的任何额外数据,则需要执行选择并提取列。我想认为添加一个WHERE条件对你有好处,但在我看来,移动到必要的位置是好的。

  

由于我的ViewHolder类是静态的,我无法访问那里的适配器光标

我认为你不想要适配器游标,因为它已经迭代了行,但是如果你的click方法定义在适配器类上,你可以在那里获得光标。否则adapter.this.cursor可能会有效。

关于交换光标,您解雇的大多数示例都具有该逻辑。结帐,Using the recyclerview with a database