Deletes an image given its Uri and refreshes the gallery thumbnails. - Android Graphics

Android examples for Graphics:Image Download

Description

Deletes an image given its Uri and refreshes the gallery thumbnails.

Demo Code


//package com.java2s;

import java.io.File;

import android.content.Context;
import android.content.Intent;

import android.net.Uri;
import android.os.Environment;

public class Main {
    /**/*from   w  ww.  j  av a 2s  . c om*/
     * Deletes an image given its Uri and refreshes the gallery thumbnails.
     * @param cameraPicUri
     * @param context
     * @return true if it was deleted successfully, false otherwise.
     */
    public static boolean deleteImageWithUriIfExists(Uri cameraPicUri,
            Context context) {
        try {
            if (cameraPicUri != null) {
                File fdelete = new File(cameraPicUri.getPath());
                if (fdelete.exists()) {
                    if (fdelete.delete()) {
                        refreshGalleryImages(context, fdelete);
                        return true;
                    }
                }
            }
        } catch (Exception e) {
        }
        return false;
    }

    /**
     * Forces the Android gallery to  refresh its thumbnail images.
     * @param context
     * @param fdelete
     */
    private static void refreshGalleryImages(Context context, File fdelete) {
        try {
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                    Uri.parse("file://"
                            + Environment.getExternalStorageDirectory())));
        } catch (Exception e1) {
            try {
                Intent mediaScanIntent = new Intent(
                        Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri contentUri = Uri.fromFile(fdelete);
                mediaScanIntent.setData(contentUri);
                context.sendBroadcast(mediaScanIntent);
            } catch (Exception e2) {
            }
        }
    }
}

Related Tutorials