[英]Why does program stop unexpectedly?
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. 我正在编写一个非常基本的程序,旨在使文本视图在屏幕上按下按钮后显示短语“Hello”,但无法弄清楚为什么每次运行它时,它都说应用程序意外停止了。
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. 另外,我在我的main.xml文件中插入了一个
android:onClick = "updateTV"
按钮。
Thanks for any help! 谢谢你的帮助!
It is because you don't set the tvResponse
member variable. 这是因为你没有设置
tvResponse
成员变量。 Instead you set a new local variable by the same name. 而是使用相同的名称设置新的局部变量。 So when you call
setText()
, you are accessing an invalid reference 因此,当您调用
setText()
,您正在访问无效的引用
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) 设置成员变量,以便稍后有一个有效的引用(当
updateTV()
时)
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. 我怀疑你有一个名为
tvResponse
的实例变量,你没有向我们展示过 - 这就是updateTV
方法所指的内容。 That's entirely separate from the local tvResponse
variable you've declared inside onCreate
. 这与您在
onCreate
声明的本地 tvResponse
变量完全分开。 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. 我怀疑如果你将
onCreate
的最后一行从局部变量声明更改为tvResponse
变量的简单赋值,它可能会起作用。 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
. 否则,如果没有为实例
tvResponse
变量赋值,则它将具有默认值null
,从而在updateTV
导致NullPointerException
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.