The room database is re-populated every time I re-run Android so any changes I made before quitting Android are not saved
I want this data to persist forever without Prepopulate the Room database once it's imported Here's the code I created to prepopulate
@Database(entities = {DeviceInfo.class, AddressInfo.class},version = 1)
public abstract class AppDataBase extends RoomDatabase {
public abstract DeviceDao deviceDao();
public abstract AddressDao addressDao();
private static AppDataBase instance;
public static synchronized AppDataBase getInstance(Context context){
if(instance == null){
instance = Room.databaseBuilder(context.getApplicationContext(), AppDataBase.class,"device.db")
.createFromAsset("device.db")
.fallbackToDestructiveMigration()
.build();
}
return instance;
}
}
Here's the update code
@Update
public void updateAddressInfo(AddressInfo addressInfo);
I believe that removing
.fallbackToDestructiveMigration()will resolve your issue; an alternative is to ensure that the prepopulated database's user_version is set to the coded database version.However, there shouldn't really be the need as the destruction should only be invoked if the database version differs from the coded version and the database's version should be set to the coded version.
Some basic testing appears to highlight what may well be a bug. That is, if the prepopulated version is set to 0 (using
PRAGMA user_version = 0;) then the copied database appears to be destroyed and copied again. If however, the prepopulated database's version (PRAGMA user_version = 1) then the database persists.Demonstration
First some basic
@Entityannotated classes were created as per:-and :-
Also some
@Daoannotated interfaces:-and :-
Then a modified (to add a calback)
@Databaseannotated AppDataBase class:-.allowMainThreadQueriesadded so the main thread could be utilised and thus reducing the code needed.Using Navicat the following SQL was used to create 2 database files one with user_vesrion as 0, other as 1 using:-
The files were copied into the assets folder e.g. :-
device.dbfile being deleted and copied from the respective other file depending on the testing being undertaken.Finally some activity code to test:-
TESTING
Test 1
Initially
device_userversion0.dbwas copied asdevice.db. The app uninstalled and then run (i.e. brand new install). Resulting in the log showing:-Test 2
The App is simply rerun, the output:-
Test 3
The line
.fallbackToDestructiveMigrationhas been commented out and the App rerun.This time the output is:-
Test 4 The App is uninstalled and run 3 times with
.fallbackToDestructiveMigrationcommented out. This time the address rows are:-**So at this stage not including
.fallback....get's around the issue (bug).Test5 The App is uninstalled and the
device.dbfile is deleted and copied from device_userversion1.db and.fallbackToDestructiveMigrationis reinstated as per:-The output from the first run is:-
Test 6 The App is rerun, the output:-
Test 7 a third run:-