i built a RecyclerView Adapter which reads data out of a SQLite database. I have trouble updating the Adapter after the database were edited.
I know there are a few examples which show how to implement a swapCursor method into a RecyclerView Adapter, but they all contain a lot of additional code which i dont really know how to fit in. I feel like there is too little information about this out there.
In the following method i delete a database row depending on its position in the Adapter. When i call adapter.notifyItemRemoved(position) afterwards, it re-adds the item at the bottom. When i close and re-open the Activity, the database is correct. The problem is, that i dont swap the Cursor and i dont know how.
@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
}
- How do i swap the Cursor properly and close the old one?
- What Cursor do i have to provide? The one that queries the database for deletion is not up-to-date. So i would have to create a 2nd Cursor after deleting the row. That seems like a lot of Cursor creating and closing to me.
- Is it ok to delete a row depending on its position in the Adapter, like i do in the above example? Since my ViewHolder Class is static, i cant access the Adapter's Cursor in there and can only get the Adapter position into the onClick method.
Edit:
Here is my approach for change the Cursor. It does work, but i dont know if its correct. Can anyone confirm this and are the Cursors closed prperly?
@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);
}
Adapter:
public void changeCursor(Cursor newCursor) {
Cursor oldCursor = mCursor;
mCursor = newCursor;
oldCursor.close();
}