android - 房间数据库在添加新表和更新版本号后挂起
问题描述
一旦我的应用程序执行第一个房间命令(在不同的表中),应用程序就会冻结。
我从控制台收到的最后一条消息是:
I/SQLiteOpenHelper: DB version upgrading from 3 to 4
我以为我使用 Migration 命令正确升级了数据库。我还看到一个文件4.json
,其中包含新创建的实体。
主数据库.kt
@Database(
entities = [
PaymentEntity::class,
PaymentOptionsEntity::class,
exportSchema = true,
version = 4
)
abstract class MainDatabase : RoomDatabase() {
abstract fun paymentDao(): PaymentDao
companion object {
@Volatile
private var INSTANCE: MainDatabase? = null
val MIGRATION_3_4 = object : Migration(3, 4){
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("CREATE TABLE IF NOT EXISTS `PaymentOptionsEntity` (`id` INTEGER, PRIMARY KEY(`id`))")
}
}
fun getDatabase(
context: Context,
scope: CoroutineScope? = null
): MainDatabase {
// if the INSTANCE is not null, then return it,
// if it is, then create the database
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
MainDatabase::class.java,
BuildConfig.APPLICATION_ID + "_" + BuildConfig.FLAVOR + "_db"
)
.addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4)
.build()
INSTANCE = instance
// return instance
instance
}
}
}
}
支付道
@Dao
interface PaymentDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertPaymentOptions(paymentOptions: List<PaymentOptionsEntity>)
@Query("SELECT * FROM PaymentOptionsEntity")
suspend fun getPaymentOptions(): List<PaymentOptionsEntity>
}
支付选项实体
@Parcelize
@Entity(tableName="PaymentOptionsEntity")
data class PaymentOptionsEntity (
@PrimaryKey
val id: String = ""
): Parcelable
build.gradle(应用程序):
implementation "androidx.room:room-runtime:2.4.0-alpha03"
implementation "androidx.room:room-ktx:2.4.0-alpha03"
解决方案
您已在 PaymentOptionsEntity 中将 id 定义为 String
并在 MIGRATION_3_4 作为 Integer ("CREATE TABLE IF NOT EXISTS
PaymentOptionsEntity (
id INTEGER, PRIMARY KEY(
id))")
在两个地方保持相同
推荐阅读
- reactjs - 使用 React 和 Ant Design Pro / UmiJS 实施 AWS Amplify Authenticator
- powershell - 使用 Powershell 查找子网站所属的网站集
- python - 如何在 python 中将 CSV 表转换为 COCO 格式?
- python-sphinx - Python 代码中注释和文档字符串的基本语法
- groovy - 更新的 groovy 和 spock 导致 propertymissing 和 methodmissing 调用问题
- audio - 改变音频音高的最佳方法是什么?
- python - Selenium 刮取 Power BI
- jquery - 多选择框 Jquery 1.7 在 IE 中不起作用
- python - 如何显示列表中的特定列,将它们制成表格并在控制台上打印
- apache - 激活 Apache 部署的虚拟环境