2017-12-18 438 views
1

我想要在我的firebase数据库中的“服装”参考下获取所有firebase节点。要做到这一点,我附上ChildEventListener到基准并在onChildAdded回调我的Clothing对象添加到衣服对象的列表,假设onChildAdded回调被调用的次数也有在“衣”参考节点。为什么Firebase 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回调是一个权限被拒绝的数据库错误。为什么会这样?

+0

当我添加该行上会被忽略,因为该行没有被调用一个破发点。根据调试器的服装节点的参考url是:https://good-deal-9a0b2.firebaseio.com/clothing看起来正确 –

+0

@TomFinet你能分享你的完整活动代码吗? – mark922

+0

此代码不在活动中,但是它使用'mCatalogRepository.loadClothing()'从活动中调用。我会将其添加到问题中。 –

回答

1

要显示的数据,请使用如下代码:

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

记得在'onDataChange()'方法内声明和使用'ArrayList',否则它将是'null'。 –

+0

你有没有试过我的上面的代码? –

+0

这个问题似乎是,我与我的两个方法和你的方法@Alex马莫 –

0

每当有更改添加/删除/任何节点修改,我们应该使用onChildChanged回调方法,而不是增加。在这种方法中,我们得到DataSnapshot的实例,它具有所需的新数据。

相关问题