I am trying to set a spinner value that has been passed from another Fragment. This spinner is populated with data from a LiveModel and I want just set the index of the spinner to the String value passed.
Currently the code below gives me the default value of the spinner as the line below returns -1;
spinner.setSelection(adapter.getPosition(holidaySelected));
Can anyone see why this is returning -1 and not the position of the adapter at which the value sits?
I have read this thread: How to set selected item of Spinner by value, not by position?
public class PlaceInputFragment extends Fragment {
private String holidaySelected;
private HolidayViewModel holidayViewModel;
private List<String> holidayNames;
private Spinner spinner;
private ArrayAdapter<String> adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
holidayNames = new ArrayList<>();
spinner = v.findViewById(R.id.spinner);
adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item, holidayNames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
holidayViewModel = ViewModelProviders.of(this).get(HolidayViewModel.class);
holidayViewModel.getAllHolidays().observe(this, new Observer<List<Holiday>>() {
@Override
public void onChanged(@Nullable final List<Holiday> holidays) {
for (Holiday holiday : holidays) {
holidayNames.add(holiday.getName());
}
adapter.notifyDataSetChanged();
}
});
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (getArguments() != null) {
spinner = v.findViewById(R.id.spinner);
holidaySelected = getArguments().getString("Holiday");
spinner.setSelection(adapter.getPosition(holidaySelected));
}
}