我有一個RecyclerView,它可以從SQLite數據庫遊標中獲取數據,而不必將數據存儲在ArrayList之前。RecyclerView + SQLite - 從數據庫中刪除行並調用.notifyItemRemoved在底部臨時重新添加行
我嘗試刪除按鈕上某個給定位置的一行,但立即重新添加RecyclerView底部的行。但是,當我關閉並重新打開活動時,條目已不存在(如我所願)。另外當我嘗試點擊重新添加的條目時,我得到一個異常,所以它似乎不在那裏了。
我GOOGLE了一段時間,但我無法找到答案。它與光標有關嗎?從表中刪除一行後,是否必須提供一個新的光標到適配器?如果是,如何?
這是我的代碼:
public MyViewHolder(View itemView, final RecyclerViewClickListener listener) {
super(itemView);
mDeleteImage = itemView.findViewById(R.id.image_delete);
[...]
mDeleteImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onDeleteClick(position);
}
}
}
});
}
@Override
public void onDeleteClick(int position) {
SQLiteDatabase database = new MySQLiteHelper(this).getWritableDatabase();
Cursor cursor = database.rawQuery("select * from " + MyContract.MyEntry.TABLE_NAME, null);
cursor.moveToPosition(position);
database.delete(MyContract.MyEntry.TABLE_NAME, MyContract.MyEntry._ID + "=?", new String[] {cursor.getString(cursor.getColumnIndexOrThrow(MyContract.MyEntry._ID))});
mAdapter.notifyItemRemoved(position);
}
謝謝。但我不使用CursorAdapter,所以我沒有swapCursor方法。這個CursorAdapter僅適用於ListViews嗎? 我試圖通過一種方法提供一個新的遊標,但它沒有奏效。 –
那是自定義回收站視圖適配器嗎? –
是的。我嘗試將mCursor設置爲一個新的遊標,但它沒有奏效。我最初提供Cursor的方式是通過Adapter的構造函數。 –