[英]How to get a single child from firebase database
I have checked high and low but all I see are people trying to to get all the children into lists and stuff.我检查了高低,但我看到的只是人们试图让所有的孩子都进入列表和东西。 I just want to get a single child from the database.我只想从数据库中获取一个孩子。
{
"Haydn" : {
"Users" : {
"email" : "user@gmail.com",
"name" : "kofi"
}
}
}
I want to get the name from the structure.我想从结构中获取名称。
My code:我的代码:
rootNode = FirebaseDatabase.getInstance();
reference = rootNode.getReference().child("Users");
reference.addListenerForSingleValueEvent(
new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
String displayName = (String) snapshot.child("Haydn").child("Users").child("name").getValue();
loggedInUserTextView.setText(displayName);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
}
You set up your reference like this:你设置你的参考是这样的:
reference = rootNode.getReference().child("Users");
That means that Firebase reads the data from /Users
in your database.这意味着 Firebase 从数据库中的/Users
读取数据。 Since there is no Users
node at the root of the JSON you posted, that means the snapshot
you get is going to be empty.由于您发布的 JSON 的根目录中没有Users
节点,这意味着您获得的snapshot
将为空。
To read a single node, as you're trying to do here, set up a reference to the exact path of that node:要读取单个节点,就像您在此处尝试做的那样,设置对该节点确切路径的引用:
reference = rootNode.getReference().child("Haydn/Users/name");
As you can see, you can pass the entire path to the node in the child(...)
.如您所见,您可以将整个路径传递给child(...)
中的节点。
With this reference, you can then read the value like this:使用此参考,您可以读取如下值:
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
String displayName = snapshot.getValue(String.class);
loggedInUserTextView.setText(displayName);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
throw error.toException();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.