How do I check if specific child value exists in FireBase (Android)

前端 未结 1 894
难免孤独
难免孤独 2021-01-26 12:13

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 fr

1条回答
  •  隐瞒了意图╮
    2021-01-26 12:59

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

    0 讨论(0)
提交回复
热议问题