我在我的Android应用中使用Firebase,我想读取数据。特别是我想选择具有特定ID的用户。当我使用调试器时,代码似乎没有执行onDataChange()指令。
private User readUserById(){
final User u = new User("","","");
Query query = mDatabaseReferences.child("users").orderByChild("id").equalTo(id);
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
u.setId(ds.child("id").getValue(User.class).getId());
u.setNumber((ds.child("number").getValue(User.class).getNumber()));
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
return u;
}
private void initFirebase() {
FirebaseApp.initializeApp(this);
mFirebaseDatabase = FirebaseDatabase.getInstance();
mDatabaseReferences = mFirebaseDatabase.getReference();
}
public void sendCode(View v){
id= id.getText().toString();
readUserById();
phoneNumber = phoneText.getText().toString();
if (phoneNumber.equals("") || id.equals("")) {
Toast t = Toast.makeText(this, "Please insert a nickname and a valid phone number", Toast.LENGTH_LONG);
t.show();
} else {
setUpVerificationCallbacks();
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber,
60,
TimeUnit.SECONDS,
this,
verificationCallbacks
);
}
// }
}
使用调试器我已经看到了' id'价值是正确的。
我使用了sendCode()的Firebase文档,用户注册正常工作,就像短信发送一样。我想检查昵称是否已经存在,并且值是在' id' TextView中。我通过一个按钮调用sendCode()。
我已经尝试过这种方式,但是没有工作。使用调试器运行user的结果为null
private User readUserByName(){
final User[] user = {new User()};
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("users").child(nick).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
user[0] = dataSnapshot.getValue(User.class);
Log.d("Tag", user[0].toString());
}
else
Log.e("Tag","No such user exists");
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
return user[0];
}
答案 0 :(得分:0)
假设users
节点是Firebase根目录的直接子节点,请使用以下代码:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference testRef = rootRef.child("users").child("test");
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String id = dataSnapshot.child("id").getValue(String.class);
String idName = dataSnapshot.child("idName").getValue(String.class);
String number = dataSnapshot.child("number").getValue(String.class);
Log.d("TAG", id + " / " + idName + " / " + number);
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
testRef.addListenerForSingleValueEvent(eventListener);
输出将是:
test / f70eb... / number
答案 1 :(得分:0)
假设:
这是你应该怎么做的
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("users").ref(id).addListenerforSingleValueEvent(listener);
在Listener的OnDataChange(DataSnapshot snap)中;
if(snap.exists()){
user = snap.getValue(User.class);
Log.d("Tag",user.toString());
}
else
Log.e("Tag","No such user exists");