无法将表格添加到Room数据库-日志中的异常表明“预期”表格与“找到”不同

时间:2019-11-20 05:37:35

标签: java database sqlite android-room

我正在尝试向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`))");
        }
    };

1 个答案:

答案 0 :(得分:1)

我不认为您可以在Java的Kotlin代码中使用${your_variable}。因此,您创建的表将使用:-

创建
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`))");
            }
        };