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.
– Androiderson
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"
– ademar111190
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
– Rafael Neiva