How to create Android directory automatically if it doesn't already exist

user3739970 picture user3739970 · Aug 8, 2014 · Viewed 26.4k times · Source

I am creating a gallery app using a tutorial but get the following error:

abc directory path is not valid! Please set the image directory name AppConstant.java class

Please visit the following link to see the entire tutorial's code as I am using the same code:

http://www.androidhive.info/2013/09/android-fullscreen-image-slider-with-swipe-and-pinch-zoom-gestures/

I found this code in Utils Class:

else { // image directory is empty Toast.makeText( _context, AppConstant.PHOTO_ALBUM + " is empty. Please load some images in it !", Toast.LENGTH_LONG).show(); }

    } else {
        AlertDialog.Builder alert = new AlertDialog.Builder(_context);
        alert.setTitle("Error!");
        alert.setMessage(AppConstant.PHOTO_ALBUM
                + " directory path is not valid! Please set the image directory name AppConstant.java class");
        alert.setPositiveButton("OK", null);
        alert.show();
    }

    return filePaths;

How can I create the missing directory programmatically instead of display this error dialog?

Answer

Simas picture Simas · Aug 8, 2014

Here's how you create directories if they don't exist. Considering that directory is indeed a directory.

// If the parent dir doesn't exist, create it
if (!directory.exists()) {
    if (parentDir.mkdirs()) {
        Log.d(TAG, "Successfully created the parent dir:" + parentDir.getName());
    } else {
        Log.d(TAG, "Failed to create the parent dir:" + parentDir.getName());
    }
}

mkdirs() will also create missing parent directories (i.e. all directories that lead to directory).