How to update a spinner dynamically?

Viewed 64145

I've been trying to update my spinner in android dynamically but nothing I try has been working.

This is the following code I'm using to update the spinner.

typeList = dbAdapter.getList(); //array list with the values

adapter.notifyDataSetChanged();
groupSpinner.postInvalidate();
groupSpinner.setAdapter(adapter);

The values of typeList are correct but they're not being updated in the Spinner.

11 Answers

Change the underlying data and call the notifyDataSetChanged() on adapter.

   list.clear();
  list.add("A");
      list.add("B");
  dataAdapter.notifyDataSetChanged();

First of all, you have to initialize the adapter with ArrayList<T>. Otherwise, you might get an exception.

val list: ArrayList<String> = arrayListOf()
private lateinit var spinnerAdapter:  ArrayAdapter<String>

After that initialize the adapter:

spinnerAdapter = ArrayAdapter<String>(requireContext(),
        android.R.layout.simple_spinner_item,
        list) // initialize with empty arrayList
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
    binding.spinnerCurrency.apply {
        adapter = spinnerAdapter
}

After that when you have data clear and add all list.

 spinnerAdapter.clear()
 spinnerAdapter.addAll(list)
    
Related