来自另一个方法的spinner setSelection()导致空指针异常

时间:2012-02-20 21:30:24

标签: android methods null

班级建设

protected Spinner tipSpinner;
private ArrayAdapter<CharSequence> adapterTip;

在setContentView(R.layout.main)之后的onCreate中;

Spinner spinner= (Spinner) findViewById(R.id.spinner);
    ArrayAdapter<CharSequence> adapterTip = ArrayAdapter.createFromResource(this, R.array.tipArray, android.R.layout.simple_spinner_item);   
    adapterTip.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapterTip);
    spinner.setSelection(14, true);
    spinner.setOnItemSelectedListener(new tipSelectorListener());

Spinner Listener

public class tipSelectorListener implements OnItemSelectedListener{

    public void onItemSelected(AdapterView<?> parent,View view, int pos, long id) {
            Toast.makeText(parent.getContext(), "TEST " +
                      parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
    }

    public void onNothingSelected(AdapterView parent){
        //Do Nothing
    }

}

EditText输入 - 在键更改时调用计算,更改微调器的值

billAmount = (EditText)findViewById(R.id.textLblBillAmount);
EditText billAmount = (EditText) findViewById(R.id.textLblBillAmount);

 billAmount.setOnKeyListener(new EditText.OnKeyListener() {
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        // If the event is a key-down event on the "enter" button
        if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
            (keyCode == KeyEvent.KEYCODE_ENTER)) {
          // Perform action on key press

            recalculate();
            //Spinner tipSpinner.setSelection(0, true);

            Toast toast = Toast.makeText(getBaseContext(), "TEST", Toast.LENGTH_SHORT);
            toast.show();

          return true;
        }
        return false;
    }
});

计算方法

public void recalculate(){
    // Recalculate Values of all
    tipSpinner.setSelection(0, true);

}

EditText更改时出现错误空指针,认为这有c

1 个答案:

答案 0 :(得分:3)

您没有初始化您的tipSpinner变量。

更改此代码:

Spinner spinner= (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapterTip = ArrayAdapter.createFromResource(this,
      R.array.tipArray, android.R.layout.simple_spinner_item);   
adapterTip.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapterTip);
spinner.setSelection(14, true);
spinner.setOnItemSelectedListener(new tipSelectorListener());

对此:

tipSpinner= (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapterTip = ArrayAdapter.createFromResource(this,
      R.array.tipArray, android.R.layout.simple_spinner_item);   
adapterTip.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
tipSpinner.setAdapter(adapterTip);
tipSpinner.setSelection(14, true);
tipSpinner.setOnItemSelectedListener(new tipSelectorListener());