使用Volley从http请求返回值

时间:2016-10-19 12:05:25

标签: java android json google-maps android-volley

我尝试使用Google地图的http请求获取某个位置的高度。不幸的是,我收到了回复,但我无法使用它。在这段代码中,我尝试设置位置的高度,但它不起作用。我的OnResponse方法的高度是正确的,但在其他地方是错误的。你知道为什么吗?

public class MainActivity extends AppCompatActivity {
Location location = new Location("");

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    location.setLatitude(39.7391536);
    location.setLongitude(-104.9847034);
    getElevation();
    Log.d("OnCreate", ""+location.getAltitude()); //print OnCreate: 0.0

}

public void getElevation(){
    String urlName = "https://maps.googleapis.com/maps/api/elevation/json?locations="
            +location.getLatitude()+","+location.getLongitude()
            +"&key=mykey";


    RequestQueue queue = Volley.newRequestQueue(this);

    JsonObjectRequest requester = new JsonObjectRequest(urlName, null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
                TextView mTxtDisplay = (TextView) findViewById(R.id.elevation);
                double altitude;

            try {
                altitude = response.getJSONArray("results").getJSONObject(0).getDouble("elevation");
                mTxtDisplay.setText("Elevation : " + altitude);
                location.setAltitude(altitude);
                Log.d("OnResponse", ""+location.getAltitude()); //print OnResponse: 1608.637939453125
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            //TODO
        }
    });
    queue.add(requester);
    }
}

2 个答案:

答案 0 :(得分:0)

您希望使用如下的回调接口:

public void getString(final VolleyCallback callback) {
StringRequest strReq = new StringRequest(Request.Method.GET, url, new       Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        result=response;
        callback.onSuccess(result);
    }
  }...
}}

public interface VolleyCallback{
void onSuccess(String result);
}

活动内的示例代码:

public void onResume(){
super.onResume();
getString(new VolleyCallback(){
     @Override
     public void onSuccess(String result){
         ... //do stuff here
     }
  });
}

答案 1 :(得分:0)

  

我尝试设置位置的高度,但它不起作用。

是的确有效,因为你说自己。

  

我的OnResponse方法中的海拔高度正确

所以,当你说

  

其他地方都是错的。

没错,它是单元化的。排球不只是立即返回升高的结果。因此,打印0的日志语句发生在打印值的onResponse之前。

因此,要回答“如何从排球中返回值”,您已经这样做了 - 在onResponse中获取该值并延迟执行依赖于该值的任何内容直到那时