Wubin Ouyang Wubin Ouyang - 3 months ago 167
Android Question

How can I return value from function onResponse of Volley?

public class getString {
String tag_string_req = "string_raq";
String url = "http://10.0.2.2/eat/locations/index.json";
String result="";

public String get_String() {
StringRequest strReq = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
result=response;
System.out.println(response);
;

}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
System.out.println(volleyError.getMessage());
}
});
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
return result;
}}


I would to build an object of getString and call get_String in other fields. But it seems that it is hard to get the result out from the onResponse. I know it cannot work in this current way. Could anyone help me to settle this problem?

Answer

You want to use callback interfaces like so:

public void getString(final VolleyCallback callback) {
    StringRequest strReq = new StringRequest(Request.Method.GET, url, new     Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            result=response;
            callback.onSuccess(result);
        }
    }...
}}

public interface VolleyCallback{
    void onSuccess(String result);
}

Example code inside activity:

public void onResume(){
    super.onResume();
    getString(new VolleyCallback(){
         @Override
         public void onSuccess(String result){
             ... //do stuff here
         }
    });
}

You can also make VolleyCallback more robust, using generic types if you want to do processing, or adding start(), failed(Exception e), complete(), etc methods to do a little more fine-grained state checking.

Keep in mind this is an async call, so you will have to update views, etc when you get the result back (inside success()).