-1

I'm trying to delete some files with .delete() method, but the method seems to be not working.

Example file directory: “/storage/emulated/0/Pictures/something/68419.jpg”

My code:

File deletefile = new File(path); //The path is in the format I said
boolean didIt = deletefile.delete()
//didIt is false

I am using write&read external storage permissions. The code was tested on Android 10.

Also, this person has the same code as me but theirs work, apparently. Android File.delete not working

Shazniq
  • 423
  • 4
  • 16
  • 1
    It is likely either that the path is wrong or that your program does not have permission to delete the file. – khelwood Feb 26 '21 at 16:37
  • You need to check if the file exists in that location first. assuming you have added the permimssion. – Kidus Tekeste Feb 26 '21 at 16:39
  • @khelwood The path is in the example format I gave so it should work. The program has the permission to delete the file – Shazniq Feb 26 '21 at 16:39
  • 3
    or the file is open somewhere else? (?! after next comment, "showing to user first") –  Feb 26 '21 at 16:40
  • @KidusTekeste I did check it while showing the photo to the user first. So the code wouldn'tve been triggered if the file didn't exist. – Shazniq Feb 26 '21 at 16:41

2 Answers2

1

To analyze why the file cannot be deleted you should use the Files.delete method instead. It will throw an IOException with a message why the file cannot be deleted. If you use File you can simply convert it by using deletefile.toPath();

alex87
  • 449
  • 3
  • 8
  • 1
    Turns out it was because my program was still counting as using the file, even after getting the data and showing it, like @user15244370 suggested. Thanks. – Shazniq Feb 26 '21 at 17:02
0

Check if the file exists first.

File deletefile = new File(path); //The path is in the format I said
boolean didIt = deletefile.delete()
//didIt is false
if (deletefile.exists()) {
    // you can delete
}
Kidus Tekeste
  • 651
  • 2
  • 10
  • 28
  • Thank you for your answer. I did check it because I was showing the photo to the user first. So the code couldn't have been triggered if the file didn't exist. – Shazniq Feb 26 '21 at 16:43
  • https://stackoverflow.com/a/24659789/6021740 Please check this answer. There are different forms of getting the real path. – Kidus Tekeste Feb 26 '21 at 16:45
  • I checked what you said & it shows that the file exists but couldn't be deleted. – Shazniq Feb 26 '21 at 16:51