无法将表添加到房间 日志中的异常显示"预期"表与"找到"不同



我正试图向我的Room数据库添加第二个表,但在运行应用程序时会出现以下异常。

java.lang.IllegalStateException: Migration didn't properly handle people_table(com.example.soundguard.People).
Expected:
TableInfo{name='people_table', columns={name=Column{name='name', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=1}, priority=Column{name='priority', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0}}, foreignKeys=[], indices=[]}
Found:
TableInfo{name='people_table', columns={}, foreignKeys=[], indices=[]}

我创建了一个类:

@Entity(tableName = "people_table")
public class People {
@PrimaryKey
@NonNull
@ColumnInfo(name = "name")
private String mName;
@NonNull
@ColumnInfo(name = "priority")
private int mPriority;
public People(@NonNull String name, @NonNull int priority) {
this.mName = name;
this.mPriority = priority;
}
public String getName(){return this.mName;}
public int getPriority(){return this.mPriority;}
public void setPriority(int priority){this.mPriority = priority;}
}

并在数据库类中添加了第二个实体以及迁移,因此我不确定为什么找到的表与预期的表不匹配:

@Database(entities = {AppName.class, People.class}, version = 4, exportSchema = true)
public abstract class SoundguardRoomDatabase extends RoomDatabase {
...
static final Migration MIGRATION_3_4 = new Migration(3, 4) {
@Override
public void migrate(SupportSQLiteDatabase database) {
database.execSQL("CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`name` TEXT NOT NULL, `priority` INTEGER NOT NULL, PRIMARY KEY(`name`))");
}
};

我不相信你能在java中使用${your_variable}——它是Kotlin代码。因此,您创建的表将使用以下方法创建:-

CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`name` TEXT NOT NULL, `priority` INTEGER NOT NULL, PRIMARY KEY(`name`))

即表名将是${table_name}而不是people_table,因此它什么也没找到。

所以尝试使用:-

@Database(entities = {AppName.class, People.class}, version = 4, exportSchema = true)
public abstract class SoundguardRoomDatabase extends RoomDatabase {
...
static final Migration MIGRATION_3_4 = new Migration(3, 4) {
@Override
public void migrate(SupportSQLiteDatabase database) {
database.execSQL("CREATE TABLE IF NOT EXISTS `" + TABLE_NAME + "` (`name` TEXT NOT NULL, `priority` INTEGER NOT NULL, PRIMARY KEY(`name`))");
}
};

最新更新