我正在尝试使房间实体可观察(扩展BaseObservable),以便可以在具有双向绑定的LiveData中使用它。所以我有这个数据类:
@Entity
data class Model(
@PrimaryKey(autoGenerate = true)
val id: Int,
val name: String) : Serializable
在XML中,我想这样使用它:
<EditText
...
android:text="@{viewModel.myLiveData.name}"
在ViewModel中,我有:
val myLiveData: MutableLiveData<Model>
我找到了基本上相同的问题here ..,但是对于JAVA,我在将其转换为Kotlin时遇到了问题。我的kotlin等效项是:
@Entity
class Model: BaseObservable, Serializable {
constructor(id: Int, name: String) {
this.id = id
this.name = name
}
@PrimaryKey(autoGenerate = true)
var id: Int = 0
@get:Bindable
var name: String = ""
set(value) {
field = value
notifyChange()
}
}
不起作用并导致以下原因:
> A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution
> java.lang.reflect.InvocationTargetException (no error message)
答案 0 :(得分:0)
回答我自己的问题... 因此,我的问题缺少一个重要的细节-在我的模型类中,我有第二个构造函数,该构造函数未使用@Ignore进行注释,因此Android Room抱怨“由于多个构造函数均适用,因此Room无法选择构造函数。尝试使用@Ignore注释不需要的构造函数。 “
BUT(!)错误仅在Java中显示,而不是在Kotlin中显示,原因很奇怪。
所以在Java中,我有这个课:
@Entity
public class Model extends BaseObservable implements Serializable {
@PrimaryKey(autoGenerate = true)
public int id;
private String name;
//@Ignore (THIS SHOULD BE UNCOMMENTED TO GET RID OF AN ERROR!!!!!
public Model(String name) {
this.id = 0;
this.name = name;
}
public Model(int id, String name) {
this.id = id;
this.name = name;
}
public void setName(String name) {
if (!Objects.equals(name, this.name)) {
this.name = name;
notifyPropertyChanged(BR.name);
}
}
@Bindable
public String getName() {
return name;
}
}
因此对于这个Java类,我得到了:
Room cannot pick a constructor since multiple constructors are suitable. Try to annotate unwanted constructors with @Ignore.
然后选择等效的Kotlin类:
@Entity
class Model: BaseObservable, Serializable {
constructor(id: Int, name: String) {
this.id = id
this.name = name
}
// @Ignore - THIS VAS MISSING!!!
constructor(name: String): this(0, name)
@PrimaryKey(autoGenerate = true)
var id: Int = 0
@get:Bindable
var name: String = ""
set(value) {
field = value
notifyChange()
}
}
我仅收到此错误:
> Task :app:kaptDebugKotlin FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:kaptDebugKotlin'.
> A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution
> java.lang.reflect.InvocationTargetException (no error message)
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 2s
28 actionable tasks: 2 executed, 26 up-to-date
令人失望的是什么也没说第二个构造函数!