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