如何检查FireBase(Android)中是否存在特定的子值 [英] How do I check if specific child value exists in FireBase (Android)
问题描述
尝试检查用户信息是否已存储在FireBase数据库中时遇到一些麻烦. 基本上,我正在尝试做这样的愚蠢的事情: 从用户中选择user_name,其中user_id ="+ userID +" 如果昵称存在,则应使布尔值var isFirstTime = false,否则应保持为true.然后,它应该显示或不显示注册框.
I have some trouble trying to check if user information is stored already in the FireBase database. Basically I'm trying to do something stupid like this: "select user_name from user where user_id="+userID+" And if the nickname exists it should make the boolean var isFirstTime = false and if it doesn't it should stay true. And after that it should show register box or not.
这是我的数据库: Firebase 这是我在onCreate方法中的代码:
This is my db: Firebase And this is my code in onCreate method:
databaseReference = FirebaseDatabase.getInstance().getReference();
DatabaseReference dbRefFirstTimeCheck = databaseReference.child("User").child(user.getUid()).child("Nickname");
isFirstTime = true;
dbRefFirstTimeCheck.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.getValue() != null) {
isFirstTime=false;
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
if(isFirstTime) {
showNewUserBox();
}
else {
}
无论我做什么,都会调用methor showNewUserBox().如何获取所需的数据并检查是否存在?
No matter what I do, the methor showNewUserBox() is being called. How do I get the data i need and check if it's there?
推荐答案
正如其他人所评论的那样,数据是从Firebase异步加载的.到您检查isFirstTime
时,尚未加载数据,onDataChange
尚未运行,因此ifFirstTime
将具有其默认值(布尔值为false
).
As others have commented, data is loaded from Firebase asynchronously. By the time you check isFirstTime
, the data hasn't been loaded yet, onDataChange
hasn't been run yet, so ifFirstTime
will have its default value (false
for a boolean).
所有需要从数据库获取数据的代码都应在onDataChange
内部(或在其中调用).您的代码最简单的解决方法是:
All code that requires data from the database should be inside onDataChange
(or invoked from within there). The simplest fix for your code is:
databaseReference = FirebaseDatabase.getInstance().getReference();
DatabaseReference dbRefFirstTimeCheck = databaseReference.child("User").child(user.getUid()).child("Nickname");
dbRefFirstTimeCheck.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
showNewUserBox();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
另请参阅许多有关从Firebase异步加载的问题,例如 getContactsFromFirebase()方法返回空列表(或这个非常古老的经典:设置Singleton属性值在Firebase侦听器中).
Also see some of the many questions about asynchronous loading from Firebase, such as getContactsFromFirebase() method return an empty list (or this quite old classic: Setting Singleton property value in Firebase Listener).
这篇关于如何检查FireBase(Android)中是否存在特定的子值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!