views:

91

answers:

1

Hi there, I'm trying to make a list containing names. This list should be modifiable (add, delete, sort...). However, whenever I tried to change the items in the ArrayAdapter, the program crash, 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) {
    // TODO Auto-generated method stub
    try{
    adapter.insert("h", 7);
    }catch (Exception e){
     String a = e.getMessage();
     Log.e("Array Adapter", a);
    }
   }
  });

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

+1  A: 

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>();
lst.addAll(Arrays.asList(array));
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 
android.R.layout.simple_list_item_1, lst); 

Cheers!

st0le
Thank you so much! You saved me hours of frustration. Would you mind explain to me why String[] didn't work?
Ryan
Added an edit... :) please read it again.
st0le
@Ryan 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.
Stephen Denne