sharedPref.getInt:java.lang.String无法强制转换为java.lang.Integer

问题描述:

我有 preferences.xml ,其中包含以下定义:

I have a preferences.xml which contains the following definition:

<ListPreference
    android:title="@string/LimitSetting"
    android:summary="@string/LimitSettingText"
    android:key="limitSetting"
    android:defaultValue="10"
    android:entries="@array/limitArray"
    android:entryValues="@array/limitValues" />

并且值定义如下:

<string-array name="limitArray">
    <item>1 %</item>
    <item>3 %</item>
    <item>5 %</item>
    <item>10 %</item>
    <item>20 %</item>
</string-array>
<string-array name="limitValues">
    <item>1</item>
    <item>3</item>
    <item>5</item>
    <item>10</item>
    <item>20</item>
</string-array>

在活动中调用如下:

SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
int offsetProgressInitial = sharedPref.getInt("limitSetting", 10);

到目前为止一直很好,但是当代码实际调用时我得到了这个错误:

So far so good, but when the code gets actually called I get this error:

Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at android.app.SharedPreferencesImpl.getInt(SharedPreferencesImpl.java:239)
at com.test.app.NewEntryActivity.onCreate(NewEntryActivity.java:144)
at android.app.Activity.performCreate(Activity.java:5977)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2258)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365) 
at android.app.ActivityThread.access$800(ActivityThread.java:148) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283) 

这个错误对我没有任何意义。该列表仅包含可以转换为int的值,xml文件和代码中给出的默认值也只表示一个数字。那么为什么我会得到这个错误,以及如何修复它?

This error does not make any sense to me. The list only contain values that can be converted into an int, and the default values given in the xml file and in the code also represents just a number. So why do I get this error, and how to fix it?

如果你看一下 getInt()在内部你会看到问题:

If you look at what getInt() does internally you will see the problem:

Integer v = (Integer)mMap.get(key);

您的密钥limitSetting返回字符串不能转换为整数。

Your key "limitSetting" is returning a String which cannot be cast to an Integer.

你可以自己解析它:

int offsetProgressInitial = Integer.parseInt(sharedPref.getString("limitSetting", "10"));