Firebase Value事件侦听器 [英] Firebase Value Event Listener
本文介绍了Firebase Value事件侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从Firebase数据库中读取值并显示在ListView中.但是出了点问题.它没有给出正确的值.这是代码:
I want to read the values from Firebase Database and show in a ListView. But something gone wrong. It's not giving correct values. Here is the code:
Java
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference reference = database.getReference("Stats").child(ders);
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
stats.put(dataSnapshot.getKey(), dataSnapshot.getValue().toString());
StatsAdapter adapter = new StatsAdapter(stats);
listView.setAdapter(adapter);
}
@Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
startActivity(new Intent(StatsActivity.this, DerslerListActivity.class));
}
});
JSON
"Stats" : {
"Matematik" : {
"ahmetozrahat25" : "50",
"nihatkeklik" : 50
},
"Türkçe" : {
"abdullah" : 98,
"ahmetozrahat25" : "0",
"banuozrht" : 95,
"nihatkeklik" : 60
}
}
结果是Matematik, {ahmetozrahat=50, nihatkeklik=50}
,但我想要:ahmetozrahat25: 50, nihatkeklik: 50
.我该怎么办?
Result is Matematik, {ahmetozrahat=50, nihatkeklik=50}
but I want: ahmetozrahat25: 50, nihatkeklik: 50
. What should I do?
推荐答案
Egek92的答案是正确的.而且我想我知道为什么它不提供您想要的数据.也许使用以下代码,您将:
Egek92's answer is right. And I think I know why it doesn't provide data you want. Maybe with this following code, you will:
DatabaseReference reference = database.getReference("Stats").child("Matematik");
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// dataSnapshot value will be Matematik, {ahmetozrahat=50, nihatkeklik=50}
// because it is indeed the value we need
// But you want key value pair to be added to your stats
// So we can just loop through the values
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
stats.put(childSnapshot.getKey(), childSnapshot.getValue().toString());
}
StatsAdapter adapter = new StatsAdapter(stats);
listView.setAdapter(adapter);
}
...
}
希望这会有所帮助
这篇关于Firebase Value事件侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文