2011-09-24 53 views
9

我有我需要在新活動中顯示的位圖,所以我cahe它和在打開的活動中,我嘗試加載它,但我得到一個nullPointerException。在這裏,我保存圖片:Android,從不同的活動保存和加載緩存中的位圖

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

您應該提及哪一行會引發NullPointerException。 –

回答

4

只是檢查你的代碼:

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 
    } 
+0

omg,我需要休息一下),它現在正常工作,謝謝指出= = – user924941

+0

你應該看看logcat輸出中的錯誤行號。請始終記住,不要忘記檢查logcat輸出。 :) –