Home > database >  How can I delete from firebase database only selected items in my recyclerview - andorid - java
How can I delete from firebase database only selected items in my recyclerview - andorid - java

Time:04-16

delete method

private void deleteExpense(Expense s) {
    if (dialogConfirmed) {

        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("Expenses").child(Objects.requireNonNull(FirebaseAuth.getInstance().getCurrentUser()).getUid());
        databaseReference.child(s.getId()).removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {

            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (!task.isSuccessful()) {
                    Toast.makeText(activity, activity.getString(R.string.input_error)   task.getException(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

I have an arraylist where I save selected items, but when I delete and come back to the activity they show up again because I cannot find a way to delete them from firebase. would anyone please let me know how I can take my selection list and delete those items from firebase.

Based on the answers I tried this, but still no luck.

private void deleteExpense() {
    if (dialogConfirmed) {

        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("Expenses").child(Objects.requireNonNull(FirebaseAuth.getInstance().getCurrentUser()).getUid());

        Map<String, Object> delete = new HashMap<>();
        for (Expense i : selectedExpenses) {
            delete.put("item"   i, null);
        }

        databaseReference.updateChildren(delete).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
            }
        });
    }
}

CodePudding user response:

If you want to remove multiple items you can either delete them by calling removeValue() for each of them, or you can run a single multi-path update statement. That second option takes the form of:

Map<String,Object> updates = new HashMap<>();
updates.put(s.getId());
updates.put(second.getId());
updates.put(third.getId())

databaseReference.updateChildren(updates).addOnCompleteListener(...);
  • Related