SharedPreferences.getInt() results in ClassCastException - Why?

倖福魔咒の 提交于 2019-11-30 00:38:08

问题


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


回答1:


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.




回答2:


android:defaultValue="0"

is a string.

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



来源:https://stackoverflow.com/questions/7257232/sharedpreferences-getint-results-in-classcastexception-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!