-1

I am looking for a clean and simple way to delete all the pictures that my app put in the public gallery.

I tried this, but it does not work, while it goes in the right directory :

File dir =
  Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
    File[] files = dir.listFiles();
    if (files != null){
    for (File file : files) {
        deleteRecursively(file);
    }
}

Do I need a permission ? Why can't I delete the files I created in my app ?

Here is the deleteRecursively method :

void deleteRecursively(File fileOrDirectory) {
    if (fileOrDirectory.isDirectory()){
        for (File child : fileOrDirectory.listFiles()){
            deleteRecursively(child);
        }
    }
    fileOrDirectory.delete();
}
cleroo
  • 1,145
  • 2
  • 11
  • 17

2 Answers2

1

Try changing the deleteRecursively() method to:

void deleteRecursively(File fileOrDirectory) {
    if (fileOrDirectory.isDirectory()){
        for (File child : fileOrDirectory.listFiles()){
            deleteRecursively(child);
        }
    } else {
        fileOrDirectory.delete();
    }
}
Raghav Sood
  • 81,899
  • 22
  • 187
  • 195
0

You have to add uses permission in manifest file android.permission.WRITE_EXTERNAL_STORAGE"

J.K
  • 2,290
  • 1
  • 18
  • 29
  • I added it before you told me, thanks anyway, but is does not work – cleroo Aug 13 '12 at 09:46
  • `File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM); File[] files = dir.listFiles(); if (files != null){ for (File file : files) { file.delete(); } }` is enough :) – J.K Aug 13 '12 at 09:50
  • No it is not, my pictures are still in the gallery ! Or maybe there are just the thumbnails ? – cleroo Aug 13 '12 at 09:54
  • They are not in the file system (in `/mnt/sdcard/DCIM/` and `/mnt/sdcard/DCIM/Camera`. But I still see them in the gallery. – cleroo Aug 13 '12 at 10:01
  • @cleroo If you are passing camera intent, then image file goes only inside the Camera folder. You can check in MyFiles/DCIM/Camera – Narendra Pal Aug 13 '12 at 10:06
  • Strange, I still see the pictures in the gallery. – cleroo Aug 13 '12 at 10:26
  • Probably, due to thumbnail cache, the gallery still shows you the pictures. Refreshing the gallery or clearing thumbnail cache will do the trick. – pavi2410 Oct 10 '18 at 16:08