我有一个需要在新 Activity 中显示的位图,所以我缓存它并在打开的 Activity 中尝试加载它,但我得到一个 nullPointerException。我在这里保存图像:
File cacheDir = getBaseContext().getCacheDir();
File f = new File(cacheDir, "pic");
try {
FileOutputStream out = new FileOutputStream(
f);
pic.compress(
Bitmap.CompressFormat.JPEG,
100, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Intent intent = new Intent(
AndroidActivity.this,
OpenPictureActivity.class);
startActivity(intent);
然后在新 Activity 中我尝试打开它:
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
File cacheDir = getBaseContext().getCacheDir();
File f = new File(cacheDir, "pic");
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(fis);
ImageView viewBitmap = (ImageView) findViewById(R.id.icon2);
viewBitmap.setImageBitmap(bitmap);
setContentView(R.layout.open_pic_layout);
最佳答案
只需检查您的代码:
ImageView viewBitmap = (ImageView) findViewById(R.id.icon2);
viewBitmap.setImageBitmap(bitmap);
setContentView(R.layout.open_pic_layout);
您在设置内容 View 之前编写了 findViewById()。这是错误的。
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.open_pic_layout);
// do your operations here
}
关于Android,从不同的 Activity 在缓存中保存和加载位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7540386/