copy database file to sdcard in android
Unfortunatelly, the accepted answer is not relevant for these days. The problem is on wrong detected SD path. Actual path usually depends on manufacterer of mobile device and could be different on different models.
I figured out a simple solution to detect an actual path to SD independently of android version, ContextCompat.getExternalFilesDirs[1] contains a relevant string. Tested on devices with android 6 till 9 version
The second one trouble is defined path to DB. It should contains "data/data/" before package name like: "/data/data/" + getPackageName() + "/databases/" + dbFilename;
Here the part of code from my project
String sdPath;
private boolean isSDPresent(Context context) {
File[] storage = ContextCompat.getExternalFilesDirs(context, null);
if (storage.length > 1 && storage[0] != null && storage[1] != null) {
sdPath = storage[1].toString();
return true;
}
else
return false;
}
private boolean isContextValid(Context context) {
return context instanceof Activity && !((Activity) context).isFinishing();
}
public boolean exportDatabase(Context context, String localDbName, String backupDbName) {
if (isContextValid(context))
try {
if (!SettingsFile.isSDPresent(context)) {
Log.e(TAG, "SD is absent!");
return false;
}
File sd = new File(sdPath);
if (sd.canWrite()) {
File currentDB = new File("/data/data/" + context.getPackageName() +"/databases/", localDbName);
File backupDB = new File(sd, backupDbName);
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.e(TAG, "SD can't write data!");
return false;
}
} catch (Exception e) {
}
else {
Log.e(TAG, "Export DB: Context is not valid!");
return false;
}
return true;
}
Try this hope this helps you
public void exportDatabse(String databaseName) {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//"+getPackageName()+"//databases//"+databaseName+"";
String backupDBPath = "backupname.db";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
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();
}
}
} catch (Exception e) {
}
}
How to call
exportDatabse("YourDBName");
NOTE :
Remember to add permission to write to external storage with
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
, otherwise sd.canWrite() will be false.