2010-01-25 52 views
0
import android.app.Activity; 
import android.os.Bundle; 
import android.view.KeyEvent; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.ArrayAdapter; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.Spinner; 
import android.widget.SpinnerAdapter; 
import android.widget.TextView; 

public class calctest extends Activity { 
/** Called when the activity is first created. */ 
private EditText input; 
private EditText input2; 
private EditText input3; 
private EditText input4; 
private TextView output; 
private TextView output2; 
private Spinner aperture; 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

// Extract the text fields from the XML layout 
    input = (EditText) findViewById(R.id.input1); 
    input2 = (EditText) findViewById(R.id.input2); 
    input3 = (EditText) findViewById(R.id.input3); 
    input4 = (EditText) findViewById(R.id.input4); 
    output = (TextView) findViewById(R.id.result); 
    output2 = (TextView) findViewById(R.id.result2); 

    //aperture dropdown 
    final Spinner aperture = (Spinner) findViewById(R.id.apt); 
    ArrayAdapter adapter = ArrayAdapter.createFromResource(
    this, R.array.apertures, android.R.layout.simple_spinner_item); 
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
    aperture.setAdapter(adapter); 

    Spinner mode = (Spinner) findViewById(R.id.mode); 
    ArrayAdapter adapter2 = ArrayAdapter.createFromResource(
    this, R.array.formats, android.R.layout.simple_spinner_item); 
    adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
    mode.setAdapter(adapter2); 

    // Perform calculation when button is pushed 

    final Button button = (Button) findViewById(R.id.calculate); 
    button.setOnClickListener(new View.OnClickListener() {    
     public void onClick(View v) {     
      doCalculation(aperture.getSelectedItem()); 
       }   
      }); 
     } 


private void doCalculation(Object selectedItem) { 
    // Get entered input value 
    String cinput1 = input.getText().toString(); 
    String cinput2 = input2.getText().toString(); 
    String cinput3 = input3.getText().toString(); 
    String cinput4 = input4.getText().toString(); 
    Object cinput5 = aperture.getSelectedItem(); 
} 

}在計算中調用Spinner值時,應用程序崩潰了嗎?

我知道doCalculation方法心不是實際計算任何東西,因爲應用程序崩潰剛從試圖讓輸入的值。如果我禁用cinput5行,它工作得很好。我在這裏做錯了什麼?在那個筆記上,我如何將微調器的值轉換爲一個字符串用於計算?

此外,作爲一個雙重檢查...微調器顯示數字列表(1.4,2,2.8,4,5.6等),無論選擇哪個數字,都是我需要用於計算的數字。我正在調整微調器的正確值,對吧?

我爲可能非常明顯的錯誤表示歉意。我剛開始Java,並在我完成這個應用程序是承諾我會得到一本書!

回答

2

您聲明aperture兩次,一次在您的代碼的開頭,一次在onCreate方法中。

在這一行:

final Spinner aperture = (Spinner) findViewById(R.id.apt); 

嘗試刪除final Spinner

當應用程序到達doCalculation方法的最後一行時,很可能會拋出一個空對象引用,因爲它引用了尚未實例化的專用光圈實例。

+0

非常感謝!我有一天會得到這個機會...... – Sean 2010-01-25 23:09:16

相關問題