delete Images In Folder From Media Provider - Android android.graphics

Android examples for android.graphics:Image

Description

delete Images In Folder From Media Provider

Demo Code

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 deleteImagesInFolderFromMediaProvider(Context ctxt, File folder) {
    if (folder == null)
      return 0;/*from   w w  w.ja  va 2s .c  om*/

    ContentResolver cr = ctxt.getContentResolver();
    // images
    int count = 0;
    Cursor imageCursor = null;
    try {
      String select = Images.Media.DATA + " like ? escape '!'";
      String[] selectArgs = { escapePath(folder.getAbsolutePath()) };

      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();
      }
    }
    return count;
  }

  private static String escapePath(String path) {
    String ep = path;
    ep = ep.replaceAll("\\!", "!!");
    ep = ep.replaceAll("_", "!_");
    ep = ep.replaceAll("%", "!%");
    return ep;
  }

}

Related Tutorials