今天在做 Room 迁移的时候,想测试Room 是否按预期工作,报上面错误:
检查发现 我报 它放在主线执行的使用报错了, 对数据库的操作由于是耗时操作,所以必须放在子线程中完成, 不允许在主线程上访问数据库,
Caused by: java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
java.lang.RuntimeException: Unable to start activity ComponentInfo{space.dua/com.fox.app.ui.local.AppActivity}: java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
/** * entities: 实体类 * version: 数据库初始版本号 * exportSchema: 是否允许数据库架构将导出到给定的文件夹中【 默认true 】 * @Database(entities = [User::class], version = 1, exportSchema = false) */
@Database(entities = [RuleBean::class, UserDate::class], version = 2) abstract class BoxDatabase : RoomDatabase() { // 在类的主体内,声明一个返回 RuleDao 的抽象值。您可能有多个 DAO。 abstract fun ruleDao(): RuleDao // TODO 定义一个 companion 对象。伴生对象允许客户端访问用于创建或获取数据库,而无需该类进行实例化的方法 companion object { //TODO 提供一个Migration实例,指明迁移的版本号 private val MIGRATION_1_2: Migration = object : Migration(1, 2) { override fun migrate(database: SupportSQLiteDatabase) { // Migration code here, if needed database.execSQL("alter table Book add column chuban text"); } } //TODO Room.databaseBuilder()中传入上下文、数据库类,以及数据库的名称 @SuppressLint("StaticFieldLeak") val instance = Room.databaseBuilder(ContextHolder.get(), BoxDatabase::class.java, "boxConfig").addMigrations( MIGRATION_1_2) .build() } }