Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spinner doesn't show array and texts

The spinner doesn't work. It didn't use to show arrow when I was just playing with it in design mode, it's not showing text after I implemented it with some code somehow.

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
Spinner spinner;
ArrayList spinnerArrayList;
ArrayAdapter spinnerAdapter;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    spinner = findViewById(R.id.spinner);
    spinnerArrayList = new ArrayList();
    spinnerAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item,spinnerArrayList);
    spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(spinnerAdapter);

    spinnerArrayList.add("Guitar");
    spinnerArrayList.add("Drums");
    spinnerArrayList.add("Keyboard");

}
like image 288
Himenez Avatar asked Jul 02 '26 06:07

Himenez


1 Answers

What you are doing is you are changing your ArrayList after setting up the adapter. So adapter doesn't know that the data is changed.

You can solve this in 2 ways :

  1. Add elements in the ArrayList before setting up the adapter

  2. Use notifyDataSetChanged() at the end of the code or whenever you change the ArrayList

Like this : spinnerAdapter.notifyDataSetChanged()

like image 73
Chetan Khanna Avatar answered Jul 04 '26 19:07

Chetan Khanna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!