【发布时间】:2019-10-09 17:16:58
【问题描述】:
房间版2.2.0-rc01
Android版本7.1、8.1
我有一个有点大的迁移。添加几个表、索引等。当它运行时,它会锁定数据库。由于需要一段时间,它会在应用程序的所有其他部分导致android.database.sqlite.SQLiteDatabaseLockedException: database is locked (code 5)。
有没有办法在尝试使用数据库之前等待迁移完成?
缩写迁移:
try {
// database.beginTransaction()
database.execSQL("ALTER TABLE DeviceItem ADD COLUMN #### INTEGER NOT NULL DEFAULT 0")
database.execSQL("ALTER TABLE DeviceItem ADD COLUMN #### TEXT NOT NULL DEFAULT ''")
database.execSQL("CREATE INDEX IF NOT EXISTS ### ON #### (###, ###)")
//helper method that just creates the table
createLocalityTable(database)
//database.setTransactionSuccessful()
} catch (e: SQLiteException) {
Crashlytics.logException(e)
throw e
} catch (e: Throwable) {
Crashlytics.logException(e)
throw e
} finally {
// database.endTransaction()
database.close()
}
这是我的 appDatabase 单例
package com.company.app.data
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
@Database(entities = [someClass::class, otherClass::class, etc::class], version = 3)
@TypeConverters(Converters::class)
abstract class AppDatabase : RoomDatabase() {
abstract fun somethingDao(): somethingDao
@Synchronized
override fun close() {
if (INSTANCE != null) {
super.close()
INSTANCE = null
}
}
companion object {
@Volatile
private var INSTANCE: AppDatabase? = null
var canGo = false
fun getAppDatabase(context: Context): AppDatabase? {
val tempInstance = INSTANCE
if (tempInstance != null) {
return tempInstance
}
synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java,
"myDb"
).addMigrations(MIGRATION_X_X).build()
INSTANCE = instance
return instance
}
}
}
}
【问题讨论】:
标签: android kotlin android-sqlite android-room