[英]How to add a new node dynamically in firebase real-time database
Newbie to Firebase DB. Firebase 数据库的新手。 Below is the structure of my DB:
下面是我的数据库的结构:
Cart-List
|
|-UserCarts
|
|- 2020-11-11 ( using dateformat :yyyy-MM-dd)
| |
| | -items
| |- productCode
| |- price
|-
create the node as follows:创建节点如下:
FirebaseDatabase.getInstance().getReference().child("Cart-List").child("UserCarts") FirebaseDatabase.getInstance().getReference().child("Cart-List").child("UserCarts")
How to add a new node ( say 2020-11-11) under UserCarts?如何在 UserCarts 下添加一个新节点(比如 2020-11-11)?
Before adding this new node, is there a way to check if this node is created?在添加这个新节点之前,有没有办法检查这个节点是否被创建?
This will allow me to look for items by date easily.这将使我能够轻松地按日期查找项目。 Maybe this will reduce the compute time thus incur fewer charges?
也许这会减少计算时间从而减少费用?
Thanks谢谢
When you are using the following reference:当您使用以下参考时:
FirebaseDatabase.getInstance().getReference().child("Cart-List").child("UserCarts")
It means that you creating a schema that looks like this:这意味着您创建了一个如下所示的模式:
Firebase-root
|
--- Cart-List
|
--- UserCarts
If you need to write data at a lower level in your tree, you need to add a few more .child()
calls.如果您需要在树的较低级别写入数据,则需要添加更多的
.child()
调用。 Assuming you want to write data under the items
node, the reference should look like this:假设你想在
items
节点下写入数据,引用应该是这样的:
val itemsRef = FirebaseDatabase.getInstance().getReference()
.child("Cart-List")
.child("UserCarts")
.child("2020-11-11")
.child("items");
One thing to remember, the keys in Firebase are always Strings.需要记住的一件事是,Firebase 中的键始终是字符串。 If you want to store a Date is more convenient to store it as a Timestamp.
如果要存储日期,将其存储为时间戳更方便。 So it would be more helpful to add the Timestamp as a property of the object, as explained in my answer from the following post:
因此,将时间戳添加为 object 的属性会更有帮助,正如我在以下帖子的回答中所解释的那样:
Before adding this new node, is there a way to check if this node is created?
在添加这个新节点之前,有没有办法检查这个节点是否被创建?
If want to check if a node exists, you need to attach a listener, as in the following lines of code:如果要检查一个节点是否存在,你需要附加一个监听器,如下代码行:
val valueEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
if(dataSnapshot.exists()) {
//Do what you need to do
}
}
override fun onCancelled(databaseError: DatabaseError) {
Log.d("TAG", databaseError.getMessage()) //Don't ignore potential errors!
}
}
itemsRef.addListenerForSingleValueEvent(valueEventListener)
And for Java users:对于 Java 用户:
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
//Do what you need to do
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
itemsRef.addListenerForSingleValueEvent(valueEventListener);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.