Now I’m developing an Android program that download MP3 file and store it on the external storage. Download is fine. But I had stuck at creating a directory on the external storage. 😅

Always fail when call dir.mkdirs() Why?

  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  File dir = new File(Environment.getExternalStorageDirectory(),"/Podcasts/temp");
  if(!dir.exists()) {
    dir.mkdirs();
  }

Reason is: permission is not granted before creating. So, I should have a permission before do it.

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

I hope this will help.