setImageBitmap()抛出nullPointerExceprion

时间:2017-10-08 10:47:24

标签: android nullpointerexception

//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);

}
}

1 个答案:

答案 0 :(得分: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();
    }

}

我希望能帮助你。