0

I create an application for Android, which saves GPS coordinates and displays them with addresses.

I have a function:

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

It is returned NULL all the time. Can You help me what is wrong with my code?

TofferJ
  • 4,678
  • 1
  • 37
  • 49
Chrisss
  • 87
  • 1
  • 10

1 Answers1

0

Using JsonObjectRequest with a RequestQueue is an asynchronous mechanism--the work is performed in the background and the onResponse callback is called whenever the response is ready.

Because of this, it is very likely that you return from your method before onResponse gets called, and since address isn't set beforehand (that you've shown, anyway), its value will be null.

If you want to block your thread until the request has completed and set the value of address, you should use a RequestFuture: Can I do a synchronous request with volley?

VeeArr
  • 6,039
  • 3
  • 24
  • 45