I'm currently looking to build a backup feature in my Android application. However I'm kinda struggling before even starting to implement it because I'm not sure what the correct way to go is.
I found some interesting articles on the net and so I came up with three possible solutions:
Now I was wondering what you guys think about these 3 solutions, or do you know another (maybe an even better way to go) and what is in your eyes the best way to go?
Here are my remarks on the possible implementations:
I'm looking forward to see some input on this issue!
Thanks in advance!
Kr,
Dirk
You don't need to have a rooted phone to restore the database from a file on the SD card. Each application can write to it's own private directories, so you can just copy the file. As for 2, do you have any concrete numbers? Handling XML is fairly fast, and since it's backup/restore, it doesn't happen too often and users would expect that it takes some time, so it shouldn't be a problem. As usual, measure the actual time it takes and consider how much data you have, before you make any decisions.
I always use 1.). Here's a class of mine that does backup of a DB to SD-card. I'm using FileUtils from the Apache commons-io here, you need to change that if you don't use that jar. In addition there's need for a method in your SQLiteOpenHelper class (here MySQLiteOpenHelper.getDatabaseName()) that returns the name of your database file.
You will call that from within an AsyncTask in one of your activities...
public class MyDatabaseTools {
private String appName = "";
private String packageName = "";
public boolean backup() {
boolean rc = false;
boolean writeable = isSDCardWriteable();
if (writeable) {
File file = new File(Environment.getDataDirectory() + "/data/" + packageName + "/databases/" + MySQLiteOpenHelper.getDatabaseName());
File fileBackupDir = new File(Environment.getExternalStorageDirectory(), appName + "/backup");
if (!fileBackupDir.exists()) {
fileBackupDir.mkdirs();
}
if (file.exists()) {
File fileBackup = new File(fileBackupDir, MySQLiteOpenHelper.getDatabaseName());
try {
fileBackup.createNewFile();
FileUtils.copyFile(file, fileBackup);
rc = true;
} catch (IOException ioException) {
//
} catch (Exception exception) {
//
}
}
}
return rc;
}
private boolean isSDCardWriteable() {
boolean rc = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
rc = true;
}
return rc;
}
public MyDatabaseTools(final Context context, final String appName) {
this.appName = appName;
packageName = context.getPackageName();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.