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

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


After revisiting my question, I was able to get it to work after looking at how ConnectBot does it. Thanks Kenny and Jeffrey!

It's actually as easy as adding:

FileBackupHelper hosts = new FileBackupHelper(this,    "../databases/" + HostDatabase.DB_NAME);addHelper(HostDatabase.DB_NAME, hosts);

to your BackupAgentHelper.

The point I was missing was the fact that you'd have to use a relative path with "../databases/".

Still, this is by no means a perfect solution. The docs for FileBackupHelper mention for instance: "FileBackupHelper should be used only with small configuration files, not large binary files.", the latter being the case with SQLite databases.

I'd like to get more suggestions, insights into what is expected of us (what is the proper solution), and advice on how this might break.


Here's yet cleaner way to backup databases as files. No hardcoded paths.

class MyBackupAgent extends BackupAgentHelper{   private static final String DB_NAME = "my_db";   @Override   public void onCreate(){      FileBackupHelper dbs = new FileBackupHelper(this, DB_NAME);      addHelper("dbs", dbs);   }   @Override   public File getFilesDir(){      File path = getDatabasePath(DB_NAME);      return path.getParentFile();   }}

Note: it overrides getFilesDir so that FileBackupHelper works in databases dir, not files dir.

Another hint: you may also use databaseList to get all your DB's and feed names from this list (without parent path) into FileBackupHelper. Then all app's DB's would be saved in backup.


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));}