Android,如何在不同的活动中将位图保存和加载到缓存中

11

我有一张位图需要在一个新的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);

然后在新的活动中,我尝试打开它:

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

3
请指出哪一行抛出了空指针异常。 - Mathias Conradt
1个回答

8

请检查您的代码:

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

您在设置Content View之前使用了findViewById(),这是错误的。
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.open_pic_layout);

  // do your operations here
  }

1
你应该查看logcat输出中的错误行号。永远记住要检查logcat输出。 :) - Paresh Mayani

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接