[英]You must annotate primary keys with @NonNull (composite primary key)
我的 Android 項目中有以下 Java 類。
@Entity
public class Daily {
@PrimaryKey
private Date dailyId;
//Other non important attrs, getters, setters, etc.
}
@Entity(primaryKeys = {"dailyId", "dailyDetailId"})
public class DailyDetail {
private Date dailyId; //which is the value of its unique parent.
private Long dailyDetailId;
//Other non important attrs, getters, setters, etc.
}
順便說一句:我已經添加了類型轉換器。
當我嘗試構建項目時出現以下錯誤:
You must annotate primary keys with @NonNull. "dailyId" is nullable. SQLite considers this a bug and Room does not allow it.
然后,當我按照說明將 @NonNull 添加到dailyid
時,它說Not-null fields must be initialized
(?)
我應該如何解決這個問題? 我的想法是初始化兩個主鍵,但是當我嘗試將新的 object 插入數據庫時應該會出現問題。
然后,當我按照說明將@NonNull 添加到dailyid 時,它說必須初始化非空字段(?)
如果你用@NonNull
注釋一個字段,你就是在告訴編譯器“這個東西永遠不會為空”。 但是 Java 中未初始化的 object 的默認值是多少? 這是正確的! Null 。 因此,如果您使用@NonNull
注釋字段,則必須對其進行初始化以保證它不會從 null 開始。
我應該如何解決這個問題?
初始化您的字段。 立即聲明或在 class 構造函數中。
@NonNull
@PrimaryKey
private Date dailyId = new Date(); // Now it's initialized and not null
或者
@Entity
public class Daily {
@NonNull
@PrimaryKey
private Date dailyId;
public Daily() {
dailyId = new Date(); // Now it's initialized and not null
}
// ^- this AND / OR this -v
// Note here that if using an argument in the constructor, it too must be
// annotated as @NonNull to tell the compiler that you're setting the value
// of your non-nullable field to something that won't itself be null
public Daily(@NonNull Date initialDate) {
dailyId = initialDate; // Now it's initialized and not null
}
}
希望有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.