【发布时间】:2013-01-13 01:43:07
【问题描述】:
我正在使用 Asynctask 来执行一个耗时的方法,doStuff(),其中包括分配全局数据结构。调试器确认调用了 doStuff(),但是当在 Asynctask 结束时绘制新视图时,在访问全局数据结构时出现空指针异常。代码如下:
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();
}
}
我使用 new MyTask(this).execute(); 从多个活动中执行 Asynctask。
【问题讨论】:
-
您如何确定
AsyncTask的结尾以绘制新视图?它不在你的onPostExecute -
new MyTask(this).execute();之后我开始打算转到新视图。 -
这听起来像你的问题,
execute启动了任务,但直到onPostExecute执行后你才知道它已经完成。您可以将代码移至onPostExecute或对其进行回调 -
在你确定 asynctask 完成后你想做什么。 NPE 当前失败的代码,因为它很可能在完全初始化之前运行并访问事物。
-
好的,所以 Asynctasks 就像线程一样,因为主线程在 Asynctask 启动时继续运行,而不是在它完成时。谢谢!将此作为答案发布,我会接受。
标签: android android-asynctask progressdialog