【发布时间】:2018-03-28 04:55:20
【问题描述】:
我已经开始使用 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).
这在编译时出现了两次,没有证据表明它来自哪个类,但我能够弄清楚(通过从数据库中删除类)这是其中一个文件。我假设它与主键是字符串而不是 Int (这是使用它的两个类之一)有关,但文档中没有任何内容表明问题是什么,实际上文档显示字符串是有效的主键。
@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.
我已经尝试了一些方法来解决这个问题。
- 移除该类的data属性,使其成为普通的POKO
- 从默认构造函数中移除变量,并将它们放入类中
- 从空构造函数中删除 Ignore(注意,这会导致不同的问题,
Room cannot pick a constructor since multiple constructors are suitable- 默认构造函数上的 Ignore 注释可以解决这个问题。)这是最让我困惑的部分 - 删除它表示“多个构造函数是有效的”,保持它说“没有构造函数是有效的”。
更新:从我的项目中添加更多相关代码 sn-ps。
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'
数据库类
@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(",") ?: ""
}
}
另一个数据类
@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.
UserPermissions 类:
data class UserPermissions(
@SerializedName("id")
var pid: Int = 0,
...
// Rest of code left off for brevity, found to not be related to the issue.
【问题讨论】:
标签: android kotlin android-room