Masroor
Masroor

Reputation: 1604

How to update value of a particular child node in firebase realtime database?

I'm making a basic android app project, I have this database structure and want to update a specific child node (lets say room_price)
I've tried doing this but looks like I'm missing something which is preventing me from achieving this.

DatabaseReference dbRef=FirebaseDatabase.getInstance().getReference();    
dbRef.child("Rooms")
     .child(roomNumber)
     .child("room_price")
     .setValue(updatedPrice);

roomNumber and updatedPrice are variables having int values.

When I execute this code, instead of updating the value of room_price it deletes the room_price node from the tree structure and I haven't been able to get why it does that. Please correct me if something is wrong with the code, or suggest some other way of doing this.

Please note that it has no issue with database rules. its either the code or the database path that causes this problem.

Upvotes: 2

Views: 3989

Answers (2)

Guilherme Lemmi
Guilherme Lemmi

Reputation: 3487

Please note that Firebase database does not accept null values, so if you try to update a node with anything that results in null value, the node will be deleted. For more information, please check the documentation on https://firebase.google.com/docs/database/admin/save-data

I'm not sure if that is the reason behind your issue, I would need more information on what updatedPrice is, but try to log this variable and examine its contents, maybe it is resolving as a null value and causing the error.

Good luck!

Upvotes: 0

Peter Haddad
Peter Haddad

Reputation: 80914

To update room_price, try the following:

DatabaseReference dbRef=FirebaseDatabase.getInstance().getReference();  
dbRef.child("Rooms").child(roomNumber);
Map<String, Object> updates = new HashMap<>();
updates.put("room_price", updatedPrice);

dbRef.updateChildren(updates);

more info here:

Update Field

Upvotes: 4

Related Questions