1

Using SqliteOpenHelper, I can rely on the onCreate() method to initialize some database work if the database is created for the first time.

Also, using the onUpdate() method, I can easily detect if the user has an older version of the DB and I can update it easily.

Does Room support alternative methods to use?

Mena
  • 3,019
  • 1
  • 25
  • 54

2 Answers2

3

1. SQLiteOpenHelper.onCreate

YES, there is Callback class for that. You can add Callback to RoomDatabase.Builder like this

Room.databaseBuilder(getApplicationContext(), MyDb.class, "database-name")
    .addCallback(new Callback() {
        @Override
        public void onCreate(@NonNull SupportSQLiteDatabase db) {
            super.onCreate(db);
            //do something
        }

        @Override
        public void onOpen(@NonNull SupportSQLiteDatabase db) {
            super.onOpen(db);
            //do something
        }
    })
    .build();

2. SQLiteOpenHelper.onUpdate

YES, there is Migration class for that. You can add Migration to RoomDatabase.Builder like this

Room.databaseBuilder(getApplicationContext(), MyDb.class, "database-name")
    .addMigrations(MIGRATION_1_2, 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");
    }
};

If app is upgrading database version 1 to 4.

  1. case A. if you have defined migrations for version 1 to 4.
    • Boom. room will trigger only one migration code. version 1 to 4.
  2. case B. if you have defined migrations for version 1 to 2, version 2 to 3, version 3 to 4.
    • room will trigger all migrations one after another.

you should check this documentation Migrating Room databases

and this article Understanding migrations with Room

yeonseok.seo
  • 2,696
  • 3
  • 13
  • 14
0

Here's an example of how to do schema migrations in Room which is similar to using the onUpdate() method in SqliteOpenHelper:

Room.databaseBuilder(context, RepoDatabase.class, DB_NAME)
.addMigrations(FROM_1_TO_2)
.build();

static final Migration FROM_1_TO_2 = new Migration(1, 2) {
    @Override
    public void migrate(final SupportSQLiteDatabase database) {
        database.execSQL("ALTER TABLE Repo 
                         ADD COLUMN createdAt TEXT");
        }
    };

More info Here

Mena
  • 3,019
  • 1
  • 25
  • 54