所以,我正在做一个项目,我想从 RecyclerView 中删除一个项目,但我希望用户能够通过在 Snackbar 中按“UNDO”来恢复该项目。RecyclerView 项目正在从 SQLite 数据库中提取它们的数据,当用户删除一个项目时,它会将其从 RecyclerView 以及数据库中我的表的相应行中删除。我的问题是我似乎无法弄清楚如何恢复已删除的数据(SQLite 数据)。
我试图在我的 DataBaseHelper 类中创建一个方法,该方法将位置作为参数,以便我的光标知道要访问哪一行,然后我使用光标将该行的所有值分配给一个 AlarmData(我的 setter 和 getter 类)对象和将其返回到我的适配器类,以便我可以尝试在我的 Snackbar 的 UNDO 操作方法中恢复表的行。
这是代码:
数据库助手.java
// Is public AlarmData even legal? that's my setter and getter class
// and the object type I'm trying to return
public AlarmData recoverAlarms(int position) {
AlarmData recoverData = new AlarmData();
String ALARM_RESTORE_QUERY = "SELECT * FROM " + TABLE_ALARMS + " WHERE " + COLUMN_INDEX +
" = " + position + ";";
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery(ALARM_RESTORE_QUERY, null);
try {
if (cursor.moveToFirst()) {
do {
recoverData.set_dispLabel(cursor.getString(cursor.getColumnIndex(COLUMN_LABEL)));
recoverData.set_dispTime(cursor.getString(cursor.getColumnIndex(COLUMN_TIME)));
recoverData.set_alarmId(cursor.getInt(cursor.getColumnIndex(COLUMN_INDEX)));
} while (cursor.moveToNext());
}
} catch (Exception e) {
throw e;
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
db.close();
}
}
return recoverData;
}
报警适配器.java
public void deleteAlarm(final int position, final View view) {
final AlarmData recoverAlarmData = new DataBaseHelper(context, null, null, 1).recoverAlarms(position); //INITIALIZES VARIABLE TO THE OBJECT THAT'S RETURNED
final AlarmData recoverItem = alarmData.get(position); //Recovers RecyclerView item (this works)
final DataBaseHelper dataBaseHelper = new DataBaseHelper(context, null, null, 1);
alarmData.remove(position);
notifyItemRemoved(position);
dataBaseHelper.deleteAlarms(position); //DELETES TABLE'S ROW
Snackbar snackbar = Snackbar.make(view, "Alarm Removed", Snackbar.LENGTH_LONG)
.setAction("UNDO", new View.OnClickListener() {
@Override
public void onClick(View v) {
alarmData.add(position, recoverItem);
notifyItemInserted(position); //RESTORES RECYCLERVIEW ITEM
dataBaseHelper.addAlarm(recoverAlarmData); //TRIES TO RECOVER TABLE
}
});
snackbar.show();
}
只是为了澄清,我想知道如何在我的数据库中复制特定行,以便在用户点击 Snackbar 上的 UNDO 时重新创建它。也可能向我解释我做错了什么。哈哈..
我希望我在这里没有表现出我的笨拙。您的帮助将不胜感激。谢谢!