'Difference between FileProvider.getUriForFile and Uri.Parse() in Kotlin Android Studio
can anyone please help me with the difference between FileProvider.getUriForFile and Uri.Parse() in Kotlin Android Studio? I am working on a code in Kotlin to create a excel file and share it on various apps like Gmail, Whatsapp, etc. My issue is:
- when I have to share the file on Gmail, if I use
Uri.Parse(filepath)to get the URI of the file, I get an "Unable to attach file" so I have to use FileProvider then it works fine. - when I have to share the file on Whatsapp, its vice versa, i.e. if I use
FileProvider.getUriForFile(context,context.applicationContext.packageName.toString() + ".provider",file)to get the URI of the file, I get an "Sharing failed. Please try again" so I have to use Uri.Parse(filepath) then it works fine.
My code for share:
private fun ShareViaEmail(context: Context, path: String, file: File) {
if (!file.exists()){
context.ShowToast( "File doesn't exists", Toast.LENGTH_LONG)
return;
}
val uri = FileProvider.getUriForFile(
context,
context.applicationContext.packageName.toString() + ".provider",
file
)
Log.i(TAG, uri.toString())
val intentShare = Intent(Intent.ACTION_SEND)
intentShare.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intentShare.type = "*/*"
//intentShare.putExtra(Intent.EXTRA_STREAM, Uri.parse(path))
intentShare.putExtra(Intent.EXTRA_STREAM,uri)
context.startActivity(Intent.createChooser(intentShare, "Share the file ..."))
}
private fun Share(context: Context, path: String, file: File) {
if (!file.exists()){
context.ShowToast( "File doesn't exists", Toast.LENGTH_LONG)
return;
}
Log.i(TAG, Uri.parse(path).toString())
val intentShare = Intent(Intent.ACTION_SEND)
intentShare.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intentShare.type = "*/*"
intentShare.putExtra(Intent.EXTRA_STREAM, Uri.parse(path))
//For system files: intentShare.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+path))
context.startActivity(Intent.createChooser(intentShare, "Share the file ..."))
}
Thanks in Advance!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
