I want to cancel the asynctask and stops its background execution , I found a solution in this question,:
But actually, My code in asynctask is to upload/post some data to server, I don't know how to use a while or for loop and break statements here according to answer of above question
My AsyncTask is:
private class Userdataupload extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String[] params) {
// do above Server call here
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.example.com/example.php");
int mode = Activity.MODE_PRIVATE;
SharedPreferences my2 = getSharedPreferences("data", mode);
String u = my2.getString("name", "error");
String v = my2.getString("coin", "error");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("name", u));
nameValuePair.add(new BasicNameValuePair("coin", v));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
HttpResponse response = httpClient.execute(httpPost);
// write response to log
//tdt(response.toString());
Log.d("Http Post Response:", response.toString());
} catch (ClientProtocolException e) {
// Log exception
e.printStackTrace();
} catch (IOException e) {
// Log exception
e.printStackTrace();
}
return null;
}
@Override
protected void onPreExecute()
{
pf = new ProgressDialog(MainActivity.this);
pf.setMessage("Loading User Data...");
pf.show();
pf.setCanceledOnTouchOutside(false);
pf.setCancelable(true);
}
@Override
protected void onPostExecute(String message) {
//process message
pf.cancel();
}
}