views:

163

answers:

2

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?

+1  A: 

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>).

CommonsWare
+1  A: 

Here's the source code of ArrayAdapter#remove:

public void remove(T object) {
    if (mOriginalValues != null) {
        synchronized (mLock) {
            mOriginalValues.remove(object);
        }
    } else {
        mObjects.remove(object);
    }
    if (mNotifyOnChange) notifyDataSetChanged();
}

The only thing that can throw an UnsupportedOperationException there is the line in the else-block. So the problem is that the list you're using doesn't support removing items. My guess is you're using an array. Try an ArrayList, for instance.

edit: So yeah, what Mark said...

benvd