How to refresh Gallery after deleting image from SDCard

AndroidDev picture AndroidDev · Mar 24, 2014 · Viewed 8.6k times · Source

When deleting the images on Android’s SD Card, sometimes the images are correctly removed but in the gallery still remains a preview of the removed image. When tapping on it, it is loaded as a black image. To resolve it I need to run MediaScanner. But this code doesn't work and still, the preview of review image remains in the Gallery.

Anyone knows how to resolve this.

Uri contentUri = Uri.fromFile(file);
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,contentUri); 
sendBroadcast(mediaScanIntent);

Answer

Yaroslav Mytkalyk picture Yaroslav Mytkalyk · Mar 24, 2014

You should delete it from mediaStore

public static void deleteFileFromMediaStore(final ContentResolver contentResolver, final File file) {
    String canonicalPath;
    try {
        canonicalPath = file.getCanonicalPath();
    } catch (IOException e) {
        canonicalPath = file.getAbsolutePath();
    }
    final Uri uri = MediaStore.Files.getContentUri("external");
    final int result = contentResolver.delete(uri,
            MediaStore.Files.FileColumns.DATA + "=?", new String[] {canonicalPath});
    if (result == 0) {
        final String absolutePath = file.getAbsolutePath();
        if (!absolutePath.equals(canonicalPath)) {
            contentResolver.delete(uri,
                    MediaStore.Files.FileColumns.DATA + "=?", new String[]{absolutePath});
        }
    }
}