Rookie
Rookie

Reputation: 193

How to notify MediaStore that Some Items are Deleted?

I have a simple gallery app in which user can take or delete photos. For taking photos this works in notifying MediaStore of the newly created file:

File file = new File(storageDir, createImageName());

final Uri uri = Uri.fromFile(file);

Intent scanFileIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
sendBroadcast(scanFileIntent);

I delete photos but local gallery app still shows them as a blank file. This does not work. I target minimum Android 5.0 :

File file = new File(Environment.getExternalStorageDirectory() + File.separator + "Folder where application stores photos");

final Uri uri = Uri.fromFile(file);


Intent scanFileIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
sendBroadcast(scanFileIntent);

What I'm trying to do is to scan the folder my application creates when a file deleted to inform MediaStore of the images and folders deleted. How can I do this?

Upvotes: 3

Views: 597

Answers (1)

Samwise Gamgee
Samwise Gamgee

Reputation: 11

Here is a method that deletes any record(s) of a media file from the MediaStore.

Note that the DATA column in the MediaStore refers to the file's full path.

    public static boolean deleteFileFromMediaStore(
            Context context, String fileFullPath)
    {
        File file = new File(fileFullPath);

        String absolutePath, canonicalPath;
        try { absolutePath = file.getAbsolutePath(); }
        catch (Exception ex) { absolutePath = null; }
        try { canonicalPath = file.getCanonicalPath(); }
        catch (Exception ex) { canonicalPath = null; }

        ArrayList<String> paths = new ArrayList<>();

        if (absolutePath != null) paths.add(absolutePath);
        if (canonicalPath != null && !canonicalPath.equalsIgnoreCase(absolutePath))
            paths.add(canonicalPath);

        if (paths.size() == 0) return false;

        ContentResolver resolver = context.getContentResolver();
        Uri uri = MediaStore.Files.getContentUri("external");

        boolean deleted = false;

        for (String path : paths)
        {
            int result = resolver.delete(uri,
                    MediaStore.Files.FileColumns.DATA + "=?",
                    new String[] { path });

            if (result != 0) deleted = true;
        }

        return deleted;
    }

Upvotes: 1

Related Questions