Android 从 Google Play 首次安装时未 运行 房间迁移

Android Room Migration not running on First Install from Google Play

我向我的应用程序添加了一个新的迁移(我在其中插入了 table)并上传到 Google Play(最新更新)。在 MIGRATION_7_8 中,我将这些 INSERT 添加到类型 table 中。当我从 Google Play(全新安装)安装它时,插件不会出现在应用程序中。但是我检查了是否有人将 Google Play 中的 uapp 从以前的版本更新到应用程序中插入的最新版本。这很有趣... Google Play update 触发了什么,第一次安装时没有触发什么?

现在的问题是,更新应用程序的人有这些 INSERT,但第一次安装它的人不会有这些 INSERT。我尝试了一些方法,但没有任何效果。 有什么想法吗?

@Database(entities = {Types.class, Item.class, Most.class}, version = 8, exportSchema = true)
...
    Room.databaseBuilder(context.getApplicationContext(),
                        MyDatabase.class, "mydatabase.db")
                        .allowMainThreadQueries()
                        .addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4,
                                MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, MIGRATION_7_8)
                        .addCallback(roomCallback)
                        .build();

迁移不会 运行 用于新安装。

新安装接收当前版本的数据库 schema/tables,无需迁移。

在 Room 注释框架之前,大多数 Android 开发人员更直接地 SQL 使用名为 SQLLiteOpenHelper 的 class 实现 class,Room it 所基于的 class上。

SQLLiteOpenHelper有两个重要的方法:

// Method is called during creation of the database
@Override
public void onCreate(SQLiteDatabase database) {
    ...
    database.execSQL(DATABASE_CREATE); // Crate the DB in SQL
    populateDb(); // Add any necessary data
}

// Method is called during an upgrade of the database
@Override
public void onUpgrade(SQLiteDatabase database,int oldVersion,int newVersion){
    Log.w(MyDatabaseHelper.class.getName(),
                     "Upgrading database from version " + oldVersion + " to "
                     + newVersion);
    performUpgrade(db, upgradedVersion, newVersion);
}

// Helper method to upgrade the DB
private int performUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Usually implemented as large switch statement with one case statement for
    // each migration. In other words, 1 case statement for each DB version
    // (1,2, 3, .... n)
    //
    // A typical implementation would recursively call performUpgrade until all the
    // individual migration cases have been run
    //
    // Typical migration case:
    // 1. Add a new table or add a new column to an existing table
    // 2. Add some data to the new table or column when necessary
} 

回到 Room,当新用户安装数据库时,数据库是根据 Room 实体上的注释使用 SQL 语句(如 CREATE TABLE)在幕后创建的. (onCreate 案例)

但是,例如,如果有人从数据库版本 1 迁移到数据库版本 2,我们无法重新创建 table,因为数据将会丢失。在这种情况下,像ALTER TABLE x ADD COLUMN y这样的迁移语句是运行修改现有的table。 (onUpgrade 案例)

关于添加新数据,是的,它需要在创建数据库时和 migrated/upgraded 时添加。新用户在创建数据库时获得他们需要的所有数据。但现有用户在某些情况下需要在添加 table 或列时接收数据。通常可以通过在两种情况下调用相同的函数来避免代码重复。

更新:一个不错的 post 展示了 Room 和平台上底层事件方法之间的关系: