如果我在启用破坏性回退的情况下运行 Room 迁移:
Room.databaseBuilder(applicationContext, MyDb::class.java, "database-name")
.fallbackToDestructiveMigration()
.build()
有没有办法确定破坏性迁移是否被触发与迁移是否成功完成?我希望能够记录一些信息以进行跟踪。
最佳答案
您可以使用房间 Callback
和 add it to your database ,它有以下方法:你可以在哪里使用onDestructiveMigration
这是一个示例
@Database(entities = {.....}, version = 1)
public abstract class MyDatabase extends RoomDatabase {
private static final String DATABASE_NAME = “myDatabaseName.db”;
private static final Object LOCK = new Object();
private static volatile MyDatabase instance;
public static MyDatabase getDatabase(final Context context) {
if (INSTANCE == null) {
synchronized (MyDatabase.class) {
if (INSTANCE == null) {
// Create database here.
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
MyDatabase.class, DATABASE_NAME)
.fallbackToDestructiveMigration()
.addCallback(mCallback) // Trigger the callback
.build();
}
}
}
return INSTANCE;
}
/*
* Callback when database is created & when it’s opened
* */
static RoomDatabase.Callback mCallback = new Callback() {
@Override
public void onCreate(@NonNull SupportSQLiteDatabase db) { // Callback when database is first-time created or recreated after destruction
super.onCreate(db);
Log.i("LOG_TAG", “Database is created”);
}
@Override
public void onOpen(@NonNull SupportSQLiteDatabase db) { // callback when the activity is opened
super.onOpen(db);
Log.i("LOG_TAG", “Database is opened”);
}
};
@Override
public void onDestructiveMigration(@NonNull SupportSQLiteDatabase db) { // Called after the database was destructively migrated
super.onDestructiveMigration(db);
Log.i(LOG_TAG, “Database is destructed”);
}
}
关于android - 检测是否执行了房间破坏性迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64828407/