Employing Migrations
Simply creating a Migration
as a static
field somewhere is necessary but not sufficient to have Room know about performing the migration. Instead, you need to use the addMigrations()
method on RoomDatabase.Builder
to teach Room about your Migration
objects. addMigrations()
accepts a varargs, and so you can pass in one or several Migration
objects as needed.
package com.commonsware.android.room;
import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.content.Context;
@Database(
entities={Trip.class, Lodging.class, Flight.class},
version=2
)
abstract class TripDatabase extends RoomDatabase {
abstract TripStore tripStore();
private static final String DB_NAME="trips.db";
private static volatile TripDatabase INSTANCE=null;
synchronized static TripDatabase get(Context ctxt) {
if (INSTANCE==null) {
INSTANCE=create(ctxt, false);
}
return(INSTANCE);
}
static TripDatabase create(Context ctxt, boolean memoryOnly) {
return(create(ctxt, DB_NAME, memoryOnly));
}
static TripDatabase create(Context ctxt, String name, boolean memoryOnly) {
RoomDatabase.Builder<TripDatabase> b;
if (memoryOnly) {
b=Room.inMemoryDatabaseBuilder(ctxt.getApplicationContext(),
TripDatabase.class);
}
else {
b=Room.databaseBuilder(ctxt.getApplicationContext(), TripDatabase.class,
name);
}
return(b.addMigrations(Migrations.FROM_1_TO_2).build());
}
}
Here, we teach the RoomDatabase.Builder
about the FROM_1_TO_2
Migration
. In this sample project, the migrations are implemented in a separate Migrations
class, though you are welcome to have them directly in your RoomDatabase
class or wherever makes sense for you.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.