How to export CSV File wih OpenCSV Library in Android Q API 30? – Kotlin

Issue

I have learn how to export CSV file in this link, but I have problem to export in android API 30+. I have tried with MediaStore to writing file but no luck.

Problem in ExportService.kt

object ExportService {

    fun <T : Exportable> export(context: Context, type: Exports, content: List<T>): Flow<Boolean> =
        when (type) {
            is Exports.CSV -> writeToCSV<T>(context, type.csvConfig, content)
        }

    private fun <T : Exportable> writeToCSV(
        context: Context,
        csvConfig: CsvConfig,
        content: List<T>
    ) =
        flow {
            with(csvConfig) {
                val collection = sdk29AndUp {
                    MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
                } ?: MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL)
                val values = ContentValues().apply {
                    put(MediaStore.MediaColumns.DISPLAY_NAME, filename)
                    put(MediaStore.MediaColumns.MIME_TYPE, "text/csv")
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                        put(
                            MediaStore.MediaColumns.RELATIVE_PATH,
                            Environment.DIRECTORY_DOCUMENTS + "/Medisy's Clinic/"
                        )
                    }
                }
                val uri = context.contentResolver.insert(collection, values)
                Log.e("TAG", "writeToCSV: ${uri!!.path} $filename")
                val csvWriter = CSVWriter(FileWriter(uri!!.path?.let { File(it) }))

                StatefulBeanToCsvBuilder<T>(csvWriter)
                    .withSeparator(CSVWriter.DEFAULT_SEPARATOR)
                    .build()
                    .write(content)

                csvWriter.close()
            }
            emit(true)
        }
}

Output Log

E/TAG: writeToCSV: /external_primary/file/40 Medisy's Clinics-May_31_2022_10:58:58_AM.csv
W/System.err: java.io.FileNotFoundException: /external_primary/file/40: open failed: ENOENT (No such file or directory)
W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:492)
W/System.err:     at com.example.medisyclinics.data.csv.ExportService$writeToCSV$1.invokeSuspend(ExportService.kt:47)

Can anyone give me solutions?

Solution

I solved this with Enviroment.getExternalStorageDiretory() function

Answered By – Reksa Fitrananda

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published