我正在尝试从geoquery中检索值。这些值将添加到地图中,但是当我返回值时,地图为空。
这里myPosition
是我的位置Latlng值我正在使用的位置。
我编辑了这个问题,但问题仍然是地图仍然是空的
private Map<String, GeoLocation> geoMap;
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view= inflater.inflate
(R.layout.fragment_new_search2, container, false);
geoMap= new HashMap<>();
readdata(new MyCallback() {
@Override
public void onCallback(Map<String,
GeoLocation> geomap) {
// int size = geomap.size();
}
});
int size = geoMap.size();
Toast.makeText(getContext(),
String.valueOf(size), Toast.LENGTH_SHORT).show();
return view;
}
private void readdata(final MyCallback myCallback){
DatabaseReference ref =
FirebaseDatabase.getInstance().getReference()
.child("WorkLocation");
GeoFire geoFire = new GeoFire(ref);
GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(myPosition.latitude, myPosition.longitude), 2);
geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
@Override
public void onKeyEntered(String key, GeoLocation location) {
geoMap.put(key,location);
}
@Override
public void onKeyExited(String key) {
}
@Override
public void onKeyMoved(String key, GeoLocation location) {
}
@Override
public void onGeoQueryReady() {
}
@Override
public void onGeoQueryError(DatabaseError error) {
}
});
myCallback.onCallback(geoMap);
}
public interface MyCallback {
void onCallback(Map<String, GeoLocation> geomap);
}
我在onkeyentered
内尝试了一个toast值,但是它们正在添加但是仍然没有返回到方法,并且地图的大小仍为零。
答案 0 :(得分:0)
所有需要加载数据的代码必须在on...
方法内部(或从内部调用)。所以:
DatabaseReference ref =
FirebaseDatabase.getInstance().getReference()
.child("WorkLocation");
GeoFire geoFire = new GeoFire(ref);
GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(myPosition.latitude, myPosition.longitude), 2);
geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
@Override
public void onKeyEntered(String key, GeoLocation location) {
geoMap.put(key,location);
myCallback.onCallback(geoMap);
}
@Override
public void onKeyExited(String key) { }
@Override
public void onKeyMoved(String key, GeoLocation location) { }
@Override
public void onGeoQueryReady() { }
@Override
public void onGeoQueryError(DatabaseError error) { }
});
}
如果您只希望在通过Geofire加载所有初始密钥后调用onCallback
,请将其放入onGeoQueryReady
:
DatabaseReference ref =
FirebaseDatabase.getInstance().getReference()
.child("WorkLocation");
GeoFire geoFire = new GeoFire(ref);
GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(myPosition.latitude, myPosition.longitude), 2);
geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
@Override
public void onKeyEntered(String key, GeoLocation location) {
geoMap.put(key,location);
}
@Override
public void onKeyExited(String key) { }
@Override
public void onKeyMoved(String key, GeoLocation location) { }
@Override
public void onGeoQueryReady() {
myCallback.onCallback(geoMap);
}
@Override
public void onGeoQueryError(DatabaseError error) { }
});
}