I am deleting an image file from my application. I was doing
new File(filename).delete ();
This was actually deleting the file. But the image was still visible in the gallery.
On search i found that we should use
getContentResolver().delete(Uri.fromFile(file), null,null);
to delete
But here i am getting the exception:
Unknown file URL. java.lang.IllegalArgumentException: Unknown URL file:///mnt/sdcard/DCIM/Camera/IMG_20120523_122612.jpg
When i see with any file browser, this particular image is present. Please help me to fix this issue. Is there any other way to update gallery when image is physically deleted
I've seen a lot of answers suggesting the use of
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
This works but causes the Media Scanner to re-scan the media on the device. A more efficient approach would be to query/delete via the Media Store content provider:
// 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();