Search code examples
javaandroidmkdirs

Android MKDirs() not working for me - NOT EXTERNAL Storage


I have read over the various other postings on this and have not yet found an answer that is working for me. They have been discussing the use of External Storage and I need to use 'default' (internal) storage.

I have a very simple routine in one of my Activity routines

String PATH = "/data/data/com.mydomain.myapplicationname/files";
SystemIOFile.MkDir(PATH);  // Ensure Recipient Path Exists

And then in my SystemIOFile class I have

static public Boolean MkDir(String directoryName) 
  {
    Boolean isDirectoryFound = false;
    File Dir = new File(directoryName);
    if(Dir.isDirectory())
    {
      isDirectoryFound = true;
    } else {
      Dir.mkdirs();
      if (Dir.isDirectory()) 
      {
         isDirectoryFound = true;
      }
  }
  Dir = null;
  return isDirectoryFound;
}

And in my Android.Manifest.xml I have

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

So it seems as though all of the pieces are in place for this to work.

BUT it is not working.
When I single step through the MKDir() routine it ALWAYS fails.
The

if (Dir.isDirectory())

always returns false
And the subsequent Dir.mkdirs() always returns false

What am I missing?


Solution

  • This is a great question. First, it's better if you don't reference the /sdcard path directly. Use Environment.getExternalStorageDirectory().getPath() instead. Second, assuming you want to access your own app's files - you also don't want to reference the /data/data path directly because it can vary in multi-user scenarios. Use Context.getFilesDir().getPath() instead.

    Implementing the above, we see that:

    String PATH = "/data/data/com.mydomain.myapplicationname/files";
    SystemIOFile.MkDir(PATH);
    

    Returns false, whereas:

    String PATH = Environment.getExternalStorageDirectory().getPath() 
            + getApplicationContext().getFilesDir().getPath();
    SystemIOFile.MkDir(PATH);
    

    Returns true.

    Also note that you ignored the result of Dir.mkdirs() inside Boolean MkDir(String directoryName) .

    Hope this helps.