Mugur
Mugur

Reputation: 19

Room database with one-to-one relation foreign key constraint failed error

I have a database with two tables Student and Course. I can insert data in Student table but when I try to insert data into Course table app crash. Here is the logcat:

2019-01-21 19:56:22.302 28939-29121/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
Process: com.rodroiddev.catalogulinstructoruluiauto, PID: 28939
java.lang.RuntimeException: An error occurred while executing doInBackground()
    at android.os.AsyncTask$3.done(AsyncTask.java:353)
    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
    at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
    at java.util.concurrent.FutureTask.run(FutureTask.java:271)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
    at java.lang.Thread.run(Thread.java:764)
 Caused by: android.database.sqlite.SQLiteConstraintException: FOREIGN KEY constraint failed (code 787)
    at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
    at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
    at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
    at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
    at android.arch.persistence.db.framework.FrameworkSQLiteStatement.executeInsert(FrameworkSQLiteStatement.java:50)
    at android.arch.persistence.room.EntityInsertionAdapter.insertAndReturnId(EntityInsertionAdapter.java:114)
    at com.rodroiddev.catalogulinstructoruluiauto.db.CourseDao_Impl.insert(CourseDao_Impl.java:104)
    at com.rodroiddev.catalogulinstructoruluiauto.course.CourseRepository$InsertCourseAsyncTask.doInBackground(CourseRepository.java:53)
    at com.rodroiddev.catalogulinstructoruluiauto.course.CourseRepository$InsertCourseAsyncTask.doInBackground(CourseRepository.java:44)
    at android.os.AsyncTask$2.call(AsyncTask.java:333)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636) 
    at java.lang.Thread.run(Thread.java:764) 

Here is the insert code:

private static class InsertCourseAsyncTask extends AsyncTask<Course, Void, Void> {
    private CourseDao courseDao;

    public InsertCourseAsyncTask(CourseDao courseDao) {
        this.courseDao = courseDao;
    }

    @Override
    protected Void doInBackground(Course... courses) {
        courseDao.insert(courses[0]);
        return null;
    }
}

Course.java

@Entity(tableName = "course_table",
    foreignKeys = @ForeignKey(entity = Student.class,
            parentColumns = "sId",
            childColumns = "studentId",
            onDelete = CASCADE),
            indices = {@Index("studentId")})

public class Course {

@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "cId")
public int id;

public String kmStart;

public String  kmStop;

@ColumnInfo(name = "studentId")
public int studentId;

public Course(String kmStart, String kmStop) {

    this.kmStart = kmStart;
    this.kmStop = kmStop;

}

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

public int getId() {
    return id;
}

public String  getKmStart() {
    return kmStart;
}

public String getKmStop() {
    return kmStop;
}

public void setStudentId(int studentId) {
    this.studentId = studentId;
}

public int getStudentId() {
    return studentId;
}

}

CourseDao

@Dao

public interface CourseDao {

@Insert(onConflict = OnConflictStrategy.IGNORE)
void insert(Course... courses);

@Update(onConflict = OnConflictStrategy.IGNORE)
void update(Course course);

@Delete
void delete(Course course);

@Query("DELETE FROM course_table")
void deleteAllCourses();

@Query("SELECT * FROM course_table ORDER BY kmStart ASC")
LiveData<List<Course>> getAllCourses();

}

I hope that you can help me based on the info that I posted here. Thanks!

Upvotes: 0

Views: 1275

Answers (1)

rgaraisayev
rgaraisayev

Reputation: 396

Do you set studentId to course object before saving? If you dont, it will crash because it will try to add 0 for studentId as foreign key value which doesnt exist.

Set studentId of Course object to Student object's id. And save Student first so it can get an id

Upvotes: 1

Related Questions