Ilias Ahmed Ilias Ahmed - 19 days ago 6
Android Question

android- Taking screenshot of a particular view programmatically does not work

I want to take screenshot of a layout from another activity. When I take view into Bitmap it shows NullPointerExcenption. Here is my code

View v=LayoutInflater.from(this).inflate(R.layout.score_share, null);
layoutScore.setDrawingCacheEnabled(true);
Bitmap bm= Bitmap.createBitmap(v.getDrawingCache());
layoutScore.setDrawingCacheEnabled(false);
File file= new File(Environment.getExternalStorageDirectory()+"/scs.jpg");
try {
FileOutputStream outputStream= new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG,100, outputStream);
outputStream.flush();
outputStream.close();

openScreenshot(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Answer

If the problem is getDrawingCache returning null, then just add this lines of code before v.buildDrawingCache(true);

v.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 
          MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));

v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight()); 

This will prevent that the view has a size of (0,0), and because of that it turns null safe.

Comments