java - 房间数据库 - 外键约束失败错误代码 787

标签 java android android-sqlite android-room

我遇到了上述问题,即使查看其他类似问题及其解决方案以及关于外键的sqlite文档也无法解决。

据我所知,外键必须先存在于父表中,然后才能在子表中创建。然而,即使首先做到了这一点,问题仍然存在。

这就是我的程序直到崩溃为止的流程: MainActivity -> 创建行程 -> 显示为 RecyclerView -> 单击它进入另一个 Activity (传递其 trip_id) -> 创建位置 -> 选择保存时崩溃(trip_id、locationName、latLng)

在这种情况下,Trip 有一个 PK:trip_id,而 Location 将其作为 FK。

    Process: com.example.TravelPlanner, PID: 4701
    java.lang.RuntimeException: An error occurred while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:354)
        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:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:764)
     Caused by: android.database.sqlite.SQLiteConstraintException: FOREIGN KEY constraint failed (code 787 SQLITE_CONSTRAINT_FOREIGNKEY[787])
        at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
        at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:995)
        at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
        at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
        at androidx.sqlite.db.framework.FrameworkSQLiteStatement.executeInsert(FrameworkSQLiteStatement.java:51)
        at androidx.room.EntityInsertionAdapter.insert(EntityInsertionAdapter.java:64)
        at com.example.travelplanner.LocationDao_Impl.insert(LocationDao_Impl.java:110)
        at com.example.travelplanner.LocationRepository$InsertLocationAsyncTask.doInBackground(LocationRepository.java:48)
        at com.example.travelplanner.LocationRepository$InsertLocationAsyncTask.doInBackground(LocationRepository.java:39)
        at android.os.AsyncTask$2.call(AsyncTask.java:333)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)

这是在 onActivityResult 方法的第二个 Activity 中创建 Location 对象的行

 String locationName = data.getStringExtra("locationName");
            String latLng = data.getStringExtra("latLng");

            Intent intent = getIntent();
            Bundle bundle = intent.getExtras();
            int tripId = (int)bundle.get("tripId"); // D/TRIPID: Trip id is 1

            Log.d("TRIPID", "Trip id is " + tripId);

            String[] latlong = latLng.split(",");
            double latitude = Double.parseDouble(latlong[0]);
            double longitude = Double.parseDouble(latlong[1]);
            LatLng locationLatLng = new LatLng(latitude,longitude);

 Location location = new Location(tripId, locationName, locationLatLng); 
 Log.d("LOCATIONID", "Trip id is " + location.getTripId()); // D/LOCATIONID: Trip id is 1

locationViewModel.insert(location); //crashes here

位置.类

@Entity(tableName = "location_table",foreignKeys = @ForeignKey(entity = Trip.class, parentColumns = "location_Id", childColumns = "trip_Id"),
        indices = {@Index(value = {"trip_Id"})})

public class Location {

    @PrimaryKey(autoGenerate = true)
    private int locationId;

    @ColumnInfo (name = "trip_Id")
    private int tripId;

    private String locationName;

    @TypeConverters(LatLngConverter.class)
    private LatLng latLng;


    public Location(int tripId, String locationName, LatLng latLng) {
        this.tripId = tripId;
        this.locationName = locationName;
        this.latLng = latLng;
    } 

旅行.class

@Entity(tableName = "trip_table",
        indices = {@Index(value = {"location_Id"},
                unique = true)})

public class Trip {

    @PrimaryKey(autoGenerate = true) 
    @ColumnInfo (name = "location_Id")
    private int id;

    private String title;

    private String description;

    private int priority;

    //id will be auto generated so it need not be inside constructor
    public Trip(String title, String description, int priority) {
        this.title = title;
        this.description = description;
        this.priority = priority;
    } 

我看不出这是如何在将外键添加到父表中之前添加外键的...

最佳答案

显示的代码似乎没有任何问题,即使用您的代码(为方便起见,稍作修改(只是 latLng 的 long 并在主线程上运行)。

然后使用:-

    appDatabase = Room.databaseBuilder(this,AppDatabase.class,"travel_planner")
            .allowMainThreadQueries()
            .build();
    Trip trip1 = new Trip("A Trip","My first trip",1);
    int tripID = (int) appDatabase.tripDao().insertTrip(trip1);
    appDatabase.locationDao().insertLocation(new Location(tripID,"Here",100));
    appDatabase.locationDao().insertLocation(new Location(tripID,"Here again",200));
    List<Trip> tripList = appDatabase.tripDao().getAllTrips();
    for (Trip t: tripList) {
        Log.d("TRIPINFO","Trip is " + t.getDescription() + " ID is " + t.getId());
    }
    List<Location> locationList = appDatabase.locationDao().getAllLocations();
    for (Location l: locationList) {
        Log.d("LOCINFO","Location is " + l.getLocationName() + " ID is " + l.getLocationId() + " REFERENCES Trip " + l.getTripId());
    }

结果(如预期):-

2019-10-31 06:28:09.591 27335-27335/? D/TRIPINFO: Trip is My first trip ID is 1 
2019- 10-31 06:28:09.593 27335-27335/? D/LOCINFO: Location is Here ID is 1 REFERENCES Trip 1 
2019-10-31 06:28:09.593 27335-27335/? D/LOCINFO: Location is Here again ID is 2 REFERENCES Trip 1

即 TripId 1 存在,并且已添加 2 个引用该行程的位置。

同样如此

  1. //日志中显示为1不正确或
  2. 尝试添加位置时,该行程不存在。

我建议添加以下内容以进行调试:-

  1. 将以下内容添加到适当的 Dao (以下内容使用 TripDao,并且 abstract TripDao tripDao(); 在 @Database 类中进行编码(AppDatabase 是下面使用))

:-

@Query("SELECT * FROM trip_table")
List<Trip> getAllTrips();
  • 在行Location location = new Location(tripId, locationName, locationLatLng);之后并在插入之前添加
  • :-

    List<Trip> tripList = appDatabase.tripDao().getAllTrips();
    for (Trip t: tripList) {
        Log.d("TRIPINFO","Trip is " + t.getDescription() + " ID is " + t.getId());
    }
    Log.d("LOCINFO","Location is " + location.getLocationName() + " ID is " + location.getLocationId() + " REFERENCES Trip " + location.getTripId());
    

    这将列出当前的行程和要添加的位置。假设故障是行程 ID 和 REFERENCES 行程值之间的差异。如果 Trip 不按预期存在,则由于某种原因不会添加它,否则将传递错误的 TripId。上述内容应该有助于确定哪个。

    关于java - 房间数据库 - 外键约束失败错误代码 787,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58627377/

    相关文章:

    java - 客户端突然与 Java NIO 断开连接后,服务器以 30% CPU 运行,我的修复是否有效?

    java - Android 无法在表面 View 中切换到前置摄像头

    java - 枚举当前设置的值

    java - 乘法时结果不同

    android - Xamarin 向导项目无法调试

    android - ListView 底部的 TextView - api 7

    android - 使用 SQLite 将数据从一个 Activity 传输到另一 Activity : Android Studio

    android - 每次使用后打开和关闭一个sqlite数据库

    Android 应用启动时崩溃 : SQLite NullPointerException in ContactsFragment

    java - 如何通过本地主机从 JavaMail 发送邮件