【问题标题】:What's wrong with Room Database on Kotlin?Kotlin 上的房间数据库有什么问题?
【发布时间】:2017-06-26 08:34:44
【问题描述】:

我有一个数据类

@Entity(tableName = "type")
data class Type(
    @PrimaryKey(autoGenerate = true) var id: Int = 0,
    var type: Int = 0
)

编译项目时收到消息

错误:房间不能选择一个构造函数,因为多个构造函数是合适的。

但如果我将数据类更改为

@Entity(tableName = "type")
data class Type(
    @PrimaryKey(autoGenerate = true) var id: Int = 0,
    var type: String = ""
)

或java类

@Entity(tableName = "type")
public class Type {
    @PrimaryKey(autoGenerate = true)
    private int id;
    private int type;
    // getters and setters
}

它工作正常。 是 Kotlin 的 bug 还是别的什么?

【问题讨论】:

  • 我无法复制问题,您的房间版本是多少?
  • 这可能是因为当您有默认参数时,Kotlin 会为您的 Type 类生成多个 Java 构造函数。这似乎与here 描述的问题有关
  • @Tuby Room 版本是1.0.0-alpha3

标签: java android kotlin android-room


【解决方案1】:

我不知道为什么会出现这种情况,但是如果你使用 id 呢? = 0 解决了这个问题,至少在我做的测试中。

Android Studio Beta 7
ext.support_version = '26 .1.0 '
ext.kotlin_version = '1.1.51'
ext.anko_version = '0.10.1'
ext.archroom_version = '1.0.0-alpha9-1'

    @Entity(tableName = "type")
    data class Type(
            @PrimaryKey(autoGenerate = true) var id: Int? = 0,
            var type: Int = 0
    )

【讨论】:

  • 这是因为当你创建对象时它应该有一个空的主键,只有当你将它插入数据库时​​才会被填充。我认为您应该将其默认为 null,否则 Room 可能会更新索引 0 而不是插入。
猜你喜欢
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-11
  • 2018-03-28
  • 1970-01-01
相关资源
最近更新 更多