Search code examples
androidandroid-roomauto-migration

Android Room database - how to get context in Automigration?


I need to change the Room database schema. In addition to the usual things like deleting a database table or renaming columns, I need to do some data transformations.

I have created an Automigration class and I want to do the data transformations in the onPostMigrate method.

But for data transformations I need to read some data from assets and I need context. Is there any way to pass this context to the Automigration class in the constructor?

Something like this

public class MyAutoMigration implements AutoMigrationSpec {

    private Context context;

    public MyAutoMigration(Context context) {
        this.context = context;
    }

    @Override
    public void onPostMigrate(SupportSQLiteDatabase database) {
        // Perform data transformations here
    }
}

I have no idea how to do this.


Solution

  • Instances of AutoMigrationSpec are created automatically and you can't inject any parameters into them.

    If you need a reference to a Context during the migration, then you can do a manual migration.

    Here's an example:

    public class Migration1to2 extends Migration {
        private final Context context;
    
        public Migration1to2(Context context) {
            super(1, 2);
            this.context = context;
        }
    
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            // todo: implement the migration logic.
            // database.execSQL(...)
        }
    }
    

    Note that numbers 1 and 2 are the starting and ending versions of the database.

    Now you can create your migration and add it to the database:

    Room.databaseBuilder(getApplicationContext(), MyDb.class, "database-name")
            .addMigrations(Migration1to2(getApplicationContext()))
            .build();