I have a method that makes an API call which requires an anonymous inner class. Inside the anonymous inner class, there is an onResponse
method, which has a void
return type, where I can access the JSON. I want the method to return the JSON.
public JSONObject makeAPIRequest() {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>(){
@Override
public void onResponse(JSONObject response){
//have makeAPIRequest() return response
},
new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError error){
...
}
});
}
Short answer - you need to refactor your method so it isn't procedural and use return
...
For example,
public void makeAPIRequest(Response.Listener<JSONObject> listener) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, listener);
// TODO: submit request
}
Then in the other classes, you have a callback acting as your "return"
apiInstance.makeAPIRequest(new Response.Listener<JSONObject>(){
@Override
public void onResponse(JSONObject response){
// do stuff
},
new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError error){
...
}
});