75

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" />
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Randall Stephens
  • 1,037
  • 1
  • 10
  • 16
  • I don't use getCanonicalFile(), but just File.delete() and it works fine on my system. Unless your path from the URI isn't valid. – Jay Snayder Jul 09 '14 at 17:05
  • My path is this: /external/images/media/2918 Does that look right? – Randall Stephens Jul 09 '14 at 17:12
  • ... no. something like `/mnt/sdcard/your_folder/your_file.png` does. However, it's better to get the storage path through `getExternalDirectory`. Last, the permission `WRITE_EXTERNAL_...` includes the `READ_EXTERNAL_...` one. – Phantômaxx Jul 09 '14 at 17:37
  • Possible duplicate of [android : deleting an image](https://stackoverflow.com/questions/10716642/android-deleting-an-image) – Aashish Kumar Apr 22 '19 at 15:26

7 Answers7

167

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.

Morgoth
  • 4,935
  • 8
  • 40
  • 66
Shawnic Hedgehog
  • 2,353
  • 1
  • 15
  • 20
  • 1
    I think you might be onto something. it keeps saying that fdelete doesn't exist. My file path is /external/images/media/2918. Does that look right? – Randall Stephens Jul 09 '14 at 17:16
  • i don't think your solution will work in his case because he is already doing it like you told him to do. – migos Jul 09 '14 at 17:18
  • Instead of `uri.getPath()` try what I just implemented into the answer. – Shawnic Hedgehog Jul 09 '14 at 17:20
  • @Saturisk he is nearly doing the same like you told to do. his problem is that he has the wrong path. – migos Jul 09 '14 at 17:22
  • My solution will work, he just had his answer wrong. He said he was using a uri to get the path, when he wasn't. I fixed my answer to answer his question. – Shawnic Hedgehog Jul 09 '14 at 17:23
  • That's correct. I'm just fixing my application and testing it and then I'll be upvoting and marking things as correct. – Randall Stephens Jul 09 '14 at 17:36
  • using this code image deleted successfully but there is blank black image remains in gallery is there any solution for this problem ? – Dhara Patel Dec 20 '17 at 07:26
  • Eh? He has not one but two lines of code that 'try to delete the file'. – user207421 May 14 '18 at 10:35
  • "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." ? What he's doing in his question is correct. The File.delete() function does return a boolean value to inform you if the delete was a success or not. Nothing wrong with that... – Allinone51 Nov 10 '20 at 14:54
  • Code is not working in android 11 – EAS Jan 26 '22 at 14:25
  • How can you delete a file by using `getApplicationContext().deleteFile(file.getName());`? The `deleteFile()` method can only passed in a name which without the leading path, so how can you delete the file? It does nothing actually, after delete my file is exist still, and I can open the file. – zeleven May 11 '22 at 06:59
15

Try this one. It is working for me.

handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        // Set up the projection (we only need the ID)
        String[] projection = { MediaStore.Images.Media._ID };

        // Match on the file path
        String selection = MediaStore.Images.Media.DATA + " = ?";
        String[] selectionArgs = new String[] { imageFile.getAbsolutePath() };

        // Query for the ID of the media matching the file path
        Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        ContentResolver contentResolver = getActivity().getContentResolver();
        Cursor c = contentResolver.query(queryUri, projection, selection, selectionArgs, null);

        if (c != null) {
            if (c.moveToFirst()) {
                // We found the ID. Deleting the item via the content provider will also remove the file
                long id = c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
                Uri deleteUri = ContentUris.withAppendedId(queryUri, id);
                contentResolver.delete(deleteUri, null, null);
            } else {
                // File not found in media store DB
            }
            c.close();
        }
    }
}, 5000);
Abandoned Cart
  • 4,512
  • 1
  • 34
  • 41
Krishna
  • 159
  • 1
  • 3
10

I tested this code on Nougat emulator and it worked:

In manifest add:

<application...

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>
</application>

Create empty xml folder in res folder and past in the provider_paths.xml:

<?xml version="1.0" encoding="utf-8"?>
 <paths xmlns:android="http://schemas.android.com/apk/res/android">
   <external-path name="external_files" path="."/>
  </paths>

Then put the next snippet into your code (for instance fragment):

File photoLcl = new File(homeDirectory + "/" + fileNameLcl);
Uri imageUriLcl = FileProvider.getUriForFile(getActivity(), 
  getActivity().getApplicationContext().getPackageName() +
    ".provider", photoLcl);
ContentResolver contentResolver = getActivity().getContentResolver();
contentResolver.delete(imageUriLcl, null, null);
CodeToLife
  • 3,672
  • 2
  • 41
  • 29
6

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):

System.out.println(new File(path).getAbsoluteFile().delete());

The System out can be ignored obviously, I put it for convenience of confirming the deletion.

A B
  • 189
  • 2
  • 9
3
File file=new File(getFilePath(imageUri.getValue()));
boolean b= file.delete();

not working in my case. The issue has been resolved by using below code-

ContentResolver contentResolver = getContentResolver ();
contentResolver.delete (uriDelete,null ,null );
Mohammad Ersan
  • 12,304
  • 8
  • 54
  • 77
sweet_vish
  • 141
  • 1
  • 8
1

first call the intent

Intent intenta = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intenta, 42);

then call the result

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case 42:
            if (resultCode == Activity.RESULT_OK) {
                Uri sdCardUri = data.getData();
                DocumentFile pickedDir = DocumentFile.fromTreeUri(this, sdCardUri);
                for (DocumentFile file : pickedDir.listFiles()) {
                    String pp = file.getName();
                    if(pp.equals("VLC.apk"))
                        file.delete();
                    String ppdf="";
                }
                File pathFile = new File(String.valueOf(sdCardUri));
                pathFile.delete();
            }
            break;
    }
}
0

You can delete a file by using delete() method.

For that first you need to create a File reference in your code by specifying the path of the file as argument, then call delete() method to delete the file.

String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/video1.mp4";
new File(path).delete();
Codemaker2015
  • 12,190
  • 6
  • 97
  • 81