Kotlin 数据的房间数据库错误 Class

Room Database error with Kotlin Data Class

我一直在使用 Room,但 运行 遇到了阻塞问题。我已经完成并修复了 Room 库中的所有编译时检查,但现在遇到以下错误:

Entities and Pojos must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type).

这在编译时出现了两次,没有证据表明它来自哪个 class,但我能够弄清楚(通过从数据库中删除 classes)这是其中之一文件。我假设它与主键是字符串而不是 Int 有关(这是使用它的两个 classes 之一),但文档中没有任何内容表明问题所在,并且事实上,文档显示字符串是有效的主键。

@Entity(tableName = "inspections")
data class Inspection(
@SerializedName("id")
var id: Int = 0,

...
// Rest of code left off for brevity, found to not be related to the issue.

我尝试了一些方法来尝试解决这个问题。

更新:从我的项目中添加更多相关代码片段。

build.gradle

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
.....
implementation 'android.arch.persistence.room:runtime:1.0.0-alpha9-1'
implementation 'android.arch.persistence.room:rxjava2:1.0.0-alpha9-1'
kapt 'android.arch.persistence.room:compiler:1.0.0-alpha9-1'

数据库class

@Database(entities =
    arrayOf(Account::class, Category::class,
            Inspection::class, InspectionForm::class,
            InspectionFormItem::class, InspectionFormsStructure::class,
            InspectionItemPhoto::class,
            InspectionItem::class, LineItem::class,
            LocalPhoto::class, Rating::class,
            Structure::class, SupervisoryZone::class,
            Upload::class, User::class),
    version = 16)
@TypeConverters(Converters::class)
abstract class OrangeDatabase : RoomDatabase() {
    abstract fun inspectionDao(): InspectionDao

    abstract fun localDao(): LocalDao

    abstract fun ratingsDao(): RatingsDao

    abstract fun structureZoneDao(): StructureZoneDao

    abstract fun userAccountDao(): UserAccountDao
}

转换器

class Converters {
@TypeConverter
fun fromTimestamp(value: Long?): Date? {
    return if (value == null) Date() else Date(value)
}

@TypeConverter
fun dateToTimestamp(date: Date?): Long? {
    return date?.time ?: 0
}

@TypeConverter
fun fromStringToArray(value: String?): Array<String>? {
    return value?.split(",")?.toTypedArray() ?: arrayOf()
}

@TypeConverter
fun stringToStringArray(strings: Array<String>?): String? {
    return strings?.joinToString(",") ?: ""
}
}

另一个数据class

@Entity(tableName = "users")
data class User(
@PrimaryKey
@SerializedName("id")
var id: Int = 0,

...
// Rest of code left off for brevity, found to not be related to the issue.

用户权限class:

data class UserPermissions(
@SerializedName("id")
var pid: Int = 0,

...
// Rest of code left off for brevity, found to not be related to the issue.

你的问题是,如果你有可为空的值,Kotlin 将为每个可能的构造函数生成多个构造函数。

这意味着你必须定义一个默认构造函数并用默认值填充它。

如果你想要另一个应该被忽略的参数,你应该确保使用带有所有这些参数的父构造函数。

示例:

@Entity(tableName = "inspections")
data class Inspection(
@SerializedName("id")
var id: Int = 0,

@PrimaryKey
@SerializedName("guid")
var guid: String = "",

@SerializedName("score")
var score: Double = 0.0,

@SerializedName("notification_sent_at")
var notificationSentAt: Date = Date(),

var wasUploaded: Boolean = false)  {

@Ignore
constructor() : this(0, "", 0.0, Date(), false)
}

在这种情况下,只会生成两个构造函数"under the hood"。如果您有可为空的值,您将拥有所有可能的构造函数。

示例:

data class Test(var id: Int = 0, var testString: String? = null, var testBool : Boolean? = null) {
   constructor(0)
} 

生成

constructor(var id:Int)
constructor() : this(0)
constructor(var id:Int, var testString: String)
constructor(var id:Int, var testBool: Boolean) 
constructor(var id:Int, var testString: String, var testBool : Boolean)
// .. and so on

由于您正在寻找官方文档,因此您可能需要查看 Overloads Generation

在测试完你的 class 后,我在另一个 post 中发现你必须检查你是否在你的 Gradle.[=19= 中使用了 apply plugin: 'kotlin-kapt' ]

仔细检查您的日期 class 是否有有效的类型转换器。我很久以前写过 that issue

在重新编码上面的内容后,通过添加 UserPermissions class 就可以正常工作了:

data class UserPermissions(var permissionid: String) 

编辑:使用您的 UserPermission class 后一切正常。如果您使用正确的导入(例如 util.Date 而不是 sql.Date),请小心。

另一个问题是您使用的是一个旧的、有很多错误的库。

当前版本(写这篇文章时)是

implementation "android.arch.persistence.room:runtime:1.0.0-beta2"
kapt "android.arch.persistence.room:compiler:1.0.0-beta2"
implementation "android.arch.persistence.room:rxjava2:1.0.0-beta2"

我很久以前就写过an issue

尽量避免使用可为 null 的值,并使所有内容都具有某种默认值。这是解决这个问题最简单的方法。

如果你真的想使用它们,那么你可以创建一个包含所有这些的构造函数。

您的主键应该如下所示使用 Annotation Use-site Targets

@field:PrimaryKey @field:SerializedName("guid") var guid: String = ""

@field:PrimaryKey @field:SerializedName("id") var id: Int = 0

这个问题极难调试,也更难重现,但我找到了问题所在。我使用的是 @Embedded 对象,但进入的结果实际上是该对象的 List。这给自动嵌入任务带来了麻烦,并且没有可以为其编写的完美转换器。

@SerializedName("range_choices")
@Embedded
var rangeChoices: List<RangeChoice>? = null,

我不得不用 @Ignore 注释,相反,我将把这个列表的结果保存到它自己的 table,现在新的 table range_choices.