user6750923
user6750923

Reputation: 479

Unable to delete a node from Firebase in Android

I want to delete Room2 node from the Firebase database. I have this database structure:

db-24f7f
 |
 - Hotel
       |
    -Room1
         |
          beds:"2"
          Chairs: "6"
    -Room2
         |
         beds:"3"
         Chairs: "8"

I tried as

database = FirebaseDatabase.getInstance();
myRef = database.getReference();
database.getReference("Hotel").orderByChild("Chairs").equalTo("8").addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
           dataSnapshot.getRef().setValue(null);
    }

That delete the whole database. Then I tried as

database = FirebaseDatabase.getInstance();
myRef = database.getReference();
database.getReference("Hotel").orderByChild("Chairs").equalTo("8").addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
               for(DataSnapshot ds:dataSnapshot.getChildren()){
                    ds.getRef().removeValue();
                }
            }

and find this :

12-28 12:31:21.813 22950-22950/PKGName_o E/ViewRootImpl: sendUserActionEvent() mView == null 12-28 12:31:21.813 22950-22950/PKGName_o E/ViewRootImpl: sendUserActionEvent() mView == null W/PersistentConnection: pc_0 - Using an unspecified index. Consider adding '".indexOn": "Chairs"' at Hotel to your security and Firebase Database rules for better performance

After this, the node does not delete from the Firebase. Why it is unable to delete the node?

Upvotes: 1

Views: 394

Answers (1)

Nishanth Sreedhara
Nishanth Sreedhara

Reputation: 1286

Under Room node add the room key.

db-24f7f
 |
 - Hotel
       |
    -Room1
         |
          beds:"2"
          roomKey: "Room1"
          Chairs: "6"
    -Room2
         |
         beds:"3"
         roomKey: "Room2"
         Chairs: "8"

Now take the reference of the 'Hotel'.

DatabaseReference hotelRef = myRef.child("Hotel");

If you just want to remove Room2, then do so by setting the value of Room2 to null-

hotelRef.child("Room2").setValue(null);

If you want to delete all the rooms with 8 chairs, then -

hotelRef.orderByChild("Chairs").equalTo("8").addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                   for(DataSnapshot ds:dataSnapshot.getChildren()){
                        String roomKey = (String) ds.child(roomKey).getValue();
                        hotelRef.child(roomKey).setValue(null);
                    }
                }

Upvotes: 1

Related Questions