0

I have a problem with @ForeignKey, using Room.

I have 3 entities: Location, User, Car.

One Location can have One User.
One Location can have One Car.
One User can have multiple Location(s).
One Car can have multiple Location(s) (with different users).

I have a list of Cars. When I swipe left on one of them, I can create a new Location.

I have two forms, one to create a new User (this new User is sent into a Spinner to Location's form) and as quoted, one to create a new Location. In Location, as mentionned, I have a Spinner of Users. As I create a new User, I first save it and then I send it to Location.

When I save my Location, I go back on my Cars's list and when I swiped right I can see the list of Locations related to this car.

So, when I first add a new User (let's call it Tom) and then a new Location with these new User, it perfectly works. I can see this Location on swipe right, all good.

When I add a second new User (Let's call it Jerry), it is sent to the Spinner and I can fill my Location's form. But when I try to save this form, I have a Foreign Key error (code 787).

Could you help please? I really don't get how Tom's Location can be saved but not Jerry's (Don't let Jerry alone please...)

I checked those solutions (and many other..) but no one seems to have the same problem as I:

Android Room FOREIGN KEY constraint failed (code 787)
How to avoid room foreign key error - constraint failed (code 787)

Location.java

@Entity(tableName = "location", foreignKeys = {
        @ForeignKey(
                onDelete = ForeignKey.CASCADE,
                entity = User.class,
                parentColumns = "id",
                childColumns = "userId"),
        @ForeignKey(
                onDelete = ForeignKey.CASCADE,
                entity = Car.class,
                parentColumns = "id",
                childColumns = "carId")
})

public class Location implements Parcelable{

    @PrimaryKey (autoGenerate = true)
    private int id;
    private Date dateStart;
    private Date dateEnd;
    private int userId;
    private int carId;


    public Location(Date dateStart, Date dateEnd, int userId, int carId) {
        this.dateStart = dateStart;
        this.dateEnd = dateEnd;
        this.userId = userId;
        this.carId = carId;
    }

Car.java

@SuppressWarnings(RoomWarnings.PRIMARY_KEY_FROM_EMBEDDED_IS_DROPPED)
@Entity(tableName = "car")
public class Car implements Parcelable{

    @PrimaryKey(autoGenerate = true)
    private int id;
    private String immatriculation;
    private float price;
    private boolean isRestore;
    private String imagePath;
    private String model;

    @Embedded
    private CarType carType;

    public Car(int id, String immatriculation, float price, boolean isRestore, String imagePath, String model, CarType carType) {
        this.id = id;
        this.immatriculation = immatriculation;
        this.price = price;
        this.isRestore = isRestore;
        this.imagePath = imagePath;
        this.model = model;
        this.carType = carType;
    }

User.java

@Entity(tableName = "user")
public class User implements Parcelable {


    @PrimaryKey(autoGenerate = true)
    private int id;

    private String name;
    private String firstname;
    private String phoneNumber;
    private String email;


    public User(String name, String firstname, String phoneNumber, String email) {
        this.name = name;
        this.firstname = firstname;
        this.phoneNumber = phoneNumber;
        this.email = email;
    }

I get this error

04-25 08:51:30.312 10581-10709/fr.eni.lokacar E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #3
    Process: fr.eni.lokacar, PID: 10581
    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.insert(EntityInsertionAdapter.java:64)
        at fr.eni.lokacar.dao.LocationDAO_Impl.insert(LocationDAO_Impl.java:112)
        at fr.eni.lokacar.repository.LocationRepository$AsyncInsert.doInBackground(LocationRepository.java:71)
        at fr.eni.lokacar.repository.LocationRepository$AsyncInsert.doInBackground(LocationRepository.java:65)
        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)
Lena
  • 511
  • 1
  • 4
  • 19

1 Answers1

1

After hours, I found the answer.

The answer was in the constructor of Location.

When I created the constructor, I have these parameters: dateStart, dateEnd, userId, carId

And when I initialized a Location somewhere else, I switch userId and carId's values... It could never work.

If someone comes to this post, and your code is pretty similar to mine, check your initialization :).

Ps: Jerry found Tom back :)

Lena
  • 511
  • 1
  • 4
  • 19