2011-03-14 28 views
1

大家好,我在設置ImageView時得到了一個N​​PE位圖。位圖已經從字節數組解碼並且不爲空或空。有任何想法嗎?感謝在imageview中設置位圖時出現NullPointerException

public class LoadPic extends Activity{ 

    private static final String TAG = "Loadpic"; 
    private ImageView imageview; 
    private File tempFile; 
    private byte[] imageArray; 

    public void onCreate(Bundle icicle) { 
     super.onCreate(icicle); 

     Log.e(TAG, " loadpic onCreate"); 
     setContentView(R.layout.load); 

     imageview = (ImageView)findViewById(R.id.imageView1); 

     tempFile = new File(Environment.getExternalStorageDirectory(). 
      getAbsolutePath() + "/"+"image.jpg"); 

     imageArray = new byte[(int)tempFile.length()]; 

    try{ 

     InputStream is = new FileInputStream(tempFile); 
     BufferedInputStream bis = new BufferedInputStream(is); 
     DataInputStream dis = new DataInputStream(bis); 


     int i = 0; 

     while (dis.available() > 0) { 
     imageArray[i] = dis.readByte(); 
     i++; 
     } 

     dis.close(); 

    } catch (Exception e) { 

      e.printStackTrace(); 
     } 

     BitmapFactory.Options bfo = new BitmapFactory.Options(); 
     bfo.inSampleSize = 5; 
     Bitmap bm = BitmapFactory.decodeByteArray(imageArray, 0, imageArray.length, bfo); 
     Log.e(TAG, bm.toString()); 
     imageview.setImageBitmap(bm); 

    }// end of onCreate 


}//end of Activity 








<?xml version="1.0" encoding="UTF-8"?> 
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
        android:orientation="vertical" android:layout_width="match_parent" 
        android:layout_height="wrap_content" android:gravity="fill"> 


     <ImageView android:id="@+id/imageView1" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"></ImageView> 


    </RelativeLayout>    
+0

請提一下,什麼特定的行導致npe。 – 2011-03-14 15:10:38

+0

一個想法是你imageView爲null – Tima 2011-03-14 15:11:15

+0

@Vladimir lvanov imageview.setImageBitmap(bm);是破損的地方 – turtleboy 2011-03-14 15:13:50

回答

5

確保與android:id="@+id/imageView1"ImageView居然出現在res/layout/load.xml

+0

@Mathew Willis當我在添加代碼設置圖像之前運行它時,屏幕彈出正常。我怎麼能告訴圖像視圖在那裏。它在設計時在圖形佈局中出現 – turtleboy 2011-03-14 15:18:40

+0

嘗試將您的佈局粘貼到問題 – 2011-03-14 15:26:09

+0

我在代碼後粘貼了xml佈局文件,只需向下滾動即可。對不起,如果這不是你的意思。 – turtleboy 2011-03-14 15:28:08

相關問題