Caused by: java.lang.IllegalStateException: Unable to create directory in Android 6.0 devices

malavika picture malavika · Mar 3, 2016 · Viewed 9.8k times · Source

I have to store the download the image from the url using DownloadManager and store it into the sdcard with my own directory like "xyz". This is my code

File img_directory = null;

img_directory = new File(Environment.getExternalStorageDirectory() + "/xyz");
if (!img_directory.exists()) {
    img_directory.mkdirs();
    DownloadManager mgr = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    Uri downloadUri = Uri.parse("my image url");
    DownloadManager.Request request = new DownloadManager.Request(downloadUri);
    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
      .setAllowedOverRoaming(true)
      .setTitle("Demo")
      .setDescription("Something useful. No, really.")
      .setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
      .setDestinationInExternalPublicDir(Environment.getExternalStorageDirectory().getAbsolutePath() + "/xyz", image.jpeg);
    mgr.enqueue(request);
}

This code will run upto Android 5.1.1 . When I run this same code in 6.0 its raising the error like this

Caused by: java.lang.IllegalStateException: Unable to create directory: /storage/emulated/0/storage/emulated/0/xyz at android.app.DownloadManager$Request.setDestinationInExternalPublicDir(DownloadManager.java:538)

I have added the READ and WRITE permissions in manifest file. How can I resolve this error? Any body can help me ? Thanks in advance.

Answer

Bhavesh Patadiya picture Bhavesh Patadiya · Mar 3, 2016
Caused by: java.lang.IllegalStateException: Unable to create directory: /storage/emulated/0/storage/emulated/0/xyz at android.app.DownloadManager$Request.setDestinationInExternalPublicDir(DownloadManager.java:538)

Issue seems it be related with Android Runtime Permission introduced in Android 6.0

When your app targeting is API Level 23 or higher, by default all the permissions are false. To resolve this, you have to request a permission dialog and approve the permission before using that into your app.