I have a Room database, containing two entities: MusicItem and FormatItem, with the former containing a foreign key to the latter. Using "DB Browser for SQLite" I have filled the table for FormatItem with some formats and added this DB as a prepackaged DB to the Room database with createFromAsset.
The database seems to be working fine - the user can add, remove and edit items in the database as expected, but for some reason, when the app is closed and opened again, the DB is empty. It seems that the fallbackToDestructiveMigration method is called (I haven't implemented a migration strategy yet) when building the database, and I don't understand why. Room doesn't say anything about the prepackaged DB (meaning the schema is correct). When I disable createFromAsset everything works fine, and the data is persistent after closing and restarting the app.
My question is why is the migration code called, and how can I prevent the deletion of the data.
My code:
class ItemsRoomDatabase:
public abstract class ItemsRoomDatabase extends RoomDatabase {
private static final String TAG = ItemsRoomDatabase.class.getSimpleName();
private static ItemsRoomDatabase INSTANCE;
static ItemsRoomDatabase getDatabase(final Context context) {
if (INSTANCE == null) {
synchronized (ItemsRoomDatabase.class) {
if (INSTANCE == null) {
Log.d(TAG, "called");
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
ItemsRoomDatabase.class, "items_database")
// Wipes and rebuilds instead of migrating
// if no Migration object.
// Migration is not part of this practical.
// TODO: add migration support
.fallbackToDestructiveMigration()
.createFromAsset("prepackaged_db.db")
.build();
}
}
}
return INSTANCE;
}
public abstract MusicItemDao musicItemDao();
public abstract FormatItemDao formatItemDao();
}
class MusicItem:
@Entity(tableName = "music_items_table",
foreignKeys = @ForeignKey(entity = FormatItem.class,
parentColumns = "id", childColumns = "formatId", onDelete = NO_ACTION))
class MusicItem implements Parcelable {
enum Classification {
COLLECTION,
WISHLIST,
NONE;
}
@PrimaryKey
@NonNull
private final String id;
@NonNull
private final String title;
@NonNull
private final String artist;
private final String thumbUrl;
private List<String> genres;
@NonNull
private List<Track> tracks;
private String year;
@NonNull
private Classification classification;
@NonNull
private int formatId;
.
.
.
}
class FormatItem:
@Entity(tableName = "format_items_table")
class FormatItem {
@PrimaryKey(autoGenerate = true)
@NonNull
private int id;
@NonNull
private final String name;
@NonNull
private int itemsCount = 0;
FormatItem(String name) {
this.name = name;
}
int getId() {
return id;
}
String getName() {
return name;
}
int getItemsCount() {
return itemsCount;
}
void setId(int id) {
this.id = id;
}
void setItemsCount(int itemsCount) {
this.itemsCount = itemsCount;
}
}