I am having trouble iterating through a dataSnapshot. When I debug the code, I can see that the dataSnapshot has a size of 2 and it contains the correct key / value pairs. But it seems as if it doesn't see the key / value pairs as children, I guess.
//IMPLEMENT FETCH DATA AND FILL ARRAYLIST
private void fetchData(DataSnapshot dataSnapshot) {
spacecrafts.clear();
//for (DataSnapshot ds : dataSnapshot.getChildren())
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Spacecraft spacecraft = new Spacecraft();
try {
spacecraft.setLevel(Integer.parseInt(ds.getKey()));
} catch (NumberFormatException ex) {
System.out.println("Could not parse " + ex);
}
long v = (long) ds.getValue();
spacecraft.setNumCorrect(v);
//Spacecraft spacecraft=ds.getValue(Spacecraft.class);
spacecrafts.add(spacecraft);
}
Collections.sort(spacecrafts, new Comparator<Spacecraft>() {
@Override
public int compare(Spacecraft spacecraft, Spacecraft t1) {
return Integer.valueOf(spacecraft.getLevel()).compareTo(t1.getLevel()); // To compare integer values
}
});
}
//RETRIEVE
public ArrayList<Spacecraft> retrieve() {
String myUserId = acct.getId();
DatabaseReference LevelsRef = db.child("levels/uid/").child(myUserId);
Query queryRef = LevelsRef;
queryRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//fetchData(dataSnapshot);
fetchData(dataSnapshot);
adapter.notifyDataSetChanged();
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
return spacecrafts;
}
So when the code gets to the for (DataSnapshot ds : dataSnapshot.getChildren())
, it just goes right to the sort code and the spacecrafts arraylist is empty. So dataSnapshot.getChildren
is empty.
I tried removing the for loop and just processing the first "Record" in the dataSnapshot and it processes fine. Does anyone have any idea why this is happening and what I can do about it?
Edit: The solution
public ArrayList<Spacecraft> retrieve() {
String myUserId = acct.getId();
//DatabaseReference LevelsRef = db.child("levels/uid/" + myUserId + "/");
DatabaseReference LevelsRef = db.child("levels/uid/");
Query queryRef = LevelsRef.orderByChild(myUserId);
queryRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//fetchData(dataSnapshot);
fetchData(dataSnapshot);
adapter.notifyDataSetChanged();
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
return spacecrafts;
}