SharedPreferences.getInt()导致ClassCastException - 为什么?

时间:2011-08-31 12:59:37

标签: android android-preferences

我在首选项XML中定义了一个简单的(非用户可编辑的)数字设置,如下所示:

<EditTextPreference
  android:key="@string/numeric_val"
  android:defaultValue="0" />

我用这个简单的陈述读了它:

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

虽然有效但是当我尝试阅读,这是应用安装后的第一次时,会生成ClassCastException

documentation表示getInt() “如果此名称的偏好不是int,则抛出ClassCastException。” - 我知道这种偏好很明显定义为<EditTextPreference>(字符串?)但是,如果这是异常的原因,我应该如何使用SharedPreferences.getInt()

我知道我可以使用SharedPreferences.getString()然后自己进行解析/转换,但那么SharedPreferences.getInt()的目的是什么?

2 个答案:

答案 0 :(得分:29)

您可以将首选项存储为sharedPreferences.edit().putInt(..).commit()(作为示例);

然后将它们作为getInt。但是如果使用EditTextPreference,它会将首选项的类型设置为string。因此,如果您使用EditTextPreference存储某些数据,请使用Integer.valueOf(getString)将其恢复。

如果您手动 ,请使用getInt()

作为一种变通方法,您可以在此EditTextPreference上设置onPreferenceChangeListener,每当用户更改它时,您将手动将其保存为int,这样,getInt将正常工作。

答案 1 :(得分:6)

android:defaultValue="0"

是一个字符串。

无法在首选项的xml中声明实际的int