Room loading database from file

Viewed 836

How to load Room Android Database from file on SD card? This is code for saving the database:

private void saveAppDatabase() {
    try {
        File sd = Environment.getExternalStorageDirectory();

        if (sd.canWrite()) {
            String currentDBPath =
                    getDatabasePath("AppDatabase").getAbsolutePath();
            String backupDBPath = "AppDatabase.db";
            File currentDB = new File(currentDBPath);
            File backupDB = new File(sd, backupDBPath);

            if (currentDB.exists()) {
                FileChannel src = new FileInputStream(currentDB).getChannel();
                FileChannel dst = new FileOutputStream(backupDB).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Thank you for help!

1 Answers

Either copy the database back to where you copied it from, or try passing the fully-qualified path to Room.databaseBuilder() and see if that works. It's possible you will need to create your own SupportSQLiteOpenHelper.Factory if the stock one does not work. I do not recommend working with a database that is on external storage, as bad things can happen if other apps try messing with that file while you are using it. – CommonsWare

Related