Мой подход заключается в следующем: я копирую старые таблицы базы данных в новую (Room) сразу после первого создания базы данных Room
Room.databaseBuilder(app.getApplicationContext(), AppDatabase.class, ROOM_DB_NAME)
.addCallback(new Callback(){
@Override
public void onCreate(@NonNull SupportSQLiteDatabase roomDb){
// This is called when the database is created for the first time.
super.onCreate(roomDb);
OldDatabase oldDatabase = ...// your old database of type SQLiteOpenHelper
MigrationHelper migrationHelper = new MigrationHelper(oldDatabase,roomDb);
migrationHelper.doMigrateFromOldToNewDb();
}
})
.build();
и вспомогательного класса Migration
public class MigrationHelper {
private OldDatabase oldDatabase;
SupportSQLiteDatabase roomDb;
public MigrationHelper(OldDatabase oldDatabase, SupportSQLiteDatabase roomDb){
this.oldDatabase = oldDatabase;
this.roomDb = roomDb;
}
public void doMigrateFromOldToNewDb(){
roomDb.beginTransaction();
copyTableData("table1");
copyTableData("table2");
copyTableData("table3");
roomDb.setTransactionSuccessful();
roomDb.endTransaction();
}
private void copyTableData(String tableName){
Cursor c = oldDatabase.select("SELECT * FROM " + tableName);
while(c.moveToNext()){
StringBuilder columns = new StringBuilder();
StringBuilder values = new StringBuilder();
columns.append(" (");
values.append(" VALUES (");
for(int i = 0;i< c.getColumnCount();i++){
columns.append("`");
columns.append(c.getColumnName(i));
columns.append("`");
if(c.getString(i) != null) {
values.append("'");
values.append(c.getString(i));
values.append("'");
} else {
values.append("''");
}
if(i < c.getColumnCount()-1){
columns.append(",");
values.append(",");
}
}
columns.append(")");
values.append(")");
String insertQuery = "INSERT INTO " + tableName + columns.toString() + values.toString();
Log.e("TAG",insertQuery);
roomDb.execSQL(insertQuery);
}
}}