获取ClassCastException:java.lang.Integer无法在不强制转换的情况下强制转换为java.lang.String错误
我正在为Android开发一款应用程序,但无法找出我所犯的错误。我搜索错误已经超过4个小时了,所以请不要认为我是因为调试的懒惰而打扰了你 我在使用SharedReference时遇到以下异常:获取ClassCastException:java.lang.Integer无法在不强制转换的情况下强制转换为java.lang.String错误,java,android,exception,casting,sharedpreferences,Java,Android,Exception,Casting,Sharedpreferences,我正在为Android开发一款应用程序,但无法找出我所犯的错误。我搜索错误已经超过4个小时了,所以请不要认为我是因为调试的懒惰而打扰了你 我在使用SharedReference时遇到以下异常: E/AndroidRuntime: FATAL EXCEPTION: main Caused by: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String at android.
E/AndroidRuntime: FATAL EXCEPTION: main
Caused by: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at android.app.SharedPreferencesImpl.getString(SharedPreferencesImpl.java:235)
at de.immozukunft.quicksteuer.QuickSteuerActivity.updateTextView(QuickSteuerActivity.java:56)
at de.immozukunft.quicksteuer.QuickSteuerActivity.onCreate(QuickSteuerActivity.java:36)
但根据我的理解,我并没有在这一行做演员。第36行是updateTextView()方法的调用
我在XML文件中的首选项如下:
<EditTextPreference
android:defaultValue="0"
android:dialogTitle="@string/capitalownership"
android:inputType="number"
android:key="capitalownership"
android:title="@string/capitalownership" />
:
返回首选项值(如果存在),或返回defValue。投掷
ClassCastException,如果此名称的首选项不是
一串
所以我猜您有一个“capitalownership”首选项,它在您第一次保存
capitalownership
时被存储为整数,您可能没有将它保存为字符串,所以当您尝试检索它时,它将检索一个整数,但当您执行getString
时,您尝试将其转换为String,它将得到异常
String tmp = prefs.getString("capitalownership", "0");
试着这样做:
int tmp = prefs.getInt("capitalownership", 0);
此外,您已经将编辑文本设置为仅输入数字,因此这里不会出现字符串
编辑:
共享首选项存储为映射
。正如您所看到的,映射的值是一个通用的对象
,如果保存为整数
,则需要作为整数进行检索。这是非常动态的,因此如果您一次保存为整数
,下一次保存为字符串
(保存到同一个键),则需要跟踪保存的类型,以便检索它
如果已将其保存为Integer
一次,然后将其再次保存为String
,则在检索时需要使用getString()
。如果您不确定其中包含什么,可以使用getAll()方法以映射的形式检索整个首选项,然后在此映射中使用get(“capitalownership”)
,最后使用instanceof
检查它是什么类型。但这太麻烦了,你只需要确定你将以某种类型保存密钥(资本所有权),并确保你总是这样做
这就是正在发生的事情:
1) 您尝试检索与该键关联的值,Android会给您一个对象
2) 然后,Android尝试强制转换为与该方法关联的值(在您的示例中是一个字符串)。因为该值实际上是一个整数,这就是类强制转换问题的根源。您不应该使用
int capitalOwnership = Integer.parseInt(tmp);
因为您正在尝试将整数作为字符串获取
<EditTextPreference
android:defaultValue="0"
android:dialogTitle="@string/capitalownership"
**android:inputType="number"**
android:key="capitalownership"
android:title="@string/capitalownership" />
你也需要像这样保存它
pref.putInt("key",value);
String tmp=prefs.getInt(“capitalownership”,“0”)+“String tmp=prefs.getString(“capitalownership”,“0”)-->这必须是整数。显示SharedReferencesImpl.java类中第235行的代码将“capitalownership”更改为声明的字符串,但当我使用它时,不可能清除旧值吗?我不熟悉SharedReference是如何存储的以及它是如何检索的。我想,当我简单地从设备上删除应用程序并重新安装时,应该没问题。非常感谢!我将更改我的代码:)是的,但问题是,共享首选项是基于字符串的。我不得不把所有的整数都改成字符串。每当我使用编辑器时,我想会有一种转换。。。我在我的第一篇文章中就有了解决方案。是的,那一定是对的,有可能澄清这个偏好吗?还是那个条目?
<EditTextPreference
android:defaultValue="0"
android:dialogTitle="@string/capitalownership"
**android:inputType="number"**
android:key="capitalownership"
android:title="@string/capitalownership" />
int capitalOwnership = pref.getInt("capitalownership", 0);
pref.putInt("key",value);