2

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);
        }
    }
}

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.

4

2 回答 2

1

您在课堂上创建了两次对象。ProgressDialog.show已经返回了一个创建的对象ProgressDialog,但是您首先在顶部实例化了它。ProgressDialog应该实例化一次,因此请尝试删除顶部的实例化并重试,如下所示:

private ProgressDialog dialog;

protected void onPreExecute() {
    dialog = ProgressDialog.show(Activity.this, "wait...", "", true, true);
}
于 2012-08-13T22:25:05.033 回答
0

也许是因为 void 参数导致了这个问题。只需尝试使用 Integer 作为参数。:

public class Upload extends AsyncTask<Integer, Integer, Integer>
于 2013-10-11T21:01:55.613 回答