我有一个像这样的数据库,
Users
COd3XoRnWOMRIFrbYSrNMZjm2Jj2
admin: false
email: "test@test.com"
name: "aa"
surname: "aa"
username: "test"
KtUAjavm3TUmonRXl37CS4ePhuK2
admin: false
email: "test2@test.com"
name: "aa"
surname: "bb"
username: "test"
我有一个User类。我想从数据库中获取用户数据,创建一个User实例并使用user.getUsername()
方法,获取我从数据库中获取的用户名。但是当使用下面的代码时,user.getUsername()
将返回null。
User user = new User("USER_ID");
user.getUsername();
这是我的构造函数,
public User(String id) {
UID = id;
Users = database.getReference("Users").child(id);
Users.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
Log.d(TAG, UID);
username = (String) dataSnapshot.child("username").getValue();
email = (String) dataSnapshot.child("email").getValue();
surname = (String) dataSnapshot.child("surname").getValue();
name = (String) dataSnapshot.child("name").getValue();
admin = (Boolean) dataSnapshot.child("admin").getValue();
} else {
Log.e(TAG, "Invalid UID");
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
}
});
}