2011-03-28 87 views
1

我是應用程序開發的初學者。我的問題是,當我運行我的應用程序,然後點擊計算按鈕時,程序停止。代碼:按鈕單擊問題

public class screen1 extends Activity { 
    private EditText name; 
    private CheckBox box1; 
    private Spinner spinner; 
    private TextView text1, text2, text3, text4, text5, text6; 
    private Button calcbutton, closebutton; 
    String strength; 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     Spinner hubSpinner = (Spinner) findViewById(R.id.myspinner); 
     ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.military_ranks , android.R.layout.simple_spinner_item); 
     adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
     hubSpinner.setAdapter(adapter); 

     name = (EditText)findViewById(R.id.editText1);  
     strength = name.getText().toString(); 

     box1 = (CheckBox)findViewById(R.id.checkBox1); 

     text1 = (TextView)findViewById(R.id.textView4); 
     text2 = (TextView)findViewById(R.id.textView6); 
     text3 = (TextView)findViewById(R.id.textView8); 
     text4 = (TextView)findViewById(R.id.textView10); 
     text5 = (TextView)findViewById(R.id.textView12); 
     text6 = (TextView)findViewById(R.id.textView14); 

     final Button calcbutton = (Button) findViewById(R.id.button1); 
     calcbutton.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       int str = Integer.valueOf(strength); 
       int rank = spinner.getSelectedItemPosition()+1; 
       double sebzes; 
       if(box1.isChecked()){ 
        sebzes = (((rank-1)/20+0.3)*((str/10)+40))*1*(1+1/100); 
        text1.setText(Double.toString(sebzes)); 
       } 
       else{ 
        sebzes = (((rank-1)/20+0.3)*((str/10)+40))*1; 
        text1.setText(Double.toString(sebzes)); 
       } 
      } 
     }); 

     final Button closebutton = (Button) findViewById(R.id.button2); 
     closebutton.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       finish(); 
      } 
     }); 
    } 
} 

edittext組件中,您應該只能寫數字。我不知道爲什麼它不起作用。

+0

你必須發佈你的日誌。然後我們可以看到編碼失敗。我認爲這是一個問題:int str = Integer.valueOf(strength); – RoflcoptrException 2011-03-28 22:59:01

+0

突然編輯出現了什麼情況?那個彈出窗口太可怕了。 – MusiGenesis 2011-03-28 23:01:09

+0

我在說StackOverflow,而不是你的代碼示例(它根本不可怕)。 :) – MusiGenesis 2011-03-28 23:02:04

回答

1

問題是這兩行:

int str = Integer.valueOf(strength); 
int rank = spinner.getSelectedItemPosition()+1; 

,如果你在你的EditText只使用數字的第一個不會失敗,但它會更好地保證或至少趕上拋出異常時您嘗試將字符轉換爲數字值。此外,您也可以使用Integer.valueOf(strength).intValue();,即使如此,它通常不是真的有必要。

真正的問題是第二行。你聲明瞭變量spinner,但你永遠不會實例化它。這就是爲什麼你會在那裏得到一個NullPointerException。

在不相關的說明上:您還應該用大寫字母開頭,以遵循Java命名約定。

+1

+1用於回答沒有logcat輸出 – 2011-03-28 23:04:23

0

你沒有在任何地方實例化spinner,但是你在第二行按鈕點擊方法中引用它。可能是空引用問題。