4

How can I delete an image file using my app?

File file = new File("path"); //PATH is: /storage/sdcard0/DCIM/Camera/IMG_20160913_165933.jpg
  1. file.delete(); // try this one but not delete file....
  2. boolean isDelete = file.delete(); //this also not delete...
  3. context.deleteFile(file); // thisn one also not working in my example....
4444
  • 3,541
  • 10
  • 32
  • 43
Hiren Vaghela
  • 61
  • 1
  • 1
  • 6

6 Answers6

5

If you are trying to delete a picture or similar you may have issues. It may return to you that the result is true but the file still will exist. I have lost so much time and what best worked for me was:

  private void deleteImage(File file) {
        // 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[]{file.getAbsolutePath()};

        // Query for the ID of the media matching the file path
        Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        ContentResolver contentResolver = getContentResolver();
        Cursor c = contentResolver.query(queryUri, projection, selection, selectionArgs, 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(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
            contentResolver.delete(deleteUri, null, null);
        } else {
            // File not found in media store DB
        }
        c.close();
    }
f.trajkovski
  • 794
  • 9
  • 24
2

try this working code

 File target = new File(path);
    Log.d(" target_path", "" + path);
    if (target.exists() && target.isFile() && target.canWrite()) {
        target.delete();
        Log.d("d_file", "" + target.getName());
    }

Add AndroidManifest.xml

 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Ramesh Prajapati
  • 654
  • 6
  • 10
2

This post help me so mutch, I was searching how to delete all the pictures from the gallery and I finally found it.

In my case I wanted to delete all the photos in one click and this method works.

My code :

    private void deletePictures(){

    String[] projection = {MediaStore.Images.Media._ID};
    Cursor cursor = getContext().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null,null, null);
    while (cursor.moveToNext()) {
        long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
        Uri deleteUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
        getContext().getContentResolver().delete(deleteUri, null, null);
    }
    cursor.close();

}

I tested on Android 10 and it's working.

Louis Chabert
  • 399
  • 2
  • 15
  • You might wanna be cautious with this since (for my usage) I didn't want to remove all gallery images from myself, just the ones I made with my app. So correct me if I'm wrong but it seems like your deleting everything, (couldn't test it because I don't want that), I simply replaced MediaStore.Images.Media._ID with my array of imagepaths I wanted to delete. Still didn't work though (Android 13, Api level 33) so I'm gonna do something else for today since I'm going nuts trying to delete a simple f.... file. – frankhardenberg Mar 28 '23 at 08:30
  • yeah, I already mentioned this method delete all the pictures from your gallery but you can maybe try to modify it for just one with sommeting like that : `public void deletePicture(Context myContext, long pictureId) { Uri deleteUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, pictureId); myContext.getContentResolver().delete(deleteUri, null, null); }` I don't know if you can use your array of imagepaths for this – Louis Chabert Mar 28 '23 at 09:53
  • 1
    Yes I saw you mentioning it but it might be good to EXPLICITLY (or make that part of the text bold) because I can imagine a lot of people testing on their own devices and being really sad if they lose their entire gallery. Your code should work fine, however on my device I cannot get any code to work. Set all the permissions, set like 5 try catches in a row with different methods, none of them work. So decided to quit with this for today or else I'm going insane. – frankhardenberg Mar 28 '23 at 09:58
  • You don't have any errors ? My method works on Android 11 so that's weird – Louis Chabert Mar 28 '23 at 10:03
  • I probably have some errors with the paths I use, my colleague set up this uploading flow which is really complicated to follow, so the paths are being altered and I'm not sure what to use, I would guess the absolute path but apparently that doesn't work. I'm just gonna ask my colleague when we're both at the office, not worth my time trying to figure it out myself at the moment! – frankhardenberg Mar 28 '23 at 10:15
  • Ok ok no problems, if you think your problem can be a post go for it and I would be happy to help you – Louis Chabert Mar 28 '23 at 10:21
0

Check file.isExist() then delete and also check permission in AndroidManifest.xml file.

D.J
  • 1,439
  • 1
  • 12
  • 23
0

Try this..

permission add to mainfiest also

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

for marashmallow runtime permission add

 private static final int REQUEST_RUNTIME_PERMISSION = 123;

if (CheckPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// you have permission go ahead
 File file = new File("path");
    if(file.exists())
    {
        file.delete();
    }

} else {
// you do not have permission go request runtime permissions
RequestPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE, REQUEST_RUNTIME_PERMISSION);
}


  @Override
    public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults) {

        switch (permsRequestCode) {

            case REQUEST_RUNTIME_PERMISSION: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                } else {
                    // you do not have permission show toast.
                }
                return;
            }
        }
    }
    public void RequestPermission(Activity thisActivity, String Permission, int Code) {
        if (ContextCompat.checkSelfPermission(thisActivity,
                Permission)
                != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
                    Permission)) {

            } else {
                ActivityCompat.requestPermissions(thisActivity,
                        new String[]{Permission},
                        Code);
            }
        }
    }

    public boolean CheckPermission(Activity context, String Permission) {
        if (ContextCompat.checkSelfPermission(context,
                Permission) == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            return false;
        }
    }
Arjun saini
  • 4,223
  • 3
  • 23
  • 51
0
//PATH is: /storage/sdcard0/DCIM/Camera/IMG_20160913_165933.jpg

That would appear to be on removable storage. On Android 4.4+ devices, you do not have the ability to read, write, or delete files in arbitrary locations on removable storage.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491