我怎样才能得到每个孩子? Firebase getValue [android]
问题描述:
我怎么能从我的数据库中获取所有孩子?我怎样才能得到每个孩子? Firebase getValue [android]
此代码获得第一个元素,我如何获得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} }
答
你应该使用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
用于检索数据,如果使用ArrayList
店面,你从火力地堡获得所有孩子的,它看起来像
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());
}
});
答
试试这个
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for(DataSnapshot post:dataSnapshot.getChildren())
{
countryModel countryModel cm = post.getValue(countryModel.class);
}
}