我在迭代dataSnapshot时遇到了麻烦。当我调试代码时,我可以看到dataSnapshot的大小为2,它包含正确的键/值对。但似乎它似乎并没有将键/值对看作是孩子,我猜。
//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;
}
因此,当代码到达for (DataSnapshot ds : dataSnapshot.getChildren())
时,它就直接进入排序代码,并且航天器arraylist为空。所以dataSnapshot.getChildren
是空的。
我尝试删除for循环并只处理第一个&#34;记录&#34;在dataSnapshot中它处理正常。有谁知道为什么会发生这种情况以及我能做些什么呢?
编辑:解决方案
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;
}