Search code examples
javaandroidimageandroid-sharing

Sharing image from android app


I am trying to share an image from my Android app. I am trying to send it as an Email attachment as well as a photo on WhatsApp.

The code is:

String imageUrl = Path to image (eg. sdcard/pictures/image1.jpg);
shareImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Uri uriToImage= Uri.parse(imageUrl);
                    Log.d("Image", ""+uriToImage);
                    Intent shareIntent = new Intent();
                    shareIntent.setAction(Intent.ACTION_SEND);
                    shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage);
                    shareIntent.setType("image/*");
                    startActivity(Intent.createChooser(shareIntent, "Share image:"));
                }
            });

What's happening is:

  1. On WhatsApp I can share the image easily.
  2. On Gmail, it says that the attachment could not be sent.
  3. On Hangouts I get a toast which says Photo couldn't be found
  4. On Facebook too, the post is not accompanied with the Image but I can post.
  5. On Facebook Messenger, it crashes without opening.

The tutorial that I have followed for this is given here. The send binary content part of the tutorial is the one that I have implemented.

Another thing I tried was to set the image in an ImageView and see if it is displayed. The image is displayed correctly. Also, the log message prints the correct path of the image.

I also read and tried the answers to: Question 1 and Question 2 but to no avail.

Where am I going wrong?


Solution

  • try this,

    try
                    {
                        File myFile = new File(share_image_path);
                        MimeTypeMap mime = MimeTypeMap.getSingleton();
                        String ext = myFile.getName().substring(myFile.getName().lastIndexOf(".") + 1);
                        String type = mime.getMimeTypeFromExtension(ext);
                        Intent sharingIntent = new Intent("android.intent.action.SEND");
                        sharingIntent.setType(type);
                        sharingIntent.putExtra("android.intent.extra.STREAM", Uri.fromFile(myFile));
                        startActivity(Intent.createChooser(sharingIntent, "Share using"));
                    }
                    catch (Exception e)
                    {
                        Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                    }