Python中文网

一个关于 编程问题的解答网站.

有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法在文件室数据库的表内创建条目

我在房间数据库中创建了两个@Entity(tables)。第一个任务(Task.class)和;第二个是它的统计数据(TaskStat.class)。我想从第一个类(Task.class)在第二个表中自动创建条目。为了在第二个表中插入条目,我在TaskDao.class接口中创建了一个@Dao方法。以下是我的java代码:

Task.class

public class Task {
    @PrimaryKey
    @ColumnInfo(name = "task_ID")
    private Long taskId;

    @ColumnInfo(name = "creator_ID")
    private Long creatorId;
    private String title;
    private String description;

    @Ignore
    private TaskDao taskDao;

    public Task(String title){
        this.taskId = IdGenerator.generate();
        this.title = title;
        TaskStat taskStat = new TaskStat(getTaskId());
        taskDao.insertStat(taskStat);
    }

    public Long getTaskId() {
        return taskId;
    }

TaskStat.class

@Entity(tableName = "task_statistic",
        foreignKeys = @ForeignKey(entity = Task.class, parentColumns = "task_ID",
                                    childColumns = "ownerId", onDelete = ForeignKey.CASCADE))
public class TaskStat {
    @PrimaryKey(autoGenerate = true)
    private int id;

    private long ownerId;
    private boolean completed;

    TaskStat(long ownerId) {
        this.ownerId = ownerId;
        this.completed = false;
    }

    public int getId() {
        return id;
    }
    public long getOwnerId() {
        return ownerId;
    }
    public boolean isCompleted() {
        return completed;
    }

    public void setId(int id) {
        this.id = id;
    }
    public void setCompleted(boolean completed) {
        this.completed = completed;
    }
}

TaskDao.class

@Dao
public interface TaskDao {
    @Insert
    void insert(Task task);

    @Insert
    void insertStat(TaskStat taskStat);

正如您在Task.class中看到的,我希望每当我创建Task.class的对象时,它会自动创建TaskStats.class的对象,然后将其插入taskStat表中。这两个表都是在数据库中创建的,但在第二个表中没有条目(task_statistic)。 enter image description here enter image description here enter image description here 它正在投掷NullPointException。问题出在哪里

编辑:

Dependencies I've used:

dependencies {
    def lifecycle_version = "2.2.0"
    def room_version = "2.2.5"
    /*ViewModel and LiveData (New Style-in one Line)*/
    implementation "安卓x.lifecycle:lifecycle-extensions:$lifecycle_version"
    annotationProcessor "安卓x.lifecycle:lifecycle-compiler:$lifecycle_version"
    /*Room Dependencies*/
    implementation "安卓x.room:room-runtime:$room_version"
    annotationProcessor "安卓x.room:room-compiler:$room_version"
}

共 (0) 个答案