【问题标题】:How to handle the response of Volley in AndroidAndroid中如何处理Volley的响应
【发布时间】:2016-05-02 16:56:36
【问题描述】:

我在 Android Activity 中使用 volley,并发出请求并得到响应,但我想用另一种方法处理响应,但它不起作用,我该怎么办?

public class TestActivity extends Activity {

RequestQueue queue;

private String result;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String url = "www.google.com/something/I/need";

    queue = Volley.newRequestQueue(this);

    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    // Do something with the response
                    Log.i("resp", response);
                    // I want to do sth with the response out of here
                    // maybe like this, let result = response
                    // and see the log at the end of the code
                    // but it failed, what should I do?
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // Handle error
                    Log.e("error", error.toString());
                }
            });
    queue.add(stringRequest);
    Log.e("result", result);
}

【问题讨论】:

    标签: android request android-volley


    【解决方案1】:

    Volley 请求是异步的,所以程序在发送请求后会继续执行而不等待应答。因此处理结果的代码被插入到 OnResponse 方法中。如需更准确的帮助,请解释您为什么要退出 OnResponse 方法

    【讨论】:

      【解决方案2】:

      想想你在做什么:你正在创建一个StringRequest,然后你将它添加到请求队列中,然后你立即尝试检查结果。显然,这行不通,因为请求还没有被处理。

      您的响应将通过onResponse 方法到达,只有这样您才能对它进行操作。您可以在此处设置result = response,但您只能在调用onResponse 时才能看到该值,这可能需要一些时间。

      希望这可以澄清事情。

      【讨论】:

        猜你喜欢
        • 2015-10-07
        • 1970-01-01
        • 1970-01-01
        • 2021-03-30
        • 2014-06-23
        • 1970-01-01
        • 1970-01-01
        • 2017-06-28
        • 2018-10-23
        相关资源
        最近更新 更多