Firebase DataSnapshot Null值 [英] Firebase DataSnapshot Null values
问题描述
我的应用程序允许您将播放器添加到节点,一旦添加了播放器,我将使用以下方法通过phoneNum搜索以查看该播放器是否在用户"节点中.
My app allows you to add a Player to a node, once they have been added I am using the below method to search by phoneNum to see if that player exists in the 'users' node.
我遇到麻烦的地方是,我需要能够从找到的匹配节点内的用户的数据快照中访问值.例如返回用户ID的值.当我尝试这样做时,它一直显示为空值,而当我尝试登录到控制台时,它抱怨说这是一个空值,这是没有意义的,因为if语句应该注意这一点.
Where I am having trouble is that I need to be able to access the values from the datasnapshot for the user within the found matching node. e.g.return the value of the user id. When I attempt this it keeps showing as a null value and when I try to log to the console it complains that it is a null value which doesn't make sense as the if statement should take care of this.
该方法能够找到用户节点中是否存在玩家,并显示一条Toast消息来表明这一点.
The method is able to find if a player exists in the the users node and displays a Toast message to indicate this.
代码:
public void checkPlayerNum(final String phoneNum) {
DatabaseReference mDatabaseReference =
FirebaseDatabase.getInstance().getReference().child("users");
if (!TextUtils.isEmpty(phoneNum)) {
final Query phoneNumReference = mDatabaseReference.orderByChild("phoneNum").equalTo(phoneNum);
ValueEventListener phoneNumValueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
// String key = String.valueOf(dataSnapshot.getValue());
User mUser = dataSnapshot.getValue(User.class);
String uId = mUser.getUid();
// Log.d("TAG",uId);
Toast.makeText(getApplicationContext(), "* found **"+ uId , Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "****NOT FOUND****", Toast.LENGTH_LONG).show();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
phoneNumReference.addListenerForSingleValueEvent(phoneNumValueEventListener);
} else {
Log.e("Error","phoneNum is null");
}
}
推荐答案
final Query query = mFirebaseDatabase.orderByChild("phoneNum").equalTo("userPhoneNumber");
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
//here means the value exist
//do whatever you want to do
} else {
//here means the value not exist
//do whatever you want to do
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
使用它来检查数据是否存在.
Use this to check whether the data exist or not.
这篇关于Firebase DataSnapshot Null值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!