Android Firebase addListenerForSingleValueEvent is not working

Viewed 5835

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

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

Good lord, I spent a few minutes here. I turned out I created the database in the firebase console AFTER downloading the google-services.json.

You have to download again google-services.json from the project config and this time will have the right reference to the database

Then clean project, uninstall and install the app to make sure the new config file is shipped.

"project_info": { "project_number": "596410010449", "firebase_url": "https://yourname.europe-west1.firebasedatabase.app",

Related