简体   繁体   English

如何更新Firebase实时数据库中特定子节点的值?

[英]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) 我正在制作一个基本的android应用程序项目,我具有此数据库结构,并且想要更新特定的子节点(比如说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. roomNumber和updatedPrice是具有int值的变量。

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. 当我执行此代码时,没有更新room_price的值,而是从树结构中删除了room_price节点,但我无法知道为什么这样做。 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. 它是导致此问题的代码或数据库路径。

To update room_price , try the following: 要更新room_price ,请尝试以下操作:

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 更新栏位

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. 请注意,Firebase数据库不接受空值,因此,如果您尝试使用会导致空值的任何内容更新节点,则该节点将被删除。 For more information, please check the documentation on https://firebase.google.com/docs/database/admin/save-data 有关更多信息,请查看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. 我不确定这是否是您问题背后的原因,我需要更多有关updatedPrice是什么的信息,但是尝试记录此变量并检查其内容,也许它解析为空值并导致错误。

Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM