Unable to modify ArrayAdapter in ListView: UnsupportedOperationException

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?

  • How to listen to doubletap on a view in android?
  • Bluetooth not sending file to other device
  • Android NDK - write only in C/C++
  • Adding my own keyboard instead of default keyboard in Android device as input
  • c2dm 401 error when sending messages after receiving id and auth token
  • Should I inflate a layout or programmatically create it?
  • Related posts:

    What does this mean: Failure ?
    Libgdx game crashes on Android
    how to make httpPost call with json encoded body?
    Is there an SQLite database viewer tool in Eclipse?
    Why is getCount called so many times in PagerAdapter?
    Call .NET Webservice with Android
  • Can I call stopSelf() in Service.onStartCommand?
  • Android Material Design Datepicker with AppCompat
  • How to select the first item in a navigation drawer and open a fragment on application start
  • How to get access token after user is signed in from Gmail in Android?
  • How to show progress dialog in Android?
  • How to set edittext preference summary and have it stick
  • One Solution collect form web for “Unable to modify ArrayAdapter in ListView: UnsupportedOperationException”

    I tried it out, myself…Found it didn’t work. So i check out the source code of ArrayAdapter and found out the problem. The ArrayAdapter, on being initialized by an array, converts the array into a AbstractList (List) 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); 
    

    Cheers!

    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.