我有简单的Singleton数据库和miration_1_2,所以它很简单,可能就是这样的例子。您可以看到数据库类
@Database(entities = [Feed::class, NewsWidget::class, NewsWidgetFeed::class], version = 2)
abstract class Database : RoomDatabase() {
abstract fun feedDao(): FeedDao
abstract fun newsWidgetDao(): NewsWidgetDao
abstract fun newsWidgetFeedDao(): NewsWidgetFeedDao
companion object {
@Volatile private var INSTANCE: com.example.Database? = null
fun getInstance(context: Context): com.example.Database =
INSTANCE ?: synchronized(this) {
INSTANCE ?: buildDatabase(context).also { INSTANCE = it }
}
private val IO_EXECUTOR = Executors.newSingleThreadExecutor()
/**
* Utility method to run blocks on a dedicated background thread, used for io/database work.
*/
fun ioThread(f: () -> Unit) {
IO_EXECUTOR.execute(f)
}
private fun buildDatabase(context: Context) =
Room.databaseBuilder(context.applicationContext,
com.example.Database::class.java, "settings.db")
.addMigrations(MIGRATION_1_2)
.fallbackToDestructiveMigration()
.addCallback(object : RoomDatabase.Callback() {
override fun onOpen(db: SupportSQLiteDatabase) {
LogManager.LogEA(db.version)
super.onOpen(db)
}
override fun onCreate(db: SupportSQLiteDatabase) {
super.onCreate(db)
ioThread {
getInstance(context).feedDao().insert(*INIT_FEED_TABLE)
}
}
})
.build()
val MIGRATION_1_2: Migration = object: Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE NewsWidget ADD COLUMN interval_anim INTEGER DEFAULT 6000")
}
}
val INIT_FEED_TABLE = arrayOf(
Feed("https://geektimes.ru/rss/interesting/"),
Feed("http://k.img.com.ua/rss/ru/companies.xml"))
}
}
当我打电话
Database.getInstance(context)
Database.getInstance(context)
或
Database.getInstance(this).feedDao().getAllFeed()
.flatMap({ url -> Database.getInstance(this).feedDao().getItem(url)})
我看到错误消息
java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase
我知道问题是两次调用onMigrate。我如何添加onUpgrade回调?如何解决?感谢您的支持。