androidsqlitekotlinandroid-roomandroid-room-prepackageddatabase

Cannot pre-populate room database when changing schema


I am at my wits end with a problem I cannot resolve - when trying to change the schema/data of a table in my database. I am pre-populating the database with Rooms .createFromAsset method.

Current schema and data (working) - as shown in DB Browser - this is the database used to Pre-Populate the apps database. enter image description here

enter image description here

As I build the database with this code:

 val instance = Room.databaseBuilder(
                context.applicationContext,
                MetarDatabase::class.java,
                "metar_database"
            )
                    .createFromAsset("database/metar_database.db")
                    .fallbackToDestructiveMigration()
                    .build()

And this data class:

    @Entity(tableName = "airport_table")
data class Airport(
    @PrimaryKey(autoGenerate = false)
    val icao : String,
    val name : String?,
    val municipality : String?,
    val scheduled : Boolean,
    val iata : String?
)

It successfully pre-populates the database into the app: as seen on Database Explorer: enter image description here



The problem is this: If I try and change the schema at all: adding columns, removing columns (done by changing a csv file and importing into a new table in DB Browser, then re-naming to airport_table and adding one to the database version), it does not load the data.

Eg: (Does NOT pre-populate):

 @Entity(tableName = "airport_table")
data class Airport(
    @PrimaryKey(autoGenerate = false)
    val icao : String,
    val name : String?
)

enter image description here enter image description here enter image description here I get NO errors apart from "E/libc: Access denied finding property "ro.serialno"" which I don't think is relevant.

In addition - changing this one table means that my other table does not pre-populate. However the empty database has still been made successfully, and I can add to it within the app.

Please help me - I've looked around stack overflow for similar questions. Some are similar, but involve getting anything to happen at all - my problem is it only works with one exact schema that I happen to succeed with whilst testing - but I want another schema.

Thanks a lot, Liam


Solution

  • After a long time I realised the problem.

    I thought I did not need migration as I only wanted to change the pre-populating database, and not migrate anything currently on the device. However the use of destructive migration also deletes your pre-populating data when you add one to the schema number.

    So simply add an empty migration and it works

    val migration1: Migration = object : Migration(5, 6) { override fun migrate(database: SupportSQLiteDatabase) {}}
    

    Thanks very much to myself for sorting my problem.