添加setonclick侦听器方法后出现错误:
CODE:
ImageView first, second_img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
first = (ImageView) findViewById(R.id.first_image);
second_img = (ImageView)findViewById(R.id.second_image);
setContentView(R.layout.main);
first.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent get_img = new Intent();
get_img.setType("image/*");
get_img.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(get_img, "Select Picture"), 1);
}
});
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.anonymous);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bytes = stream.toByteArray();
//for(byte bite: bytes){
// System.out.println("@@@: " + bite);
//}
Bitmap second_bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
second_img.setImageBitmap(second_bmp);
}
ERROR:
Process: com.example.example, PID: 3100
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.example/com.example.example.example}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
我不知道发生了什么,有人帮助我,谢谢你的帮助,谢谢。
答案 0 :(得分:3)
正确的顺序应该是:
setContentView(R.layout.main);
first = (ImageView) findViewById(R.id.first_image);
second_img = (ImageView)findViewById(R.id.second_image);
否则,first和second_img将为null。