androiddatabaserestoredatabase-restoreandroid-backup-service

Android backup/restore: how to backup an internal database?


I have implemented a BackupAgentHelper using the provided FileBackupHelper to backup and restore the native database I have. This is the database you typically use along with ContentProviders and which resides in /data/data/yourpackage/databases/.

One would think this is a common case. However the docs aren't clear on what to do: http://developer.android.com/guide/topics/data/backup.html. There is no BackupHelper specifically for these typical databases. Hence I used the FileBackupHelper, pointed it to my .db file in "/databases/", introduced locks around any db operation (such as db.insert) in my ContentProviders, and even tried creating the "/databases/" directory before onRestore() because it does not exist after install.

I have implemented a similar solution for the SharedPreferences successfully in a different app in the past. However when I test my new implementation in the emulator-2.2, I see a backup being performed to LocalTransport from the logs, as well as a restore being performed (and onRestore() called). Yet, the db file itself is never created.

Note that this is all after an install, and before first launch of the app, after the restore has been performed. Apart from that my test strategy was based on http://developer.android.com/guide/topics/data/backup.html#Testing.

Please also note I'm not talking about some sqlite database I manage myself, nor about backing up to SDcard, own server or elsewhere.

I did see a mention in the docs about databases advising to use a custom BackupAgent but it does not seem related:

However, you might want to extend BackupAgent directly if you need to: * Back up data in a database. If you have an SQLite database that you want to restore when the user re-installs your application, you need to build a custom BackupAgent that reads the appropriate data during a backup operation, then create your table and insert the data during a restore operation.

Some clarity please.

If I really need to do it myself up to the SQL level, then I'm worried about the following topics:


Solution

  • A cleaner approach would be to create a custom BackupHelper:

    public class DbBackupHelper extends FileBackupHelper {
    
        public DbBackupHelper(Context ctx, String dbName) {
            super(ctx, ctx.getDatabasePath(dbName).getAbsolutePath());
        }
    }
    

    and then add it to BackupAgentHelper:

    public void onCreate() {
        addHelper(DATABASE, new DbBackupHelper(this, DB.FILE));
    }