如何从 Volley 的 onResponse 函数返回值? [英] How can I return value from function onResponse of Volley?

查看:32
本文介绍了如何从 Volley 的 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_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 void getString(final VolleyCallback callback) {
    StringRequest strReq = new StringRequest(Request.Method.GET, url, new     Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            ...  // (optionally) some manipulation of the response 
            callback.onSuccess(response);
        }
    }...
}}

回调定义为

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

活动中的示例代码:

public void onResume(){
    super.onResume();

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

你也可以让 VolleyCallback 更健壮,如果你想做处理,可以使用泛型类型,或者添加 start(), failed(Exception e)complete() 等方法进行更细粒度的状态检查.

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.

请记住,这是一个异步调用,因此您必须在返回结果时更新视图等(在 success() 中).

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

这篇关于如何从 Volley 的 onResponse 函数返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆