首页 > 解决方案 > 房间数据库在添加新表和更新版本号后挂起

问题描述

一旦我的应用程序执行第一个房间命令(在不同的表中),应用程序就会冻结。

我从控制台收到的最后一条消息是:

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"

标签: androidandroid-room

解决方案


您已在 PaymentOptionsEntity 中将 id 定义为 String

并在 MIGRATION_3_4 作为 Integer ("CREATE TABLE IF NOT EXISTS PaymentOptionsEntity (id INTEGER, PRIMARY KEY(id))")

在两个地方保持相同


推荐阅读