I have the following kotlin code to send an email with an attachment:
val file = File(directory, filename)
file.createNewFile()
file.writeText("My Text", Charsets.UTF_8)
// ---- file is written succesfully, now let us
// try to get the URI and pass it for the intent
val fileURI = FileProvider.getUriForFile(this, "com.mydomain.myapp", file!!)
val emailIntent = Intent(Intent.ACTION_SEND).apply {
putExtra(Intent.EXTRA_SUBJECT, "My subject"))
putExtra(Intent.EXTRA_TEXT, "My message")
putExtra(Intent.EXTRA_STREAM, fileURI)
}
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
emailIntent.type = "text/plain"
startActivity(emailIntent)
Now, when I run the above code, I get an error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference
for the fileURI assignment line. If instead of FileProvider, if I use:
putExtra(Intent.EXTRA_STREAM, file!!.toURI())
as the extra intent parameter, then I get an error:
W/Bundle: Key android.intent.extra.STREAM expected Parcelable but value was a java.net.URI. The default value <null> was returned.
03-22 11:39:06.625 9620-9620/com.secretsapp.secretsapp W/Bundle: Attempt to cast generated internal exception:
W/Bundle: Key android.intent.extra.STREAM expected Parcelable but value was a java.net.URI. The default value <null> was returned.
W/Bundle: Attempt to cast generated internal exception:
java.lang.ClassCastException: java.net.URI cannot be cast to android.os.Parcelable
at android.os.Bundle.getParcelable(Bundle.java:945)
The file is created under a sub-directory under the global Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) directory and the app has Manifest.permission.WRITE_EXTERNAL_STORAGE permission too. Any pointers on how I can get the URI for the file and attach it to the email intent ?