Reputation: 5705
CURRENT SCENARIO
I have a requirement that I have to run an asynctask
on click of a button and send some data to the server and don't show any progress to the user. Now if user press the button again a new instance of asynctask will execute without waiting for the previous version to finish. This I am able to achieve using this class.
public class AsyncTaskTools {
public static <P, T extends AsyncTask<P, ?, ?>> void execute(T task) {
execute(task, (P[]) null);
}
@SuppressLint("NewApi")
public static <P, T extends AsyncTask<P, ?, ?>> void execute(T task, P... params) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
} else {
task.execute(params);
}
}
}
PROBLEM
Now when I run the same code in Android Kitkat it doesn't gives success response after first asynctask and that too only if I click button with short interval between them. If I wait for say 5-10 seconds before clicking the button again then my code works perfectly fine, but when I click button rapidly about 5 times, my code fails to work.
Only issue that I was able to catch related to this is the following
exceeded content-length limit of 12900 bytes
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
This exception is caught some time in catch block.
This is my complete asynctask code.
class SendCallDispositionAsyncTask extends AsyncTask<Void, Void, Void> {
public SendCallDispositionAsyncTask() {
// TODO Auto-generated constructor stub
//this.activity = profile_Info;
}
protected void onPreExecute() {
super.onPreExecute();
// utils.showProgressDialog(ActivityCallScreen.this, "Loading. Please wait..");
}
@SuppressWarnings("deprecation")
@Override
protected Void doInBackground(Void... params) {
String responseArray = null;
Log.d("asyncresponse", "do in background");
CallDurationReceiver.start_time=0;
try {
byte[] data;
try {
Log.d("callduration","Duration: "+prefManager.getDouble(PrefrenceConstants.CALL_DURATION));
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("userid", new StringBody(String.valueOf(prefManager.getInt(PrefrenceConstants.USER_ID))));
entity.addPart("dialerno", new StringBody(mobile));
entity.addPart("dipositionid", new StringBody(dispositionId));
entity.addPart("dipositiongroup", new StringBody(dipositiongroup));
entity.addPart("callduration", new StringBody(prefManager.getDouble(PrefrenceConstants.CALL_DURATION)+""));
entity.addPart("callename", new StringBody(name));
entity.addPart("calleage", new StringBody(age));
entity.addPart("callecontact", new StringBody(contact));
entity.addPart("isnote", new StringBody(checked));
entity.addPart("cbdate", new StringBody(date));
entity.addPart("aliment", new StringBody(aliment));
entity.addPart("callelocation", new StringBody(location));
entity.addPart("remarks", new StringBody(selectedRemarks));
entity.addPart("file", new FileBody(file));
entity.addPart("contactid", new StringBody(String.valueOf(contact_id)));
HttpEntity httpEntity = entity.build();
URL url = new URL(sendDispositionUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(60000);
httpURLConnection.setConnectTimeout(60000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setUseCaches(false);
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestProperty("Authorization", prefManager.getString(PrefrenceConstants.API_KEY));
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
// httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.addRequestProperty("Content-length", httpEntity.getContentLength() + "");
httpURLConnection.addRequestProperty(httpEntity.getContentType().getName(), httpEntity.getContentType().getValue());
OutputStream os = httpURLConnection.getOutputStream();
httpEntity.writeTo(httpURLConnection.getOutputStream());
os.close();
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == HttpsURLConnection.HTTP_OK) {
response = BufferReaderMaker.readContentFromIS(httpURLConnection.getInputStream());
Log.v("log_tag", "image upload status ::: " + response);
} else if (httpURLConnection.getResponseCode() == HttpsURLConnection.HTTP_CREATED) {
response = BufferReaderMaker.readContentFromIS(httpURLConnection.getInputStream());
Log.d("responce", response);
}
// {"error":true,"message":"Required field(s) userid, dialerno, dipositionid, dipositiongroup, callduration, contactid is missing or empty"}
} catch (final UnknownHostException e) {
// TODO: handle exception
Log.d("host", e.getMessage());
}
} catch (final ConnectTimeoutException e) {
// TODO: handle exception
Log.d("timeout", e.getMessage());
} catch (Exception e) {
e.printStackTrace();
Log.d("exec", e.getMessage());
}
return null;
// return "Success";
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Log.d("asyncresponse", response);
// utils.hideProgressDialog();
}
}
I checked several links regarding this issue but none of them is working for me.
Can anybody tell me if this is some problem in my code or a server side issue.
EDIT
Also I am uploading a file to the server which is about 50 kb currently.Can this cause any issue?
Upvotes: 0
Views: 65
Reputation: 4848
It sound like your problem might be the length of content you are posting.
httpURLConnection.addRequestProperty("Content-length", httpEntity.getContentLength() + "");
You need to get the length in bytes. You should check to see what value httpEntity.getContentLength()
returns. It should be the number of bytes you are uploading - including the size of the file.
You might have some restrictions on the amount of data you may upload - but I doubt that is the problem, because that is not many bytes in the error message.
I use this code with no issues:
public String makeHttpRequestJsonString(String path, int requestType, Map<String, String> params){
String json = "";
InputStream responseStream = null;
try {
startTime = System.currentTimeMillis();
StringBuilder postData = new StringBuilder();
for(Map.Entry<String, String> param : params.entrySet()){
if(postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
URL url = makeURL(path, requestType);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Cache-Control", "no-cache");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
DataOutputStream request = new DataOutputStream(conn.getOutputStream());
request.write(postDataBytes);
request.flush();
//Some people have reported issues when closing the the request before reading the
request.close();
//Check the response code of the server -
Integer replyCode = conn.getResponseCode();
//System.out.println("Reply Code: " + replyCode.toString());
responseStream = new BufferedInputStream(conn.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
responseStreamReader.close();
json = stringBuilder.toString();
}
catch (UnsupportedEncodingException e) {
} catch (IOException e) {
Log.e(TAG, "makeHttpRequestJsonString --- " + e.getMessage());
}
return json;
}
I add my data differently but you could adapt your solution.
Upvotes: 1