我想从Firebase数据库中读取值并在ListView中显示。但出了点问题。它没有给出正确的值。这是代码:
爪哇
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
。我该怎么办?
答案 0 :(得分:2)
Egek92's answer是对的。我想我知道它为什么不提供你想要的数据。也许使用以下代码,您将:
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);
}
...
}
希望这有帮助
答案 1 :(得分:1)
尝试:
DatabaseReference reference = database.getReference("Stats").child("Matematik");