Search code examples
androidimagesd-cardimage-gallerydelete-file

Delete images from SD card as well as from gallery


I am saving some pictures on the SD card in this way:

File dir = new File(fullPath);
                        if (!dir.exists()) {
                            dir.mkdirs();
                        }
                        String id = Integer.toString(i+1);
                        OutputStream fOut = null;
                        File file = new File(fullPath, id);
                        file.createNewFile();
                        fOut = new FileOutputStream(file);

                        // 100 means no compression, the lower you go, the stronger the compression
                        bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
                        fOut.flush();
                        fOut.close();

                        MediaStore.Images.Media.insertImage(this.getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());

However when I delete those images from the SD card they are kept in the gallery.

File path = new File(path);
            File[] lstFile;

            if(path.exists()){
                lstFile = path.listFiles();
                for(int i =0; i<lstFile.length;i++){
                    File file = lstFile[i];
                    file.delete();
                }
                path.delete(); 
            }

How come that those images stay in the gallery and how can I delete those? Is there a way to avoid in the first place that those images are saved in the gallery?


Solution

  • Oh! I hadn't noticed

    "Is there a way to avoid in the first place that those images are saved in the gallery?"

    Yes, there is. Remove

     MediaStore.Images.Media.insertImage(this.getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
    

    and save the file using only the File class, not the MediaStore class, whose purpose is precisely to help manage the gallery.