2

How do I remove values in Google Firebase?

I want to remove values in Google Firebase, but I don't know how to do it with this code.

I'd tried the following method, but it didn't work:

FirebaseDatabase.getInstance().getReference().child("Notifications")
                                             .child(firebaseUser.getUid())
                                             .child("postid").child(postid)
                                             .removeValue();

enter image description here

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Emily
  • 25
  • 5

1 Answers1

1

Your code deletes the node at /Notifications/$uid/postid/$postid. Since there is no node at that exact path, the operation doesn't delete anything.

To delete the child nodes of Notifications where the postid matches a specific value, you'll need to:

  1. Perform a query to find the matching node(s).
  2. Then call removeValue() for each node.

In code that'd be something like:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference()
    .child("Notifications").child(firebaseUser.getUid());

Query query = ref.orderByChild("postid").equalTo(postid);

query.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
            snapshot.getRef().removeValue();
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
}

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • is it snapshot.getRef().removeValue(); ?? Because I cannot use getReference(), and still cannot remove notification values – Emily Aug 06 '21 at 14:04