Search code examples
androidspinner

Why am I getting null from spinner item?


I am new at Android. I am getting null value when I try to get spinner's selected item.

I tried to design two Spinners and when clicked the button, write one of the spinner's selected item into the text field. But I am getting null. Could you explain the reason of that?

public class EERActivity extends AppCompatActivity implements  
OnItemSelectedListener {
private Spinner spinner1; 
private Spinner spinner2; 
private String[] array1= {"xx","yy"};
private String[] array2= {"x2", "y2"};
private ArrayAdapter<String> dataAdapterForArray1;
private ArrayAdapter<String> dataAdapterForArray2;
String selected1;
String selected2;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_eer);

    spinner1 = (Spinner)findViewById(R.id.spinner2);
    spinner2 = (Spinner)findViewById(R.id.spinner3);

    dataAdapterForArray1 = new ArrayAdapter<String>(this, 
    android.R.layout.simple_spinner_item, array1);
    //and 2 is here..//

    spinner1.setAdapter(dataAdapterForArray1);
    spinner2.setAdapter(...filled...);

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, 
long id) {
    if(parent.getId() == R.id.spinner2) {
        selected1 = spinner1.getSelectedItem().toString();
    }

    else if(parent.getId() == R.id.spinner3){
        selected2 = spinner2.getSelectedItem().toString();
    }
    selectedSpinner1 = spinner1.getSelectedItem().toString();
    selectedSpinner2 = spinner2.getSelectedItem().toString();
}

public void onNothingSelected(AdapterView<?> arg0) {

}


public void run (View view){
textView.setText("Result: " + selected1);  }

I expect the output is selected from spinner1 but the result is null.


Solution

  • It's most likely that the event is being triggered before the value is actually changed in the spinner component. To solve this, you can add a null check. Try adding the following in the first line of your "onItemSelected" method:

    if ((parent.getId() == R.id.spinner2 && spinner1.getSelectedItem() == null) || (parent.getId() == R.id.spinner3 && spinner2.getSelectedItem() == null)) {
        return ;
    }

    Also, I'm not sure you posted the whole code, but this looks wrong:

    spinner1 = (Spinner)findViewById(R.id.spinner2);
    spinner2 = (Spinner)findViewById(R.id.spinner3);