Search code examples
androidsqlitecopyandroid-sdcard

Trying to Copy SQLite DB from data to SD card


I am using the following code that was posted somewhere on Stack Overflow and modified for my purposes:

try {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();

        if (sd.canWrite()) {
            String currentDBPath = "//data//"+ "com.exercise.AndroidSQLite" +"//databases//"+"MY_DATABASE";
            String backupDBPath = "/temp/MY_DATABASE";
            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();
                Toast.makeText(getBaseContext(), backupDB.toString(), Toast.LENGTH_LONG).show();

        }
    } catch (Exception e) {

        Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();


    }
}

So the error I get when I try to access it is:

java.io.FileNotFoundException: /data/data/com.exercise.AndroidSQLite/databases/MY_DATABASE: open failed: EACCES (Permission Denied)

I am trying to copy this file without rooting my tablet. The write external storage directory permission is set in the application; I just can't get around this error. Would appreciate help on resolving this issue, it's driving me mad


Solution

  • You are using "MY_DATABASE" literally when you probably actually want to use it as a variable...

    Remove the quotes from around it and see if that doesn't solve your problem.