I am getting can't create handler inside thread in asynchronous background task. Below is my code. I made the necessary modifications to progress bar after searching in google but still the error is rising. Please help me with this. Will be thankful.
My code:
private class LongOperation1 extends AsyncTask<String, Void, String> {
private final WeakReference<MainActivity> mainActivityWeakRef;
ProgressDialog dialog;
public LongOperation1(MainActivity mainActivity) {
super();
this.mainActivityWeakRef = new WeakReference<MainActivity>(
mainActivity);
// this.activity = mainActivity;
}
@Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://.............php");
// This is the data to send
// String MyName = 'adil'; //any data to send
// publishProgress(5);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
1);
nameValuePairs.add(new BasicNameValuePair("param1", "1"));
nameValuePairs.add(new BasicNameValuePair("param2",
"Cities"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
// This is the response from a php application
String reverseString = response;
Toast.makeText(MainActivity.this, "response" + reverseString,
Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
Toast.makeText(MainActivity.this,
"CPE response " + e.toString(), Toast.LENGTH_LONG)
.show();
// TODO Auto-generated catch block
} catch (IOException e) {
Toast.makeText(MainActivity.this,
"IOE response " + e.toString(), Toast.LENGTH_LONG)
.show();
// TODO Auto-generated catch block
}
return "All Done!";
}
@Override
protected void onPostExecute(String result) {
Log.d("onpostexecute", (mainActivityWeakRef.get() != null) + "");
if (mainActivityWeakRef.get() != null
&& !mainActivityWeakRef.get().isFinishing()) {
AlertDialog alertDialog = new AlertDialog.Builder(
mainActivityWeakRef.get()).create();
alertDialog.setTitle(result);
alertDialog.setMessage("On post execute");
alertDialog.setCancelable(false);
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
dialog.incrementProgressBy(5);
}
}