DatabaseReference dr1 = FirebaseDatabase.getInstance().getReference("DailyExpenseTable");
dr1.removeValue();
Toast.makeText(getActivity(),"DailyExpense Removed",Toast.LENGTH_LONG).show();`
Asked
Active
Viewed 44 times
0
Frank van Puffelen
- 499,950
- 69
- 739
- 734
Vicky Gupta
- 60
- 1
- 10
1 Answers
1
The code you have in your question removes the entire DailyExpenseTable node, so also all expenses under there.
If you want to remove a single node under it and you know the key of that node, you can remove it with:
DatabaseReference dr1 = FirebaseDatabase.getInstance().getReference("DailyExpenseTable");
dr1.child("-M2QsnCvO7jTtZbXp47s").removeValue();
If you don't know the key, but know another property, you can first execute a query and then remove the results of that query with:
DatabaseReference dr1 = FirebaseDatabase.getInstance().getReference("DailyExpenseTable");
dr.orderByChild("dailyExpenseID").equalTo("2").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot expenseSnapshot: dataSnapshot.getChildren()) {
expenseSnapshot.getRef().removeValue();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
In the latter case, you may end up deleting multiple nodes, if multiple expenses can have the same value for dailyExpenseID.
If that can never happen, you might want to consider using the dailyExpenseID as the key for the child nodes. So store them with:
dr1.child(expenseId).setValue(...)
Instead of the dr1.push.setValue(...) that you now likely use.
Frank van Puffelen
- 499,950
- 69
- 739
- 734
-
1Hey, puf. There's a `.getRef()` call missing. Should be `expenseSnapshot.getRef().removeValue();`. – Alex Mamo Mar 15 '20 at 13:21
-
Good point Alex. Thanks, and fixed. Feel free to make such edits yourself in the future btw. Yay for the wiki nature of SO. :) – Frank van Puffelen Mar 15 '20 at 15:27
-
Ok, I'll do it. Thanks – Alex Mamo Mar 15 '20 at 15:48