I am trying to get a single integer value with Volley.
In this example the number is 14
In the debugger I get the correct value 14 and assign it to vNumber while in the try/catch block but then when I try to return the vNumber I get value 0 as returned number.
This is the JSON result.
{"result":[{"version":"14"}]}
Here is the code for this function:
int vNumber; public int getVersionNumber() { StringRequest stringRequest = new StringRequest(Request.Method.POST, GET_VERSION_NUMBER, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject object = new JSONObject(response); JSONArray jsonArray = object.getJSONArray("result"); JSONObject jsonObject = jsonArray.getJSONObject(0); vNumber = jsonObject.getInt("version"); } catch (JSONException e) { e.printStackTrace(); Log.d(TAG, "JSONException: " e); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d(TAG, "VolleyError: " error); } }); RequestQueue requestQueue = Volley.newRequestQueue(context); requestQueue.add(stringRequest); return vNumber; }
I already tried using sharedPreferences and putting the value inside a textView (the value is correct when I set it in a textView) and then getting it from it but it's still not working. I could create a new table inside my local DB and save the data but it is not necessary in this use case.
Do you have any suggestions on how the return the correct value, and what am I doing wrong here?
Cheers
CodePudding user response:
public void fetchVersionNumber() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, GET_VERSION_NUMBER,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject object = new JSONObject(response);
JSONArray jsonArray = object.getJSONArray("result");
JSONObject jsonObject = jsonArray.getJSONObject(0);
vNumber = jsonObject.getInt("version");
compareAndUpdate(vNumber)
} catch (JSONException e) {
e.printStackTrace();
Log.d(TAG, "JSONException: " e);
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "VolleyError: " error);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
}
public void compareAndUpdate(int vNumber){
//compare and do your operation
// Get from sharedPref and compare
}