Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mkdir() returns false after deleting the folder

I have a button in my app called "Reset" which deletes an entire folder (user folder). After that, I am trying to create again the same folder and the first time I try it, it allows me to create the folder, but the second time I try to Reset and re-create the user folder, the app crashes because the mkdir() did not create the folder and I attempted to create a database on that folder. But, the weird thing is that, after crashing, the folder has been created.

I have the permission:

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

I have tried both methods:

f.mkdir();
f.mkdirs();

What could I make wrong? Any idea?

like image 724
Mario Velasco Avatar asked Sep 29 '22 19:09

Mario Velasco


1 Answers

I also faced the same problem. But, finally, I think I found a solution (may be workaround).

When you delete the directory, rename it and delete. Then, usually, create the directory using File.mkdirs(). This should work fine. I tested in my case. It works!!!

public static final void renameAndDelete(File fileOrDirectory) {
    File newFile = new File(fileOrDirectory.getParent() + File.separator
                + "_" + fileOrDirectory.getName());
    fileOrDirectory.renameTo(newFile);
    delete(newFile);
}
public static final void delete(File fileOrDirectory) {
    if (fileOrDirectory.isDirectory())
        for (File child : fileOrDirectory.listFiles())
            delete(child);

    fileOrDirectory.delete();
}
like image 139
gopalanrc Avatar answered Oct 05 '22 07:10

gopalanrc