0

I'm trying to create a directory and save a file into the directory, my program returns that the directory was created, but I can not find the directory using either the USB port to explore from a PC, or using ES file Explorer. The program also returns true (that the directory was created) every time I run the program, if it did create it, it should return true only the first time. Additionally when I try to create a file within the directory it returns that the file does not exist. In the manifest I am setting user permissions for write to both external and internal storage. Please advise what I'm doing wrong, why does my program not actually create a folder (or file) (note that the tager folder path is storage/emulated/0/Documents/Saved_Receipts), which I assume will end up being /My Documents/Saved_Receipts)

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

boolean success = false;
                String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).toString();
                File myDir = new File(root + "/Saved_Receipts");

                if (!myDir.exists()) {
                    success = myDir.mkdir();
                    textIncoming.append("creating folder");
                    }
                if (success) {
                    textIncoming.append("created folder");
                } else {
                    textIncoming.append("folder existed");
                }

                Random generator = new Random();
                int n = 10000;
                n = generator.nextInt(n);
                String fname = "DRcpt_.xml";
                File file = new File (myDir, fname);
                if (file.exists ()) {
                    textIncoming.append("file exists");
                }
                else{
                    textIncoming.append("file does not exist");
                }
Chrish
  • 9
  • 2

1 Answers1

0

You are probably using SDK (API) 23 or higher. If that's the case, declaring permissions in the manifest is no longer enough.

You should be able to fix that issue by adding the following block in your code:

if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
        }
        else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }
    }

See:

Storage permission error in Marshmallow

Community
  • 1
  • 1
Jakub H.
  • 56
  • 5