1

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: 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 {

    }

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?

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
A. Newbie
  • 187
  • 1
  • 3
  • 17
  • 2
    callbacks are asyncronous. onDataChange or onCancelled will call asynchronously. So showNewUserBox will always be called – Shubham AgaRwal Jun 17 '18 at 20:04
  • Firebase queries are always asynchronous and return immediately. To learn more about that, read this blog: https://medium.com/@CodingDoug/why-are-firebase-apis-asynchronous-callbacks-promises-tasks-e037a6654a93 – Doug Stevenson Jun 17 '18 at 20:15

1 Answers1

0

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 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).

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807