Search code examples
androidandroid-fileproviderandroid-sharing

Sharing a cache file using FileProvider not attaching the file


I have a file in cache that I have verified does exist (I can read it and print it out). In this particular instance it is a .csv file. I get the chooser UI to show up, but the file never gets attached to email for example. Can anyone spot what I am missing? I have tried several things now but don't see what's wrong.

        val file = File(parentContext.cacheDir, fileName)
        Timber.i("Sharing file of size: ${file.length()}")
        val fileURI = FileProvider.getUriForFile(parentContext.applicationContext, parentContext.packageName + ".provider", file)
        Timber.i("The fileURI path is: ${fileURI.path}")
        val intent = Intent(Intent.ACTION_SEND)
        intent.putExtra(Intent.EXTRA_SUBJECT, "Share of $fileName")
        intent.type = URLConnection.guessContentTypeFromName(fileName)
        intent.data = fileURI
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        startActivity(parentContext, Intent.createChooser(intent, "Share File"), null)

The output of the Timber lines is: Sharing file of size: 1719 and The fileURI path is: /cache/myfilename-10-30-2020.csv so that looks correct. I get the Subject of the email filled in when I select email but there is just no attachment.


Solution

  • Replace:

    intent.data = fileURI
    

    with:

    intent.putExtra(Intent.EXTRA_STREAM, fileURI)