Search code examples
androidkotlinandroid-roomdatabase-migration

Get Context in Android Room Migration


Get Context in Android Room Migration:

In my Migration i want to get context to read some files from assets:

@Module
@InstallIn(SingletonComponent::class)
object
PersistenceModule : Application() {

    @Provides
    @Singleton
    fun provideAppDatabase(
        @ApplicationContext context: Context,
    ): AppDatabase = Room.databaseBuilder(context, AppDatabase::class.java, "app")
        .addMigrations(MIGRATION_3_4)
        .build()
}
val MIGRATION_3_4 = object : Migration(3, 4) {
    override fun migrate(database: SupportSQLiteDatabase) {
        //...
        val txt = context.resources.assets.open("example.txt").bufferedReader().use { it.readText() }
    }
}

Solution

  • Create a class extending Migration which takes context as parameter in constructor

    class Migration3to4(@ApplicationContext val context: Context): Migration(3.4) {
     override fun migrate(database: SupportSQLiteDatabase) {
            // access context here
            val txt = context.resources.assets.open("example.txt").bufferedReader().use { it.readText() }
        }
    }
    

    Callsite

    @Module
    @InstallIn(SingletonComponent::class)
    object
    PersistenceModule : Application() {
    
        @Provides
        @Singleton
        fun provideAppDatabase(
            @ApplicationContext context: Context,
        ): AppDatabase = Room.databaseBuilder(context, AppDatabase::class.java, "app")
            .addMigrations(Migration3to4(context))
            .build()
    }