cpt
cpt

Reputation: 77

Firebase Completion Callback in Java

I want to save data in a RealtimeDatabase via databaseReference.child("someChild").setValue(someObject). For my project I need to wait with the further program until the whole writing-process is finished. The Documentation recommends a CompletionListener. But is there a way to wait until this Listener is fired and finished its work?

I tried various approaches like CountDownLatch.await(), synchronized and Thread.join(), but none of those turned out to be the correct solution. The problem is, that things like CountDownLatch.await() block the Listener, and therefore the listener can't be fired. That of course causes the whole process to stuck.

Is there a different and easy approach to this problem?

I basically have written the code

databaseReference.child("someChild).setValue(someObject, 
new DatabaseReference.CompletionListener() {
    @Override
    public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
        System.out.println("This should be 1st.");
    }
});
System.out.println("This should be 2nd.");

The outputs should be in the correct order, but in reality it looks like that:

OUTPUT:

System.out: This should be 2nd.
System.out: This should be 1st.

I hope, that someone in here can help me.

EDIT

My original plan was something like this:

public static void saveThis(SomeObject someObject) {

databaseReference.child("someChild).setValue(someObject, 
new DatabaseReference.CompletionListener() {
    @Override
    public void onComplete(DatabaseError databaseError, 
DatabaseReference databaseReference) {
        System.out.println("This should be 1st.");
    }
});
System.out.println("This should be 2nd.");
}

The point is, that I want to call the saveThis(someObject)-method from anywhere. Is there a way to do this?

Upvotes: 3

Views: 1676

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

This is happening because of the asynchronous behaviour of onComplete() method which is called even bebore you are trying to print This should be 1st.. This is why you are getting that order in your logcat. There are two approaches to solve this problem.

  1. Everything that you need to achieve must be placed inside the onComplete() method. This means that if you want to use a list for example, both the declaration and the usage must be done inside.

  2. If you want to use some values outside that method, please take a look at my answer from this post. onComplete() has the same behaviour as onDataChange().

Upvotes: 1

Related Questions