Skip to content

Instantly share code, notes, and snippets.

@chizmw
Created July 17, 2013 14:23
Show Gist options
  • Save chizmw/6020994 to your computer and use it in GitHub Desktop.
Save chizmw/6020994 to your computer and use it in GitHub Desktop.
Extending Wheeler's example for copying a sqlite3 database to somewhere accessible (and examinable)
public void copy_db() {
// copy the db to the sdcard
try {
File sd = Environment.getExternalStorageDirectory();
if (sd.canWrite()) {
String currentDBPath = this.myContext.getDatabasePath(this.getDatabaseName()).toString();
// use out package as the place to store files
String backupDirectory = "/" + this.myContext.getPackageName();
String backupFile = "myapp.sqlite";
// build the backup file path from the directory and the filename
// weirdly File.pathSeparator gives us ':'
String backupDBPath = backupDirectory + "/" + backupFile;
Log.d("COPYDB", "backupDBPath: " + backupDBPath);
// make sure the output directory exists
File backupDir = new File(sd, backupDirectory);
if (!backupDir.exists()) {
backupDir.mkdirs();
}
// open files
File currentDB = new File(currentDBPath);
File backupDB = new File(sd, backupDBPath);
// ensure we have a destination
if(!backupDB.exists()) {
backupDB.createNewFile();
}
@SuppressWarnings("resource")
FileChannel src = new FileInputStream(currentDB).getChannel();
@SuppressWarnings("resource")
FileChannel dst = new FileOutputStream(backupDB).getChannel();
// make the copy
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Log.d("COPYDB", "db copied to "+backupDBPath);
}
else {
// useful if you forget to add the SD Card to your emulator
Log.w("COPYDB", "No write access to SD Card");
}
}
catch (Exception e) {
// we want to know if things don't work out
Log.e("COPYDB", "error on copying db to sdcard: " + e.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment