Monday, April 16, 2012

NullpointerException when trying to save the current Android app view as image

Hi stackoverflow community,



in my application I'd like to have a button which allows the user to capture the current view. For that reason, I've written the following method (oriented towards: Android save view to jpg or png ):



private LinearLayout container; 

public void createImageOfCurrentView(View v) {
if(isExternalStoragePresent()) {
container = findViewById(R.id.container);
container.setDrawingCacheEnabled(true);
Bitmap b = container.getDrawingCache();
File dir = new File(Environment.getExternalStorageDirectory().getPath()+"/"+getPackageName()+"/");
dir.mkdirs();
File file = new File(dir, "image.jpg");
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
b.compress(CompressFormat.JPEG, 95, fos); // NullPointerException!
Toast.makeText(this, "The current view has been succesfully saved as image.", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
Toast.makeText(this, "Unfortunatly an error occured and this action failed.", Toast.LENGTH_SHORT).show();
}
}else {
Toast.makeText(this, "Bacause of lacking access to the storage of this device, the current view couldn't be saved as an image.", Toast.LENGTH_LONG).show();
}
}


The problem is according to LogCat that there occured a NullPointerException when trying to create the jpeg. So probably the method container.getDrawingCache() is not working. On the phone the file is generated. However with the size of 0 bytes and no visible image. I would appreciate any suggestions what I have to do in order to make it work as I want.





No comments:

Post a Comment