首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >JSON通过坐标获取地址

JSON通过坐标获取地址
EN

Stack Overflow用户
提问于 2018-07-13 03:14:01
回答 1查看 55关注 0票数 0

我为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。你能告诉我我的代码出了什么问题吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-13 03:27:01

使用带有RequestQueueJsonObjectRequest是一种异步机制--工作在后台执行,只要响应准备就绪,就会调用onResponse回调。

因此,很可能在调用onResponse之前从您的方法返回,而且由于address没有预先设置(无论如何您已经展示过了),它的值将是null

如果希望在请求完成之前阻塞线程并设置address的值,则应使用RequestFutureCan I do a synchronous request with volley?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51312921

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档