Volley and processing data returned in background on Android
Asked Answered
L

1

6

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

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.

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 ?

Thank you.

EDIT :

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();
    }
Less answered 20/3, 2014 at 3:39 Comment(1)
Alright, I edited with what I'm doing now ... but I still open for any suggestionsLess
P
4

Please read my reply until the end

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)

Example :


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));
        }
    }
}

This is the reply to your question but I think it's not what you actually want.

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.

Also, I would recommend you to use an AsyncTask instead of a thread.

Playwriting answered 20/3, 2014 at 10:13 Comment(4)
Thanks for your reply :). I will take a look at your solution about extend from JsonRequest directly. Actually write in the DB in the main thread generate "strictMode violation". In order it's not only about data size but also trying to do something clean.Less
Actually, I forgot to mention, process is about write in the DB.Less
I have one doubt, what if our main thread is still in executing something when volley returns the callback. What will be executed now?Vastha
I'm not sure in understand your question. Volley execute the request in a background thread then post a callback on the main thread's Looper.Playwriting

© 2022 - 2024 — McMap. All rights reserved.