Search code examples
androiddirectoryandroid-external-storageandroid-storage

Create Android application directory compatible with all versions and devices


I need an Android application directory path to my application pictures compatilbe with all versions. I have searched a lot and I hadn't find anything compatible with ALL devices yet. Now we have this piece of code but it is still giving NullPointerExcepction at picturesDir.exists() with U55 and ZTE devices.

    File picturesDir;
    String state = Environment.getExternalStorageState();
    // Make sure it's available, if there is no SD card, create new directory objects to make
    // directory on device.
    if (!Environment.MEDIA_MOUNTED.equals(state)) {
        picturesDir = new File(Environment.getDataDirectory() + "/data/" + getApplicationContext().getPackageName() + "/Pictures/");
    } else if (Environment.getExternalStorageState() != null) {
        picturesDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    } else{
        String externalStoragePath = Environment.getExternalStorageDirectory()
                .getAbsolutePath();
        picturesDir = new File(externalStoragePath + getApplicationContext().getPackageName() + "/Pictures/");
    }

    if (!picturesDir.exists()) {
        picturesDir.mkdir();
    }

enter image description here

What should we do? I don't want to check if it is null to avoid the crash. I want a path where I can save pictures. Thanks.


Solution

  • Per documentation of getExternalFilesDir: "the absolute path to application-specific directory. May return null if shared storage is not currently available". So according to documentation, you have to check for null, if you use getExternalFilesDir.

    There may be other reasons why external storage is not available besides not being mounted. There is also a possibility of race between calling getExternalStorageState and calling getExternalFilesDir. In other words, the SD card may be unmounted immediately after call to getExternalStorageState() reports it as mounted, but before call to getExternalFilesDir. This race condition may result in your crash.