How to copy Sqlite Db of an application to external storage in android 11

79 Views Asked by At

I try to copy Sqlite DB of an application to external storage. In android below 10 it is working perfectly but in android 11 and above it is not working. Getting error operation not allowed Any suggestion will be helpful for me.

I have tried below sample.

private class ExportDatabaseFileTask extends AsyncTask<File, Void, Boolean> { private final ProgressDialog dialog = new ProgressDialog(MainDashBoard.this);

    protected void onPreExecute() {
        this.dialog.setMessage("Exporting database...");
        this.dialog.show();
    }

    // automatically done on worker thread (separate from UI thread)
    protected Boolean doInBackground(final File... args) {
        File des=args[0];
        File dbFile;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
            dbFile = new File(db.getDbPath(MainDashBoard.this)+"/"+"MOC.db");

        }else {
            dbFile = new File(db.getDbPath(MainDashBoard.this)+"/"+"MOC.db");
        }
        File exportDir = new File(des, "");

        if (!exportDir.exists()) {
            exportDir.mkdirs();
        }
        SimpleDateFormat s = new SimpleDateFormat("dd-MM-yyy_hh:mm:ss");
        String format = s.format(new Date());

        String localDBName = "SMRD_" + "Rishi" + "_" + format + ".db";
        File file = new File(exportDir, localDBName.trim());

        try {
            //file.createNewFile();
            this.copyFile(dbFile, file);
            return true;
        } catch (IOException e) {
            Log.e("mypck", e.getMessage(), e);
            return false;
        }
    }

    // can use UI thread here
    protected void onPostExecute(final Boolean success) {
        if (this.dialog.isShowing()) {
            this.dialog.dismiss();
        }
        if (success) {
            Toast.makeText(MainDashBoard.this, "Export successful!", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(MainDashBoard.this, "Export failed", Toast.LENGTH_SHORT).show();
        }
    }

    void copyFile(File src, File dst) throws IOException {
        FileChannel inChannel = new FileInputStream(src).getChannel();
        FileChannel outChannel = new FileOutputStream(dst).getChannel();
        try {
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } finally {
            if (inChannel != null)
                inChannel.close();
            if (outChannel != null)
                outChannel.close();
        }
    }
}
0

There are 0 best solutions below