My Database Image from Firebase
我想检索Dosa和Dosa2并将其放入TextView。 下面是我尝试的代码,但我只能检索Dosa2。
mMessagesDatabaseReference = mFirebaseDatabase.getReference("messages");
// Attach a listener to read the data at our posts reference
mMessagesDatabaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
Food food = postSnapshot.getValue(Food.class);
foodnameTextView.setText(food.getFoodname()+"\n");
}}
@Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
答案 0 :(得分:1)
因为你每次都在循环中设置textview。这样做: 在顶部初始化变量并将文本追加到循环中,而不是将其设置为textview
mMessagesDatabaseReference = mFirebaseDatabase.getReference("messages");
// Attach a listener to read the data at our posts reference
String foodName="";
mMessagesDatabaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
Food food = postSnapshot.getValue(Food.class);
foodName+=food.getFoodname()+"\n";
}
foodnameTextView.setText(foodName);
}
@Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});