I'm retrieving data from my server through JSON using Volley
JSONObjectRequest
to achieve this. After getting the JSON response, I want to save it into a variable and use it through out the activity. Below is my code sample:
private String description;
private int status;
private boolean validateIntegrationCode() {
if (checkNetwork()) {
String url = "sample url";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
status = response.getInt("status");// ** STATUS IS 1 HERE **
description = response.getString("description");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
} else {
// No network, check from SQLite
}
if (status == 1) { // ** STATUS IS 0 HERE **
return true;
} else {
return false;
}
}
When I check the status
value before returning true
or false
, the value of status
is now 0 and the description
also returns null
.
My JSON response:
{"status":1,"description":"Integration code is valid"}
The volley request is an asynchronous call. It doesn't block the code till the response is received. So what is happening is your check for
if(status==1)
is happening before the volley response is received. Hence it is 0.What you should do:
1) Make your function return type void.
2) In
onResponse
, put the code