Search code examples
androiddirectorymkdirs

unusual error in Directory Creation


I have been trying to fix an issue since yesterday but no luck yet. I made a very simple android application to create directory and the application was working fine. The main source code is mentioned here.

@Override public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main); 
    //View vi = null;

    File extDir= Environment.getExternalStorageDirectory(); 
    File sddir = new File(extDir+"/test10");  


    if (sddir.mkdirs()) {  
        Toast toast = Toast.makeText(this,  
        "Directory successfully created!",  
               Toast.LENGTH_SHORT);  
    toast.setGravity(Gravity.CENTER, 0, 0);  
    toast.show();  
    }
    else{  
       Log.e(TAG, "Create dir in sdcard failed");  
       Toast toast = Toast.makeText(this,  
       "Directory creation failed!",  
              Toast.LENGTH_SHORT);  
       toast.setGravity(Gravity.CENTER, 0, 0);  
    toast.show();  
   } 
   ..... followed by remaining code 

However, yesterday, when I integrated this code to my own application (a simple videolist that plays videos from the sd-card), the directory function, for whatever reasons, resulted in directory creation failed... I debugged the application but couldn't find exception errors or other errors in it. I don't know what could be wrong.. I am just wondering if there is any method to get the error statement behind directory creation failed. I mean if mkdirs failed, it could generate a small print statement about why it got failed?? any suggestions??


Solution

  • Please try with below function.

    File cacheDir = new File(android.os.Environment.getExternalStorageDirectory(),"test10");
    if (!cacheDir.exists())
        cacheDir.mkdirs();
    

    and declare <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> in manifest file.