Android,从不同的活动保存和加载缓存中的位图
问题描述:
我有我需要在新活动中显示的位图,所以我cahe它和在打开的活动中,我尝试加载它,但我得到一个nullPointerException。在这里,我保存图片:Android,从不同的活动保存和加载缓存中的位图
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);
,然后在新的活动我尝试打开它:
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);
你已经写了findViewById()在设置内容视图之前。这是不对的。
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.open_pic_layout);
// do your operations here
}
+0
omg,我需要休息一下),它现在正常工作,谢谢指出= = – user924941
+0
你应该看看logcat输出中的错误行号。请始终记住,不要忘记检查logcat输出。 :) –
您应该提及哪一行会引发NullPointerException。 –