Yoan Martin Yoan Martin - 1 month ago 7
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("");

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

Answer

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

Comments