Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I delete files programmatically on Android?

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" /> 
like image 275
Randall Stephens Avatar asked Jul 09 '14 17:07

Randall Stephens


People also ask

How do I delete files from external storage on Android?

To delete data from a memory card or USB device attached to your Android device, do the following: On the Home screen, tap (*) - [Delete file from external storage]. You will be navigated to the dedicated screen.

How do I delete files from internal storage?

Choose a folder you wish to delete files from. Tap and hold each file you wish to delete, to put a check mark on it, then tap the More (three dots) icon in the top right corner. Select Delete from device from the drop-down menu. Then select Delete from device from the pop-up menu at the bottom.


1 Answers

Why don't you test this with this code:

File fdelete = new File(uri.getPath()); if (fdelete.exists()) {     if (fdelete.delete()) {         System.out.println("file Deleted :" + uri.getPath());     } else {         System.out.println("file not Deleted :" + uri.getPath());     } } 

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:

File file = new File(uri.getPath()); file.delete(); if(file.exists()){       file.getCanonicalFile().delete();       if(file.exists()){            getApplicationContext().deleteFile(file.getName());       } } 

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:

String root = Environment.getExternalStorageDirectory().toString(); File file = new File(root + "/images/media/2918");  

Then try to delete the file.

like image 199
Shawnic Hedgehog Avatar answered Oct 14 '22 12:10

Shawnic Hedgehog