Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SharedPreferences.getInt() results in ClassCastException - Why?

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()?

like image 360
uTubeFan Avatar asked Aug 31 '11 12:08

uTubeFan


2 Answers

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.

like image 74
Alex Orlov Avatar answered Oct 22 '22 10:10

Alex Orlov


android:defaultValue="0"

is a string.

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

like image 7
njzk2 Avatar answered Oct 22 '22 12:10

njzk2