
Question:
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.
This is my db: <a href="https://i.stack.imgur.com/25tNt.png" rel="nofollow">Firebase</a> 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 {
}
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?
Answer1: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).
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
}
});
Also see some of the many <a href="https://stackoverflow.com/search?tab=votes&q=%5bfirebase-database%5d%5bandroid%5d%20asynchronous" rel="nofollow">questions about asynchronous loading from Firebase</a>, such as <a href="https://stackoverflow.com/questions/50434836/getcontactsfromfirebase-method-return-an-empty-list/50435519#50435519" rel="nofollow">getContactsFromFirebase() method return an empty list</a> (or this quite old classic: <a href="https://stackoverflow.com/questions/33203379/setting-singleton-property-value-in-firebase-listener/33204705#33204705" rel="nofollow">Setting Singleton property value in Firebase Listener</a>).