1

I'm trying to make a screenshot of an activity in android, I found many examples online, but none works properly. In my case with a broadcast-receiver I intercept a specific event, and I launch an activity and I need to make the screenshot of this activity? Does anyone have any advice?

PS. I have already imported all the permissions to be able to save the screens on the disk. I use android api 26.

code that I found online

    try {
        // image naming and path  to include sd card  appending name you choose for file
        View view = getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap b1 = rootView.getDrawingCache();
        Rect frame = new Rect();
        getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int statusBarHeight = frame.top;

        //Find the screen dimensions to create bitmap in the same size.
        int width = getWindowManager().getDefaultDisplay().getWidth();
        int height = getWindowManager().getDefaultDisplay().getHeight();

        Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight);

    } catch (Throwable e) {
        // Several error may come out with file handling or DOM
        e.printStackTrace();
    }

When the code reaches the line who try to create Bitmap b, return java null point exception, because b1 is null.

apollo9
  • 131
  • 1
  • 8

1 Answers1

0

As you're getting NPE creating bitmap I suppose you don't have rootView variable . I don't see it initialized , maybe you wanted to put there view.getDrawingCache();

Refer this working example of creating bitmap

// create bitmap screen capture
        View v1 = getWindow().getDecorView().getRootView();
        v1.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
        v1.setDrawingCacheEnabled(false);

Check this thread. I think there're nice answers to you question

Rainmaker
  • 10,294
  • 9
  • 54
  • 89
  • Returns java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference, when it try to create Bitmap – apollo9 Feb 18 '18 at 14:40
  • You should debug and see which parameter of createBitmap is null, it could be because your methods of getting width and height are deprecated. It could cause a problem too – Rainmaker Feb 18 '18 at 15:02