排球和处理数据在Android上后台返回 [英] Volley and processing data returned in background on Android

查看:72
本文介绍了排球和处理数据在Android上后台返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难找到有关Volley和response.Listener的一些信息.

I have some troubles finding some informations about Volley and the response.Listener.

基本上,我有一个向后端询问数据的操作,该调用在后台整个Volley中进行(由Volley本身处理),同时它在主线程上调用onResponse.

Basically I have an operation to ask data to my backend, call is made throughout Volley in background (Handled by Volley itself) meanwhile it call the onResponse on the main thread.

我需要自己执行一个可运行的操作以在后台处理这些数据吗,还是有一种方法可以强制onResponse在后台运行?

Do I need to do a runnable by myself to process theses datas in background or there is a way to force the onResponse to run in background ?

谢谢.

这是我当时正在运行的代码.

Here is the code I'm running then.

private Response.Listener<String> volleyResp = new Response.Listener<String>() {
    @override
    public void onResponse(final String jsonResp) {
        new Thread() {
            public void run() {
                // Do something ... Insert in DB for example.
            }
        }.start();
    }

推荐答案

请仔细阅读我的回复

如果要在与请求相同的线程中处理"数据,则应具有Request(或JsonRequest)的子类并实现parseNetworkResponse(NetworkResponse response)

If you want to 'process' data in the same thread as the request, you should have subclasses of Request (or JsonRequest) and implements parseNetworkResponse(NetworkResponse response)

示例:


public class TotoRequest extends JsonRequest {
    @Override
    protected Response parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString =
                    new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            JSONObject jsonObject = new JSONObject(jsonString);
            // Process data here
        } catch (UnsupportedEncodingException | JSONException e) {
            return Response.error(new ParseError(e));
        }
    }
}

这是对您问题的答复,但我认为这并不是您真正想要的.

如果数据较小,则在主线程中处理数据可能更安全.

It's probably safer to either process your data in the main thread if your data is small.

如果您的数据很重要,或者要在数据库中插入/更新数据,则只需继续做您正在做的事情即可.

If your data is important, or if you want to insert/update it in a database you should simply continue doing what you are doing.

此外,我建议您使用AsyncTask而不是线程.

这篇关于排球和处理数据在Android上后台返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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