如何在有两个孩子的事件文件夹中检索数据? 我是android studio的新手...
示例代码如下:
database = FirebaseDatabase.getInstance();
ref = database.getReference("Event");
list = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this,R.layout.event_info,R.id.eventTitle,list);
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren())
{
eventInfo = ds.getValue(EventInfo.class);
list.add(eventInfo.getTitle() + " \n " + eventInfo.getAddress() +
" \n " + eventInfo.getDescription() + " \n " + eventInfo.getImgURL() +
" \n " + eventInfo.getLatitude() + " \n " + eventInfo.getLongitude());
}
listView.setAdapter(adapter);
}
答案 0 :(得分:0)
当您遍历DataSnapshot.getChildren()
时,每个孩子本身都是DataSnapshot
。因此,您也可以遍历那个孩子的孩子。由于JSON中有两个动态级别,因此您的代码中需要两个嵌套循环:
ref = FirebaseDatabase.getInstance().getReference("Event");
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
for(DataSnapshot eventSnapshot: userSnapshot.getChildren()) {
eventInfo = eventSnapshot.getValue(EventInfo.class);
Log.d("Event", eventSnapshot.getKey());
Log.d("Event", eventSnapshot.child("title").getValue(String.class));
}
}
}
...