【问题标题】:Integer cannot be cast to Long整数不能转换为 Long
【发布时间】:2020-01-25 10:07:21
【问题描述】:

我正在跟踪我的 sqlite 数据库的共享首选项中的行 ID。我使用的是 int,但后来我意识到 long 可能更适合于此,因为 id 值可能会随着时间的推移而变得巨大。当我尝试从共享首选项中获取 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);

我的锻炼标识初始化代码是一个全局变量private long workoutId; 我不确定它从错误消息中的何处获取整数值。 或者也许 int 会很好?

【问题讨论】:

  • @NIKHILAGGARWAL 0Ffloat-literal。我看不出这有什么帮助。

标签: java android


【解决方案1】:

问题在于您的默认值是整数。

你应该使用

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

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

【讨论】:

  • 感谢您的建议,但我只是尝试了这两种方法,但仍然遇到相同的错误。这很奇怪。
  • 我发现了我的问题。当我将它作为 int 时,它仍在读取设置。我清除了我的模拟器的数据,它工作。谢谢!
猜你喜欢
  • 1970-01-01
  • 2016-09-03
  • 1970-01-01
  • 2017-10-03
  • 2021-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多