0

I am not able to read from or write to my Android device. There were similar questions asked on the same topic (I have implemented the code) but they all seem to crash my app.

Button btnUpload = (Button) findViewById(R.id.btnUpload);
File created = new File(Environment.getExternalStorageDirectory().getPath()
                        + File.separator + "MyNewFolder" + File.separator + "created");    

if (created.isDirectory()) {    
    File[] contents = created.listFiles();

    //Should not trigger as directory check is in place
    if (contents == null) {            //<--not adding this section causes a crash
        btnUpload.setEnabled(false);
    } 

    //Check to see if the number of files is 0
    else if (contents.length == 0) {
        btnUpload.setEnabled(false);
    } 

    //All checks pass. Enable button
    else {
        btnUpload.setEnabled(true);
    }
}
  • Manifest file has the "WRITE_EXTERNAL_STORAGE" permission added
  • Ensured the phone (Nexus 5, with marshmallow) is on debugging mode and "File transfer" mode is selected.
Prem
  • 83
  • 1
  • 1
  • 5
  • 1
    Have a look at [this post](http://stackoverflow.com/questions/32635704/cant-get-the-permission). – Mike M. Jan 24 '16 at 12:38
  • 1
    Use LogCat to examine the Java stack trace associated with your crash: https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this If you cannot understand that stack trace, edit your question to provide that, along with the manifest and the code where you are creating this directory. And, as Mike notes, if your `targetSdkVersion` is 23 or higher, be sure to show your code where you are requesting `WRITE_EXTERNAL_STORAGE` at runtime. – CommonsWare Jan 24 '16 at 12:39

1 Answers1

0

Thanks a lot Mike and Commonwares.

SUMMARY: Along with permissions in the Manifest file, we need to check permission (and request them if absent) during runtime. The issue is with API level 23.

Added two lines of code based on some reading. Will not be the best or following all best coding practices but a quick and dirty solution so please modify accordingly.

if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
    }

I've added this to the beginning of my Main Activity so that I get the permission and its set for the rest of the time.

Prem
  • 83
  • 1
  • 1
  • 5