在preExecute的Andr​​oid的AsyncTask不indeterminantly叫 [英] Android AsyncTask onPreExecute not called indeterminantly

查看:106
本文介绍了在preExecute的Andr​​oid的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);
}

这篇关于在preExecute的Andr​​oid的AsyncTask不indeterminantly叫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆