Krzysztof Pokrywka Krzysztof Pokrywka - 11 days ago 6
Android Question

Java Android why delete a images does't delete

I want to delete a images older than N days I do this :

File f = new File("/sdcard/Foto+");
File[] files1 = f.listFiles();

public void deleteFilesOlderThanNdays(File[] listFiles) {
long purgeTime = System.currentTimeMillis() - (Config.daysBackToDelete * 24 * 60 * 60 * 1000);
for (File listFile : listFiles) {
if (listFile.lastModified() < purgeTime) {
listFile.delete();
if(listFile.exists()){
try {
listFile.getCanonicalFile().delete();
} catch (IOException e) {
e.printStackTrace();
}
if(listFile.exists()){
getApplicationContext().deleteFile(listFile.getName());
}
}
}
}
}


And in this case when I try do this a images doesn't remove from this folder.

enter image description here

Answer

You need to delete file from MediaStore as well. Use the following method

deleteFileFromMediaStore(getContext().getContentResolver(), listFile);

Just call above method after deleting your image.

public static void deleteFileFromMediaStore(final ContentResolver contentResolver, final File file) {
        String canonicalPath;
        try {
            canonicalPath = file.getCanonicalPath();

            final Uri uri = MediaStore.Files.getContentUri("external");
            final int result = contentResolver.delete(uri,
                    MediaStore.Files.FileColumns.DATA + "=?", new String[]{canonicalPath});
            if (result == 0) {
                final String absolutePath = file.getAbsolutePath();
                if (!absolutePath.equals(canonicalPath)) {
                    contentResolver.delete(uri,
                            MediaStore.Files.FileColumns.DATA + "=?", new String[]{absolutePath});
                }
            }
        } catch (IOException e) {
            canonicalPath = file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }