Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't one add/remove items from an ArrayAdapter?

I am using an ArrayAdapter<CharSequence> to populate the items to list in a android.widget.Spinner. That works all fine.

But now I want to keep the list of items dynamic, i.e. I want to be able to add/remove items from the selection list at runtime. However, when I call adapter.add(item) or adapter.remove(item) I always get a UnsupportedOperationException, even though the Javadocs of the ArrayAdapter class describe these two methods as to be usable for exactly that intended purpose.

Is this a bug, really not implemented or what am I missing here?

like image 894
mmo Avatar asked Aug 13 '10 12:08

mmo


People also ask

How do I add items to ArrayAdapter?

Create a global ArrayList and add the contents to it using add() and pass it to ArrayAdapter. It's better to pass the List or String[] to ArrayAdapter and set that adapter to List You should update the List or Array being passed to Adapter, not Adapter itself.

How do I remove items from Listadapter?

Just call submitList with a new list, the diffutil will take care of the old list and the new list. If you add or remove something, add to your original list or remove an item from your list and then call submitList. you can call use adapter.

How do I use ArrayAdapter?

Go to app > res > layout > right-click > New > Layout Resource File and create a new layout file and name this file as item_view. xml and make the root element as a LinearLayout. This will contain a TextView that is used to display the array objects as output.


1 Answers

You probably initialized the adapter with a plain Java array (e.g., String[]). Try using something that implements the java.util.List interface (e.g., ArrayList<String>).

like image 127
CommonsWare Avatar answered Oct 21 '22 06:10

CommonsWare