I am trying to get a image of a view (constraint-layout) and share it via an android send-intent.
I tried a lot of methods, but until now none have worked. This is what I have so far:
public void shareStatsImage(){
    constraintLayout.setDrawingCacheEnabled(true);
    Bitmap bitmap = constraintLayout.getDrawingCache();
    File path = null;
    try {
        path = saveImageToExternal(generateImageTitle(), bitmap);
    } catch (IOException e) {
        e.printStackTrace();
    }
    final Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("image/png");
    final File photoFile = new File(Objects.requireNonNull(getActivity()).getFilesDir(), Objects.requireNonNull(path).getAbsolutePath());
    shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(photoFile));
    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    startActivity(Intent.createChooser(shareIntent, "Share image using"));
}
public static String generateImageTitle(){
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy-hh-mm-ss");
    return sdf.format(new Date());
}
public File saveImageToExternal(String imgName, Bitmap bm) throws IOException {
    //Create Path to save Image
    String appFolder = "test";
    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + File.separator + appFolder); //Creates app specific folder
    path.mkdirs();
    File imageFile = new File(path, imgName+".png"); // Imagename.png
    FileOutputStream out = new FileOutputStream(imageFile);
    try{
        bm.compress(Bitmap.CompressFormat.PNG, 100, out); // Compress Image
        out.flush();
        out.close();
        // Tell the media scanner about the new file so that it is
        // immediately available to the user.
        MediaScannerConnection.scanFile(getContext(),new String[] { imageFile.getAbsolutePath() }, null,new MediaScannerConnection.OnScanCompletedListener() {
            public void onScanCompleted(String path, Uri uri) {
                Log.i("ExternalStorage", "Scanned " + path + ":");
                Log.i("ExternalStorage", "-> uri=" + uri);
            }
        });
    } catch(Exception e) {
        throw new IOException();
    }
    return imageFile;
}
There are multiple problems with this solution, for example I am getting an error message ("Permission denied for the attachment") when sharing the image to gmail. When uploading the image to google drive I only get an "upload unsuccessful message".
One good thing is that the images seem to appear in the phone's gallery, just not when sharing them via the intent :(
Thanks for your help!
 
                        
Convert Bitmap to Uri