2

I have a linear layout with android:visibility="gone". I want to generate a png file of that layout. I have my code as -

Generator Function-

public Bitmap viewToBitmap(View v) {
        v.setDrawingCacheEnabled(true);
        v.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
        v.buildDrawingCache(true);
        Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
        v.setDrawingCacheEnabled(false);
        return b;
    }

Main code -

LinearLayout linearLayout = (LinearLayout)findViewById(R.id.share_layout);
                try {
                    Bitmap bitmap = viewToBitmap(linearLayout);
                    FileOutputStream output = new FileOutputStream(getExternalFilesDir(null)+ "/Image.png");
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
                    output.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

I am getting following error @ line:

Bitmap b = Bitmap.createBitmap(v.getDrawingCache());

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference

What am I doing wrong ?

EDIT: This is clearly different from the question-[What is a NullPointerException, and how do I fix it?. I know what a NullPointerException is and common reasons that triggers it, but in this case I can't figure out why there is NPE.

Community
  • 1
  • 1
  • 1
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – nhouser9 Oct 04 '16 at 21:20
  • stupid question but i have to ask, did you try with visibility visible? – lelloman Oct 05 '16 at 09:41

1 Answers1

0

You have to wait until System generates your view. You can set listener by:

final View rootView = getWindow().getDecorView().getRootView();
rootView.getViewTreeObserver().addOnDrawListener(new ViewTreeObserver.OnDrawListener() {
            @Override
            public void onDraw() {
                \\write your code here
            }
        });
prsnlme
  • 179
  • 8