0

I am making A meme creator application. I am not able to share the bitmap of a layout(rl_meme_container) as image to other platforms like whatsapp. I tried to see various comments and posts by different users but none worked for me. This is the code i tried to share bitmap as image:

val file_path:String = Environment.getExternalStorageDirectory().absolutePath + "/ProjectName"
        val dir:File =File(file_path);
        if(!dir.exists())
        dir.mkdirs();
        val file:File = File(dir,"share")
        try {
        val fOut:FileOutputStream =FileOutputStream(file)
        rl_meme_container.drawToBitmap().compress(Bitmap.CompressFormat.PNG, 85, fOut)
        fOut.flush();
        fOut.close();
        } catch (e:Exception) {
        e.printStackTrace();
        }

        var uri:Uri = Uri.fromFile(file);
        val intent:Intent = Intent();
        intent.action = Intent.ACTION_SEND;
        intent.type = "image/*";

        intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "")
        intent.putExtra(android.content.Intent.EXTRA_TEXT, "")

        intent.putExtra(Intent.EXTRA_STREAM, uri)
        startActivity(Intent.createChooser(intent, "Share Cover Image"))

Its showing this error:

FATAL EXCEPTION: main
    Process: com.meme.finalmeme, PID: 26583
    android.os.FileUriExposedException: file:///storage/emulated/0/ProjectName/share exposed beyond app through ClipData.Item.getUri()
  • One can share files with other apps. There is no such thing for bitmaps and platforms. – blackapps Jun 30 '20 at 09:59
  • I just want to share the bitmap of a layout as an image – Vipul Sharma Jun 30 '20 at 10:03
  • One cannot share bitmaps or images. Only files. – blackapps Jun 30 '20 at 10:04
  • ya. i dont really care how it is shared. Even if first makes it a file and then share. Do you have a working code of converting bitmap to file and then share it in kotlin? – Vipul Sharma Jun 30 '20 at 10:11
  • Such code is published on this site nearly every day. So read a few pages tagged `android` -or Google- and you are done quickly. Please remove the `android-studio` tag. It has nothing to do with it. – blackapps Jun 30 '20 at 10:13
  • see the code i used. Its showing this error. Do you know where i am going wrong? – Vipul Sharma Jun 30 '20 at 10:46
  • You know that too. You have a FileUriExposedException. A little googling would have told you that you have to use a FileProvider to share the file. – blackapps Jun 30 '20 at 10:48
  • var uri:Uri = Uri.fromFile(file); would becomev ar uri:Uri = FileProvider.getUriFromFile(file); and you have to add an xml file to res and adapt your manifest. – blackapps Jun 30 '20 at 10:49
  • In addition to fixing the `FileUriExposedException`, you need to replace `intent.type = "image/*";` with `intent.type = "image/png"`, and you need to add `FLAG_GRANT_READ_URI_PERMISSION` to the `Intent` before using it with `startActivity()`. – CommonsWare Jun 30 '20 at 10:56

0 Answers0