gpt4 book ai didi

android - Firebase 值事件监听器

转载 作者:行者123 更新时间:2023-12-05 00:17:12 28 4
gpt4 key购买 nike

我想从 Firebase 数据库读取值并在 ListView 中显示。但出了点问题。它没有给出正确的值。这是代码:

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。我该怎么办?

最佳答案

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);
}
...
}

希望这有帮助

关于android - Firebase 值事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42986449/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com