I have a datePicker dialog in my app. It works fine when I select a date. However if in the dialog I change the date and then press cancel, the original edittext remains unchanged as it should, but the Date picker still has the date from before when it was cancelled. I would like to make sure that EVERY time I go into the Date Picker, it sets the date from the EditText. My code is as follows.
onCreate() Method
// Date Listener
fdEtDate.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
showDialog(DATE_DIALOG_ID);
return false;
}
});
Further down the Activity
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
dateSetListener,
cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE));
case STD_DIALOG_ID:
return new TimePickerDialog(this,
stdSetListener,
stdHH, stdMM,
true);
case STA_DIALOG_ID:
return new TimePickerDialog(this,
staSetListener,
staHH, staMM,
true);
}
return null;
}
// the callback received when the user "sets" the date in the dialog
private DatePickerDialog.OnDateSetListener dateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, monthOfYear);
cal.set(Calendar.DATE, dayOfMonth);
updateDisplay();
}
};
// updates the date in the TextView
private void updateDisplay() {
fdEtDate.setText(
new StringBuilder()
.append(Utils.pad(cal.get(Calendar.DATE))).append(Const.SQL_DATE_SEP)
.append(Utils.pad(cal.get(Calendar.MONTH)+1)).append(Const.SQL_DATE_SEP)
.append(cal.get(Calendar.YEAR)));
fdEtStd.setText(
new StringBuilder()
.append(Utils.pad(stdHH)).append(Const.SQL_TIME_SEP)
.append(Utils.pad(stdMM)));
fdEtSta.setText(
new StringBuilder()
.append(Utils.pad(staHH)).append(Const.SQL_TIME_SEP)
.append(Utils.pad(staMM)));
}
Is seems to create a new Dialog each time, so why isn’t it initialised each time with the Date from fdEtDate (EditText)
Thanks in advance
you should use onPrepareDialog to set the initial date every time the dialog is shown.
A dialog is created only the first time it is shown and from that point it is reused unless you destroy it explicitly with removeDialog().
http://developer.android.com/guide/topics/ui/dialogs.html