我已经检查了高低,但我看到的只是人们试图让所有孩子都进入列表和其他东西。我只想从数据库中获得一个孩子。
{
"Haydn" : {
"Users" : {
"email" : "[email protected]",
"name" : "kofi"
}
}
}
我想从结构中获取名称。
我的代码:
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) {
}
}
您可以这样设置参考:
reference = rootNode.getReference().child("Users");
这意味着Firebase从/Users
数据库中读取数据。由于Users
您发布的JSON的根目录中没有节点,这意味着snapshot
您将得到的是空的。
要读取单个节点(如您在此处尝试的那样),请设置对该节点的确切路径的引用:
reference = rootNode.getReference().child("Haydn/Users/name");
如您所见,您可以将整个路径传递到中的节点child(...)
。
使用此参考,您可以像下面这样读取值:
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();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句