0

I am trying to create a directory in internal storage for my app. Following is the code I am using to check if the directory exists or not. If the directory already exists, it is returned; else, the directory is created and returned. But even in the subsequent calls to the method, the exists() call on the directory always return false. What is the reason? Thanks

public File getMessageVoiceDirectory() {
    File messageVoiceDirectory = this.myContext.getDir("Voice",Context.MODE_PRIVATE);


    if (messageVoiceDirectory.exists() == false) {
        messageVoiceDirectory.mkdirs();
    }


    return messageVoiceDirectory;
}
pratim
  • 361
  • 5
  • 18
  • @pratim- check the path you are getting from "this.myContext.getFilesDir()".. by debbugging... Environment.getExternalStorageDirectory() use this..if you are getting wrong path – Mr Code Aug 09 '17 at 11:38

3 Answers3

0

First off, switch your condition to

if (!messageVoiceDirectory.exists()) {
    boolean actuallyCreated = messageVoiceDirectory.mkdirs();
    if (!actuallyCreated){
       Log.e("Activity", "Woah... the mkdirs command got called, but was not successful. We need to investigate.");
    }
}

Next, you need to check the return value of mkdirs. Presumably the directory isn't being created. This could happen if you don't have the correct permissions.

bremen_matt
  • 6,902
  • 7
  • 42
  • 90
0

You can try this one. It will work

 File path = new File(this.getFilesDir(), "DirectoryName");
     if (!path.exists()) {
         path.mkdirs();
         Toast.makeText(this,"Created",Toast.LENGTH_LONG).show();
     }
     else
         Toast.makeText(this,"Already Exist",Toast.LENGTH_LONG).show();
Raja
  • 2,775
  • 2
  • 19
  • 31
0

When you exactly call getMessageVoiceDirectory(), ensure that you call inside onCreate(),

Khaled Lela
  • 7,831
  • 6
  • 45
  • 73