-2

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

}           
klipach
  • 818
  • 7
  • 21
  • Try to run your app not in debugger. – kukido Dec 13 '13 at 19:45
  • Why does the debugger stop at `tv.setText(x)`? Is there a breakpoint there? Does the debugger tell you why it stopped? Was any message displayed? – Eric Dec 13 '13 at 19:54

1 Answers1

0

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);
Alexis C.
  • 91,686
  • 21
  • 171
  • 177