How to validate a spinner?

Asked

Viewed 679 times

0

Good afternoon. I’m making an Android application that has a form, and in this form there are spinners and response text fields. Someone can help me as I check if the spinner was selected?

3 answers

1

It’s kind of manly, but it’s a solution that works well for me.

Add a blank item in the spinner, with a default text, example, "Select an option". Then treat the setOnItemSelectedListener event from the spinner and save the selected position. If different from the initial spinner, the user has selected something.

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mSpinnerPos = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

If anyone has any tips to increase the solution and make it less manly I appreciate.

  • Good afternoon! Thank you very much for the suggestion, I am not using the Ner, because it is always active in the execution of the call, to avoid the use of memory I ended up making only the call to check. Plus your solution is quite interesting tbm, has a condition that I will use.

1

I ended up doing this manual way to solve, this way she already disconsidera the spinner null, it worked. If there is a better suggestion thank you.

boolean validaConfere = false;
if (spnConheceAbrigo.getSelectedItem().toString().equals("Sim")){
    if (listaAbrigoSolicitacao.size() == 0){
        validaConfere = false;
        imprimirAlertaAbrigos();
    }else {
        validaConfere = true;
    }
}
else if (spnConheceAbrigo.getSelectedItem().toString().equals("Não")){

    if (listaAbrigoSolicitacao.size() == 0){
        validaConfere = true;
    }else {
        listaAbrigoSolicitacao.clear();
        cbOcoArvore.setChecked(false);
        cbCaverna.setChecked(false);
        cbForroCasa.setChecked(false);
        cbTuneuTrem.setChecked(false);
        cbBueiro.setChecked(false);
        cbCasaVelha.setChecked(false);
        validaConfere = true;
    }
}

0

Hello,

So considering your Spinner will have a default value null, a simpler way to validate it would be like this:

String valor = null;

if(spinnerNome != null && spinnerNome.getSelectedItem() !=null ) {
   valor = (String) spinnerNome.getSelectedItem();
} else  { 
    //Spinner vazio
}

There are also more examples in this documentation of Android.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.