Two Asynctask running parallel with Httpclient request

Asked

Viewed 587 times

1

I have two classes extending Asynctask, in which they return me a JSON from a server. I am using the following code to run them simultaneously:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
    AsyncTaskExemplo1.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "");
else
    contact.execute("");

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
    AsyncTaskExemplo2.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "");
else
    contact.execute("");

I use the following code to create my connection:

public static HttpClient httpclient = new DefaultHttpClient();
public JSONObject GET(String url, JSONObject jsonObject) {
    InputStream inputStream = null;
    String result = "";
    JSONObject jArray = null;
    try {
        HttpGet httpGet = new HttpGet(url);
        if (jsonObject != null) {
            String json = "";
            json = jsonObject.toString();
            StringEntity se = new StringEntity(json);
            ((HttpResponse) httpGet).setEntity(se);
        }
        httpGet.setHeader("Accept", "application/json");
        httpGet.setHeader("Content-type", "application/json");
        HttpResponse httpResponse = httpclient.execute(httpGet);
        inputStream = httpResponse.getEntity().getContent();
        if (inputStream != null) {
            result = convertInputStreamToString(inputStream);
        } else {
            result = "Did not work!";
        }
    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

    if (result != null) {
        try {
            jArray = new JSONObject(result);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    return jArray;
}

When I run the Asynctask one after the other, they return me the Jsons correctly, however if I run them simultaneously ONE of them does not wait for the return of the server and continues the execution returning null in the 'GET' function of my code.

I have read that Android does not accept two simultaneous http requests with Apache’s standard Httpclient library.

Please, if anyone has ever faced a similar situation and can help me, I am most grateful.

  • I advise you to use a library Volley (recommended by google) and forget that threads exist.

  • I know it’s not exactly an answer, but just like @Exceptional I recommend you drop these asynctasks and use a lib. Except my recommendation is another lib, it’s the loopj http://loopj.com/android-async-http/ "instagram and Pinterest use it"

  • Thank you for your answers. I even implemented a code using loopj, but it still has some bugs and I ended up facing one of them, unfortunately with no solution. I found a great lib called robospice. I’m still doing some tests, but he promises a lot

1 answer

2


According to the Android documentation

public final Asynctask execute (Params... params)

Note: this Function Schedules the task on a Queue for a single background thread or pool of threads Depending on the Platform version. When first introduced, Asynctasks Were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing Multiple tasks to Operate in Parallel. Starting HONEYCOMB, tasks are back to being executed on a single thread to avoid common application errors caused by Parallel Execution. If you Truly want Parallel Execution, you can use the executeOnExecutor(Executor, Params...) version of this method with THREAD_POOL_EXECUTOR; However, see Commentary there for warnings on its use.

This way, it is not possible to run more than one Asynctask in parallel. Asynctasks are used to facilitate the use of Threads, since they allow modifications to the UI. However, it is possible to achieve the same effect using conventional threads combined with some communication mechanism with the main thread. The android documentation presents a good tutorial on the subject in the link http://developer.android.com/training/multiple-threads/communicate-ui.html

  • After Honeycomb it is possible to run up to 5 Asynctasks at the same time. The problem occurs when 2 or more Asynctask make some http request. Android only runs one at a time and I call the Async with the run.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.