Natheem Safin Natheem Safin - 4 months ago 24
Android Question

How to update data in Spinner Dynamically in Android?

i have added my data in array.xml file and link to

<string-array name="state">
<item>ANDAMAN NICOBAR ISLANDS</item>
<item>ANDHRA PRADESH</item>
<item>ARUNACHAL PRADESH</item>

<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/drpstate"
android:entries="@array/state"/>


i want to change this entries dynamically

thanks in advance ..

Answer

Use adapter.add() to add data and then call adapter.notifyDataSetChanged() to apply changes.

    Spinner spinner = (Spinner)findViewById(R.id.mySpinner);
    List<String> list = Arrays.asList(getResources().getStringArray(R.array.state));

    ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
    spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(spinnerAdapter);
    spinnerAdapter.add("DELHI");
    spinnerAdapter.notifyDataSetChanged();