运行这段代码时:
private void getData(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
Log.d(TAG, "UserID inside getData: "+userID);
Log.d(TAG, "User Name inside getData: "+ds.child(userID).child("name").getValue());
Log.d(TAG, "DS inside getData: "+ds.child(userID));
hospitalCity = String.valueOf(ds.child(userID).child("city").getValue());
Log.d(TAG, "User city inside getData: "+ds.child(userID).child("city").getValue());
break;
}
}
日志显示:
UserID inside getData: Lsncj8CIsfTQXc7E425AtLuDI5v2
User Name inside getData: null DS inside getData: DataSnapshot { key = Lsncj8CIsfTQXc7E425AtLuDI5v2, value = null }D/DonorList: User city inside getData: null
这是数据库:
如您所见,它获取了键,但值为 null
,尽管数据库显示其中有值。
最佳答案
为了获取Hospital
节点下的数据,需要修改如下引用:
hospitalDatabase = FirebaseDatabase.getInstance().getReference();
与
hospitalDatabase = FirebaseDatabase.getInstance().getReference().child("Hospital");
要获取getData()
方法中的数据,请使用以下代码:
private void getData(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String key = ds.getKey();
String city = ds.child("city").getValue(String.class);
String name = ds.child("name").getValue(String.class);
}
}
ds.getKey()
将返回 userId
ds.child("city").getValue(String.class)
将返回城市。
ds.child("name").getValue(String.class)
将返回名称。
关于java - dataSnapshot.getChildren() 获取用户 ID 但不获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49581550/