I have a following Spinner in the OnCreate Method:
spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, accounts);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spinner.setAdapter(spinnerArrayAdapter);
spinner.setOnItemSelectedListener(this);
and I want add some entries to the Spinner in a other Method like this:
spinnerArrayAdapter.add(value.toString());
spinner.setAdapter(spinnerArrayAdapter);
but the app crashes. What can I do?
Thanks!
You have 2 possibilities:
Either:
in place where you are about to add new record to adapter:
spinnerArrayAdapter.add("Your new item");spinnerArrayAdapter.notifyDataSetChanged();Or:
In your onCreate when initialising adapter add
spinnerArrayAdapter.setNotifyOnChange(true);when you want to add record to adapter later simply call
spinnerArrayAdapter.add("Your new item");. No need to callnotifyDataSetChanged()as it has been called byaddinternally.in both cases you don’t have to re-assign adapter to spinner.
if you initialize your adapter with array, add method will raise exception, as what adapter stores internally is
(List<T>) Arrays.asList(objects)whereobjectsis the array you provided in constructor.asListreturns the List interface wrapper implementation over the array so it does not support add opeation. In order to be able to use adapter’s add method you must provide the backing data as List with supported add/remove methods – i suggest ArrayList.so in your case init it like that:
or longer but more efficent (e.g. you do not create
overhead list object to be abandoned a moment later)