我如何从数据库中获取所有孩子?
此代码获取第一个元素,我如何获得Element_2,3和连续?我所做的最好的是序列化第一个国家并打印出来。
我的数据库:
{
"Capitals" : {
"Country_1" : {
"Country" : "Macedonia",
"Capital" : "Skopje"
},
"Country_2" : {
"Country" : "Madagascar",
"Capital" : "Antananarivo"
},
"Country_3" : {
"Country" : "Malawi",
"Capital" : "Lilongwe"
}
}
我的代码
@Override
public void onStart(){
super.onStart();
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference capitalsRef = database.getReference("Capitals");
compresoresRef.orderByChild("Ref").addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
countryModel cm = dataSnapshot.getValue(countryModel.class);
String country = cm.getCountry();
String capital= cm.getCapital();
textData1.setText(country);
textData2.setText(capital);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
执行时的 dataSnapshot 如下所示:
DataSnapshot { key =Country_1, value = {Country=Macedonia, Capital=Skopje} }
答案 0 :(得分:3)
您应该使用ArrayList
来存储使用addChildEventListener
ArrayList<countryModel> countryList = new ArrayList<countryModel)();
compresoresRef.orderByChild("Ref").addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
countryModel cm = dataSnapshot.getValue(countryModel.class);
countryList.add(cm);
...
}
}
或使用addValueEventListener
检索数据时,它看起来像
compresoresRef.addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot snapshot) {
countryList.clear();
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
countryModel cm = postSnapshot.getValue(countryModel.class);
countryList.add(cm);
}
}
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
答案 1 :(得分:1)
试试这个
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for(DataSnapshot post:dataSnapshot.getChildren())
{
countryModel countryModel cm = post.getValue(countryModel.class);
}
}