0

screenshot of data

DatabaseReference dr1 = FirebaseDatabase.getInstance().getReference("DailyExpenseTable");
dr1.removeValue();
Toast.makeText(getActivity(),"DailyExpense Removed",Toast.LENGTH_LONG).show();`
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Vicky Gupta
  • 60
  • 1
  • 12

1 Answers1

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
  • 565,676
  • 79
  • 828
  • 807