[英]How to update the Cursor in a RecyclerView Adapter
我建立了一个RecyclerView适配器,可以从SQLite数据库中读取数据。 编辑数据库后,更新适配器时遇到问题。
我知道有一些示例显示了如何在RecyclerView Adapter中实现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
}
编辑:
这是我更改光标的方法。 它确实有效,但是我不知道它是否正确。 谁能确认这一点,并且游标是否已正确关闭?
@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与数据库一起使用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.