0

Why do I get a NPE (return dialog is null) with the following?

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;
    }
}

The following does work. Why?

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;
    }
}
stefana
  • 2,606
  • 3
  • 29
  • 47

1 Answers1

1

In Java (I don't know much about other languages) , the global(instance) fields will be initialized immediately after the object is Constructed(instance created). so when you declare Dialog as field like

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));
 }

here Dialog will be initialzed after Constructor call and still onAttach() is not called. thus here getActivity() returns null

Gopal Gopi
  • 11,101
  • 1
  • 30
  • 43
  • How can the dialog be constructed if the Calendar hasn't been initialized yet? If you say that the field will be initialized after the object has been created, how is this possible? – stefana Jan 08 '14 at 11:31
  • you are getting NPE only because of getActivity(). it does not matter how you declared Calender as global instance or local field... – Gopal Gopi Jan 08 '14 at 11:35