Tarun Bisht Tarun Bisht - 2 months ago 12
Java Question

How to get the spinner value not in integer but in character

public class MainActivity extends AppCompatActivity {

Spinner spinner;
ArrayAdapter<CharSequence> adapter;

int noc = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner =(Spinner)findViewById(R.id.spinner);
String text= spinner.getSelectedItem().toString();
adapter= ArrayAdapter.createFromResource(this,R.array.Coffee_names,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(),parent.getItemIdAtPosition(position) + " is selected",Toast.LENGTH_SHORT).show();

}

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

}
});
}


My app stops when i add " String text= spinner.getSelectedItem().toString(); " to my code but it works fine when i remove this line from the program. But when i select a item from dropdown list it says 4 is selected.
I want it to say the name of the item i selected and not the index value.
Please help.

Answer

I think it should be:

Toast.makeText(getBaseContext(), parent.getSelectedItem() + " is selected", Toast.LENGTH_SHORT).show();