首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么没有调用Firebase onChildAdded?

为什么没有调用Firebase onChildAdded?
EN

Stack Overflow用户
提问于 2017-12-18 21:55:40
回答 2查看 974关注 0票数 1

我想在我的firebase数据库中获取"clothing“引用下的所有firebase节点。为此,我将ChildEventListener附加到引用,并在onChildAdded回调中将Clothing对象添加到clothing对象列表中,假设调用onChildAdded回调的次数等于"clothing“引用下存在节点的次数。

代码语言:javascript
复制
mClothingRef = FirebaseDatabase.getInstance()
                               .getReference()
                               .child("clothing");
final List<Clothing> clothingItems = new ArrayList<>();

mClothingRef.addChildEventListener(new ChildEventListener() {
    public void onChildAdded(DataSnapshot snapshot, String s) {
        Clothing clothing = snapshot.getValue(Clothing.class);
        clothingItems.add(clothing);
        Log.d(TAG, "onChildAdded called");      
    }
    public void onCancelled(DatabaseError databaseError) {
        Log.e(TAG, databaseError.getMessage() + " " + 
        databaseError.getCode() + " " + databaseError.getDetails()  + " " + databaseError.toString());
        mEventBus.post(new ListClothingFailEvent());
    }
    ...
}

下面是数据库结构:

代码语言:javascript
复制
-->root
---->clothing
------>clothing_id
-------->title
-------->category
-------->img_download_url
------>clothing_id_1
-------->title
-------->...

我需要获取clothing节点下的所有节点。

我的数据库安全规则目前是:

代码语言:javascript
复制
{
  "rules": {
    ".read": "auth == null",
    ".write": "auth != null"
  }
}

调用包含此代码的方法时,不会调用onChildAdded回调,相反,onCancelled回调会出现权限被拒绝的数据库错误。为什么会这样呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-12-18 22:47:07

要显示该数据,请使用以下代码:

代码语言:javascript
复制
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference clothingRef = rootRef.child("clothing");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<Clothing> clothingItems = new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            Clothing clothing = snapshot.getValue(Clothing.class);
            clothingItems.add(clothing);
        }
        Log.d("TAG", clothingItems);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
clothingRef.addListenerForSingleValueEvent(eventListener);
票数 1
EN

Stack Overflow用户

发布于 2017-12-18 22:56:28

每当在任何节点中发生添加/删除/修改的更改时,我们都应该使用onChildChanged回调方法而不是添加。在此方法中,我们获得了具有新的所需数据的DataSnapshot实例。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47869990

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档