I have a method below which converts an address to longtitude/latitude. LatLng is a Google Maps API class and LonLat is my own custom util class.
The below wont work because I cant set the variable coords within the callback method. I am unsure how I get the value out. It is probably very simple but its confusing me.
Thanks in advance.
public LonLat convert(String address) {
LonLat coords;
geocoder.getLatLng(address, new LatLngCallback() {
public void onFailure() {
// TODO Exception handling
}
@Override
public void onSuccess(LatLng point) {
coords = new LonLat(point.getLongitude(), point.getLatitude());
}
});
return coords;
}
If you want to get the result directly this is how you wait for the result using wait
and notify
:
class MyLatLngCallback {
LonLat coords = null;
boolean gotAnswer = false;
public synchronized void onFailure() {
gotAnswer = true;
notify();
}
@Override
public synchronized void onSuccess(LatLng point) {
gotCoords = true;
coords = new LonLat(point.getLongitude(), point.getLatitude());
notify();
}
};
public LonLat convert(String address) {
MyLatLngCallback cb = new MyLatLngCallback();
geocoder.getLatLng(address, cb);
synchronized (cb) {
while (!cb.gotAnswer) // while instead of if due to "spurious wakeups"
cb.wait();
}
// if cb.coords is null then failure!
return cb.coords;
}
Simply store the result in a private field in the callback object, and make it accessible via a getter.
But since these callbacks are asynchronous, you can't expect the value to be fetched immediately. So you must instead restructure your logic - instead of returning the coords and processing it in the caller, return nothing, and pass the result to a new piece of code that will process it (or process it directly in the callback)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With