Firebase数据库中仅显示最后一个元素 [英] Only the last element is shown in Firebase database
问题描述
我在Firebase中有一个示例数据库,旨在显示一些事实.当前,我希望textview显示所有五个示例事实1,2,3,4,5 ..,但仅显示最后一个.我应该在哪里修改我的代码?
I have a sample database in Firebase that is meant to display some facts. Currently, I want the textview to display all the five sample facts 1,2,3,4,5..but it shows only the last one. Where should I modify on my code?
Java示例:
fact = database.getInstance().getReference().child("Facts");
fact.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
Fact factdata = postSnapshot.getValue(Fact.class);
factViewBox.setText(factdata.getFactDetail());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
还有json:
"Facts":{
"01":{
"factDetail":"1"
}
,
"02":{
"factDetail":"2"
}
,
"03":{
"factDetail":"3"
}
,
"04":{
"factDetail":"4"
}
,
"05":{
"factDetail":"5"
}
}
推荐答案
您的代码所做的只是将TextView中的当前文本替换为factdata.getFactDetail()
.
What your code doing is just replacing the current text in the TextView with the factdata.getFactDetail()
.
例如,您有3个元素1、2和3.然后您想要在TextView中显示该元素.使用您的代码,这就是发生的情况
For example you have 3 elements 1, 2, and 3. Then you want to display the element inside the TextView. With your code, this is what happen
第一次迭代:
element = elements[0]; // element = 1
factViewBox.setText(element); // TextView text is "1"
第二次迭代:
element = elements[1]; // element = 2
factViewBox.setText(element); // TextView text is "2"
第三次迭代:
element = elements[2]; // element = 3
factViewBox.setText(element); // TextView text is "3"
因此,您的TextView仅显示最后一个元素/事实详细信息
Therefore, your TextView only displaying the last element/fact detail
这篇关于Firebase数据库中仅显示最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!