My app collects data for experiments. I am trying to pre-populate the database. I create directories for each experiment and store the database in each of those.
Folder storedData holds the database to reuse. I have a button to use the saved database and not create one. Whenever I try to load data from the saved database, Room starts off fresh:
private static volatile AppDatabase INSTANCE;
public static AppDatabase getDatabase(final Context context, String directory) {
if(INSTANCE == null) {
synchronized (AppDatabase.class) {
if (INSTANCE == null) {
File dbFile = new File(directory, "test_database_1.db");
if(dbFile.exists()) {
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
AppDatabase.class, "test_database")
.createFromAsset("databases/test_database_1.db")
.setJournalMode(JournalMode.TRUNCATE)
.build();
System.out.println("Database initialized");
} else {
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
AppDatabase.class, dbFile.getAbsolutePath())
.setJournalMode(JournalMode.TRUNCATE)
.build();
}
System.out.println("Database initialized");
}
}
}
return INSTANCE;
}
createFromFile
and createFromAsset
have not given me success. I prefer createFromFile
. Having both database files named the same causes issues, so a workaround would be great. I am targeting Android 13+.
If the database file exists, then createFromAsset
(or file) will not be invoked. i.e. they are only invoked when there is no database file (aka simply coding .createFrom....
does not mean that the method does anything)
Furthermore Room has expectations, one being that the database exists in the standard/recommended location (data/data/
the_package_name
/databases
) (as per Context
‘s getDatabasePath
method).
1