Question

can u tell me why this code is not working? The app stops as soon as I click on Image(Imageview1). Debugger points to tv.setText(x);

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final TextView tv = (TextView)findViewById(R.id.textView1);
setContentView(R.layout.activity_main);
ImageView img = (ImageView) findViewById(R.id.imageView1);
img.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        String x="You clicked on the image.";
            tv.setText(x);
        }
    });

}           
Was it helpful?

Solution

You need to get your UI elements after inflating your layout, otherwise findViewById returns null and hence the NPE is thrown when you try to set the text on your textView.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);                       /// I swap these two lines
    final TextView tv = (TextView)findViewById(R.id.textView1);   ///
    ImageView img = (ImageView) findViewById(R.id.imageView1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top