简体   繁体   中英

Return data from inside an anonymous inner class for method it is contained in

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){
    ...
   }
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM