I'm on 4.4.2, trying to delete a file (image) via uri. Here's my code:
File file = new File(uri.getPath());
boolean deleted = file.delete();
if(!deleted){
boolean deleted2 = file.getCanonicalFile().delete();
if(!deleted2){
boolean deleted3 = getApplicationContext().deleteFile(file.getName());
}
}
Right now, none of these delete functions is actually deleting the file. I also have this in my AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
Try this one. It is working for me.
Why don't you test this with this code:
I think part of the problem is you never try to delete the file, you just keep creating a variable that has a method call.
So in your case you could try:
However I think that's a little overkill.
You added a comment that you are using an external directory rather than a uri. So instead you should add something like:
Then try to delete the file.
I see you've found your answer, however it didn't work for me. Delete kept returning false, so I tried the following and it worked (For anybody else for whom the chosen answer didn't work):
The System out can be ignored obviously, I put it for convenience of confirming the deletion.
I tested this code on Nougat emulator and it worked:
In manifest add:
Create empty xml folder in res folder and past in the provider_paths.xml:
Then put the next snippet into your code (for instance fragment):