I have an image uploader. If the internet connection stops an alert dialog is shown and asks the user if he want to retry or to cancel uploading. The problem is that sometimes when I retry, after the second uploading there are two images uploaded instead of one. What could be the problem?
Here is my code:
@Override
protected Void doInBackground(Void... params) {
Log.i("ImageUpload", "Uploading..");
setBitmap();
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(url);
httpPostRequest.setHeader("Cookie", this.cookie);
MultipartEntityBuilder multiPartEntityBuilder = MultipartEntityBuilder
.create();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
this.image.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
multiPartEntityBuilder.addBinaryBody("picture", byteArray,
ContentType.create("image/png"), "image.png");
httpPostRequest.setEntity(multiPartEntityBuilder.build());
try {
HttpResponse httpResponse = null;
Log.i("ImageUpload", "====================================================\n"
+ "httpClient.execute(httpPostRequest)");
httpResponse = httpClient.execute(httpPostRequest);
Log.i("ImageUpload", "====================================================");
Log.i("ImageUpload", "httpPost executed");
InputStream inputStream = null;
inputStream = httpResponse.getEntity().getContent();
String result;
if (inputStream != null) {
result = convertInputStreamToString(inputStream);
} else {
result = "Unable to send signiture.";
}
Log.i("Upload result", result);
} catch (IOException e) {
photoSent = false;
httpPostRequest.abort();
this.cancel(true);
e.printStackTrace();
}
return null;
}
@Override
protected void onCancelled() {
this.mainActivity.hideProgressBar();
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(
mainActivity);
myAlertDialog
.setTitle("Error why uploading the picture.");
myAlertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
return;
}
});
myAlertDialog.setPositiveButton("Retry",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
/*execute the whole AsyncTask again*/
}
});
myAlertDialog.show();
super.onCancelled();
}