Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting files in Android

I have a directory that contains a lot of files. I want to delete the entire directory as well as all the files in it.

I want my code to wait until every File in that directory (including the directory itself) is deleted before the next command is executed.

How do i wait? My code is

public void wipeMemoryCard() 
    {
        File deleteMatchingFile = new File(Environment 
                .getExternalStorageDirectory().toString()); 
        try { 
            filenames = deleteMatchingFile.listFiles(); 
            if (filenames != null && filenames.length > 0) 
            { 
                content = true;
                for (File tempFile : filenames) 
                { 
                    if (tempFile.isDirectory()) 
                    { 
                        wipeDirectory(tempFile.toString()); 
                        tempFile.delete();

                    } 
                    else 
                    {                       
                        File file = new File(tempFile.getAbsolutePath()); 
                        file.delete(); 
                    } 
                } 
            } 
            else 
            {   

                deleteMatchingFile.delete(); 
                Toast("No files to Delete");
            } 
        } 

        catch (Exception e) 
        { 
           e.printStackTrace();
        }
        if(content == true)
        {
              if (filenames == null && filenames.length == 0) 
              {
                  Toast("Files Deleted");
              }
        }
    } 

    private static void wipeDirectory(String name) { 
        File directoryFile = new File(name); 
        File[] filenames = directoryFile.listFiles(); 
        if (filenames != null && filenames.length > 0) 
        { 
            for (File tempFile : filenames) 
            { 
                if (tempFile.isDirectory()) 
                { 
                    wipeDirectory(tempFile.toString()); 
                    tempFile.delete(); 
                }
                else 
                { 
                    File file = new File(tempFile.getAbsolutePath()); 
                    file.delete();  
                } 
            } 
        } else 
        { 
            directoryFile.delete(); 
        } 
    } 
like image 207
Fresher Avatar asked Dec 16 '22 05:12

Fresher


1 Answers

You should not run this on the UI thread. If the file deletion takes too long, the system will pop up an "Application Not Responding" error. You can do this with an AsyncTask. The documentation shows a simple way to use this to pop up a "please wait" dialog, do the time-consuming work in the background, and then dismiss the dialog.

P.S. Your method name is kind of scary! :)

like image 129
Ted Hopp Avatar answered Jan 02 '23 10:01

Ted Hopp