delete Image File From Media Provider - Android Media

Android examples for Media:Picture

Description

delete Image File From Media Provider

Demo Code

/*//from ww w. j  ava2  s.c  om
 * Copyright (C) 2009-2013 University of Washington
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
//package com.java2s;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

import android.provider.MediaStore.Images;

import android.util.Log;

public class Main {
    private static final String t = "MediaUtils";

    public static final int deleteImageFileFromMediaProvider(Context ctxt,
            String imageFile) {
        if (imageFile == null)
            return 0;

        ContentResolver cr = ctxt.getContentResolver();
        // images
        int count = 0;
        Cursor imageCursor = null;
        try {
            String select = Images.Media.DATA + "=?";
            String[] selectArgs = { imageFile };

            String[] projection = { Images.ImageColumns._ID };
            imageCursor = cr
                    .query(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            projection, select, selectArgs, null);
            if (imageCursor.getCount() > 0) {
                imageCursor.moveToFirst();
                List<Uri> imagesToDelete = new ArrayList<Uri>();
                do {
                    String id = imageCursor.getString(imageCursor
                            .getColumnIndex(Images.ImageColumns._ID));

                    imagesToDelete
                            .add(Uri.withAppendedPath(
                                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                    id));
                } while (imageCursor.moveToNext());

                for (Uri uri : imagesToDelete) {
                    Log.i(t, "attempting to delete: " + uri);
                    count += cr.delete(uri, null, null);
                }
            }
        } catch (Exception e) {
            Log.e(t, e.toString());
        } finally {
            if (imageCursor != null) {
                imageCursor.close();
            }
        }
        File f = new File(imageFile);
        if (f.exists()) {
            f.delete();
        }
        return count;
    }
}

Related Tutorials