本文介绍了在RealtimeDatabase中未为.setValue调用OnCompleteListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在尝试将数据保存到Firebase实时数据库.我只想保存数据

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);

,这很好用.该对象将出现在控制台中,并且一切正常.但是我想知道是否有一个更平滑的实现,所以我尝试使用 OnCompleteListener 并得出以下代码:

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 OnCompleteListenerand 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());

同样,数据已成功写入数据库,但是 onCompleteListener 根本没有被调用,因此 while 循环不会中断.

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.

为什么不调用侦听器?我也进行了其他设置(没有 while -loop),但是这些设置也不起作用.

Why isn't the Listener called? I did other setups as well (without the while-loop), but those didn't work either.

谢谢.

推荐答案

以我的经验,紧密循环(您拥有的 while 循环)将阻塞主线程并阻止Firebase调用onComplete (这也发生在主线程上.

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.

为防止阻塞,请使用 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);

也请在此处查看我的答案在Firebase Listener中设置Singleton属性值

Also see my answer here Setting Singleton property value in Firebase Listener

这篇关于在RealtimeDatabase中未为.setValue调用OnCompleteListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 00:24