Reputation: 862
I am trying to repopulate a Spinner
after values have been removed.
Currently the app sets up a Spinner
with a list of string values and then as the app is used some of these values are removed from the ArrayAdaptor
. Then at some point the Spinner
's list needs to be reset with the default list of values. My current code simply creates a new ArrayAdaptor
and assigns this to the Spinner
using the same string array resource that the Spinner
is initially set up with:
Spinner mySpinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
Static.itemList);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(arrayAdapter);
Where Static.itemlist
is an array of type String[]
.
As it stands items are removed from the spinner but using the above code will not reset the Spinner
's values to the list stored in Static.itemList
. In my mind this should work but am clearly missing something as it does not.
Full code can be found at https://github.com/Uruwolf/VO-Miner/blob/master/src/com/uruwolf/vominer/VoMinerActivity.java The method in question is from line 142 to 147 (and I know that the indentation is off, it looks fine in my editor. I am not sure why it is not right on github).
This is my first ever question on StackOverflow so please let me know if I have done something wrong.
Upvotes: 1
Views: 4453
Reputation: 2101
You may need to call notifyDataSetChanged() on the adapter after changing the list.
I think a better approach would be to avoid re-creating a new adapter and call notifyDataSetChanged() after you've re-added the data to the main list. You don't actually need to re-create the adapter, as nothing in the adapter is changing except the the list of data that the adapter points to. Since the adapter just points to a list and doesn't consume/contain the list itself, if you change the referenced list, the adapter should be able to pick up the changes (when notified).
Something like this may work
Define variables
Static.itemlist ... /*This list is static. Data never changes */
List<String> myListOfStrings;
ArrayAdapter<String> arrayAdapter;
Initialize the spinner and adapter
Spinner mySpinner = (Spinner) findViewById(R.id.spinner);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myListOfStrings);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(arrayAdapter);
Refreshing the adapter
myListOfStrings.clear();
myListOfStrings.addAll(Static.itemList); = /* Copy/Add the data from Static.itemList into myListOfStrings */
arrayAdapter.notifyDataSetChanged(); /* Inform the adapter we've changed items, which should force a refresh */
Upvotes: 3