问题
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
}
}
Result is Matematik, {ahmetozrahat=50, nihatkeklik=50} but I want: ahmetozrahat25: 50, nihatkeklik: 50. What should I do?
回答1:
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);
}
...
}
Hope this helps
回答2:
Try:
DatabaseReference reference = database.getReference("Stats").child("Matematik");
来源:https://stackoverflow.com/questions/42986449/firebase-value-event-listener