首页 > 解决方案 > android房间迁移不调用

问题描述

在我的应用程序中,我需要迁移来创建一个新表并将数据插入其中。表本身已创建但那里没有数据,我试图破坏迁移调用方法,但它没有被调用。为什么不叫迁移?

应用程序.kt

    override fun onCreate() {
    super.onCreate()
    instance = this
    database = Room.databaseBuilder(applicationContext, TramDatabase::class.java, "tram_database")
            .addMigrations(Migrations.MIGRATION_1_2)
            .addCallback(dbCallback)
            .allowMainThreadQueries()
            .build()

    Stetho.initializeWithDefaults(this)
}

迁移.kt

class Migrations {
companion object {

    val MIGRATION_1_2: Migration = object : Migration(1, 2) {
        override fun migrate(database: SupportSQLiteDatabase) {
            database.execSQL("CREATE TABLE IF NOT EXISTS ${TrackPoint.TABLE_NAME} " +
                    "(${TrackPoint.Columns.ID} INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
                    "${TrackPoint.Columns.NUMBER} TEXT NOT NULL, " +
                    "${TrackPoint.Columns.LONGITUDE} DOUBLE PRECISION NOT NULL, " +
                    "${TrackPoint.Columns.LATITUDE} DOUBLE PRECISION NOT NULL, " +
                    "${TrackPoint.Columns.ORDER} INTEGER NOT NULL)")

            Timber.d("rrrrrrrrrrr")
            val filename = "track_points.sql"
            try {
                val input = App.instance.assets.open(filename)
                val output = ByteArrayOutputStream()
                val buffer = ByteArray(1024)
                var length = input.read(buffer)

                while (length != -1) {
                    output.write(buffer, 0, length)
                    length = input.read(buffer)
                }

                val insertSQl = output.toString("UTF-8")
                input.close()
                output.close()

                try {
                    database.beginTransaction()
                    database.execSQL(insertSQl)
                    database.setTransactionSuccessful()
                } finally {
                    database.endTransaction()
                }

            } catch (error: Exception) {
                Timber.e(error)
            }
        }
    }
}

电车数据库.kt

@Database(entities = [MapRoute::class, TrackPoint::class], version = 2)
abstract class TramDatabase: RoomDatabase() {
abstract fun mapRouteDao() : MapRouteDao
}

标签: androidandroid-roomandroid-databaseandroid-jetpack

解决方案


推荐阅读