Android 有多个好的构造函数,Room将选择无参数构造函数。如何解决此警告
我试图在AndroidKotlin项目中实现Room持久数据库库,但在编译时捕捉到了这个警告。我不知道如何解决这个问题 警告:有多个好的施工人员,房间将选择 没有参数构造函数。您可以使用@Ignore注释来消除 不需要的构造函数 自动生成类Android 有多个好的构造函数,Room将选择无参数构造函数。如何解决此警告,android,constructor,kotlin,android-room,Android,Constructor,Kotlin,Android Room,我试图在AndroidKotlin项目中实现Room持久数据库库,但在编译时捕捉到了这个警告。我不知道如何解决这个问题 警告:有多个好的施工人员,房间将选择 没有参数构造函数。您可以使用@Ignore注释来消除 不需要的构造函数 自动生成类 public final class Gender { ^ Kotlin数据类 import android.arch.persistence.room.Entity import android.arch.persistence
public final class Gender {
^
Kotlin数据类
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
@Entity
data class Gender(@PrimaryKey(autoGenerate = true)
var genderId: Int = 0,
var type: String = "")
试试这个:
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
@Entity
class Gender @Ignore constructor(@PrimaryKey(autoGenerate = true)
var genderId: Int = 0,
var type: String = "") {
constructor() : this(0, "")
}
就像警告说的那样
。。。房间将选择无参数构造函数
您的构造函数有两个参数。您需要添加一个空的构造函数而忽略另一个这里的问题是kotlin正在为您的类生成多个构造函数,因为您有一些属性的默认参数
就您而言,您有:
// this is the synthetic one, don't worry to much about it
public Gender(int var1, String var2, int var3, DefaultConstructorMarker var4) { /* some implementation */ }
// the "default" one, that can be called when you are delegating to the default params
public Gender() { /* some implementation */ }
// the one that gets all the params
public Gender(int genderId, @NotNull String type) { /* some implementation */ }
房间可以使用没有参数的房间,也可以使用有两个参数的房间,它会选择其中一个并通过警告通知您
您可以删除类型的默认参数,并且只有一个非合成构造函数:
// still synthetic
public Gender(int var1, String var2, int var3, DefaultConstructorMarker var4) { /* some implementation */ }
// this is the only usable constructor now
public Gender(int genderId, @NotNull String type) { /* some implementation */}
现在房间只有一个构造函数可以使用,所以它会很高兴地使用它
如果您的用例允许,您可以删除默认值。请注意,您只能对非原语类型执行此操作,这会使您的API更好
我不知道您的具体情况,但请注意,您也可以使用val而不是var
我有同样的警告,我只是把@Ignore放在空构造函数之前
// Empty constructor
@Ignore
public Room_Database() {
}
你们也有二级构造函数吗?不,我没有二级构造函数,就像上面的代码一样。@JeelVankhede,很抱歉,这是我的错误,但我在另一个类中也得到了这个警告,其中已经放置了data关键字。警告实际上意味着文件室在实体上找到了多个构造函数,所以它抛出了这个警告。如果您使数据类主要表示构造函数得到调用,并且如果您显式使用@Ignore标记,rest将被@Ignore标记忽略。@Redman我尝试了您的建议,但出现了以下错误:实体和POJO必须具有可用的公共构造函数。您可以有一个空构造函数,也可以有一个参数按名称和类型与字段匹配的构造函数。
// Empty constructor
@Ignore
public Room_Database() {
}