2017-10-08 154 views
-4
//setImageBitmap gives nullPointerException 

public class MainActivity extends ActionBarActivity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    try { 
     BitmapFactory.Options bitmapOptions = new BitmapFactory.Options(); 
     bitmapOptions.inSampleSize = 2; 
     Bitmap imageBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.img, bitmapOptions); 
     //imageView for referencig imageView of layout file 
     ImageView imageView=(ImageView)findViewById(R.id.imageView1);  
     imageView.setImageBitmap(imageBitmap); 
     //setImageBitmap gives nullPointerException 
    }catch (Exception e){ 
     e.printStackTrace(); 
    } 

    //setContentView(imageView); 
    setContentView(R.layout.activity_main); 

} 
} 

回答

0

這是發生,因爲您致電以下功能

setContentView(R.layout.activity_main); 

意見不被初始化。用下面的代碼重新編碼你的代碼。

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    try { 
     BitmapFactory.Options bitmapOptions = new BitmapFactory.Options(); 
     bitmapOptions.inSampleSize = 2; 
     Bitmap imageBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.img, bitmapOptions); 
     //imageView for referencig imageView of layout file 
     ImageView imageView=(ImageView)findViewById(R.id.imageView1); 
     imageView.setImageBitmap(imageBitmap); 
     //setImageBitmap gives nullPointerException 
    }catch (Exception e){ 
     e.printStackTrace(); 
    } 

} 

我希望能幫到你。