I have an app which creates a .zip file that contains .pdf and .jpgs. If the .zip file is deleted by the user on the physical device, it throws an error when the user goes to create another zip file using the same name because it says the file already exists. From my understanding, this is because the file data is still stored in the MediaStore even though it's no longer visible on the device or the file explorer. Is there a way to delete the MediaStore entry upon deletion in the file explorer - or, what is the best way to programattically handle this?
Below is my code that creates the .zip file. I've changed the fragment and variable names for privacy, otherwise the code is exactly the same.
private fun zipDocs(){
val pdfPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS + "/Report/" + Fragment.name + " " + Fragment.report + " " + date + ".pdf")
val picPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + "/" + Fragment.name + " " + Fragment.report + " " + date)
val outDest = FileOutputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS + "/" + Fragment.name+ " " + Fragment.report + " " + date + ".zip"))
val out = ZipOutputStream(outDest)
if(picPath.listFiles() != null ) {
picPath.listFiles().forEach {
var fi = FileInputStream(it)
var origin = BufferedInputStream(fi)
var entry = ZipEntry(it.name)
try {
out.putNextEntry(entry)
origin.copyTo(out, 1024)
} catch (e: ActivityNotFoundException){
Toast.makeText(requireContext(), "Cannot create", Toast.LENGTH_SHORT).show()
} finally {
out.closeEntry()
origin.close()
fi.close()
}
}
} else {
Toast.makeText(requireContext(), "No pictures found.", Toast.LENGTH_SHORT).show()
}
if(pdfPath != null ) {
var fi = FileInputStream(pdfPath)
var origin = BufferedInputStream(fi)
var entry = ZipEntry(pdfPath.name)
try {
out.putNextEntry(entry)
origin.copyTo(out, 1024)
} catch (e: ActivityNotFoundException){
Toast.makeText(requireContext(), "Cannot create", Toast.LENGTH_SHORT).show()
} finally {
out.closeEntry()
origin.close()
fi.close()
}
}
out.close()
}