Search code examples
androidandroid-roomandroid-architecture-components

Room Android - How to handle database version upgrade


I am reading about Android Architecture components Room and wanted to know if there is there anything in Room equivalent to onUpgrade in SQLiteOpenHelper method available.

@Override
 public void onUpgrade(final SQLiteDatabase database, final int oldVersion, final int newVersion) {}

Solution

  • You can use https://developer.android.com/training/data-storage/room/migrating-db-versions.html

     Room.databaseBuilder(getApplicationContext(), MyDb.class, "database-name")
                .addMigrations(MIGRATION_1_2,MIGRATION_1_3, MIGRATION_2_3).build();
    
        static final Migration MIGRATION_1_2 = new Migration(1, 2) {
            @Override
            public void migrate(SupportSQLiteDatabase database) {
                database.execSQL("CREATE TABLE `Fruit` (`id` INTEGER, "
                        + "`name` TEXT, PRIMARY KEY(`id`))");
            }
        };
    
        static final Migration MIGRATION_2_3 = new Migration(2, 3) {
            @Override
            public void migrate(SupportSQLiteDatabase database) {
                database.execSQL("ALTER TABLE Book "
                        + " ADD COLUMN pub_year INTEGER");
            }
        };
    
       static final Migration MIGRATION_1_3 = new Migration(1, 3) {
                @Override
                public void migrate(SupportSQLiteDatabase database) {
                    database.execSQL("ALTER TABLE Book "
                            + " ADD COLUMN pub_year INTEGER");
                }
            };