When clicking an EditText field in my (Scherlock)FragmentActivity a DatePicker shows up. After selecting date and clicking "apply" the Edittext field is populated with the date. This works fine until i rotate the screen while the DatePicker is visible. Its onCreateDialog-method starts again an everything looks right. But when I click "apply" no date is filled in to the EditText field.
This is most likely because I haven't managed to retain the listener. This problem is very similar to DialogFragment - retaining listener after screen rotation However in my code I have a listener interface included in the DialogFragment and I cannot manage to reach the listener from the calling FragmentActivity, (as the solution suggests in the mentioned question).
- I suppose not, but is there a way to save a listener before the activity is destroyed? (I'm not interested in the Manifest modification.)
- Is there a way to modify this DialogFragment or is this solution with included interface not suitable in this case?
Please help me, this really shouldn't be that hard but I've been working with it for longer than I will admit...
Here is the DialogFragment code:
public class DateDialogFragment extends SherlockDialogFragment {
public static String TAG = "DateDialogFragment";
static Context mContext;
static int mYear;
static int mMonth;
static int mDay;
static DateDialogFragmentListener mListener;
public static DateDialogFragment newInstance(Context context, DateDialogFragmentListener listener, Calendar now) {
DateDialogFragment dialog = new DateDialogFragment();
mContext = context;
mListener = listener;
mYear = now.get(Calendar.YEAR);
mMonth = now.get(Calendar.MONTH);
mDay = now.get(Calendar.DAY_OF_MONTH);
return dialog;
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new DatePickerDialog(mContext, mDateSetListener, mYear, mMonth, mDay);
}
private OnDateSetListener mDateSetListener = new OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
mListener.updateChangedDate(year, monthOfYear, dayOfMonth);
}
};
public interface DateDialogFragmentListener {
public void updateChangedDate(int year, int month, int day);
}
}
Edit: Here is a piece of my FragmentActivity: the method I use to call the DialogFragment:
public void showDatePickerDialog() {
now = Calendar.getInstance();
DateDialogFragment frag = DateDialogFragment.newInstance(
this, new DateDialogFragment.DateDialogFragmentListener() {
public void updateChangedDate(int year, int month, int day) {
birthdate.setText(String.valueOf(day) + "-" + String.valueOf(month+1) + "-" + String.valueOf(year));
now.set(year, month, day);
pet.setBirthdate(birthdate.getText().toString());
}
},
now);
frag.show(getSupportFragmentManager(), "DateDialogFragment");
}