- 在 Android 开发中,使用 Room 时,出现如下错误信息
java.lang.IllegalStateException: A migration from 6 to 7 was required but not found. Please provide the necessary Migration path via RoomDatabase.Builder.addMigration(Migration ...) or allow for destructive migrations via one of the RoomDatabase.Builder.fallbackToDestructiveMigration* methods.# 解读 java.lang.IllegalStateException: 需要从版本 6 到版本 7 的迁移策略,但未找到 请通过 RoomDatabase.Builder.addMigration(Migration ...) 提供必要的迁移路径 或者通过 RoomDatabase.Builder.fallbackToDestructiveMigration* 方法之一允许破坏性迁移问题原因
- 使用 Room 将数据库从版本 6 升级到版本 7,但没有提供对应的迁移策略
处理策略
- 通过 addMigration 方法提供必要的迁移策略(推荐)
privatestaticfinalMigrationMIGRATION_6_7=newMigration(6,7){@Overridepublicvoidmigrate(@NonNullSupportSQLiteDatabasedatabase){...}};MyDatabasemyDatabase=Room.databaseBuilder(MyApplication.getContext(),MyDatabase.class,DATABASE_NAME).addMigrations(MIGRATION_1_2).addMigrations(MIGRATION_2_3).addMigrations(MIGRATION_3_4).addMigrations(MIGRATION_4_5).addMigrations(MIGRATION_5_6).addMigrations(MIGRATION_6_7).build();- 通过 fallbackToDestructiveMigration 方法允许破坏性迁移(不推荐)
MyDatabasemyDatabase=Room.databaseBuilder(MyApplication.getContext(),MyDatabase.class,DATABASE_NAME).fallbackToDestructiveMigration().build();