添加新 table 和更新版本号后 Room 数据库挂起

Room database hangs after adding new table and updating version number

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

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

I/SQLiteOpenHelper: DB version upgrading from 3 to 4

我认为我使用迁移命令正确升级了数据库。我还看到一个文件 4.json,其中包含新创建的实体。

MainDatabase.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
            }
        }    
    }
}

PaymentDao

@Dao
interface PaymentDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertPaymentOptions(paymentOptions: List<PaymentOptionsEntity>)

    @Query("SELECT * FROM PaymentOptionsEntity")
    suspend fun getPaymentOptions(): List<PaymentOptionsEntity>
}

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 定义为字符串

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

两处保持一致