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:
I don't know why but the variable "test" always return value 0, which means addListenerForSingleValueEvent didn't work. Thanks for helping in advanced
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With