Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/198.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 必须使用@NonNull(复合主键)注释主键_Java_Android - Fatal编程技术网

Java 必须使用@NonNull(复合主键)注释主键

Java 必须使用@NonNull(复合主键)注释主键,java,android,Java,Android,我的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

我的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
时,它说
notnull字段必须初始化
(?)

我该如何解决这个问题?我的想法是初始化两个主键,但当我尝试向数据库插入新对象时,这应该是一个问题

然后,当我按照说明将@NonNull添加到dailyid时,它 表示必须初始化非空字段(?)

如果你用
@NonNull
注释一个字段,你告诉编译器“这个东西永远不会为null”。但是Java中未初始化对象的默认值是什么?这是正确的!无效的因此,如果用
@NonNull
注释字段,则必须对其进行初始化,以确保它不会以null开头

我该如何解决这个问题

初始化字段。 要么在声明时立即执行,要么在类构造函数中执行

@NonNull
@PrimaryKey
private Date dailyId = new Date(); // Now it's initialized and not null


希望有帮助

用@NonNull注释,并确保导入
androidx.annotation.NonNull
,正如我在帖子中所说的:然后,当我按照说明将@NonNull添加到dailyid时,它说必须初始化notnull字段(?)但是您是否导入了正确的非null如果您没有使用androidx,那么导入
android.support.annotation.NonNull
如果没有初始值设定项,这些值可能为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
    }
}