Skip to content Skip to sidebar Skip to footer

How To Use A Value Outside Datasnapshot Function?

In the code below i get the number of children but i want to use it outside the onDataChange method. mRef.addValueEventListener(new ValueEventListener() {

Solution 1:

Data is loaded from Firebase asynchronously. Your main code continues to run while the data is loading, and then when the data is available the onDataChange method is called. What that means is easiest to see if you add a few log statements:

Log.d("TAG", "Before attaching listener");
mRef.addValueEventListener(newValueEventListener() {
    @OverridepublicvoidonDataChange(DataSnapshot dataSnapshot)
    {
        Log.d("TAG", "Got data");
    }

    @OverridepublicvoidonCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
});
Log.d("TAG", "After attaching listener");

When you run this code, it logs:

Before attaching listener

After attaching listener

Got data

This is probably not the order you expected, but is completely normal when calling asynchronous APIs. And it explains why you'll get the wrong value if you print it outside of the onDataChange().

The problem is not that you can't use the data outside of the onDataChange(), the problem is that you must ensure that onDataChange() has run before you use the data.

The simplest way to do that is to put all code that requires data from the database inside the onDataChange method. But you can also create your own callback interface, and pass that into the method where you load the data. For an example of both of these approaches, see my answer here: getContactsFromFirebase() method return an empty list

Post a Comment for "How To Use A Value Outside Datasnapshot Function?"