我有一个firebase数据库,结构如下:
rides{
A{
//related datas for a
}
B{
//related datas for b
}}
所以主要问题是我想得到节点A和B的所有值。我可以使用以下命令获取单个节点的值:
final Firebase ridesDateRef = ref.child("A");
// Attach an listener to read the data at our posts reference
ridesDateRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
System.out.println(snapshot.getValue());
availableRidesList = new ArrayList<>();
System.out.println("There are " + snapshot.getChildrenCount() + " rides");
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
AvailableRidesFirebaseObject rides = postSnapshot.getValue(AvailableRidesFirebaseObject.class);
AvailableRidesFirebaseObject availableRidesFirebaseObject = new AvailableRidesFirebaseObject();
availableRidesFirebaseObject.setAdded_on(rides.getAdded_on());
availableRidesFirebaseObject.setCode(rides.getCode());
availableRidesFirebaseObject.setDate_of_ride(rides.getDate_of_ride());
availableRidesFirebaseObject.setDropoff_location(rides.getDropoff_location());
availableRidesFirebaseObject.setDropoff_coordinate(rides.getDropoff_coordinate());
availableRidesFirebaseObject.setFullname(rides.getFullname());
availableRidesFirebaseObject.setOffered_by(rides.getOffered_by());
availableRidesFirebaseObject.setPickup_location(rides.getPickup_location());
availableRidesFirebaseObject.setPickup_coordinate(rides.getPickup_coordinate());
availableRidesFirebaseObject.setSeats(rides.getSeats());
availableRidesFirebaseObject.setShare(rides.getShare());
availableRidesFirebaseObject.setVechile_type(rides.getVechile_type());
availableRidesList.add(availableRidesFirebaseObject);
System.out.println(rides.getSeats());
}
try{
AvailableRidesListAdapter adapter = new AvailableRidesListAdapter(getActivity(), R.layout.single_available_ride, availableRidesList);
availableRideList.setAdapter(adapter);
loading.setVisibility(View.GONE);
}catch(NullPointerException ne){}
}
@Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
我正在获得单一价值,但我想获得所有数据值。我怎么能得到它?
答案 0 :(得分:5)
只需在树中高出一层并添加一个额外的循环:
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot topSnapshot) {
for (DataSnapshot snapshot: topSnapshot.getChildren()) {
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
AvailableRidesFirebaseObject rides = postSnapshot.getValue(AvailableRidesFirebaseObject.class);
AvailableRidesFirebaseObject availableRidesFirebaseObject = new AvailableRidesFirebaseObject();
availableRidesFirebaseObject.setAdded_on(rides.getAdded_on());
availableRidesFirebaseObject.setCode(rides.getCode());
availableRidesFirebaseObject.setDate_of_ride(rides.getDate_of_ride());
availableRidesFirebaseObject.setDropoff_location(rides.getDropoff_location());
availableRidesFirebaseObject.setDropoff_coordinate(rides.getDropoff_coordinate());
// rest of the code left out for brevity