Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete image file from device programmatically

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....
like image 996
Hiren Vaghela Avatar asked Oct 22 '25 21:10

Hiren Vaghela


1 Answers

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();
    }
like image 132
f.trajkovski Avatar answered Oct 25 '25 11:10

f.trajkovski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!