Android全局变量java。lang.NullPointerException
我有两种方法使用相同的2个按钮+1个文本视图。比如:
public void startChange(View v) {
final Button start = (Button) findViewById(R.id.start);
final Button restart = (Button) findViewById(R.id.restart);
final TextView check = (TextView) findViewById(R.id.check);
//TO-DO part - Sets check to something based on buttons TagID
}
public void restartChange (View v) {
final Button start = (Button) findViewById(R.id.start);
final Button restart = (Button) findViewById(R.id.restart);
final TextView check = (TextView) findViewById(R.id.check);
//TO-DO part - Restars everything to basic position
}
一切都很顺利。。但当我制作这个按钮和textview全局变量时,我得到了java。lang.NullPointerException。 知道怎么修吗
编辑: 问题解决了。 你唯一需要做的就是在onCreate方法中定义按钮和文本视图,而不是在全局定义中
例如:
public class Example extends Activity {
Button start;
Button restart;
TextView t;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
start = (Button) findViewById(R.id.start);
restart = (Button) findViewById(R.id.restart);
check = (TextView) findViewById(R.id.check);
}
}
# 1 楼答案
您必须添加
setContentView(R.layout.main);
# 2 楼答案
问题解决了。 你唯一需要做的就是在onCreate方法中定义按钮和文本视图,而不是在全局定义中
例如: