Android,从不同的活动在缓存中保存和加载位图
我有一个位图需要在新活动中显示,所以我对其进行缓存,并在打开的活动中尝试加载它,但出现 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);
然后在新活动中我尝试打开它:
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);
I have i bitmap that needs to show in a new activity, so i cahe it and in the opened activity i try to load it but i get a nullPointerException. Here i save the image :
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);
and then in the new activity i try to open it :
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需检查您的代码:
您在设置内容视图之前已经编写了 findViewById() 。这是错误的。
Just check your code:
You have written findViewById() before setting Content View. Its wrong.