0

I am trying to test code to take screenshot on the android emulator. I have the following code to start with:

    View content = ((ViewGroup)findViewById(android.R.id.content)).getChildAt(0);
    content.setDrawingCacheEnabled(true);
    Bitmap bitmap = Bitmap.createBitmap(content.getDrawingCache());
    content.setDrawingCacheEnabled(false);

But I get null pointer exception in createBitmap at line 551.

Can someone please point out what am I doing wrong.

Jake
  • 16,329
  • 50
  • 126
  • 202

2 Answers2

1

I think your problem could come from your View content :

View content = ((ViewGroup)findViewById(android.R.id.content)).getChildAt(0);

Did you try remove getChildAt(0) or to replace it by getRootView() ?

Else, there is a good website with a sample there if it can help you (last post on the first forum page):

Capture Screen With Coding

Tell me if you find how to solve it.

ChapMic
  • 26,954
  • 1
  • 21
  • 20
  • I used the code : Bitmap bitmap = content.getDrawingCache(), and I did not get the null pointer exception. As the emulator has root privilege, if I ran this code on a phone, would I get an exception ? Also, why does the app not require READ_FRAME_BUFFER permission ? Thanks – Jake Mar 17 '12 at 03:17
  • On running on the emulator, I get bitmap = null. – Jake Mar 17 '12 at 03:23
0

You must use MeasureSpec in some cases. Try this:

View content = ((ViewGroup)findViewById(android.R.id.content));
content.setDrawingCacheEnabled(true);
content.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
content.layout(0, 0, content.getMeasuredWidth(), content.getMeasuredHeight());
content.buildDrawingCache(true);
Bitmap bitmap = Bitmap.createBitmap(content.getDrawingCache());
Italo Borssatto
  • 15,044
  • 7
  • 62
  • 88