OnCompleteListener is not called for .setValue in RealtimeDatabase

可紊 提交于 2019-12-25 11:26:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!