dimanche 27 avril 2014

Create backup and restore option in android application


Vote count:

0




Hi I want to create backup and restore option in my application. By googling I got following code example and it's working too.



private void importDB() {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//" + "<package name>"
+ "//databases//" + "<database name>";
String backupDBPath = "<backup db filename>"; // From SD directory.
File backupDB = new File(data, currentDBPath);
File currentDB = new File(sd, backupDBPath);

FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getApplicationContext(), "Import Successful!",
Toast.LENGTH_SHORT).show();

}
} catch (Exception e) {

Toast.makeText(getApplicationContext(), "Import Failed!", Toast.LENGTH_SHORT)
.show();

}
}

private void exportDB() {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();

if (sd.canWrite()) {
String currentDBPath = "//data//" + "<package name>"
+ "//databases//" + "<db name>";
String backupDBPath = "<destination>";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);

FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getApplicationContext(), "Backup Successful!",
Toast.LENGTH_SHORT).show();

}
} catch (Exception e) {

Toast.makeText(getApplicationContext(), "Backup Failed!", Toast.LENGTH_SHORT)
.show();

}
}


But porblem I am facing is that it's replacing created file each time, instead of that I want to create a new file each time when user clicks on backup button with the name of it's date and time of creation. So, I can give him option of import file whichever user is interested. Please give me some suggestion. Or any working tutorial will be good idea. Thanks in advance.



asked 50 secs ago






Aucun commentaire:

Enregistrer un commentaire