So, I am working on a project and I want to delete an item from a RecyclerView but I want the user to be able to restore that item by pressing "UNDO" in a Snackbar. The RecyclerView items are pulling their data from an SQLite database and when the user deletes an item it will remove it from the RecyclerView and the corresponding row of my table in the database as well. My problem is I cannot seem to figure out how to recover that deleted data (The SQLite data).
I tried to make a method in my DataBaseHelper class which takes the position as a parameter so my cursor knows which row to access then I used the cursor to assign all the values of that row to an AlarmData(my setter and getter class) object and return that back to my Adapter Class so I can try to restore the table's row in my Snackbar's UNDO action method.
Here's the code:
DataBaseHelper.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;
}
AlarmAdapter.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();
}
Just to clairify, I'd like to know how I can make a copy of a specific row in my database so I can recreate it when the user hits UNDO on the Snackbar. and also maybe explain to me what I'm doing wrong. Lol..
I hope I didn't show my noobishness too much here. Your help would be greatly appreciated. Thank you!