2013-05-05 4 views
0

У меня есть девять кнопок, каждая из которых ударяет по номеру в 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; 
} 
} 
} 

ответ

1

место этот код

ditText 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); 

внутри onCreate() после setContentView

Поскольку

вы не получите ваши взгляды ссылки пока вы setContentView в onCreate(), поэтому, когда вы пытаетесь для получения справки за пределами onCreate() вы получите null ссылки, и доступ к null даст вам NullPointerException

Объявить как этот

Button clearbtn ,ninenum ,eightnum ,sevennum ,sixnum ,fivenum ,fivenum ,fournum ,threenum ,twonum ,onenum ,enterbtn ; 
EditText display; 

И в OnCreate()

setContentView(R.layout.activity_main); 

display = (EditText)findViewById(R.id.numdisplay); 
clearbtn = (Button)findViewById(R.id.clear); 
ninenum = (Button)findViewById(R.id.nine); 
eightnum = (Button)findViewById(R.id.eight); 
sevennum = (Button)findViewById(R.id.seven); 
sixnum = (Button)findViewById(R.id.six); 
fivenum = (Button)findViewById(R.id.five); 
fournum = (Button)findViewById(R.id.four); 
threenum = (Button)findViewById(R.id.three); 
twonum = (Button)findViewById(R.id.two); 
onenum = (Button)findViewById(R.id.one); 
enterbtn = (Button)findViewById(R.id.enter); 
0

Findviewbyid вернется только после того, как вы setcontentView, что макет. То, что вы делаете, это попытка извлечь нагрузку на класс.

Попробуйте добавить

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); 

после setContentView заявление

0

setContentview() используется для установки содержания активности в явном виде, поэтому перед ссылкой на вид вы не можете использовать элементы управления внутри.

попробовать ниже код

public class MainActivity extends Activity implements OnClickListener { 
EditText display; 
Button clearbtn,ninenum,eightnum,sevennum,sixnum,fivenum,fournum,threenum,twonum,onenum,enterbtn; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    display = (EditText)findViewById(R.id.numdisplay); 
    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; 
} 
} 
} 

надеюсь, что это помогает.

+0

Он по-прежнему бросает исключение. Это то, что произошло изначально, и я не знаю, почему. Я убедился, что onclicklisteners и edittext были добавлены после части SetContentView. – ThatGuyThere

+0

@ThatGuyThere: попробуйте заменить полный код с кодом выше ... если проблема остается, поместите свой журнал здесь –

Смежные вопросы