coolcool1994
coolcool1994

Reputation: 3804

how to delete a folder in Android

I am having trouble deleting folders.

I made folders and folders.delete returns false. Why?

I also tried this below. This returns false and the folder doesn't get erased. Why?

public static boolean deleteDirectory(File path) {
            if( path.exists() ) {
              File[] files = path.listFiles();
              if (files == null) {
                  return true;
              }
              for(int i=0; i<files.length; i++) {
                 if(files[i].isDirectory()) {
                   deleteDirectory(files[i]);
                 }
                 else {
                   files[i].delete();
                 }
              }
            }
            return( path.delete() );
          }

Upvotes: 0

Views: 4718

Answers (1)

Phileo99
Phileo99

Reputation: 5659

Inspired by this solution:

Android Delete Directory Not Working

I have improved it as follows, and it worked for me:

private void deleteSubFolders(String uri)
{
     File currentFolder = new File(uri);        
     File files[] = currentFolder.listFiles();

     if (files == null) {
         return;
     }
     for (File f : files)
     {          
          if (f.isDirectory())
          {
              deleteSubFolders(f.toString());
          }
          //no else, or you'll never get rid of this folder!
          f.delete();
     }
}

Notes: be mindful of the folder name being passed around. For example:

File folder = new File("path/to/directory");

folder.getName() is not necessarily equal to the full path directory name.

Upvotes: 4

Related Questions