Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FOREIGN KEY constraint failed (code 787) in Room database

I'm trying to learn relations in the Room database, but I have some problem. I want to put Expense to Date, but app crashes and logcat shows this: Caused by: android.database.sqlite.SQLiteConstraintException: FOREIGN KEY constraint failed (code 787). The classes are pasted without setters and getters.

Date:

@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;
}

Expense:

@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;
}
like image 280
beginner992 Avatar asked May 09 '26 13:05

beginner992


1 Answers

you need to create first date table entry than add expense entry to database. for more information visit this link

like image 118
Amit Goswami Avatar answered May 12 '26 05:05

Amit Goswami