MyLinearLayout.getDrawingCache () provides a NullPointerException

edit:

Nevermind, it works that way

TopRatedPage.setDrawingCacheEnabled(true);
TopRatedPage.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
TopRatedPage.layout(0, 0, TopRatedPage.getMeasuredWidth(), TopRatedPage.getMeasuredHeight()); 
TopRatedPage.buildDrawingCache(true);
Bitmap screenshot = Bitmap.createBitmap(TopRatedPage.getDrawingCache());
TopRatedPage.setDrawingCacheEnabled(false);

old:

I am trying to take a screenshot from a layout, for example.

LinearLayout TopRatedPage = (LinearLayout)inflater.inflate(R.layout.toprated, null);
...
Bitmap screenshot;
TopRatedPage.setDrawingCacheEnabled(true);
screenshot = Bitmap.createBitmap(TopRatedPage.getDrawingCache()); // Caused by: java.lang.NullPointerException
TopRatedPage.setDrawingCacheEnabled(false);

Any ideas what I did wrong?

Thank!

edit: also tried like this, it does not throw an error, but receives an empty bitmap.

Bitmap screenshot = TopRatedPage.getDrawingCache();
+3
source share
1 answer

Try this and let me know what will happen.

LinearLayout TopRatedPage = (LinearLayout)inflater.inflate(R.layout.toprated, null);
Bitmap screenshot = Bitmap.createBitmap(LinearLayout .getWidth(), LinearLayout .getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(screenshot);
LinearLayout.draw(c);
imageView.setImageBitmap(screenshot);

Also, if possible, use

View captureView = null;
captureView = inflater.inflate(R.layout.toprated, null);
Bitmap screenshot = Bitmap.createBitmap(captureView.getWidth(), captureView.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(screenshot);
captureView .draw(c);
imageView.setImageBitmap(screenshot);
+1
source

All Articles