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
file.delete(); // try this one but not delete file....boolean isDelete = file.delete(); //this also not delete...context.deleteFile(file); // thisn one also not working in my example....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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With