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;
}
you need to create first date table entry than add expense entry to database. for more information visit this link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With