我想在我的firebase数据库中获取"clothing“引用下的所有firebase节点。为此,我将ChildEventListener附加到引用,并在onChildAdded回调中将Clothing对象添加到clothing对象列表中,假设调用onChildAdded回调的次数等于"clothing“引用下存在节点的次数。
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
-------->...我需要获取clothing节点下的所有节点。
我的数据库安全规则目前是:
{
"rules": {
".read": "auth == null",
".write": "auth != null"
}
}调用包含此代码的方法时,不会调用onChildAdded回调,相反,onCancelled回调会出现权限被拒绝的数据库错误。为什么会这样呢?
发布于 2017-12-18 22:47:07
要显示该数据,请使用以下代码:
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);发布于 2017-12-18 22:56:28
每当在任何节点中发生添加/删除/修改的更改时,我们都应该使用onChildChanged回调方法而不是添加。在此方法中,我们获得了具有新的所需数据的DataSnapshot实例。
https://stackoverflow.com/questions/47869990
复制相似问题