A DatePickerDialog is loaded in a Fragment with today's showing as the default date when the dialog is first opened. The user then selects a date and then the dialog is dismissed. On next re-open, how do I show the previously selected date as the default date rather than it showing today's date?
I have tried .set() in the Activity but don't know how to use .get() to retrieve the date in the fragment. I've tried an interface with a listener between the Activity and the fragement but could not get that to work and it seems overly complicated for the simple task I am trying to achieve. And I've tried a bundle sent from the Activity to the fragment but I haven't been able to get that to work either. Please advise.
Activity file:
...
final Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, day);
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
Fragment file:
...
public static 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);
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Save selected date in a date variable here? How?
// How do I then use the date variable in onCreateDialog
// rather than the get(Calendar) code that returns today's date?
}
}