我正在尝试通过 Sharedpreferences 获取和设置 bool 值。以下代码在 Marshmallow 上完美运行,但在 Lolipop (5.0.1) 上运行不正常 - 我收到异常: java.lang.ClassCastException: java.lang.String cannot becast to java.lang.Boolean when I call getintroStatus()
有什么帮助吗?
public void setIntrodone(boolean status) {
editor = settings.edit();
editor.putBoolean("intro_done_boolean", status);
editor.commit();
}
public boolean getintroStatus() {
try {
return settings.getBoolean("intro_done_boolean", false);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
Logcat 错误:
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean
04-20 14:06:59.438 1401-1401/io.authme.home W/System.err: at android.app.SharedPreferencesImpl.getBoolean(SharedPreferencesImpl.java:263)
04-20 14:06:59.438 1401-1401/io.authme.home W/System.err: at io.authme.home.MitroApplication.getintroStatus(MitroApplication.java:107)
04-20 14:06:59.438 1401-1401/io.authme.home W/System.err: at io.authme.home.MainActivity.onCreate(MainActivity.java:81)
04-20 14:06:59.438 1401-1401/io.authme.home W/System.err: at android.app.Activity.performCreate(Activity.java:6285)
04-20 14:06:59.438 1401-1401/io.authme.home W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
04-20 14:06:59.438 1401-1401/io.authme.home W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2405)
04-20 14:06:59.438 1401-1401/io.authme.home W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2535)
04-20 14:06:59.438 1401-1401/io.authme.home W/System.err: at android.app.ActivityThread.access$900(ActivityThread.java:154)
04-20 14:06:59.438 1401-1401/io.authme.home W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1380)
04-20 14:06:59.438 1401-1401/io.authme.home W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
04-20 14:06:59.438 1401-1401/io.authme.home W/System.err: at android.os.Looper.loop(Looper.java:148)
04-20 14:06:59.438 1401-1401/io.authme.home W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5490)
04-20 14:06:59.438 1401-1401/io.authme.home W/System.err: at java.lang.reflect.Method.invoke(Native Method)
04-20 14:06:59.438 1401-1401/io.authme.home W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
04-20 14:06:59.438 1401-1401/io.authme.home W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
最佳答案
在我看来,它与 android 版本没有任何关系,也许其他设备优先将相同的键设置为某些字符串,这会导致您出现问题。
我建议您确保不在其他地方使用相同的 key ,如果您确定不这样做,我建议您清除其他设备上的应用数据,然后重试。
关于android - java.lang.ClassCastException : java. lang.String 无法转换为 java.lang.Boolean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36738171/