Simple to do in every system but Android, but I have and app that needs to create a csv file in SHARED EXTERNAL Download folder. Shutdown/restart phone/app and the file persist. Then I need to delete the file (persistent URI somewhere?) before I recreate it with new data. (if exists() delete)
I see all kinds of doc pointing to SAF for this process, but can find no examples anywhere of how to perform this simple process of create/delete. If is can do this on API 28 and it work on 29+ that would be great.
Without SAF I've done this:
fun writeCSV() {
val CSV_HEADER = "Last,First\n"
val mockData = "Tester,Joe\n"
val contentValues = ContentValues()
contentValues.put(MediaStore.Downloads.DISPLAY_NAME, "aTest.csv")
contentValues.put(MediaStore.Downloads.MIME_TYPE, "text/csv")
contentValues.put(MediaStore.Downloads.IS_PENDING, true)
val uri = MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
val fileUri = contentResolver.insert(uri, contentValues)
if (fileUri != null) {
try {
val outputStream = contentResolver.openOutputStream(fileUri)
outputStream!!.write(CSV_HEADER.toByteArray())
outputStream!!.write(mockData.toByteArray())
outputStream!!.close()
contentValues.put(MediaStore.Images.Media.IS_PENDING, false)
contentResolver.update(fileUri, contentValues, null, null)
} catch (e: IOException) {
e.printStackTrace()
}
}
}
The problem is when fun is called again I need to delete this file and recreate it with new data because Android creates "aTest (1).csv" instead of overwriting it.