Android,从不同的活动中保存和加载caching中的位图

我有我需要在新的活动中显示的位图,所以我cahe它,并在打开的活动中,我尝试加载它,但我得到一个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); 

Solutions Collecting From Web of "Android,从不同的活动中保存和加载caching中的位图"

只需检查你的代码:

 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 }