Reputation:
Hi guys i have to copy my sqlite db to downloads with the code bellow. But if (sd.canWrite()) always returning false... Im stuck on this , and yes im already added to my manifest. Im debuging on real device not the virtual one. Ty for help
private void copyDbToExternal(Context context) {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()){
String currentDBPath = "//data//data//" + context.getApplicationContext().getPackageName() + "//databases//"
+ "qamatrisdb";
String backupDBPath = "qamatrisdb";
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();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Upvotes: 1
Views: 1253
Reputation: 51
Did you try using tutorial on Dev.Android?
http://developer.android.com/training/basics/data-storage/files.html
Example for accessing external storage:
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
Upvotes: 1
Reputation: 1006944
Your code has nothing to do with an SD card. Your code is writing to external storage, not removable storage.
If canWrite()
is returning false
, you may be missing the WRITE_EXTERNAL_STORAGE
permission, or you may have targetSdkVersion
set to 23 or higher and are not handling Android 6.0+ runtime permissions.
Also, please replace your existing currentDBPath
logic with a call to getDatabasePath()
.
Upvotes: 1