2017-12-18 243 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的實例,它具有所需的新數據。

相關問題