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



我构建了一个RecyclerView适配器,它从SQLite数据库中读取数据。编辑数据库后,我在更新适配器时遇到问题。

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

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

@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的Cursor,只能在onClick方法中获取Adapter的位置

编辑:

这是我更改光标的方法。它确实有效,但我不知道它是否正确。有人能证实这一点吗?游标是否已完全关闭?

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

对我来说,这似乎是很多Cursor的创建和关闭。

如果不在ViewHolder或适配器中存储与要删除的项目相关的任何额外数据,则需要执行选择并提取列。我认为添加WHERE条件会对您有利,但在我看来,转到必要的位置是可以的。

由于我的ViewHolder类是静态的,我无法访问中适配器的游标

我认为您不需要适配器游标,因为它已经在迭代行了,但如果您的click方法定义在适配器类上,您可以将游标放在那里。否则adapter.this.cursor可能会工作。

关于交换光标,您忽略的大多数示例都有这种逻辑。结账,使用带有数据库的recyclerview

最新更新