嗨StackOverflow的社区时,NullPointerException异常试图保存当前的Android应用程序视图图像
在我的应用我想有一个按钮,允许用户捕获当前视图。
出于这个原因,我已经写了下面的方法(面向:Android save view to jpg or png):
private LinearLayout container;
public void createImageOfCurrentView(View v) {
if (isExternalStoragePresent()) {
container = (LinearLayout) 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();
}
}
的问题是根据LogCat
有试图创建jpeg
当发生一个NullPointerException
。所以可能的方法container.getDrawingCache()
不起作用。在电话上生成文件。但是,大小为0字节并且没有可见的图像。我将不胜感激任何建议,我必须做的才能让它按照我的意愿工作。
确保** ** b不为空.. – ngesh 2012-04-16 08:15:17
你有什么打算用这条线? 'container.findViewById(R.id.container);'我不熟悉像这样使用'findviewbyid',但常见的问题(比如“是当前set视图中的R.id.container')可能适用? – Nanne 2012-04-16 08:16:17