Sunday, January 24, 2010

Android Date Picker Dialog Weirdness

Recently I needed to add a date picker dialog to a form I was designing. It was pretty straight forward, an EditText with an adjacent button to trigger a DatePickerDialog to quickly select a date.

The following is an example from my project. I create a managed date picker dialog that is set to the date in the EditText. If the EditText is empty or has an invalid date string, the date picker dialog is set to today's date.

Code snippet from my activity:

...

@Override
protected Dialog onCreateDialog(int id) {
	Log.d(TAG, "onCreateDialog() -> id = " + id);

	if (id == ID_DIALOG_DATE_PICKER) {
		return new DatePickerDialog(this, searchDateSetListener, 0, 0, 0);
	}
		
	return super.onCreateDialog(id);
}

@Override
protected void onPrepareDialog(int id, Dialog dialog) {
	Log.d(TAG, "onPrepareDialog() -> id = " + id);
	
	if (id == ID_DIALOG_DATE_PICKER) {
		DatePickerDialog dlg = (DatePickerDialog) dialog;
		
		// Get today's date
		Calendar c = Calendar.getInstance();
		
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH);
		int day = c.get(Calendar.DAY_OF_MONTH);
		
		// Get the search filter
		String filter = editSearchFrom.getText().toString().trim();
			
		// Update the date picker dialog
		try {
			Date date = dateFormat.parse(filter);
			c.setTime(date);
			dlg.updateDate(
				c.get(Calendar.YEAR),
				c.get(Calendar.MONTH),
				c.get(Calendar.DAY_OF_MONTH));
		} catch (ParseException e) {
			dlg.updateDate(year, month, day);
		}
	}
}

...