Home > Back-end >  How can I "undo" a multi-child deletion?
How can I "undo" a multi-child deletion?

Time:04-16

In this portion of code I delete a selection of items from my Firebase Realtime Database:

for (Expense i : selectedExpenses) {

    final Expense expenseBackUp = new Expense(i.getItem(), i.getCategory(), i.getDate(), i.getId(), i.getAmount());

    databaseReference.child(i.getId()).removeValue().addOnCompleteListener(task -> {

        if (task.isSuccessful()) {
            Snackbar.make(activity.findViewById(android.R.id.content), activity.getString(R.string.deleted_alert),
                    Snackbar.LENGTH_LONG).
                    setAction(R.string.undo, view1 -> databaseReference.child(i.getId()).setValue(expenseBackUp)).show();
        } else {
            Toast.makeText(activity.getApplicationContext(), activity.getString(R.string.input_error)   task.getException(), Toast.LENGTH_SHORT).show();
        }
    });
}

Now I want to implement an undo button within a Snackbar.

I get to show the Snackbar with the undo button, but I need some help with the expenseBackUp because it only retrieves my last deleted item, which works fine when a user deletes only 1 item.

How can I go around this, so I can get every deleted item back if undo button is hit?

CodePudding user response:

You can delete the items in two phases: first, you mark the 'deleted' items in the database as deleted with an extra boolean field 'deleted' in the table. Then on undo click, you can easily undo the delete.

If the user does not click the undo, you can fully delete the marked items after the snackbar timeout.

CodePudding user response:

Adding a flag to each object will work but it also has a downside. If you want to query all items of a node where the property "deleted" holds the value of true, it will solve the problem, but if you need to add another filter, it will not work, because the Firebase Realtime Database does not support queries on multiple properties.

To solve this, you can perform the delete operation, and if the user clicks on the "UNDO" button in Snackbar, write the data back. It's not the best solution, as it implies a delete operation followed by a write operation but it will do the trick.

Another option that you have, would be to simulate the delete operation. How? When the user clicks on the delete button, don't perform the actual delete operation. Wait to see if the user clicks "UNDO". If the user clicks "UNDO" take no action, otherwise, delete the elements.

To be able to update/delete multiple elements, please check my answer from the following post:

  • Related