4

I am trying to convert a card view into image and share it through whats app. I am using file provider as the test device's version is higher.

So when I am trying to create a file it is giving me an exception

e = {IllegalArgumentException@7727} "java.lang.IllegalArgumentException: Failed to find configured root that contains /com.example.onboardingversion2/images/card_image"
mCardFile = {File@7701} "com.example.onboardingversion2/images/card_image"

for the code :

   public void createFile() {

        FileOutputStream outputStream = null;
        try {

      File imagePath = new File(getActivity().getPackageName(), "images");

            mCardFile = new File(imagePath, "card_image");

            Uri contentUri = getUriForFile(getContext(), getActivity().getPackageName() + ".provider", mCardFile);
            sendCard(contentUri);

        } catch (Exception e) {
            e.printStackTrace();
        }
}

When I used below code using getFilesDir() it only goes to whats app intent and no image is shown when I try to share.

     File imagePath = new File(getActivity().getFilesDir(), "images");
            mCardFile = new File(imagePath, "card_image");

            Uri contentUri = getUriForFile(getContext(), getActivity().getPackageName() + ".provider", mCardFile);
            sendCard(contentUri);

Xml file

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="my_images" path="images/"/>
</paths>

Manifest

     <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths" />
    </provider>

Converting view to bitmap

 public Bitmap viewToBitmap(final View view) {

    cardView.post(new Runnable() {
        @Override
        public void run() {
            mBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(mBitmap);
            view.draw(canvas);

            createFile();

        }
    });

    return mBitmap;
}

Share code :

public void sendCard(Uri contentUri)
{

    Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
    whatsappIntent.setType("text/plain");
    whatsappIntent.setPackage("com.whatsapp");
    whatsappIntent.putExtra(Intent.EXTRA_TEXT, "The text you wanted to share");
    whatsappIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
    whatsappIntent.setType("image/jpeg");
    whatsappIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    try {
        getActivity().startActivity(whatsappIntent);
    } catch (android.content.ActivityNotFoundException ex) {
        Utils.showDialog(getActivity(),"Whats App have not been installed.");
    }
}

I have a card view which I am trying to create to a bitmap and convert a bitmap to image file and share using share intent.

Where am I going wrong? Is the view cant get convert to an image?

Please help. thank you.

Sid
  • 2,792
  • 9
  • 55
  • 111

2 Answers2

4

First add permission

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

use Bitmap from res

Bitmap b =BitmapFactory.decodeResource(getResources(),R.drawable.userimage);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(),
                b, "Title", null);
Uri imageUri =  Uri.parse(path);
share.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(share, "Select"));
Jitesh Prajapati
  • 2,533
  • 4
  • 29
  • 51
1

Here's a simple way without unnecessary permissions:

  1. create xml folder in your res folder (right click on res -> new -> android resource directory -> resource type:xml).

  2. create new xml file named file_paths.xml

  3. paste this code inside

file_paths.xml:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <cache-path name="Download" path="." />
</paths>

In your Manifest paste this line under application:

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.my.package.name.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>

In your class:

public void sendViewViaMail(final View view, final Context baseContext, final Context activityContextOnly, final String textToMail) {
    view.post(new Runnable() {
        @Override
        public void run() {
            int heightG = view.getHeight();
            int widthG = view.getWidth();
            sendViewViaMail(view, baseContext, activityContextOnly, widthG, heightG, textToMail);
        }
    });
}


private void sendViewViaMail(View view, final Context baseContext, Context activityContextOnly, int widthG, int heightG, String textToMail) {
    Bitmap bitmap = MyBitmapUtils.createViewBitmap(view, widthG, heightG);
    Uri imageUri = null;

        File file = null;
        FileOutputStream fos1 = null;
        try {
            File folder = new File(activityContextOnly.getCacheDir() + File.separator + "My Temp Files");

            boolean success = true;
            if (!folder.exists()) {
                success = folder.mkdir();
            }

            String filename = "img.jpg";
            file = new File(folder.getPath(), filename);

            fos1 = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos1);

            imageUri = FileProvider.getUriForFile(activityContextOnly, activityContextOnly.getPackageName() + ".my.package.name.provider", file);
        } catch (Exception ex) {

        } finally {
            try {
                fos1.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    final Intent emailIntent1 = new Intent(Intent.ACTION_SEND);
    emailIntent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    emailIntent1.putExtra(Intent.EXTRA_EMAIL, new String[]{});
    emailIntent1.putExtra(Intent.EXTRA_STREAM, imageUri);
    emailIntent1.putExtra(Intent.EXTRA_SUBJECT, "[" + "COMPANY_HEADER" + "]");
    emailIntent1.putExtra(Intent.EXTRA_TEXT, textToMail);
    emailIntent1.setData(Uri.parse("mailto:" + "mail@gmail.com")); // or just "mailto:" for blank
    emailIntent1.setType("image/jpg");
    activityContextOnly.startActivity(Intent.createChooser(emailIntent1, "Send email using"));
}

public static Bitmap createViewBitmap(View view, int widthG, int heightG) {
    Bitmap viewBitmap = Bitmap.createBitmap(widthG, heightG, Bitmap.Config.RGB_565);
    Canvas viewCanvas = new Canvas(viewBitmap);
    Drawable backgroundDrawable = view.getBackground();

    if(backgroundDrawable!=null){
        backgroundDrawable.draw(viewCanvas);
    }
    else{
        viewCanvas.drawColor(Color.WHITE);
        view.draw(viewCanvas);
    }
    return viewBitmap;
}

How to Call it:

CardView myCard = (CardView) findViewById(R.id.myCard);
sendViewViaMail(myCard, getApplicationContext(), Activity_Cabinet.this, report);
Guy4444
  • 1,411
  • 13
  • 15