在我的主要活动中,我有一个片段,我在其中应用 setRetainInstance(true),这样我在其中使用的 AsyncTask 不会受到方向变化的干扰。
AsyncTask 处理了大量工作。这就是为什么我想在我的活动之上显示一个带有进度条的对话框。
我进行了一些研究,并成功使用了 DialogFragment:
公共类 DialogWait 扩展 DialogFragment {
private ProgressBar progressBar;
public DialogWait() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_wait, container);
Dialog dialog = getDialog();
dialog.setTitle("Hello");
setCancelable(false);
progressBar = (ProgressBar) view.findViewById(R.id.progress);
return view;
}
public void updateProgress(int value) {
progressBar.setProgress(value);
}
这是我的异步任务:
public class InitAsyncTask extends AsyncTask<Void, Integer, Void> {
private Context activity;
private OnTaskDoneListener mCallback;
private DialogWait dialog;
public InitAsyncTask(Context context, OnTaskDoneListener callback, DialogWait dialogWait) {
activity = context;
mCallback = callback;
dialog = dialogWait;
}
@Override
protected Void doInBackground(Void... params) {
doStuff();
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
dialog.updateProgress(values[0]);
}
@Override
protected void onPostExecute(Void result) {
publishProgress(100);
if(dialog != null)
dialog.dismiss();
mCallback.onTaskDone();
}
private void doStuff() {
//...
}
}
如果我不改变屏幕旋转,它工作正常。但是如果我这样做了,对话框就会被关闭,几秒钟后,我得到了一个 NullPointerEsception,因为我设置了条件:if(dialog != null)
我究竟做错了什么?