如何从抽射功能onResponse返回值? [英] How can I return value from function onResponse of Volley?

查看:1609
本文介绍了如何从抽射功能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 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()).

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

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