Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting values out of java callbacks

Tags:

java

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;
}
like image 237
christophmccann Avatar asked Oct 13 '22 20:10

christophmccann


2 Answers

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;
}
like image 168
dacwe Avatar answered Nov 14 '22 00:11

dacwe


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)

like image 20
Bozho Avatar answered Nov 13 '22 22:11

Bozho