According to the documentation, we should avoid nesting data when it comes to database relationships. So I structured my data as follow:
{
"rides": {
"ride1": {
"price": "500",
"bids": {
// the value here doesn't matter, just that the key exists
"bid1": true,
"bid2": true
}
},
...
},
"bids": {
"bid1": {
"price": "550",
"ride": "ride1"
},
...
}
}
In one page of my app, the user should be able to see all "bids" that are linked to the selected "ride" in a ListView. My attempt was: Getting the keys of the bids in an arrayList and then fetching the bids by key on by one. My problem is the fact that I have to display all the bids in a listview at once.
bidsListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
ArrayList<String> bidskeysOfActiveRideArrayList = new ArrayList<>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Boolean IsbidLinkedToThisRid = snapshot.getValue(Boolean.class);
if (IsbidLinkedToThisRid) {
String bidObjectId = dataSnapshot.getKey();
bidskeysOfActiveRideArrayList.add(bidObjectId);
}
}
fetchMultipleBidsByKeys(bidskeysOfActiveRideArrayList);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
databaseReference.child("rides").child(ride.getID()).child("bids").addValueEventListener(bidsListener);
The two functions are here:
private void fetchMultipleBidsByKeys(ArrayList<String> bidskeysOfActiveRideArrayList) {
ArrayList<Bid> bidsArrayList = new ArrayList<>();
for (String bid_id:bidskeysOfActiveRideArrayList){
bidsArrayList.add(getBidByKey(bid_id));
}
displayBidList(bidsArrayList);
}
private Bid getBidByKey(String bidObjectId) {
final Bid[] bidFetched = {null};
ValueEventListener bidsSingleFetcher = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
bidFetched[0] = snapshot.getValue(Bid.class);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
databaseReference.child("bids").child(bidObjectId).addListenerForSingleValueEvent(bidsSingleFetcher);
return bidFetched[0];
}
However, firebase data fetch is asyncronuous. So what is the correct way of fetching elements by a list of IDs then displaying them on a listview?