Mkdir () returns false after deleting the folder

I have a button in my application called "Reset" that deletes the entire folder (user folder). After that, I try to create the same folder again, and the first time I try, it allows me to create the folder, but the second time I try to Reset and recreate the user folder, the application crashes because mkdir () didn't create a folder and I tried to create a database in this folder. But, itโ€™s strange that after the failure the folder was created.

I have permission:

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

I tried both methods:

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

What can i do wrong? Any idea?

+5
source share
2 answers

I also ran into the same problem. But finally, I think I found a solution (maybe a workaround).

When deleting a directory, rename it and delete. Then, as a rule, create a directory using File.mkdirs() . This should work fine. I tested in my case. He 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(); } 
+3
source

I think this is because you are calling a method to create a folder. Before creating a folder, you are trying to create a database in this folder!

Possible Solution

Try to create the database after successfully creating the folder. And when creating the database, check again if this folder / path exists.

0
source

Source: https://habr.com/ru/post/1203378/


All Articles