Prateek Prasad
Prateek Prasad

Reputation: 837

Delete single item from Firebase not working

enter image description here

I need to delete a user from the group chat once he clicks the exit group button. The above picture is how my database looks like

Suppose I want to delete the user with user_id: 15213

Here's my code:

 FirebaseDatabase database = FirebaseDatabase.getInstance();
 DatabaseReference groupMemberRef = database.getReference().child("group_users/"+chatGroup.group_id+"/"+userId);

    groupMemberRef.removeValue();

While the code is technically correct, the entry isn't getting removed from the database.

Upvotes: 0

Views: 531

Answers (2)

Alex Mamo
Alex Mamo

Reputation: 138824

To solve this, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("group_users/" + chatGroup.group_id).orderByChild("user_id").equalsTo(15213);
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            ds.getRef().removeValue();
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(valueEventListener);

Upvotes: 0

Chintan Soni
Chintan Soni

Reputation: 25267

I have never tried deleting a node the way you implemented. But I did as below:

DatabaseReference groupMemberRef = database.getReference().child("group_users/"+chatGroup.group_id+"/"+userId);
groupMemberRef.setValue(null);

See if it works..

Upvotes: 2

Related Questions