Skip to content

Instantly share code, notes, and snippets.

@VAdaihiep
Created January 17, 2017 09:31
Show Gist options
  • Save VAdaihiep/3f11bbdb3bcb5b150a35e9a25f4f29e8 to your computer and use it in GitHub Desktop.
Save VAdaihiep/3f11bbdb3bcb5b150a35e9a25f4f29e8 to your computer and use it in GitHub Desktop.
Copy Android Database to SDCard
final static String DATABASE_NAME = "your-database-name";
final static String FOLDER_EXTERNAL_DIRECTORY = Environment.getExternalStorageDirectory() + "/folder";
//______________________________________________________________________________________________
/**
* Call this method from any activity in your app (
* for example -> DatabaseUtil.copyDatabaseToExtStg(MainActivity.this);
* this method will copy the database of your application into SDCard folder "shanraisshan/MyDatabase.sqlite" (DATABASE_NAME)
*/
public static void copyDatabaseToExtStg(Context ctx) {
//external storage file
File externalDirectory = new File(FOLDER_EXTERNAL_DIRECTORY);
if (!externalDirectory.exists())
externalDirectory.mkdirs();
File toFile = new File(externalDirectory, DATABASE_NAME);
//internal storage file
//https://developer.android.com/reference/android/content/Context.html#getDatabasePath(java.lang.String)
File fromFile = ctx.getDatabasePath(DATABASE_NAME);
//example WhatsApp : /data/data/com.whatsapp/databases/msgstore.db
if (fromFile.exists())
copy(fromFile, toFile);
}
//______________________________________________________________________________________________ Utility function
/**
* @param fromFile source location
* @param toFile destination location
* copy file from 1 location to another
*/
static void copy(File fromFile, File toFile) {
try {
FileInputStream is = new FileInputStream(fromFile);
FileChannel src = is.getChannel();
FileOutputStream os = new FileOutputStream(toFile);
FileChannel dst = os.getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
is.close();
dst.close();
os.close();
} catch (Exception e) {
//todo in case of exception
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment