У меня есть девять кнопок, каждая из которых ударяет по номеру в EditText, вроде калькулятора. Я просто делаю это как простой проект, но я продолжаю получать эти NullPointerExceptions. Если я запустил его только с предварительно созданным методом onCreate(), он, похоже, работает, но как только я начну объявлять переменные под объявлением класса, он выдает некоторые исключения. Любая помощь приветствуется. Благодарю.Получение NullPointerException во время запуска
public class MainActivity extends Activity implements OnClickListener {
EditText display = (EditText)findViewById(R.id.numdisplay);
Button clearbtn = (Button)findViewById(R.id.clear);
Button ninenum = (Button)findViewById(R.id.nine);
Button eightnum = (Button)findViewById(R.id.eight);
Button sevennum = (Button)findViewById(R.id.seven);
Button sixnum = (Button)findViewById(R.id.six);
Button fivenum = (Button)findViewById(R.id.five);
Button fournum = (Button)findViewById(R.id.four);
Button threenum = (Button)findViewById(R.id.three);
Button twonum = (Button)findViewById(R.id.two);
Button onenum = (Button)findViewById(R.id.one);
Button enterbtn = (Button)findViewById(R.id.enter);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onclicks(); //setting all the onclick listeners
}
public void onclicks() { //just setting onclick listeners, so it doesn't bloat up the oncreate method
clearbtn.setOnClickListener(this);
ninenum.setOnClickListener(this);
eightnum.setOnClickListener(this);
sevennum.setOnClickListener(this);
sixnum.setOnClickListener(this);
fivenum.setOnClickListener(this);
fournum.setOnClickListener(this);
threenum.setOnClickListener(this);
twonum.setOnClickListener(this);
onenum.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.clear: /** More switch cases will be put here*/
display.setText("");
break;
}
}
}
Он по-прежнему бросает исключение. Это то, что произошло изначально, и я не знаю, почему. Я убедился, что onclicklisteners и edittext были добавлены после части SetContentView. – ThatGuyThere
@ThatGuyThere: попробуйте заменить полный код с кодом выше ... если проблема остается, поместите свой журнал здесь –