2012-01-29 49 views
0

我想使用微調器中的「值」。從微調器中提取值並將其用於計算 - NullPointerException

當用戶做出選擇我想要使用該值來做一些計算。

我的問題是:

1)如何正確地得到。我現在用的某事像 「item.MyOnItemSelectedListener == 0」 的值(項)。

2)什麼值應該是?例如,上面我有== 0。這意味着從微調列表的第一選擇?

代碼:

public class number_cores extends Activity implements OnClickListener { 
    .. 
    final Spinner spinner = (Spinner) findViewById(R.id.spinner); 

     ... 
    public void onCreate(Bundle savedInstanceState) { 
.... 


//spinner-drop_list 
     ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
       this, R.array.init_or_final, android.R.layout.simple_spinner_item); 
     adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
     spinner.setAdapter(adapter); 
     spinner.setOnItemSelectedListener(new MyOnItemSelectedListener()); 
    } 
... 
public void cores_func(){ 
      ... 
      double fcores=0; 

      MyOnItemSelectedListener obj=new MyOnItemSelectedListener(); 

     if (obj.getPosition()==0) fcores=initcores*Math.exp(-l*ttime); 
     else if (obj.getPosition()==1) fcores=initcores/Math.exp(-l*ttime); 

..} 

//spinner class 

     public class MyOnItemSelectedListener implements OnItemSelectedListener { 

      private int position; 
     public int getPosition() {return position;} 

      public void onItemSelected(AdapterView<?> parent, 
       View view, int pos, long id) { 
       position=pos; 

      } 

      public void onNothingSelected(AdapterView <?> parent) { 
       // Do nothing. 
      } 
     } 

謝謝!

+0

試過spinner.getSelectedItem()?? – 2012-01-29 18:21:38

+0

問題是如何使用我在MyOnItemSelectedListener中創建的項目對象。 – George 2012-01-29 18:29:30

+0

int或字符串?..你可以使用toString()作爲字符串或使用Integer.parseInt smthn那樣 – 2012-01-29 18:30:54

回答

1

現在,您所做的只是爲對象項分配微調器中所選項目的值。您無法在任何可以訪問的位置保存該值。

若要解決此問題,請在您的OnItemSelectedListener中將所選值或位置保存在一個字段中。通過偵聽器中的getter方法訪問它,並返回值。在onItemSelected方法中,每次用戶更改微調器的值時都會設置該值。在Activity中,通過getter方法通過偵聽器訪問保存的值。

例如: 如果你想獲得所選項目的位置,添加private int position;public int getPosition() {return position;}作爲監聽器類的字段和方法(分別),並在onItemSelected方法position = pos;保存價值。如果你想要的話,保存對象是一個類似的想法。在您的應用程序中,如果列表中的第一項是選定項目,則listenerName.getPosition() == 0將爲真,因此您可以使用它執行邏輯。

+0

:我試過了。我把spinner類放在「public int position」然後在「onItemSelected」我把「position = pos「。然後,在我的cores_func中,我做了」if(spinner.position == 0)「,但它說」無法解析或不是字段「 – George 2012-01-29 19:23:41

+0

:現在它給了我」getPosition()方法未定義爲Spinner類型「。謝謝! – George 2012-01-29 19:33:49

+0

你把它叫做你的聽衆,而不是你的微調。抱歉,是我的錯。 – AJcodez 2012-01-29 19:48:19

相關問題