2010-12-05 79 views
4

我有一種方法將地址轉換爲經度/緯度。 LatLng是Google Maps API類,LonLat是我自己定製的util類。從java回調中獲取值

以下不會工作,因爲我不能在回調方法中設置變量座標。我不確定我是如何獲得價值的。這可能很簡單,但它令我困惑。

在此先感謝。

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; 
} 

回答

1

只需將結果保存在回調對象的私人領域,使它可以通過吸氣劑進入。

但由於這些回調是異步的,所以不能期望該值立即被提取。所以你必須重新構造你的邏輯 - 而不是返回coords並在調用者中處理它,不返回任何內容,並將結果傳遞給將處理它的新代碼(或直接在回調中處理它)。

4

如果你想要得到的結果直接你這是怎麼等待使用waitnotify結果:

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; 
} 
+0

什麼是我的回答錯了嗎?我需要知道 - 不要只是低估我! :( – dacwe 2010-12-05 21:51:02

+0

它不是我,但我猜downvote是因爲它不需要同步。回調類被傳遞到一個設施,該設施可以處理線程問題。 – Bozho 2010-12-05 22:08:45