Andrew T Andrew T - 2 months ago 9
Android Question

display the selected string from android spinner

String chooseTime[] = {"7.00 - 9.00", "9.00 - 11.00", "11.00 - 13.00", "13.00 - 15.00", "15.00 - 17.00", "17.00 - 18.30" };
spTimeConsegna = (Spinner)
rootView.findViewById(R.id.timeChooseConsegna);
adapterChooseTimeConsegna = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, chooseTime);
adapterChooseTimeConsegna.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spTimeConsegna.setAdapter(adapterChooseTimeConsegna);

chooseTimeConsegna = chooseTime[spTimeConsegna.getSelectedItemPosition()];


I want to save the selected value of the spinner in the chooseTimeConsegna String, but it always saves the first value of the chooseTime string array indifferently what is choosen in the spinner. Why?

Answer

I think you are doing this in onCreate method, so it's only called when that activity is started, not every time you select things on spinner. Try something like this:

yourSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
        String chooseTime[] = {"7.00 - 9.00", "9.00 - 11.00", "11.00 - 13.00", "13.00 - 15.00", "15.00 - 17.00", "17.00 - 18.30" };
        chooseTimeConsegna = chooseTime[position];
    }

    @Override
    public void onNothingSelected(AdapterView<?> parentView) {
    }
});

This method is gonna be called every time you select something on your spinner, and argument position is the position of the selected item in the spinner.