Android Room Database Ignore Problem “Tried the following constructors but they failed to match”

早过忘川 提交于 2020-12-11 05:08:31

问题


My entity class:

@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                     
)

And then I insert like this (tested in androidTest):

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

studentDao.insert(student)

It gives me this error right after I added the @Ignore annotation:

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).

回答1:


Since Room still generates Java-classes during compile and the problem is with default-valued parameter, try to use @JvmOverloads for constructor:

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

UPDATE

It's interesting that here in documentation there is no mentioning of special treatment to this case. And this issue already exists to fix this documentation.

From this issue as for the problem itself conclusion is:

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



来源:https://stackoverflow.com/questions/64541459/android-room-database-ignore-problem-tried-the-following-constructors-but-they

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!