简体   繁体   English

Asynctask与Progressdialog

[英]Asynctask with Progressdialog

I'm using an Asynctask to execute a time-consuming method, doStuff() , which among other things allocates global data structures. 我正在使用Asynctask来执行一个耗时的方法doStuff() ,其中包括分配全局数据结构。 A debugger confirms that doStuff() is called, but when a new view is drawn at the end of the Asynctask, I get a null pointer exception while accessing the global data structures. 调试器确认调用了doStuff() ,但是当在Asynctask的末尾绘制新视图时,我在访问全局数据结构时得到空指针异常。 Here is the code: 这是代码:

public class MyTask extends AsyncTask<Void, Void, Void> {
    protected ProgressDialog dialog;

    public MyTask (Context context) {
        dialog = new ProgressDialog(context);
    }

    @Override
    protected void onPreExecute() { 
       super.onPreExecute();
       dialog.setMessage("Foo");
       dialog.show();    
    }

    @Override
    protected Void doInBackground(Void... params) {
        doStuff();
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        dialog.dismiss();
    }
}

I execute the Asynctask from multiple activities using new MyTask(this).execute(); 我使用new MyTask(this).execute();执行来自多个活动的new MyTask(this).execute(); .

AsyncTask is a really a convenience wrapper around a background thread and a handler. AsyncTask是一个真正的后台线程和处理程序的便利包装器。 You are executing code before the background task finishes. 您在后台任务完成之前执行代码。 To know when the background task is finished, you need to put the code you want to execute or otherwise signal your main activity in onPostExecute (which will run on the UI/main thread) that the task is complete. 要知道后台任务何时完成,您需要将要执行的代码放在onPostExecute (将在UI /主线程上运行)中完成任务的主要活动信号。 For more details, see the using AsyncTask section of the Processes and Threads guide . 有关更多详细信息,请参阅“ 进程和线程”指南的“使用AsyncTask”部分。

您必须在使用AsyncTask的Activity中声明ProgressDialog

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM