Landen
Landen

Reputation: 529

Removing Value from Android Firebase Removes Whole Node

I'm following the guide here for removing values from my firebase database. Here is the structure of my data.

 |---users
     |----KJSXd4ScEmJ6N4UFc5k 
          |---bookmarks
              |---KdCyKdQkDg34ny6_H-C
                  |---id:"12d5j2fa-0f70-41c3-b4g4-4d66bdcef976"
              |---KdCyKdQkDg34ny6_H-M
                  |---id:"fa95b1fa-b537-4d98-a0e7-a92ffea7b6a4"

Here's the code I'm using.

FirebaseDatabase.getInstance().getReference().child(MyConstants.FIREBASE_USERS_NODE).child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                .child(MyConstants.FIREBASE_BOOKMARKS_NODE).orderByChild("id").equalTo(uuid).addListenerForSingleValueEvent(
                new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        dataSnapshot.getRef().removeValue();
                    }

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

What's happening is the entire /bookmarks node gets deleted on this single call instead of just the reference to the bookmark wanted. How is it that I can achieve just deleting the single bookmark I want to delete instead of the whole node?

Upvotes: 0

Views: 739

Answers (2)

Deepak Goyal
Deepak Goyal

Reputation: 4907

Why are you listening for the SingleValueEvent for that node, just try the below code.

FirebaseDatabase.getInstance().getReference().child(MyConstants.FIREBASE_USERS_NODE).child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child(MyConstants.FIREBASE_BOOKMARKS_NODE).child(uuid).removeValue();

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

So in your case, the snapshot is not the item, but it's the total result of the query. Hence its getRef() returns the location on which you fired the query.

The solution is to loop over the results and delete each individually:

public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot child: dataSnapshot.getChildren()) {
        child.getRef().removeValue();
    }
}

Upvotes: 2

Related Questions