androidfilechooser

How to allow selection of CSV in a File Chooser Intent in Android


after struggling one day I found this code "almost" works:

    private fun showFileChooser() {
        val mimeTypes = arrayOf(
            "text/csv",
            "text/plain",
            "application/csv",
            "application/vnd.ms-excel",
            "application/excel",
            "application/x-excel",
            "application/x-msexcel"
        )

        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        intent.type = "text/csv" //if (mimeTypes.size == 1) mimeTypes[0] else "*/*"
        if (mimeTypes.isNotEmpty())
            intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes)
        startActivityForResult(
            Intent.createChooser(intent, "choose file"),
            MY_RESULT_CODE_FILECHOOSER
        )
    }

The problem is that *.csv files cannot be selected/opened (this is a screenshot taken for another issue where you can see how the file appears... it is light gray like it is disable and indeed it cannot be selected) Thanks to the mime type text/plain I am able to select *.txt files.
I found lots of posts here on StackOverflow with suggestions that do not work (probably anymore).
Is there any solution to this? Regards


Solution

  • When using EXTRA_MIME_TYPES you need to call setType("*/*"). See the OpenFile section of Common Intents.

    Also, you should consider using the Activity Results API instead of startActivityForResult() since it provides more type safety and the latter has been deprecated. The one you are looking for is ActivityResultContracts.GetContent