Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Firebase addListenerForSingleValueEvent is not working

I know this has been asked a lot but I still can get it to work. Here's my code:

private int test;

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("Users");

test = 0;
userRef.addListenerForSingleValueEvent(new ValueEventListener() {
   @Override
   public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.hasChild(userID))
            test = 1;
        else
            test = 2;
   }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

Log.d(TAG, "Test = " + test);

Here's what on Firebase:

  • appname-e545e
    • Users
      • userID

I don't know why but the variable "test" always return value 0, which means addListenerForSingleValueEvent didn't work. Thanks for helping in advanced

like image 899
leScepter Avatar asked Dec 24 '22 14:12

leScepter


1 Answers

The data is loaded from Firebase asynchronously. By the time your log test, the onDataChange hasn't run yet.

To see this in action, add some more logging inside onDataChange:

private int test;

test = 0;
userRef.addListenerForSingleValueEvent(new ValueEventListener() {
   @Override
   public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.hasChild(userID)) {
            test = 1;
        }
        else {
            test = 2;
        }
        Log.d(TAG, "Test2 = " + test);
   }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException(); // Don't ignore errors
    }
});

Log.d(TAG, "Test = " + test);

Now you'll first see:

Test = 0

And then once the data has loaded and onDataChange gets called:

Test = 1

or

Test = 2

For this reason you should always put (or call) the code that needs the data from the database from within onDataChange().

like image 90
Frank van Puffelen Avatar answered Dec 27 '22 02:12

Frank van Puffelen