本文主要是介绍Caused by: java.lang.IllegalStateException,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
今天在做 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 neededdatabase.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()}}
这篇关于Caused by: java.lang.IllegalStateException的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!