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.