使用orderByChild查询从Firebase获取数据 [英] Getting data from Firebase using orderByChild query
本文介绍了使用orderByChild查询从Firebase获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串stationName,我想根据我提供的stationName从FireBase获取距离. 这是我的Firebase数据库:
I have a String stationName and I want to fetch distance from FireBase according to the stationName I provided. Here is my Firebase Database:
我正在使用orderByChild查询来过滤结果,我只需要获取距离值.这是我的代码:
I am using orderByChild query to filter result and I need fetch only the distance value. Here is my code:
Query query = FirebaseDatabase.getInstance().getReference("Stations").orderByChild("Name").limitToFirst(1).equalTo(sourceName);
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String distance;
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
distance = dataSnapshot.child("Distance").getValue(String.class);
tt.setText(distance); //to check if it is working or not
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
我需要知道代码有什么问题.它没有返回任何值. 预先感谢
I need to know what is wrong with code. It's not returning any value. Thanks in advance
推荐答案
替换此
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
distance = dataSnapshot.child("Distance").getValue(String.class);
tt.setText(distance); //to check if it is working or not
}
有了这个
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
distance = snapshot.child("Distance").getValue().toString(); // you
//cannot pass the String.class as in the getValue() parameters becasue a long value
//can not be cast to class object so you need to call toString() method to convert long value
//into the string value.
tt.setText(distance); //to check if it is working or not
}
希望有帮助
这篇关于使用orderByChild查询从Firebase获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文