【问题标题】:Kotlin: java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.IntegerKotlin:java.lang.ClassCastException:java.lang.Long 无法转换为 java.lang.Integer
【发布时间】:2020-12-09 18:13:06
【问题描述】:

我知道有很多关于这个例外的问题,但没有适合我的答案。

var count = sharedPref.getInt("flutter.badgeCount", 0)    // line 12
ShortcutBadger.applyCount(applicationContext, count+1)    // line 13

count 应该是一个整数,因为sharedPref.getInt 返回一个整数,而applyCount() 接收一个整数作为第二个参数。运行时在第 12 行抛出异常。 有什么我看不到的吗? (我对 kotlin 还很陌生)

【问题讨论】:

  • 您必须在该键的共享首选项中存储一个长值。
  • “因为 sharedPref.getInt 返回一个整数”如果成功。在您的情况下,它失败了,因此存储的值不是整数(从错误消息中我们知道它很长)。第 13 行无关紧要,因为你永远也到不了那里。

标签: kotlin exception casting long-integer


【解决方案1】:

使用以下内容。这样就可以解决问题了。

var count = sharedPref.getLong("flutter.badgeCount", 0L)  
ShortcutBadger.applyCount(applicationContext, count.toInt()+1)

【讨论】:

  • 我收到一个错误:“类型不匹配:推断类型为 Long 但应为 Int”。
  • 好的,我用count.toInt()count 转换为整数,现在可以正常工作了
猜你喜欢
  • 2015-12-01
  • 2015-12-02
  • 1970-01-01
  • 2017-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
相关资源
最近更新 更多