Search code examples
android-sqlite

Replay backup database in Android


I do not know how to do it although I already looked for a solution on the Internet. I want to replay my backup database in Android.

Currently, I am creating a backup of my database like that:

    final File[] databases = new File(context.getFilesDir().getParentFile().getPath() + "/databases").listFiles();
    for (File databaseFile: databases) {
        File backupFile = new File(context.getExternalFilesDir(null), databaseFile.getName() + "-" + System.currentTimeMillis() + ".db");
        FileChannel inputChannel = null;
        FileChannel outputChannel = null;

        if(databaseFile.getName().startsWith("DATABASE")) {
            try {
                inputChannel = new FileInputStream(databaseFile.getAbsolutePath()).getChannel();
                outputChannel = new FileOutputStream(backupFile).getChannel();
                outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
...

Now I would like to replay my backup since I have changed my mobile phone and I need my data on the new phone.

If somebody know a way how I can do that?

Thank you very much in advance.


Solution

  • You basically reverse the process.

    1. Ascertain the location of the backup file (perhaps using a file picker).
    2. Delete the existing file(s) if one from it's location typically in the databases folder/directory which can be ascertained by using a Context's getDatabasePath method
      1. note that files that are the same name as the database file name but prefixed with -wal, -shm or -journal should also be deleted.
    3. Copy the file(s) (-wal and - shm if they existed and were backed up) from their backup location to the location they should be.
    • note that you could overwrite the files rather than delete, alternately you could rename it/them which would then leave a copy of the pre restored database.
    • note that you may well wish to restart the App after the restore, this being the simplest way to handle to cleanup of all the activities which may be accessing the old database.

    More at How to restore Sqlite database after backup Android