I’m writing a very basic program that aims for the text view to display the phrase “Hello” after a button is pressed on the screen, but cannot figure out why every time I run it, it says that the application has stopped unexpectedly.
This is the program I wrote:
public class EtudeActivityActivity extends Activity{
TextView tvResponse;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView tvResponse = (TextView) findViewById (R.id.tvResponse);
}
public void updateTV(View v) {
tvResponse.setText("Hello");
}
}
Also, I inserted an android:onClick = "updateTV" into my main.xml file for the button.
Thanks for any help!
It is because you don’t set the
tvResponsemember variable. Instead you set a new local variable by the same name. So when you callsetText(), you are accessing an invalid referenceYou need to change
to
to set the member variable, so it has a valid reference later on (when
updateTV()is called)