如何从抽射功能onResponse返回值?抽射、返回值、功能、onResponse

由网友(感情早已陌生)分享简介: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_Stri...
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;
}}

我想打造的getString的对象,并调用get_String其他领域。但似乎很难从onResponse得到的结果出来。我知道它不能在当前的方式工作。谁能帮我解决这个问题呢?

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?

推荐答案

您想要使用的回调接口,像这样:

You want to use callback interfaces like so:

public String get_String(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);
}

内活动实例code:

Example code inside activity:

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

您还可以VolleyCallback更强劲,使用泛型类型,如果你想要做的处理,或添加的start(),失败(例外五),完成()等方法,以做一些更细致的状态检查。

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()).

阅读全文

相关推荐

最新文章