Search code examples
androidspinnerandroid-databinding

How to update spinner items dynamically using databinding


I am applying custom spinner using data binding. I was passing array previously from resource string array , now I am fetching data from the server and i need to put that array to the spinner, so how i can do it dynamically? Like here I am using android:entries attribute Issue:How can I update my spinner values when if fetch data from API?

  <data>

    <variable
        name="model"
        type="com.abc.online.viewmodels.StoreHomeViewModel" />
</data>
<Spinner
                android:id="@+id/isspSelectCity"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:entries="@array/country_code_list"
                android:gravity="center"
                android:onItemSelected="@{(parent,view,pos,id)->model.onCitySelectItem(parent,view,pos,id)}" />
        </LinearLayout>

I am replacing

android:entries="@array/country_code_list"

with

android:entries="@{model.fetchCountriesCode()}"

Here is function for getting cities

    public List<String> fetchCountriesCode(){
    List<String> list=new ArrayList<>();
    if (getCitiesObj().getValue()!=null) {
        Result[] cities = getCitiesObj().getValue().get(0).getResult();
        for (Result cit : cities) {
            list.add(cit.getName());
        }
    } return list;}

android:entries take values if we have already list before rendering, it does not take/update values after rendering. so How can I do that?


Solution

  • I prefer to use LiveData. From document: Create an instance of LiveData to hold a certain type of data. This is usually done within your ViewModel class. Create an Observer object that defines the onChanged() method, which controls what happens when the LiveData object's held data changes. You usually create an Observer object in a UI controller, such as an activity or fragment.

    Attach the Observer object to the LiveData object using the observe() method. The observe() method takes a LifecycleOwner object. This subscribes the Observer object to the LiveData object so that it is notified of changes. You usually attach the Observer object in a UI controller, such as an activity or fragment.

    When you update the value stored in the LiveData object, it triggers all registered observers as long as the attached LifecycleOwner is in the active state.

    LiveData allows UI controller observers to subscribe to updates. When the data held by the LiveData object changes, the UI automatically updates in response.

        class Foo : ViewModel() {
      ...
      private val mSpinnerData = MutableLiveData<List<String>>()
      ...
      fun fetchSpinnerItems(): LiveData<List<String>> {
        //fetch data
        mSpinnerData.value = <some fetched list of Strings>
        return mSpinnerData
      }
    }