0

When I press the "Share" button, my app takes a screenshot of all the activity(even no visible parts) and the share it via intent. I figured out that sometime it works and sometimes it doesn't. I can't understand the problem. That's my code:

share.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkPermission();


        }
    });
// Inside the checkPermission method, if the user allow them:
Bitmap bitmapScreen = takeScreenshot();
saveBitmap(bitmapScreen);
} 

 public Bitmap takeScreenshot() {

    rechoose.setVisibility(View.GONE);
    share.setVisibility(View.GONE);
    View rootView = findViewById(android.R.id.content).getRootView();
    rootView.setDrawingCacheEnabled(true);
    rootView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
    rootView.layout(0, 0, rootView.getMeasuredWidth(), rootView.getMeasuredHeight());
    rootView.buildDrawingCache(true);

    return rootView.getDrawingCache();
}

public void saveBitmap(Bitmap bitmap) {
    UUID uuid = UUID.randomUUID();
    String randomUUIDString = "/" + uuid.toString() + ".png";
    rechoose.setVisibility(View.VISIBLE);
    share.setVisibility(View.VISIBLE);
    imagePath = new File(Environment.getExternalStorageDirectory() + randomUUIDString);
    FileOutputStream fos;
    try {
        fos = new FileOutputStream(imagePath);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        Log.v("errorFileNotFound", e.getMessage(), e);
    } catch (IOException e) {
        Log.v("Exception", e.getMessage(), e);
    }

    Uri uri = FileProvider.getUriForFile(RateActivity.this, BuildConfig.APPLICATION_ID + ".provider", imagePath);
    Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
    sharingIntent.setType("image/*");
    sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);

    startActivity(Intent.createChooser(sharingIntent, "Share via"));
}

I got this error:

 java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
    at com.my.name.myapp.RateActivity.saveBitmap(RateActivity.java:211)

The line 211 is:

bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);

It's a little bit strange, because sometimes it works and sometimes it doesn't. On my activity I load an image from my gallery. With some image that I pick from gallery, the app takes the screenshot, with others it doesn't. Obviously, if the app didn't take the screenshot, then I got a nullPointerException on bitmap.compress. But I can't figured out why it doesn't take the screenshot. If I write the takeScreenshot() method like this, it works anytime:

public Bitmap takeScreenshot() {


View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);

return rootView.getDrawingCache();
}
Nicola
  • 301
  • 3
  • 20
  • 1
    Sometime if you don't get proper path then you will not get bitmap that cause an issue. Must be sure you'r getting proper path while saving to storage. – Piyush Dec 28 '18 at 07:48

1 Answers1

0

Your Bitmap is null here. Please debug the value of bitmap and cross check if it is null or not. Or you can use the below code to take a screenshot, put this function n general method and pass your view to it.

fun takeScreenshot(context: View?, activity: Activity) {
val now = Date()
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now)
try {
    val mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg"
    // create bitmap screen capture
    context?.isDrawingCacheEnabled = true
    val bitmap = Bitmap.createBitmap(context?.drawingCache)
    context?.isDrawingCacheEnabled = false
    val imageFile = File(mPath)
    val outputStream = FileOutputStream(imageFile)
    val values = ContentValues()
    values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis())
    values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
    values.put(MediaStore.MediaColumns.DATA, mPath)
    activity.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
    val quality = 100
    bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream)
    outputStream.flush()
    outputStream.close()
    Toast.makeText(activity, activity.getString(R.string.saved_to_gallery), Toast.LENGTH_SHORT).show()
} catch (e: Throwable) {
    e.printStackTrace()
}
Mini Chip
  • 949
  • 10
  • 12