我在我的应用程序中添加了一个新的迁移(我在其中插入了一个表),并上传到了Google Play (最新更新)。在MIGRATION_7_8中,我将这些插入添加到类型表中。当我从Google Play (全新安装)安装它时,insterts将不会出现在应用程序中。但我检查了一下,是否有人将Google Play中的uapp从以前的版本更新到了最新版本,这些插件都在应用中。这很有趣。首次安装时未触发的Google Play更新触发了哪些内容?
现在的问题是,谁更新了应用程序,谁就有这些插件,但谁第一次安装它,他们就不会有这些插件。我尝试了一些方法,但都不起作用。有什么想法吗?
@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();
发布于 2020-11-21 11:19:12
对于新安装,迁移不会运行。
新安装无需迁移即可接收数据库模式/表的当前版本。
在Room注解框架之前,大多数安卓开发人员使用一个名为SQLLiteOpenHelper
的类来更直接地实现SQL,这个类是Room注解框架的基础。
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
}
回到房间,当新用户安装数据库时,将使用CREATE TABLE
等SQL语句在幕后创建数据库,这些语句基于已经放在房间实体上的注释。( onCreate
案例)
但是,如果有人从数据库版本1迁移到数据库版本2,我们就不能重新创建表,因为数据将会丢失。在本例中,运行诸如ALTER TABLE x ADD COLUMN y
之类的迁移语句来修改现有表。( onUpgrade
案例)
关于添加新数据,是的,在创建数据库和迁移/升级数据库时都需要添加新数据。创建数据库时,新用户将获得所需的所有数据。但在某些情况下,现有用户将需要在添加表或列时接收数据。在这两种情况下,通常可以通过调用相同的函数来避免代码重复。
更新:一个很好的帖子,展示了Room和平台上的底层事件方法之间的关系:
Does Android Room offer SqliteOpenHelper onCreate() & onUpdate() alternative?
https://stackoverflow.com/questions/64928681
复制