Room数据库中的FOREIGN KEY约束失败(代码787)

时间:2019-03-22 11:58:49

标签: android android-room

我正在尝试学习Room数据库中的关系,但是有一些问题。我想将Expense设置为Date,但应用程序崩溃且logcat显示此错误:原因:android.database.sqlite.SQLiteConstraintException:FOREIGN KEY约束失败(代码787)。粘贴这些类时不使用设置方法和获取方法。

日期:

@Entity(tableName = "dates")
public class Date {

@PrimaryKey(autoGenerate = true)
private int id;
private Long dateLong = System.currentTimeMillis();
private String date = new SimpleDateFormat("MM/yyyy").format(new java.util.Date(dateLong));

private int month;
private int week;
private int day;
private int dayOfWeek;
private String weekDay

public Date(int month, int week, int day, int dayOfWeek, String weekDay) {
    this.month = month;
    this.week = week;
    this.day = day;
    this.dayOfWeek = dayOfWeek;
    this.weekDay = weekDay;
}

费用:

@Entity(tableName = "expense_table",
    foreignKeys = @ForeignKey(entity = com.example.test.Date.class,
    parentColumns = "id",
    childColumns = "dateId",
            onDelete = CASCADE),
    indices = @Index("dateId"))
public class Expense {

@PrimaryKey(autoGenerate = true)
private int id;
private int dateId;
private String note;
private Double value;
private String type;

public Expense(Double value, String note, String type) {
    this.value = value;
    this.note = note;
    this.type = type;
}

1 个答案:

答案 0 :(得分:1)

您需要创建第一个日期表条目,而不是向数据库添加费用条目。有关更多信息,请访问this链接