I need the default value set in the preferences XML to be available on first run.
In some phones this works, but some other phones (e.g. Samsung) behave very strangely.
In my particular case, the following code:
String key = "@string/timeout_key"
timeout = Integer.valueOf(prefs.getString(key, "10"));
Keeps returning (to timeout) the default value of “10” (passed as the 2nd parameter to prefs.getString()), although the preferences XML specifies:
android:defaultValue="5"
The string “timeout_key” exists and I could verify that it is read correctly.
My “manual workaround” currently is to invoke the settings editor, retype the setting and press OK.
Is there a way to do this programmatically?
The SharedPreferences.getString() method is buggy and won’t return
android:defaultValue. It will only return the second param if read fails. To work around this, put null in the second param:This will of course throw an exception the first time you call it after installing the app, so what you do is enclose it in a
tryand when catching the exception, write your default (the one in your android:defaultValue, originally intended to be used if Android wasn’t buggy):Ugly, but works.