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();
}