I'm trying to use date picker widget out of the docs example here: docs
However when i call newFragment.show(getSupportFragmentManager(), "datePicker");
application crashes and stack trace shows the following:
FATAL EXCEPTION: main Process: com.wgu.andrey.clp1, PID: 8125
java.lang.IllegalStateException: Activity has been destroyed
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1864)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:650)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:609)
at android.support.v4.app.DialogFragment.show(DialogFragment.java:143)
at com.wgu.andrey.clp1.Terms.showDatePickerDialog(Terms.java:67)
DatePickerFragment.java
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
}
}
Terms.java
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
On the same lines what @Mike said, terms class can't be a sub class of the activity. Move the method to its own utility class and then call that method by Either passing the context or passing the fragment manager.
Something like this:
public void showDatePickerDialog(View v, AppCompatActivity context) {
DialogFragment newFragment = new DialogFragment();
newFragment.show(context.getSupportFragmentManager(), "TAG");
}
Alternatively, using FragmentManager
public void showDatePickerDialog(View v, FragmentManager fm) {
DialogFragment newFragment = new DialogFragment();
newFragment.show(fm, "datePicker");
}