我为Android创建了一个应用程序,它保存GPS坐标并显示它们的地址。
我有一个函数:
public String getAddressByGpsCoordinates(String latlan) {
requestQueue = Volley.newRequestQueue(this);
String url= "http://maps.googleapis.com/maps/api/geocode/json?latlng="+latlan+"&sensor=true&key=(I have a correct key :))";
JsonObjectRequest request = new JsonObjectRequest(url,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
address = response.getJSONArray("results").getJSONObject(0).getString("formatted_address");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(request);
return address;
}
它总是返回NULL。你能告诉我我的代码出了什么问题吗?
发布于 2018-07-13 03:27:01
使用带有RequestQueue
的JsonObjectRequest
是一种异步机制--工作在后台执行,只要响应准备就绪,就会调用onResponse
回调。
因此,很可能在调用onResponse
之前从您的方法返回,而且由于address
没有预先设置(无论如何您已经展示过了),它的值将是null
。
如果希望在请求完成之前阻塞线程并设置address
的值,则应使用RequestFuture
:Can I do a synchronous request with volley?
https://stackoverflow.com/questions/51312921
复制相似问题