user2872856
user2872856

Reputation: 2051

Unable to copy file from external storage to data directory in Android 9

I am using this method to copy database file from external storage to data directory of my app. This method work fine on Android 8.0 and below, but not on Android 9.

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

        if (sd.canWrite()) {
            String  currentDBPath= "//data//" + "com.mypackage"
                    + "//databases//" + "dictionary";
            String backupDBPath  = "/MyApp/dictionary";
            File backupDB = new File(data, currentDBPath);
            File currentDB  = 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(), "Imported successfully",
                   Toast.LENGTH_LONG).show();

        }
    } catch (Exception e) {

    }

The "Imported successfully" toast is displayed but the file did not copy. The app do not crash and nothing show on logcat as well.

Upvotes: 0

Views: 755

Answers (1)

Mahdi-Malv
Mahdi-Malv

Reputation: 19270

Since Android 7.0, you need to use FileProvider in order to access to files in directories.
Check out the documentation and see this example.

Upvotes: 1

Related Questions