这是我的数据库结构:
我用于数据读取的代码:
user="hrcj7";
mDatabase = FirebaseDatabase.getInstance().getReference().child("User");
Query phoneQuery = mDatabase.orderByChild(user);
phoneQuery.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {
User dinosaur = dataSnapshot.getValue(User.class);
System.out.println(dataSnapshot.getKey() + " was " + dinosaur.getEmail() + " meters tall.");
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.e("App", "onCancelled", databaseError.toException());
}
});
这是检索后的dataSnapsshot值:
DataSnapshot {
key = hrcj7,
value = {
-Kh2-jOeGXCOr-VE3uD5={
username=hrcj7,
email=rperera723@gmail.com,
imageurl=https://firebasestorage.googleapis.com/v0/b/freelancer-33195.appspot.com/o/Blog_Images%2Fcropped933315999.jpg?alt=media&token=7890f05f-87db-4a9d-9534-02da00225470
}
}
}
这是模型类:
public class User {
public String email;
public String imageurl;
public String username;
public User(String email,String imageurl,String username) {
this.email = email;
this.imageurl=imageurl;
this.username=username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getImageurl() {
return imageurl;
}
public void setImageurl(String imageurl) {
this.imageurl = imageurl;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public User() {
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
}
我的问题是dinosaur.getEmail()
在检索值后变为null。可能是什么问题?提前谢谢。
答案 0 :(得分:1)
我找到了解决方案。
排队:
User dinosaur = dataSnapshot.getValue(User.class);
应替换为以下内容:
String key = mDatabase.child("User").child(user).push().getKey();
User dinosaur = dataSnapshot.child(key).getValue(User.class);