How to run a method when query is finishing?

1.2k Views Asked by At

I am using Firebase. My problem is, while i'm querying objects and then modifying them, my main ui thread goes ahead and runs the next methods. I want my main ui thread to wait until my firebase query is finished and I made all the necessary changes in onDataChange AND THEN continue to run my other functions i written.

Currently, I just imported the external library "Otto" but im not sure how to use it and I was hoping someone can help guide me.

                Firebase cardReference = mRef.child("reference");
                cardReference.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                    //DO STUFF
                    }
                    @Override
                    public void onCancelled(FirebaseError firebaseError) {

                    }
                });
               //Once STUFF is done, run nextMethod()
               nextMethod();
        }
1

There are 1 best solutions below

0
Frank van Puffelen On

Firebase reads the data from the database asynchronously. There is no way to make your app wait, without showing an "Application Not Responding" to your users.

Instead you need to reframe your logic. Instead of saying "first load the reference, then do the next method", change it to "start loading the reference, when that is done do the next method". In code that translates to:

Firebase cardReference = mRef.child("reference");
cardReference.addValueEventListener(new ValueEventListener() {
    public void onDataChange(DataSnapshot dataSnapshot) {
        // Whenever STUFF is done, run nextMethod()
        nextMethod();
    }
    public void onCancelled(FirebaseError firebaseError) {
        throw firebaseError.toException();
    }
});

The added advantage of this approach is that nextMethod() will now also be called whenever the reference data changes. Updating your UI in such a case is one of the special effects that your users will appreciate once they notice.

For some more information, also read these: