Thursday, 21 February 2019

Android Room Copy db from asset not Upgrading on version update

I am using Android Room in an app. I have a pre-build database in assets which I need to use. I have copied the database with conventional file IO.

private fun copyDatabaseFile(context: Context) {
    val dbPath = context.getDatabasePath(DB_NAME)
    if (dbPath.exists() && AppPrefs.getInstance().dataBaseVersion== DATABASE_VERSION) {
        return
    }
    if(dbPath.delete())Log.e("datacopy", "file deleted")

    dbPath.parentFile.mkdirs()
    try {
        val inputStream = context.assets.open("databases/no_database.db")
        val output = FileOutputStream(dbPath)
        val buffer = ByteArray(8192)
        var length =0
        while ({length = inputStream.read(buffer, 0, 8192); length}() > 0) {
            Log.e("datacopy", "Write")
            output.write(buffer, 0, length)
        }
        output.flush()
        output.close()
        inputStream.close()
        AppPrefs.getInstance().dataBaseVersion= DATABASE_VERSION
    } catch (e: IOException) {
        e.printStackTrace()
    }
}
}

Here is the getter for Database instance :-

 internal fun getDatabase(context: Context): MyDatabase? {
        if (INSTANCE == null) {
            synchronized(MyDatabase::class.java) {
                if (INSTANCE == null) {
                    copyDatabaseFile(context)
                    INSTANCE = Room.databaseBuilder(
                        context.applicationContext,
                        MyDatabase::class.java, DB_NAME)
                        .addMigrations(MyDatabase.MIGRATION_1_2)
                        .build()
                }
            }

        }
        return INSTANCE
    }

First time all working fine. When I upgrade the version of database I am deleting the old file copy new file, but Room is returning the old data. I am not sure what's the problem.

I even tried some older answer which suggests:

  1. How to use Room Persistence Library with pre-populated database? library-with-pre-populated-database

  2. https://github.com/humazed/RoomAsset

Also tried some other stuff from Git, but none of it worked. What could be the issue? My need is replace old database with new one each time database version is upgrade.



from Android Room Copy db from asset not Upgrading on version update

No comments:

Post a Comment