3

In my application, I needed a migration to create a new table and insert data into it. the table itself was created but there is no data there, and I tried to debage the migration call method, but it was not called. Why is migration not called?

Application.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)
}

Migrations.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)
            }
        }
    }
}

TramDatabase.kt

@Database(entities = [MapRoute::class, TrackPoint::class], version = 2)
abstract class TramDatabase: RoomDatabase() {
abstract fun mapRouteDao() : MapRouteDao
}
ankuranurag2
  • 2,300
  • 15
  • 30
Nikitc
  • 795
  • 1
  • 6
  • 12

1 Answers1

0

Did you call any query on DAO after app update?

I learned that migration is not called until first query is called.

When Room tries to get writableDatabase and it is not migrated yet, then it will run the migration.

Beman
  • 1