我正在使用 Firebase 查询附近的位置,当我执行 systemPrint 时结果是正确的。但是当我尝试创建一个新的 Location 项并将其放入全局声明的 arrayList 时,然后循环遍历 ArrayList 以打印它。它不打印。我尝试了与哈希集类似的方法,我在其中声明了一个全局哈希集,并尝试向其中添加 id 和地理位置,然后循环遍历它,它没有打印出来。
这是我执行 systemPrint 时的打印输出:
03-05 21:42:16.225 12604-12604/? I/System.out: aa6b6c55-40da-416e-bbc0-626f10d2db80 51.02878131 -114.13542057
03-05 21:42:16.262 12604-12604/? I/System.out: 1f682c8b-be9a-4310-aa92-216f041f0547 51.02933723 -114.13514678
03-05 21:42:16.262 12604-12604/? I/System.out: 707a5af3-8fa0-4f69-b88f-593a0acd3ee8 51.02933723 -114.13514678
我全局设置了这个arrayList
List<Locations> locationList;
in onCreate(){
......
locationList = new ArrayList<>();
......
}
geoFire = new GeoFire(new Firebase("https://xyz.firebaseio.com/locations/"));
GeoLocation center = new GeoLocation(location.getLatitude(), location.getLongitude());
final HashSet hs = new HashSet();
GeoQuery geoQuery = geoFire.queryAtLocation(center, 5);
geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
@Override
public void onKeyEntered(String username, GeoLocation location) {
System.out.println(username + location.latitude + location.longitude);
Locations eachLocation = new Locations();
eachLocation.setId(username);
eachLocation.setLatitude(String.valueOf(location.latitude));
eachLocation.setLongitude(String.valueOf(location.longitude));
locationList.add(eachLocation);
//
// }
}
@Override
public void onKeyExited(String username) {
usersNearby.remove(username);
// additional code, like removing a pin from the map
// and removing any Firebase listener for this user
}
@Override
public void onKeyMoved(String s, GeoLocation geoLocation) {
}
@Override
public void onGeoQueryReady() {
}
@Override
public void onGeoQueryError(FirebaseError firebaseError) {
}
});
for (Locations x: locationList){
Log.i("eachLocation", x.getId() + x.getLatitude() + x.getLongitude());
}
System.out.println(hs);
这是我的位置类
public class Locations {
String id;
String latitude;
String longitude;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
}
*****更新 - 我还注意到另一种模式,我无法在另一个 Firebase 查询中执行功能****
我声明了一个全局 userCountry 变量 userCountry,然后我运行查询以获取保存的用户所在的国家/地区。在函数内部,它记录得很好。但是,当我尝试将国家/地区值设置为 userCountry 并将其记录在查询之外时,我的应用程序崩溃并出现 NullPointerException 错误。我需要全局设置 userCountry,以便我可以将其作为参数输入到另一个查询中。
String userCountry;
ref = new Firebase("https://xyzChat.firebaseio.com/users/" + intent.getStringExtra("userId") + "/country");
Query queryRef = ref.orderByChild("country");
queryRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i("userCountry", String.valueOf(dataSnapshot.getValue()));
userCountry = String.valueOf(dataSnapshot.getValue());
}
Log.i("secondUserCountry", userCountry);