我有一个字符串stationName,我想根据我提供的stationName从FireBase获取距离。 这是我的Firebase数据库:
我正在使用orderByChild查询来过滤结果,我只需要获取距离值。这是我的代码:
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) {
}
});
我需要知道代码有什么问题。它没有返回任何值。 预先感谢
答案 0 :(得分:0)
替换此
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
}
希望有帮助