One line answer
- Write SQL that creates the new table in AppDatabase.java
- Call the add-migration in DB initialization
The code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @Database... | |
public abstract class AppDatabase extends RoomDatabase { | |
public static final String DB_NAME = "Nhviewer"; | |
// public abstract ComicBookmarkDao comicBookmarkDao(); | |
// ... | |
public static final Migration MIGRATION_1_2 = new Migration(1, 2) { | |
@Override | |
public void migrate(SupportSQLiteDatabase database) { | |
// create comic bookmark table | |
database.execSQL("CREATE TABLE IF NOT EXISTS `ComicBookmark` (`page` INTEGER NOT NULL, `id` INTEGER NOT NULL, `dateOfCreate` TEXT, PRIMARY KEY(`id`, `page`))"); | |
} | |
}; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ... | |
private static AppDatabase appDatabase; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
// ... | |
appDatabase = Room.databaseBuilder(getApplicationContext(), | |
AppDatabase.class, AppDatabase.DB_NAME) | |
.addMigrations(AppDatabase.MIGRATION_1_2).build(); | |
} | |
// ... |
The problem
In my comic app project (NHViewer), I wanted to add a "bookmark" function to show the last seen page for each comic.
So I need to create a new table for the Room database while keeping the original tables and data in the device.
After some searching, I wrote the above code according to the AppDatabase's schema.
Coda
During my searching, the Room database migration seems improved in the version 2.2.0 (androidx.room:room-*:2.2.0)
This note did not cover that part though 🙁
This note did not cover that part though 🙁
留言
張貼留言