Jube
Jube

Reputation: 184

How can I create a File in an accessible folder on Android? (non-root)

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.

Upvotes: 0

Views: 316

Answers (1)

Darush
Darush

Reputation: 12031

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

Upvotes: 1

Related Questions