Skip to content

Instantly share code, notes, and snippets.

@umesh0492
Last active December 29, 2015 04:45
Show Gist options
  • Save umesh0492/cded5bc70c636b3a0528 to your computer and use it in GitHub Desktop.
Save umesh0492/cded5bc70c636b3a0528 to your computer and use it in GitHub Desktop.
public static void backUpCurrentDB(File db_file, String database_name) {
//call it on onUpgrade
try {
String rootPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/your_directory/";
File dir = new File(rootPath);
if (!dir.exists()) {
dir.mkdir();
}
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
Log.d(TAG, "db file " + db_file.exists() + " exits");
String currentDBPath = "//data//" + getPackageName() + "//databases//" + database_name + "";
String backupDBPath = "backup_db_name.db";
File currentDB = db_file.exists() ? db_file : new File(data, currentDBPath);
File backupDB = new File(rootPath, backupDBPath);
if (!backupDB.exists()) {
backupDB.createNewFile();
}
if (currentDB.exists()) {
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
} else {
Log.d("TAG", "current db not exits");
}
}
} catch (Exception e) {
Log.d("TAG", "backUpCurrentDB");
e.printStackTrace();
}
}
public static void rollBackCurrentDB(File db_file, String database_name) {
//call it on onDowngrade
try {
String rootPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/your_directory/";
File dir = new File(rootPath);
if (!dir.exists()) {
return;
}
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
Log.d(TAG, " rollback db file " + db_file.exists() + " exits");
String currentDBPath = "//data//" + getPackageName() + "//databases//" + database_name + "";
String backupDBPath = "backup_db_name.db";
File currentDB = db_file.exists() ? db_file : new File(data, currentDBPath);
File backupDB = new File(rootPath, backupDBPath);
if (!backupDB.exists()) {
return;
}
if (currentDB.exists()) {
FileChannel src = new FileInputStream(backupDB).getChannel();
FileChannel dst = new FileOutputStream(currentDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
} else {
Log.d("TAG", "rollback db not exits");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment