diff --git a/DatePreference/src/org/bostonandroid/datepreference/DatePreference.java b/DatePreference/src/org/bostonandroid/datepreference/DatePreference.java index 14d1d6c..d48e6d2 100644 --- a/DatePreference/src/org/bostonandroid/datepreference/DatePreference.java +++ b/DatePreference/src/org/bostonandroid/datepreference/DatePreference.java @@ -136,7 +136,7 @@ protected Parcelable onSaveInstanceState() { protected void onRestoreInstanceState(Parcelable state) { if (state == null || !state.getClass().equals(SavedState.class)) { super.onRestoreInstanceState(state); - setTheDate(((SavedState) state).dateValue); + setTheDate(defaultValue()); } else { SavedState s = (SavedState) state; super.onRestoreInstanceState(s.getSuperState()); @@ -212,6 +212,35 @@ public void onClick(DialogInterface dialog, int which) { onDialogClosed(which == DialogInterface.BUTTON1); // OK? } + /** + * Produces the date the user has selected for the given preference, as a + * calendar. + * + * @param preferences + * the SharedPreferences to get the date from + * @param field + * the name of the preference to get the date from + * @param defaultDate + * the default date to use in case no preference is already saved + * @return a Calendar that the user has selected + */ + public static Calendar getDateFor(SharedPreferences preferences, String field, Date defaultDate) { + String defaultString = defaultDate != null ? formatter().format(defaultDate) : ""; + String persisted = preferences.getString(field, defaultString); + Date date; + if ("".equals(persisted)) { + if (defaultDate == null) { + return null; + } // if + date = defaultDate; + } else { + date = stringToDate(persisted); + } // if/else + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + return cal; + } + /** * Produces the date the user has selected for the given preference, as a * calendar.