I used code sample for TimePreference from link. Related to my question methods:
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
Log.v(TAG, "a.getString(index): " + a.getString(index));
Log.v(TAG, "hasKey(): " + hasKey() );
return a.getString(index);
}
@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
String time=null;
if (restoreValue) {
if (defaultValue==null) {
time=getPersistedString(DEFAULT_NOTIF_TIME_STRING);
}
else {
time=getPersistedString(defaultValue.toString());
}
}
else {
time=defaultValue.toString();
}
lastHour=getHour(time);
lastMinute=getMinute(time);
}
In notification_time_fragment.xml:
<mypackage.preferences.TimePreference
android:key ="@string/notif_time_key"
android:title="@string/notif_time_title"
android:defaultValue="08:00"
android:persistent="true"
/>
In activity
PreferenceManager.setDefaultValues(this, R.xml.notification_time_fragment, true);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String notificationTime = sharedPreferences.getString(getString(R.string.notif_time_key), "can't read time");
And notificationTime is equal to "can't read time". Logging from onGetDefaultValue:
a.getString(index): 08:00
hasKey(): false
I guess that this false
from hasKey()
is the reason why the preference is not saved in sharedPreference
by command PreferenceManager.setDefaultValues()
.
I must say that android:defaultValue
of EditTextPreference, CheckBoxPreference
are properly retrieved from xml-resource using the same commands.
Why hasKey()
is false
?
What is wrong in TimePreference? How can I make it to write its default value without launching PreferenceActivity
and without "dirty coding" in MainActivity
?