将回调结果存储到变量中

时间:2011-04-18 15:11:43

标签: java gwt programming-languages

如何将result.getDistance()。inMeters()的结果保存到距离?

public class Route {
  private double distance;
  public Route() {
    distance = 0;
    run();
  }

  public void run() {
    Directions.load(query, opts, new DirectionsCallback() {

      public void onFailure(int statusCode) {
       Window.alert("Failed to route locations: " 
         + StatusCodes.getName(statusCode) + " " + statusCode);
      }

      public void onSuccess(DirectionResults result) {
           distance = result.getDistance().inMeters();
      }

    );
  }
  public double getDistance() {
    return distance;
  }
}

在我的主java文件中,每当我做

Route route = new Route();
double distance = route.getDistance();

距离始终为0.

2 个答案:

答案 0 :(得分:3)

@dominic的评论是正确的:

  

“在我的主要java文件中,每当我Route route = new Route(); double distance = route.getDistance();距离将始终为0.”当然,由于变量距离在构造函数0中初始化为Route();

onSuccess返回非零值之前,您需要等待getDistance()回调执行。这个问题的典型解决方案就是在回调本身内执行依赖于getDistance()的代码:

public void onSuccess(DirectionResults result) {
    distance = result.getDistance().inMeters();
    doStuffThatDependsOn(distance);
}

答案 1 :(得分:0)

您可以使用synchronized块,直到调用onSuccess或onFailure之一。

在run()方法中添加:

synchronized(this) {
    wait();
} catch (InterruptedException e) {
...
}

在onSuccess和onFailure中添加:

synchronized(Route.class.this) {
    notify();
}