在preExecute的Android的AsyncTask不indeterminantly叫
我有一个应该显示一个进度条,而它通过互联网上传了一些东西的AsyncTask的。有时它就像一个魅力和有时不显示任何进度条。这里是code:
I have an AsyncTask that is supposed to show a progress bar while it uploads some stuff via Internet. Sometimes it works like a charm and sometimes it does not show any progress bar. Here is the code:
public class Upload extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog = new ProgressDialog(Activity.this);
protected void onPreExecute() {
dialog = ProgressDialog.show(Activity.this, "wait...", "", true, true);
}
@Override
protected Void doInBackground(Void... params) {
//upload stuff
return null;
}
protected void onPostExecute(Void result) {
try {
if (dialog.isShowing())
dialog.dismiss();
dialog = null;
} catch (Exception e) {
// nothing
}
Intent next = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(next);
}
}
}
该doInBackground和onPostExecute总是工作,有时干脆它的工作原理就像一个魅力。但有时候,有没有当它被上传进度条。这是一个竞争条件吗?我不这么认为,但我找不到任何解释。
The doInBackground and onPostExecute work always, and sometimes altogether it works like a charm. But sometimes, there is no progress bar while it is uploading. Is this a race condition? I do not think so, but I cannot find any explanation.
您是在类创建对象的两倍。在 ProgressDialog.show
已返回一个创建 ProgressDialog
对象,但你已经在顶部第一次实例吧。在 ProgressDialog
应该被实例化一次,所以尝试在顶部取下实例,然后再试一次,像这样:
You're creating the object twice in the class. The ProgressDialog.show
already returns a created ProgressDialog
object, but you have instantiated it first at the top. The ProgressDialog
should be instantiated once, so try removing the instantiation at the top and try again, like so:
private ProgressDialog dialog;
protected void onPreExecute() {
dialog = ProgressDialog.show(Activity.this, "wait...", "", true, true);
}