Unable to modify ArrayAdapter in ListView: UnsupportedOperationException
Asked Answered
P

1

101

I'm trying to make a list containing names. This list should be modifiable (add, delete, sort, etc). However, whenever I tried to change the items in the ArrayAdapter, the program crashed, with java.lang.UnsupportedOperationException error. Here is my code:

ListView panel = (ListView) findViewById(R.id.panel);
String[] array = {"a","b","c","d","e","f","g"};
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, array);
adapter.setNotifyOnChange(true);
panel.setAdapter(adapter);

Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
      adapter.insert("h", 7);
   }
});

I tried insert, remove and clear methods, and none of them worked. Would someone tell me what I did wrong?

Pennington answered 8/7, 2010 at 3:51 Comment(0)
F
301

I tried it out myself and found it didn't work, so I checked out the source code of ArrayAdapter and found out the problem: The ArrayAdapter, on being initialized by an array, converts the array into an AbstractList (List<String>) which cannot be modified.

Solution Use an ArrayList<String> instead using an array while initializing the ArrayAdapter.

String[] array = {"a","b","c","d","e","f","g"}; 
ArrayList<String> lst = new ArrayList<String>(Arrays.asList(array));
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 
android.R.layout.simple_list_item_1, lst);
Fool answered 8/7, 2010 at 4:15 Comment(8)
Thank you so much! You saved me hours of frustration. Would you mind explain to me why String[] didn't work?Pennington
@Pennington you can't insert into an array, you can into a list, unless the list implementation doesn't allow it. If your backing data is not going to change, ArrayAdapter allows you to use a more memory efficient technique.Fenton
@Fool what difference it makes if I pass "new ArrayList<String>(Arrays.asList(array))" or just "Arrays.asList(array)"? The first works and the second doesn't.Contraception
@golosovsky, In the first one, you create a Mutable List, the second way creates a Immutable List. (cannot be modified once created)Fool
An insert in an array is quite possible, Arrays.copyOf and System.arraycopy will do the trick. I think a developer of the API was simply lazySarcenet
How will you update the reference of the original array that was passed to the adapter with the copy? It's a clean design decision, your comments are very callous.Fool
It's 2016 and still this ridiculous exception thrown at this specific scenario.Nea
Thanks so much! Can't believe they'll never document this out, or stop allowing immutables if they plan to provide something like notifyDatasetChangedHamiltonian

© 2022 - 2024 — McMap. All rights reserved.