sharedPref.getInt:java.lang.String无法强制转换为java.lang.Integer [英] sharedPref.getInt: java.lang.String cannot be cast to java.lang.Integer

查看:1029
本文介绍了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"));

这篇关于sharedPref.getInt:java.lang.String无法强制转换为java.lang.Integer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆