Android - How to set a selected item from a Spinner to a string?

Asked

Viewed 2,704 times

1

I have a question in my code, I’m trying to take the value of Spinner and record it in the bank, but I can’t make the spinner have String value. In case he’s giving me error at the time of setText, at the end of the code. " Cannot resolve method 'setText(java.lang.String)'"

public class editarContato extends Activity {

Spinner spinner; String[] arraySpinner;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.editar_contato);

spinner = (Spinner) findViewById(R.id.spinner);
this.arraySpinner = new String[] {"SP", "RJ", "SC"};

ArrayAdapter<String> adapter = new ArrayAdapter<String>
    (this, android.R.layout.simple_spinner_item, arraySpinner);
spinner.setAdapter(adapter);

btAtualizar   =  (Button) findViewById(R.id.atualizar);

carregaDetalhesContato();

btAtualizar.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            datasource = new DBAdapter(editarContato.this);
            datasource.open();
            contato = datasource.getContato(idContato);
            datasource.close();
            datasource.AlterarContato(spinner.getSelectedItem().toString());
            datasource.close();
}
});

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        public void onItemSelected(AdapterView parent,View view, int pos, long id) {
            Object item = parent.getItemAtPosition(pos);
        }
        public void onNothingSelected(AdapterView parent){}
    });
}

public void carregaDetalhesContato() {

    idContato = getIntent().getIntExtra("id", 0);

    datasource = new DBAdapter(this);
    datasource.open();
    contato = datasource.getContato(idContato);
    datasource.close();

spinner.setText(contato.getSpinner());
}

}

1 answer

3


The class Spinner does not have the method setText. For this you can use the method setSelection(int index). For example, set selection to SP:

spinner.setSelection(adapter.getPosition("SP"))

Browser other questions tagged

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