【问题标题】:What can I do instead of waiting for FirebaseDatabase data?除了等待 FirebaseDatabase 数据,我还能做什么?
【发布时间】:2016-12-23 18:37:25
【问题描述】:

我的 FirebaseDatabase 有问题。我想从数据库参考中读取孩子的数量。我想这样做5次。因此,如果此日期没有用户,我创建了 5 个 SingleEventListeners 并设置了值。 (我希望你明白,我想做什么:D)

while (counter<5) { 

            ... We create a new date and username here. We have to do this 5 times

            myRef.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                if (!(dataSnapshot.child(finalDate).hasChild(username)))
                      myRef.child(finalDate).child(username).setValue(true);
                }
                @Override
                public void onCancelled(DatabaseError databaseError) {
                }
            });
            counter++;
        }
            try { //TODO Synchronisation is not given without that block
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

   ...
   ...
   ...



myRef.child(chosenDate).child(username).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            participate.setChecked((Boolean) dataSnapshot.getValue());
        }

如果我们不等待接收日期,我们会得到一个 Nullpointer 异常。 我能做什么来代替使用 sleep(),这真的很糟糕:(

【问题讨论】:

    标签: java firebase firebase-realtime-database listener


    【解决方案1】:

    Thread.sleep() 几乎不是您想要的解决方案。在这种情况下,由于您知道要加载的项目数量,因此您可以只计算已加载(或肯定加载失败)的项目数量:

    myRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
        if (!(dataSnapshot.child(finalDate).hasChild(username)))
            myRef.child(finalDate).child(username).setValue(true);
            counter++;
            if (counter == 5) {
                // TODO: whatever you want to do after all items have loaded
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            counter++;
            if (counter == 5) {
                // TODO: whatever you want to do after all items have loaded
            }
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2021-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-26
      相关资源
      最近更新 更多