11

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.

1
  • Do you really need all that data at one time? Or could you only load the first 20 records to cut down the size? Then, if the user scrolls down or gets close to viewing the next set of records, load the next 20.
    – Ero
    Commented Jun 4, 2015 at 13:47

5 Answers 5

3

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

2
  • Is it AsyncTask the best solution for this ? Maybe Volley, Retrofit of Threads using are better ones ? Commented Jun 4, 2015 at 14:19
  • 1
    I dont know if it is the best, but i can say that whatever happens in MainThread will affect it and if it is not related with any UI it will give you a lag (that can even be an extremely small lag too). So i suggest that you better parse that jsonArray in new thread.
    – hrskrs
    Commented Jun 4, 2015 at 14:26
1

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.

0
0

In most GUI designs (not just Android), there are several threads having different roles and responsibilities:

  • The "main thread," running at "normal" dispatching priority, basically has nothing else to do but to respond promptly to the demands of the user-interface system. When "messages" arrive for its consumption, this thread immediately pre-empts the other threads so that the message can be processed quickly. Like any good manager ... ;-) ... they don't do the work themselves. They pass it off to other people.

  • When asynchronous requests (JSON ... etc.) are involved, there's usually a small "pool" of threads who are responsible for sending those to the host, receiving the response, doing the encoding/decoding, and then either acting-on the response or passing it along. These threads spend nearly all their time waiting on the host. They operate at a slightly-inferior dispatching priority.

  • Worker threads, operating at an even-more inferior priority, do any work that is computationally time-consuming. As much as possible, these threads don't do much I/O. They give-up their time slices quickly and readily to any other thread, but they usually consume their entire time slice when they can get one.

0

Potentially long running operations should always happen on a separate thread, or really any work (within reason...) that can be done on a separate thread should.

In your case, you're using Volley, so it's very easy for you to override your Request<T>'s parseNetworkResponse(NetworkResponse response); method, and parse the response on a background thread (since this method already runs on a background thread) before it's delivered. Since it's relatively seamless to do so, there really isn't a reason to not parse the response on a background thread.

0

Try this https://github.com/yakivmospan/volley-request-manager

//Queue using custom listener
RequestManager.queue()
    .useBackgroundQueue()
    .addRequest(new TestJsonRequest(), mRequestCallback)
    .start();

private RequestCallback mRequestCallback = new RequestCallback<JSONObject, ResultType>() {  
@Override
public ResultType doInBackground(JSONObject response) {
    //parse and save response data
    return new ResultType();
}

@Override
public void onPostExecute(ResultType result) {
    //update UI here
    Toast.makeText(getApplicationContext(), "Toast from UI", Toast.LENGTH_SHORT).show();
}

@Override
public void onError(VolleyError error) {
    //handle errors here (UI thread) 
    L.e(error.toString());
}
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.