【问题标题】:after updating from room 2.2.6 to 2.3.0 I get an error: "You must annotate primary keys with @NonNull."从房间 2.2.6 更新到 2.3.0 后,我收到一个错误:“您必须使用 @NonNull 注释主键。”
【发布时间】:2021-05-03 21:45:01
【问题描述】:

我将房间从 2.2.6 更新为 2.3.0 并开始在编译时在编译/生成的 java 代码中看到奇怪的错误。我的.kt 文件或...build/tmp/kapt3/stubs/debug/... 目录中生成的.java 文件中没有看到任何错误我只看到破坏构建的编译时错误。

我得到的完整错误:

error: You must annotate primary keys with @NonNull. "version" is nullable. SQLite considers this a bug and Room does not allow it. See SQLite docs for details: https://www.sqlite.org/lang_createtable.html
    private java.lang.Integer version;

当我查看生成的 .java 代码时,我发现它正在对其进行注释:

@org.jetbrains.annotations.Nullable()
@androidx.annotation.NonNull()
private java.lang.Integer version;

我的 Kotlin 代码也被注释了:

import androidx.annotation.NonNull
...
    @NonNull
    var version: Int? = null

我的代码运行良好,并且经过良好测试并证明可以使用2.2.6 房间。我是在更新到2.3.0 房间后才开始遇到这个问题的。

旧的dependencies.gradle

implementation "androidx.room:room-runtime:2.2.6"
kapt "androidx.room:room-compiler:2.2.6"

更新的dependencies.gradle

implementation "androidx.room:room-runtime:2.3.0"
kapt "androidx.room:room-compiler:2.3.0"

感谢任何帮助!

【问题讨论】:

  • 因为:var version: Int? = null 可以为 null,在 java 领域中,它将被转换为 Integer 对象,而不是作为原始 int 评估。该错误非常明确,主键不应为null - 作为快速修复,只需将其设为var int = -1。但是,请考虑将具有匹配构造函数的对象创建为数据类。

标签: android sqlite kotlin android-room android-jetpack


【解决方案1】:

Kotlin 不使用 @NonNull 注释 - 这是由您的类型本身决定的,在您的情况下是可以为空的 Int?

您需要将其更改为 Int 并为其分配默认值(即 -1)。

【讨论】:

  • 谢谢,@ianhanniballake!既然你指出了这一点,那就很有意义了。我想知道为什么它在以前版本的房间中有效?和更新前一样没有任何问题。
猜你喜欢
  • 1970-01-01
  • 2021-09-20
  • 2020-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-02
  • 1970-01-01
  • 2020-05-24
相关资源
最近更新 更多