简体   繁体   English

在运行时获取ClassCastException

[英]Getting ClassCastException while running

This is my code for preference.xml 这是我的preference.xml的代码

<EditTextPreference
        android:defaultValue="3"
        android:key="number"
        android:numeric="integer"
        android:summary="Enter how many Days older files"
        android:title="Set Days" />

and when i am trying to get its value with sharedpreference as below 当我尝试通过sharedpreference获取其值时,如下所示

int fileolderthan = sharedPreferences.getInt("number",7);

Getting error on running code java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer. 运行代码java.lang.ClassCastException时出错:java.lang.String无法转换为java.lang.Integer。

How to fix it, any tip please. 如何解决它,请提示。

Change this line 更改此行

int fileolderthan = sharedPreferences.getInt("number",7);

with

int fileolderthan = Integer.valueOf(sharedPreferences.getString("number","7"));

EditTextPreference saves value as string even if you set android:numeric="integer" . 即使您设置了android:numeric="integer" EditTextPreference也会将值保存为字符串。 So you first retrieve the string, then convert it into integer. 因此,您首先要检索字符串,然后将其转换为整数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM