Creating a directory in /sdcard fails

There are three things to consider here:

  1. Don’t assume that the sd card is mounted at /sdcard (May be true in the default case, but better not to hard code.). You can get the location of sdcard by querying the system:

    Environment.getExternalStorageDirectory();
    
  2. You have to inform Android that your application needs to write to external storage by adding a uses-permission entry in the AndroidManifest.xml file:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
  3. If this directory already exists, then mkdir is going to return false. So check for the existence of the directory, and then try creating it if it does not exist.
    In your component, use something like:

    File folder = new File(Environment.getExternalStorageDirectory() + "/map");
    boolean success = true;
    if (!folder.exists()) {
        success = folder.mkdir();
    }
    if (success) {
        // Do something on success
    } else {
        // Do something else on failure 
    }
    

Leave a Comment