javaandroidandroid-sdcard

How to create a directory in Android?


Everything is in the question. Here is my code :

private void createDirectory(File currentDirectory) 
{
    File f = null;
      
    try {
        f = new File(currentDirectory.getCanonicalPath() + "/directory" + count);
    
        boolean success = f.mkdir();

        if (!success) {
            Toast.makeText(currentContext, f.getName() + " could not be created", 15).show();
        }
    } catch (IOException ioe) {
        Toast.makeText(currentContext, f.getName() + " could not be created", 15).show();
    }

    count++;
}

I am writing a small file manager in Android and I would like to add the possibility to create a directory. There is no exception and the variable success always return false. Can someone tell me what is wrong my code??

Thx for your advice !!

[EDIT]

BTW, When the phone is in Developpement mode, does an application has a write access on the sdcard? I am programming on my phone (Acer liquid)


Solution

  • You have to add this permission:

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

    By the way, not sure how you are getting the SDcard directory... but it must be this way:

    File sdDir = Environment.getExternalStorageDirectory();
    

    It's important, because some programmers use to think that the SDCard is always /sdcard, but it could change.