Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android right approach : where JSON response should be parsed - in UI thread, or in another one?

I just wondering - where the JSONObject or JSONArray received from the web-server should be parsed in Android app - in the main UI or should be delivered to the another one ?

For example, I'm using Volley library :

private void fetchResults(){

    RequestQueue queue = Volley.newRequestQueue(mContext);
        String url = AuthenticationRequester.URL_GET_ALL_ORDERS;
        JsonArrayRequest jsonDepartureObj = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray jsonArray) {
                iVolleyCallback.onJSONArraySuccess(jsonArray);
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                // hide the progress dialog
            }
        });
        queue.add(jsonDepartureObj);
}

So should I put the iVolleyCallback.onJSONArraySuccess(jsonArray); in another thread execution or can be maintained the the main UI thread ?

Let's imagine that the incoming JSON is big and needs some time to be proceeded ?

The same question relates to the AsyncTask and to other possible ways working with the web-services in Android.

like image 834
Rikki Tikki Tavi Avatar asked Jun 04 '15 13:06

Rikki Tikki Tavi


2 Answers

It is prefered that, every task that takes long time, should be proccessed in another thread to avoid overloading MainThread:

AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.

So if you know that you have big data and it will take time, you will use new thread, but if the data are small and takes less time, why take the risk? Move that to the new thread too

like image 178
hrskrs Avatar answered Nov 06 '22 14:11

hrskrs


If, as you say yourself, the JSON data could be huge, and it could take some time to process, I think you could (or should?) try to process it in an AsyncTask. By doing this your UI thread will not be frozen during the processing.

like image 24
jbrulmans Avatar answered Nov 06 '22 15:11

jbrulmans