我试图将我的firebase数据库的所有子项存储到数组列表中 . 这是我的数据库结构:
我目前正在尝试循环遍历子项,以获得我需要的值,如下所示:
private void initializeData(int Destination) {
listItems = new ArrayList<>();
DatabaseReference MyRef = FirebaseDatabase.getInstance().getReference("rideShare");
switch (Destination) {
case 0:
Toast.makeText(getActivity(), "LA BUNDLE", Toast.LENGTH_SHORT).show();
MyRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
String NameValue = snapshot.child("Name").getValue(String.class);
String Price = snapshot.child("Price").getValue(String.class);
String Type = snapshot.child("Trip Type").getValue(String.class);
String Date = snapshot.child("Date").getValue(String.class);
String Destination = "LA";
String Phone = snapshot.child("Phone Number").getValue(String.class);
listingItem newItem = new listingItem(NameValue, Type, Price, Date, Destination, Phone);
listItems.add(newItem);
}
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
//Log.w(TAG , "Failed to read value.",error.toException());
}
});
break;
}
}
2 回答
将所有字符串变量添加到POJO类中,并将变量命名为与子节点键相同的变量 . 请直接使用
snapshot.get(listingItem.class)
. 请参阅https://stackoverflow.com/a/39861649/3860386要获取这些值,请使用以下代码:
在编写Java代码时,最好使用Java Naming conventions . 我相应地添加了这段代码 .
另外,正如您所见,我已经在
onDataChange()
方法中添加了listItems
的声明,否则由于此方法的异步行为,它将会被null
.