Android房间数据库忽略问题 "Tried the following constructors but they failed to match"

标签 android android-room android-jetpack android-database

我的实体类:

@Entity(tableName = "student")
data class Student(
    var name: String,  
    var age: Int,   
    var gpa: Double,
    var isSingle: Boolean,

    @PrimaryKey(autoGenerate = true)
    var id: Long = 0,    

    @Ignore                           //don't create column in database, just for run time use
    var isSelected: Boolean = false                     
)

然后我像这样插入(在 androidTest 中测试):

val student = Student("Sam", 27, 3.5, true)

studentDao.insert(student)

它在我添加了 @Ignore 注释后立即给了我这个错误:

C:\Android Project\RoomTest\app\build\tmp\kapt3\stubs\debug\com\example\roomtest\database\Student.java:7: ����: 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).
public final class Student {
         ^
  Tried the following constructors but they failed to match:
  Student(java.lang.String,int,double,boolean,boolean,long) -> [param:name -> 
matched field:name, param:age -> matched field:age, param:gpa -> matched 
field:gpa, param:isSingle -> matched field:isSingle, param:isSelected -> 
matched field:unmatched, param:id -> matched field:id][WARN] Incremental 
annotation processing requested, but support is disabled because the 
following processors are not incremental: androidx.room.RoomProcessor 
(DYNAMIC).

最佳答案

由于 Room 在编译期间仍会生成 Java 类,并且问题在于默认值参数,请尝试使用 @JvmOverloads对于构造函数:

@Entity(tableName = "student")
data class Student @JvmOverloads constructor(
    var name: String,
    .....  

更新

有趣的是here in documentation没有提到对这种情况的特殊处理。和 this issue已经存在以修复此文档。

来自 this issue至于问题本身的结论是:

Using @JvmOverloads should work. One day in the not-so-distant future we might generate Kotlin and this won't be an issue

关于Android房间数据库忽略问题 "Tried the following constructors but they failed to match",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64541459/

相关文章:

java - Android:LayoutParams 中的 addRule 出现 ArrayIndexOutOfBounds 异常

android - Clean Architecture 和 Paging 3.0 with Room

android - 我多次调用 Livedata 观察器时遇到问题

php - android room not null 约束在插入时失败

android - 如何使用 html5 音频标签在 Android 上使用 phonegap 播放本地 mp3?

android - 如何在没有用户交互的情况下以编程方式在 Android 上安装 CA 证书

android - 如何在 JetPack Navigation 组件中托管 fragment 的 Activity 中调用导航 fragment 函数?

Android 数据存储区 IOException 无法重命名为

android - 创建 AppBarIcon 图像

android - 自定义 ListView 滚动卡顿