Android: problems with getSelectedItem on a spinner

Marcellino247 picture Marcellino247 · Apr 30, 2015 · Viewed 8.3k times · Source

I have a Spinner, and put the selected item in the body of a mail. this is my code:

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

    Spinner spinnerTaglia = (Spinner) findViewById(R.id.spinnerTaglia);

// Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,     R.array.Taglie, android.R.layout.simple_spinner_item);

// Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnerTaglia.setPrompt("Seleziona la taglia!");

// Apply the adapter to the spinner
    spinnerTaglia.setAdapter(new NothingSelectedSpinnerAdapter(
            adapter,
            R.layout.contact_spinner_row_nothing_selected,
            // R.layout.contact_spinner_nothing_selected_dropdown, // Optional
            this));

    final String taglia = spinnerTaglia.getSelectedItem().toString();


    Button btnCompilaOrdine = (Button) findViewById(R.id.btnCompilaOrdine);
    btnCompilaOrdine.setOnClickListener(new View.OnClickListener(){

        public void onClick(View arg0) {

    Intent i = new Intent(Intent.ACTION_SEND);
    i.setType("message/rfc822");
    i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"[email protected]"});
    i.putExtra(Intent.EXTRA_SUBJECT, "MAIL OBJECT");
    i.putExtra(Intent.EXTRA_TEXT   , "Taglia: "+taglia);
    try {
        startActivity(Intent.createChooser(i, "Send mail..."));
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(Modulo.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
    }

    }
    });
}

The application start correctly in the emulator and the debugger show me nothing (I'm using Android Studio) but when i click on the button that take me in this activity the application crash and the Android Studio's Debugger show me a java.lang.NullPointerException in the row:

final String taglia = spinnerTaglia.getSelectedItem().toString();

how can i fix this?

Answer

Blackbelt picture Blackbelt · Apr 30, 2015

getSelectedItem() returns null if there is nothing selected on your spinner and calling toString() is making your application crash. Get rid of

final String taglia = spinnerTaglia.getSelectedItem().toString();

and in your onClick do:

if (spinnerTaglia.getSelectedItem() == null) {
      return;
}
String taglia = spinnerTaglia.getSelectedItem().toString();
// the other code