简体   繁体   English

整数不能强制转换为 Long

[英]Integer cannot be cast to Long

I am keeping track of row ids in the shared preferences for my sqlite database.我正在跟踪我的 sqlite 数据库的共享首选项中的行 ID。 I was using an int, but then I realized that maybe long would be more adequate for this since the id value could become huge over time.我使用的是 int,但后来我意识到可能 long 会更适合这个,因为 id 值可能会随着时间的推移变得很大。 I am getting this error when I try to getLong from shared preference: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long当我尝试从共享首选项 getLong 时出现此错误: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long

sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    editor = sharedPreferences.edit();
    workoutId = sharedPreferences.getLong("workoutId", 0);

My workoutId initialize code is a global variable private long workoutId;我的锻炼 ID 初始化代码是一个全局变量private long workoutId; I'm not sure where it is getting integer value from in the error message.我不确定它从错误消息中获取整数值的位置。 Or maybe int will suite just fine?或者也许 int 会很好?

The problem is with your default value which is Integer.问题在于您的默认值是整数。

You should use你应该使用

workoutId = sharedPreferences.getLong("workoutId", 0L);

OR或者

workoutId = sharedPreferences.getLong("workoutId", (long) 0);

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

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