0

我有以下代码:

public class SomeActivity extends Activity {
    Context context;
    List<MenuItem> menuItems;

    public void importList(View v) {
        menuItems = new ArrayList<MenuItem>();
        ProgressDialog dialog = ProgressDialog.show(this.context, "TITLE", "MSG");

        MyAsyncTask task = new MyAsyncTask(context); // Context is here because I tried to create ProgressDialog inside pre/postExecute, but it doesn't work either
        task.execute();
        try {
            // menuItems = task.get();
        } catch(Exception e) {
            // : (
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // ...
        this.context = this;
    }
}

当我评论该行时,我从 AsyncTask ("menuItems = task.get()") 获取值,一切正常。但是当我取消注释时,任务完成后会出现 ProgressDialog,并返回值。这是为什么?

我认为这与这些上下文有关(这就是我包含 onCreate 方法的原因),但我不知道如何解决它。显然,我希望 ProgressDialog 在任务完成之前而不是之后显示。

不确定是否相关 - MyAsyncTask 正在执行 http 请求和一些 json 解析。

4

1 回答 1

2

我认为这与这些上下文有关

一点也不。此外,Context从 an发送时,Activity您不需要创建变量。只需使用thisor ActivityName.this

 MyAsyncTask task = new MyAsyncTask(this);

But when I uncomment it, ProgressDialog appears AFTER the task is finished, and value returned. Why is that?

Calling get() blocks the UI, this is why you don't see the progress until it is done. You don't need to call this. The point of onProgressUpdate() is so the background thread (doInBackground()) can call it to update the UI since doInBackground() doesn't run on the UI.

Remove that line from your code and never look at it again. If there is a reason that you think you need it then please explain and we can help you find a better way.

Edit

See this SO answer on updating when the task is finished

于 2013-09-04T20:37:14.983 回答