DatePickerDialog NPE

时间:2014-01-08 11:06:47

标签: android

为什么我会使用以下内容获得NPE(返回对话框为空)?

public class ViewCalendar extends DialogFragment implements OnDateSetListener {
    private Calendar c = Calendar.getInstance();
    private DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {  
        return dialog;
    }
}

以下工作正常。为什么呢?

public class ViewCalendar extends DialogFragment implements OnDateSetListener {
    private Calendar c = Calendar.getInstance();

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)); 
        return dialog;
    }
}

1 个答案:

答案 0 :(得分:2)

在Java中(我对其他语言不太了解),全局(实例)字段将在构造对象(实例创建)后立即初始化。所以当你将Dialog声明为

之类的字段时
public class Sampple extends Fragment {
     private DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
 }

此处Dialog将在构造函数调用后初始化,并且仍未调用onAttach()。因此getActivity()返回null