我正在尝试从多个记录中检索嵌套数据,并将其显示在ListView中。我的数据记录如下:
我想显示记录在listView中的所有GroupVaccination的GroupNumber和GroupVaccinationDate,但是现在当我运行以下代码时,listView仍然为空:
git pull
任何帮助或建议将不胜感激!
答案 0 :(得分:1)
您需要更深入一层,其中您的ID -LZk5tpB5PXqHVJkj8Vz
(GroupID)包含其中包含数据的所有子pushKeys(groupVaccinationID)。
listView = (ListView)findViewById(R.id.listItemAllGroupVaccinations);
databaseReference = FirebaseDatabase.getInstance().getReference("groupVaccinations").child("-LZk5tpB5PXqHVJkj8Vz");
groupVaccinations = new ArrayList<>();
protected void onStart(){
super.onStart();
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot groupVaccinationSnapshot : dataSnapshot.getChildren()){
GroupVaccination groupVaccination = groupVaccinationSnapshot.getValue(GroupVaccination.class);
groupVaccinations.add(groupVaccination);
}
AllGroupVaccinationList groupVaccinationInfoAdapter = new AllGroupVaccinationList(ActivityAllGroupVaccinations.this, groupVaccinations);
listView.setAdapter(groupVaccinationInfoAdapter);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
应避免使用-LZk5tpB5PXqHVJkj8Vz
子级,因为已对其进行了硬编码以向您显示此示例,相反,您应该从获取您的 GroupID 的位置获取该子级密钥,从而可以得到弗兰克说每个 GroupID 的所有疫苗。
答案 1 :(得分:1)
Gaston的答案将向您显示所有疫苗分组。相反,如果您想显示所有组中的所有疫苗,则可以遍历onDataChange
中的嵌套快照:
databaseReference = FirebaseDatabase.getInstance().getReference("groupVaccinations");
groupVaccinations = new ArrayList<>();
AllGroupVaccinationList groupVaccinationInfoAdapter = new AllGroupVaccinationList(ActivityAllGroupVaccinations.this, groupVaccinations);
listView.setAdapter(groupVaccinationInfoAdapter);
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot groupVaccinationSnapshot : dataSnapshot.getChildren()){
for(DataSnapshot vaccinationSnapshot : groupVaccinationSnapshot.getChildren()){
GroupVaccination groupVaccination = vaccinationSnapshot.getValue(GroupVaccination.class);
groupVaccinations.add(groupVaccination);
}
}
groupVaccinationInfoAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
我还更改了代码以调用groupVaccinationInfoAdapter.notifyDataSetChanged()
,以便您可以继续使用相同的适配器并在需要时进行更新。