0

I'm able to create a file using

File directory = cw.getDir("media", Context.MODE_PRIVATE);
 //directory.mkdirs();
 File backupDB = new File(directory, backupname);

I've also tried

 File directory = new File(Environment.getExternalStorageDirectory()+File.separator+"images");

and

 File backupDB = new File(directory, backupname);

with no luck, this is the full method

   public String backUpDatabase(String backupname){

      try {
       File directory = new File(String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)));
            File currentDB = new File(DBlocation);
            File folder = new File("/sdcard/exports/Database_Backups/");
            File backupDB = new File(directory, backupname);

            if (!(folder.exists() && folder.isDirectory())) {
                folder.mkdirs();
            }

            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{
                return "didnt work";
            }

        } catch (Exception e) {
          return "didnt work";
        }

        return backupname.toString();

    }

I've used the permissions yes.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

I would just like to backup the database file to an accessible file that I can then see on the phone/computer itself.

Jube
  • 184
  • 2
  • 15
  • 1
    You can check this answer https://stackoverflow.com/questions/8330276/write-a-file-in-external-storage-in-android it may help you.. – Upendra Shah Jun 27 '17 at 05:28

1 Answers1

1

To write to external storage on android Lollipop and above you need to request permission at run time.

Three methods are important here:

  1. ContextCompat.checkSelfPermission() to check if the permission is given
  2. ActivityCompat.requestPermissions() to request if the permission not given
  3. onRequestPermissionsResult() to perform the desired operation once the user gives the permission

Refer to this answer for the code and details

Darush
  • 11,403
  • 9
  • 62
  • 60