1

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();
    }
Ilias Ahmed
  • 105
  • 3
  • 9

2 Answers2

1

Below is the method to capture screenshot.

 public Bitmap getScreenShot(View view) {
       View screenView = view.getRootView();
       screenView.setDrawingCacheEnabled(true);
       Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
       screenView.setDrawingCacheEnabled(false);
       return bitmap;
 }

Store the Bitmap into the SDCard:

public void store(Bitmap bm, String fileName){
    final static String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Screenshots";
    File dir = new File(dirPath);
    if(!dir.exists())
        dir.mkdirs();
    File file = new File(dirPath, fileName);
    try {
        FileOutputStream fOut = new FileOutputStream(file);
        bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
        fOut.flush();
        fOut.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Now Inflate your layout and capture screen shot

View view=LayoutInflater.from(this).inflate(R.layout.score_share, null);

Bitmap bmp = getScreenShot(view);

bmp is the required screenshot then save it to SDcard like

store(bmp, "Screenshot.jpg");

Don't forget to add Write External Storage permission in manifest

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

Thanks to this answer Capture Screenshot and store to sdcard

Community
  • 1
  • 1
rana_sadam
  • 1,216
  • 10
  • 18
0

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.