android - Firebase ChildEventListener 如果没有检索到数据

标签 android firebase firebase-realtime-database

我在我的应用中使用 Firebase。我有一个要使用此代码检索的元素列表:

FirebaseDatabase.getInstance()
.getReferenceFromUrl("myUrl")
.orderByChild("timestamp")
.addChildEventListener(this);

了解 ref url 中是否没有数据的最佳方法是什么?因为使用 ChildEventListener 是不可能的。

ChildEventListener 只有这 4 个方法:onChildAdded()、onChildChanged()、onChildRemoved()、onChildMoved()

如果您的对象内部没有项目,则不会调用这些方法。

所以我的问题是。我是否也必须使用 ValueEventListener? 我猜 onDataChange() 在没有找到任何项目时被调用。

一个可能的场景: 您有一个要使用 ChildEventListener 检索和填充的项目列表。 您想要涵盖未检索到任何项目的情况。因此,显示文本“无数据”而不是列表。

最佳答案

据我所知,如果您通过 addChildEventListeneraddValueEventListener 在同一数据路径上彼此直接请求数据(在代码中),您将得到结果addChildEventListener先完成,然后执行ValueEventListener中的onDataChange

所以我的解决方案是这样的:

Boolean childExist = false;

ref.addChildEventListener(new ChildEventListener() {
    ... onChildAdded() {
        // you can use List or Map here, this Boolean just to indicate if child exist or not
        childExist = true;
    }
    ...
})
ref.addValueEventListener(new ValueEventListener() {
    ... onDataChange() {
        // code you place here will be executed AFTER all of the event inside ChildEventListener is done
        // here the value of childExist will really indicate if there is child or no
    }
    ...
});

关于android - Firebase ChildEventListener 如果没有检索到数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42670627/

相关文章:

android - SurfaceView 或 TextureView 组合

android - 使用 OnClickListener 在同一 Activity 中的 Facebook Twitter 按钮

node.js - 从 Firebase Admin SDK 过滤用户

java - ListView 不使用 Firebase 查询滚动 "equalTo"

ios - Firebase 实时数据库名称和值

ios - 尝试将用户电子邮件和姓名保存到 Firebase 数据库时出现异常

javascript - 如何从 Firebase 数据库集合中准备键和值

java - 如何使底部工作表对话框的角变圆?

android - ionic 失败 : Build failed with an exception

firebase - 在firestore中高效匹配玩家