android – SharedPreferences.getInt() results in ClassCastException – Why?-ThrowExceptions

Exception or error:

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:

sharedPrefs.getInt(getString(R.string.numeric_val), 3)

It works, but when I try to read it, for the first time after application install, it generates a ClassCastException.

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 SharedPreferences.getInt()?

I know I can use SharedPreferences.getString() instead and then do the parsing/conversion myself, but then what is the purpose of SharedPreferences.getInt()?

How to solve:

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 getInt().

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.

###

android:defaultValue="0"

is a string.

There is no way to declare an actual int in the xml of your prefs

Leave a Reply

Your email address will not be published. Required fields are marked *