我想在Firebase数据库中的“ clothing”引用下获取所有firebase节点。为此,我将ChildEventListener附加到引用上,并在onChildAdded回调中将Clothing对象添加到服装对象列表中,假设onChildAdded回调被称为在以下对象中存在节点的次数。 《服装》参考。

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());
    }
    ...
}


这是数据库结构:

-->root
---->clothing
------>clothing_id
-------->title
-------->category
-------->img_download_url
------>clothing_id_1
-------->title
-------->...


我需要将所有节点都放在服装节点下。

我的数据库安全规则当前为:

{
  "rules": {
    ".read": "auth == null",
    ".write": "auth != null"
  }
}


调用包含此代码的方法时,不会使用onChildAdded回调,而是onCancelled回调将具有权限被拒绝的数据库错误。为什么会这样呢?

最佳答案

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

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

09-16 21:12