Android,从不同的 Activity 在缓存中保存和加载位图

标签 android caching android-activity bitmap

我有一个需要在新 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/

相关文章:

android httpclient 和 utf-8

android - 版本冲突更新为Play-Services 9.4.0 Android Studio 2.2

java - Hibernate缓存技术

css - Prestashop 1.6 CCC css 每次缓存中的新文件

android - 实现 Drm Dash 媒体源时发生 DecoderInitializationException

android - Google app Engine 的示例 android 应用程序,抛出异常

python - 在Python中清除缓存或内存

android - 资源 ID 不能为空字符串(位于 'id' ,值为 '@+id/")

ios - Activity 指示器 webView Xcode 5 IOS 7

android - 在每个 Activity 中显示抽屉导航 - android studio