问题
I am currently trying to save data to a Firebase Realtime-Database. I just simply want to save data with
databaseReference.child("someChild").setValue(someObject);
Thread.sleep(1000);
and this just works fine. The Object appears in the console, and everything works. But I wondered if there was a smoother implementation, so I tried to use OnCompleteListener
and worked out the following code:
final AtomicBoolean done = new AtomicBoolean(false);
databaseReference.child("someChild")
.setValue(someObject)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
System.out.println("completed");
done.set(true);
}
});
while (!done.get());
Again, the data is written successfully to the database, but the onCompleteListener is not called at all and therefore the while-loop isn't interrupted.
Why isn't the Listener called? I did other setups as well (without the while-loop), but those didn't work either.
Thanks in advance.
回答1:
In my experience the tight loop (the while loop you have) will block the main thread and keep Firebase from calling onComplete (which also happens on the main thread.
To prevent the blocking, use something like postDelayed:
final AtomicBoolean done = new AtomicBoolean(false);
databaseReference.child("someChild")
.setValue(someObject)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
System.out.println("completed");
done.set(true);
}
});
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (done.get()) {
... Do the thing that requires the data
}
}
}, 1000);
Also see my answer here Setting Singleton property value in Firebase Listener
来源:https://stackoverflow.com/questions/46513101/oncompletelistener-is-not-called-for-setvalue-in-realtimedatabase