Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot remove an image inserted with MediaStore

I'm saving an image loaded with Picasso to be shared afterwards. This is the code I'm using to save it:

String path = MediaStore.Images.Media.insertImage(
                    mContext.getContentResolver(), mImageBitmap, "Shared image", null);

return Uri.parse(path);

Now, when the image has been shared, I have to delete it using the URI. I've tried some answers I've seen here but none of them has worked. The image still appears in the gallery. These are the methods I have used:


// 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[] { new File(mImageUri.toString()).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);
}

c.close();

File file = new File(mImageUri.toString());
// This returns false
file.delete();

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(mImageUri.toString()))));

Any idea of what i've done wrong?

Thanks,

like image 969
Dani M Avatar asked May 23 '26 04:05

Dani M


1 Answers

Try this for deletion

    String[] retCol = { MediaStore.Audio.Media._ID };

        Cursor cur = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                retCol,
                MediaStore.Images.Media.TITLE + "='"+TEMP_FILE_TITLE+"'", null, null
        );
    try {
        if (cur.getCount() == 0) {
            return;
        }
        cur.moveToFirst();
        int id = cur.getInt(cur.getColumnIndex(MediaStore.MediaColumns._ID));
        Uri uri = ContentUris.withAppendedId(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id
        );
       int cnt = context.getContentResolver().delete(uri, null, null);
}finally {
                cur.close();
            }

In your case replace TEMP_FILE_TITLE = "Shared image"

like image 173
Rekha Avatar answered May 24 '26 18:05

Rekha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!