How can I dismiss ProgressDialog in AsyncTask
I am using a ProgressDialog
to be shown while my background process goes on, but after background process is completed the ProgressDialog is not dismissed still.
Here is my code
private class async extends AsyncTask<String, Void, Boolean> {
开发者_如何学JAVA final ProgressDialog progressDialog = new ProgressDialog(getParent());
@Override
protected Boolean doInBackground(String... params) {
GetJson json = new GetJson();
boolean success = false;
JSONObject mJsonObject = json
.readJsonObject("url");
try {
success = mJsonObject.getBoolean("success");
} catch (Exception e) {
}
return success;
}
@Override
protected void onPostExecute(Boolean result) {
if (result) {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
}
}
@SuppressWarnings("static-access")
@Override
protected void onPreExecute() {
progressDialog.show(getParent(), "Working..", "Please wait...");
}
}
private final class YourTask extends AsyncTask<Void, Void, Object> {
private ProgressDialog dialog;
@Override
protected void onPreExecute() {
dialog = ProgressDialog.show(YourActivity.this, "Title", "Message", true);
}
@Override
protected Object doInBackground(final Void... params) {
// Doing something
}
@Override
protected void onPostExecute(final Object result) {
// Check result or something
dialog.dismiss();
}
}
You can call progressDialog.dismiss()
in your AsyncTask
's onPostExecute()
method.
In onPostExecute()
method call dismiss()
on your dialog.
I dont know, if you solved this problem, probably yes.
But for next users what will have the same problem (i had it right now too)..
The problem is in your declaration.
final ProgressDialog progressDialog = new ProgressDialog(getParent());
or in your "second" declaration
progressDialog.show(getParent(), "Working..", "Please wait...");
Because in the first one you put in there the getParent parameter (probably MainActivity.this) and the same you do in calling show method. Therefore is there 2 parents.. and if you call dismiss() in post execute..it dismiss the first one..but not the another one what have then dialog.isShowing() equal to false.
So important is have there just 1!!!!! parent content..so you can assign the content in declaration with:
new ProgressDialog(content);
or you can do
ProgressDialog dialog=new ProgressDialog();
dialog.setMessage("Loading");
dialog.show(getParent());
and then dismiss it and everything is allright. or you can do:
ProgressDialog dialog=new ProgressDialog(getParent());
dialog.setMessage("Loading");
dialog.show();
but never give in there twice parents, contents, whatever..
AsyncTasks should not handle at ALL a dialog. Dismissing the dialog in the PostExecute phase can easily lead to an IllegalStateException as the underlying activity can already be destroyed when the dialog gets dismissed. Before destroying the activity the state of the activity will be saved. Dismissing the dialog afterwards will lead to an inconsistent state.
精彩评论