Reputation: 13
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!
Upvotes: 1
Views: 193
Reputation: 28762
It is because you don't set the tvResponse
member variable. Instead you set a new local variable by the same name. So when you call setText()
, you are accessing an invalid reference
You need to change
final TextView tvResponse = (TextView) findViewById (R.id.tvResponse);
to
tvResponse = (TextView) findViewById (R.id.tvResponse);
to set the member variable, so it has a valid reference later on (when updateTV()
is called)
Upvotes: 3
Reputation: 1500535
I suspect you've got an instance variable called tvResponse
which you haven't shown us - that's what the updateTV
method will refer to. That's entirely separate from the local tvResponse
variable you've declared inside onCreate
. I suspect that if you change the last line of onCreate
from a local variable declaration to a simple assignment to the tvResponse
variable, it may work. Otherwise, if nothing is assigning a value to the instance tvResponse
variable, it will have the default value of null
, causing a NullPointerException
in updateTV
.
Upvotes: 1