Yoan Martin Yoan Martin - 5 months ago 25
JSON Question

Return value from http request using Volley

I try to get the altitude of a location using an http request to Google Maps. Unfortunately, I receive a response but I cannot use it. In this piece of code, I try to set the altitude of a Location but it does not work. The altitude is correct in my OnResponse method but it is wrong elsewhere. Do you have any idea why?

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

protected void onCreate(Bundle savedInstanceState) {

Log.d("OnCreate", ""+location.getAltitude()); //print OnCreate: 0.0


public void getElevation(){
String urlName = "https://maps.googleapis.com/maps/api/elevation/json?locations="

RequestQueue queue = Volley.newRequestQueue(this);

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

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);
Log.d("OnResponse", ""+location.getAltitude()); //print OnResponse: 1608.637939453125
} catch (JSONException e) {
}, new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {


I try to set the altitude of a Location but it does not work.

Yes it does work, because you say yourself.

The altitude is correct in my OnResponse method

So, when you say

it is wrong elsewhere.

It isn't wrong, it is unitialized. Volley doesn't just immediately return the result of the elevation. So, the log statement that prints 0 happens before the onResponse that prints the value.

So, to answer "how to return values from volley", you already are doing that - obtain that value within the onResponse and delay execution of anything that relies on that value until then