繁体   English   中英

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

[英]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
}
  1. 我如何正确地调换光标并关闭旧的光标?
  2. 我必须提供什么游标? 用于查询数据库以进行删除的数据库不是最新的。 所以我将不得不删除行后创建第二个光标。 似乎很多Cursor正在创建和关闭。
  3. 是否可以像在上面的示例中一样根据行在适配器中的位置删除行? 由于我的ViewHolder类是静态的,因此我无法在其中访问适配器的光标,并且只能将适配器位置放入onClick方法中。

编辑:

这是我更改光标的方法。 它确实有效,但是我不知道它是否正确。 谁能确认这一点,并且游标是否已正确关闭?

@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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM