javaandroidlistactivity

How to remove items from an adapter in Android ListActivity


I am writing an android app that needs to dynamically remove players from a soccer game roster in my listActivity. The Activity has an adapter that links to an array of Strings describing each player. I then try to remove a player from the list when clicked. My problem is that whenever I use the adapters built in methods to remove I keep getting this error.

 FATAL EXCEPTION: main
 java.lang.UnsupportedOperationException
 at java.util.AbstractList.remove(AbstractList.java:638);

As far as I can tell, I don't have the right to remove items from the adapter, but I don't get why since every example I have found online seems to work with no problems. This is the code I use to try and remove a single item from the adapter.

    public void onListItemClick(ListView l, View v, int position, long id)
{
    super.onListItemClick(l, v, position, id);

    adapter.remove(adapter.getItem(position));
    adapter.notifyDataSetChanged(); //Updates adapter to new changes
}

This is the code where I tried to change the data source for the adapter and notify it of changes in hopes it would update the onscreen list.

    public void onListItemClick(ListView l, View v, int position, long id)
{
    super.onListItemClick(l, v, position, id);

    mainRoster.removePlayer(position); //removes from custom roster
    stringedRoster = mainRoster.getStringArray();  //Resets string array
    adapter.notifyDataSetChanged(); //Updates adapter to new changes

}

If anybody can shine some light on what could be going on it would be much appreciated.


Solution

  • if you're using a List to store your Object and display them in a ListVeiw through the adapter, you've to use :

        public void onListItemClick(ListView l, View v, int position, long id)
    {
        super.onListItemClick(l, v, position, id);
    
        list.remove(position);
        adapter.notifyDataSetChanged(); //Updates adapter to new changes
    }
    

    This works fine