I have a simple (not user-editable) numerical setting defined in a preferences XML as follows:
<EditTextPreference android:key="@string/numeric_val" android:defaultValue="0" />
And I read it using this simple statement:
It works, but when I try to read it, for the first time after application install, it generates a
The documentation says that
getInt() “Throws ClassCastException if there is a preference with this name that is not an int.” – and I know that this preference is clearly defined as an
<EditTextPreference> (a string?) but, if this is the reason for the exception, how I am supposed to use
I know I can use
SharedPreferences.getString() instead and then do the parsing/conversion myself, but then what is the purpose of
You can store preferences as
sharedPreferences.edit().putInt(..).commit() (as an example);
And then get them as getInt. But if you use EditTextPreference it will set the type of the preference to string. So if you use EditTextPreference to store some data, use
Integer.valueOf(getString) to get it back.
If, you put it manually, use
As a workaround, you can set
onPreferenceChangeListener on this EditTextPreference , and whenever user changes it, you will manually save it as an int, so then, getInt will work normally.
is a string.
There is no way to declare an actual int in the xml of your prefs