Hiren Vaghela
Hiren Vaghela

Reputation: 61

Delete image file from device programmatically

How can I delete an image file using my app?

File file = new File("path"); //PATH is: /storage/sdcard0/DCIM/Camera/IMG_20160913_165933.jpg
  1. file.delete(); // try this one but not delete file....
  2. boolean isDelete = file.delete(); //this also not delete...
  3. context.deleteFile(file); // thisn one also not working in my example....

Upvotes: 4

Views: 11660

Answers (6)

Louis Chabert
Louis Chabert

Reputation: 439

This post help me so mutch, I was searching how to delete all the pictures from the gallery and I finally found it.

In my case I wanted to delete all the photos in one click and this method works.

My code :

    private void deletePictures(){

    String[] projection = {MediaStore.Images.Media._ID};
    Cursor cursor = getContext().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null,null, null);
    while (cursor.moveToNext()) {
        long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
        Uri deleteUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
        getContext().getContentResolver().delete(deleteUri, null, null);
    }
    cursor.close();

}

I tested on Android 10 and it's working.

Upvotes: 2

f.trajkovski
f.trajkovski

Reputation: 825

If you are trying to delete a picture or similar you may have issues. It may return to you that the result is true but the file still will exist. I have lost so much time and what best worked for me was:

  private void deleteImage(File file) {
        // 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[]{file.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);
        } else {
            // File not found in media store DB
        }
        c.close();
    }

Upvotes: 6

D.J
D.J

Reputation: 1559

Check file.isExist() then delete and also check permission in AndroidManifest.xml file.

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1007659

//PATH is: /storage/sdcard0/DCIM/Camera/IMG_20160913_165933.jpg

That would appear to be on removable storage. On Android 4.4+ devices, you do not have the ability to read, write, or delete files in arbitrary locations on removable storage.

Upvotes: 0

Ramesh Prajapati
Ramesh Prajapati

Reputation: 662

try this working code

 File target = new File(path);
    Log.d(" target_path", "" + path);
    if (target.exists() && target.isFile() && target.canWrite()) {
        target.delete();
        Log.d("d_file", "" + target.getName());
    }

Add AndroidManifest.xml

 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Upvotes: 2

Arjun saini
Arjun saini

Reputation: 4182

Try this..

permission add to mainfiest also

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

for marashmallow runtime permission add

 private static final int REQUEST_RUNTIME_PERMISSION = 123;

if (CheckPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// you have permission go ahead
 File file = new File("path");
    if(file.exists())
    {
        file.delete();
    }

} else {
// you do not have permission go request runtime permissions
RequestPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE, REQUEST_RUNTIME_PERMISSION);
}


  @Override
    public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults) {

        switch (permsRequestCode) {

            case REQUEST_RUNTIME_PERMISSION: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                } else {
                    // you do not have permission show toast.
                }
                return;
            }
        }
    }
    public void RequestPermission(Activity thisActivity, String Permission, int Code) {
        if (ContextCompat.checkSelfPermission(thisActivity,
                Permission)
                != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
                    Permission)) {

            } else {
                ActivityCompat.requestPermissions(thisActivity,
                        new String[]{Permission},
                        Code);
            }
        }
    }

    public boolean CheckPermission(Activity context, String Permission) {
        if (ContextCompat.checkSelfPermission(context,
                Permission) == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            return false;
        }
    }

Upvotes: 0

Related Questions