Does Android Room offer SqliteOpenHelper onCreate() & onUpdate() alternative?

眉间皱痕 提交于 2021-02-11 14:39:46

问题


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?


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/52588626/does-android-room-offer-sqliteopenhelper-oncreate-onupdate-alternative

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!