How to validate a spinner?

0

Good afternoon. I'm making an Android application that has a form, and in that form there are spinners and answer text fields. Can anyone help me how do I check if the spinner has been selected?

    
asked by anonymous 09.09.2017 / 21:05

3 answers

1

It's a bit handy, but it's a solution that works well for me.

Add a blank item in the spinner, with default text, example, "Select an option." Then treat the spinner's setOnItemSelectedListener event and save the selected position. If it is different than the spinner's initial, the user 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 someone has any tips to increase the solution and leave it less than thank you.

    
11.09.2017 / 22:15
1

I ended up doing this legally to solve, so it already disconsider the spinner null, it worked. If there is a 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;
    }
}
    
20.09.2017 / 20:05
0

Hello,

So considering that your Spinner will have a default value null , a simpler way to validate it would look 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 for Android .

    
11.09.2017 / 23:16