在List <string>?</string>中添加或删除时不支持获取操作

时间:2012-04-08 05:45:06

标签: android list arraylist listactivity invalidoperationexception

Begginer android程序员,我想在用户点击listitem时添加和删除String列表中的项目,但是我尝试这样做时得到操作不支持错误。请参阅以下代码以了解我想要做什么。

@Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        if(myList != null)
        {
            StringBuilder stringBuilder = new StringBuilder();
            if(myList.contains(mylist1.get(position).getPackageName()))
            {
                for(int i = 0; i < myList.size(); i++)
                {
                    if(myList.get(i).equals(mylist1.get(position).getPackageName()))
                        continue;
                    if((myList.size() - 1) != i)
                        stringBuilder.append(myList.get(i)).append(separator);
                    else
                        stringBuilder.append(myList.get(i));
                }
                editor.putString("mypreference", stringBuilder.toString());
                mylistt1.get(position).setDisabled(false);
       //error happens in following
                myList.remove(mylist1.get(position).getPackageName());
            }
      }
}

这是logcat

04-08 11:33:00.030: ERROR/AndroidRuntime(533): FATAL EXCEPTION: main
        java.lang.UnsupportedOperationException
        at java.util.AbstractList.remove(AbstractList.java:638)
        at java.util.AbstractList$SimpleListIterator.remove(AbstractList.java:75)
        at java.util.AbstractCollection.remove(AbstractCollection.java:229)
        at com.mypackage.myActivity.onListItemClick(myActivity.java:82)
        at android.app.ListActivity$2.onItemClick(ListActivity.java:319)
        at android.widget.AdapterView.performItemClick(AdapterView.java:292)
        at android.widget.AbsListView.performItemClick(AbsListView.java:1058)
        at android.widget.AbsListView$PerformClick.run(AbsListView.java:2514)
        at android.widget.AbsListView$1.run(AbsListView.java:3168)
        at android.os.Handler.handleCallback(Handler.java:605)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4340)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
        at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:4)

如果myList的数据类型为 List ,则它是不可变的。您无法对其进行更改。因此,您将获得操作不受支持异常。在尝试进行更改之前,将myList数据类型更改为 ArrayList