本文介绍了Android Room是否提供SqliteOpenHelper onCreate()&onUpdate()替代品?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用SqliteOpenHelper,如果是第一次创建数据库,则可以依靠onCreate()方法来初始化一些数据库工作.

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

此外,使用onUpdate()方法,我可以轻松地检测用户是否具有较旧版本的数据库,并且可以轻松地对其进行更新.

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.

Room支持使用其他方法吗?

Does Room support alternative methods to use?

推荐答案

1.SQLiteOpenHelper.onCreate

是的,有回调类.您可以像这样将Callback添加到RoomDatabase.Builder

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

是的,为此提供了迁移类.您可以像这样将Migration添加到RoomDatabase.Builder

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");
    }
};

如果应用将数据库版本1升级到4.

If app is upgrading database version 1 to 4.

  1. 情况A.如果您已定义版本1到4的迁移.
    • 景气.房间将仅触发一个迁移代码.版本1到4.
  • 房间将一次又一次触发所有迁移.

您应该查看此文档迁移会议室数据库

和这篇文章了解Room的迁移

这篇关于Android Room是否提供SqliteOpenHelper onCreate()&onUpdate()替代品?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-03 12:33