Android,通过不同的活动在缓存中保存和加载位图 [英] Android, Saving and loading a bitmap in cache from different activities

查看:102
本文介绍了Android,通过不同的活动在缓存中保存和加载位图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要在新活动中显示的位图,因此我在打开的活动中尝试将其加载,但出现nullPointerException.在这里,我保存图像:

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);

推荐答案

只需检查您的代码:

ImageView viewBitmap = (ImageView) findViewById(R.id.icon2);
viewBitmap.setImageBitmap(bitmap);
setContentView(R.layout.open_pic_layout);

您已在设置内容视图之前编写了findViewById().是错的.

You have written findViewById() before setting Content View. Its wrong.

public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.open_pic_layout);

  // do your operations here
  }

这篇关于Android,通过不同的活动在缓存中保存和加载位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆