UnsupportedOperationException with ArrayAdapter.remove [duplicate]

醉酒当歌 提交于 2019-11-26 21:58:00

问题


This question already has an answer here:

  • Unable to modify ArrayAdapter in ListView: UnsupportedOperationException 1 answer

In my code I have a ListActivity. One of the context menu options for a list item is "delete", which opens a dialog confirming the action. I intended to implement this functionality by first deleting the item's data in the database and then removing it from the ArrayAdapter. It is in removing it from the ArrayAdapter that I get an UnsupportedOperationException...

public void onClick(DialogInterface dialog, int id) 
{
    asynchronousDeleteEntry(CONTEXT_SELECTED_ID);
    dialog.dismiss();                          

    //I -know- that the adapter will always be an object
    //of ArrayAdapter<JournalEntry> because this is the only type
    //I ever call setListAdapter with.  Debugging confirms this
    @SuppressWarnings("unchecked")
    final ArrayAdapter<JournalEntry> adapter = (ArrayAdapter<JournalEntry>)
        journalViewerListActivity.this.getListAdapter();

    //EXCEPTION OCCURS HERE                                
    adapter.remove(adapter.getItem(CONTEXT_SELECTED_POSITION));

    //refreshes the ListView to show the new items
    adapter.notifyDataSetChanged();

Any help appreciated. Thanks!


回答1:


It seems that this problem crops up when you initialize your ArrayAdapter with an array. Try initializing it with a List<JournalEntry>. Reference: Why can't one add/remove items from an ArrayAdapter?




回答2:


You're trying to modify list which is declared as final. Compiler tried to warn you, but you've suppressed warning by @SuppressWarnings("unchecked")



来源:https://stackoverflow.com/questions/7200331/unsupportedoperationexception-with-arrayadapter-remove

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!