自定义ListView适配器抛出UnsupportedOperationException

时间:2012-09-19 11:53:23

标签: java android listview adapter

This is the tutorial that I followed使用自定义Listview适配器。我遇到的问题是,当我尝试清除适配器时,应用程序崩溃并抛出java.lang.UnsupportedOperationException

if(adapter != null) {
    adapter.clear();
}

更新后的代码:

private void setListViewAdapterToDate(int month, int year, int dv)
{
     if(summaryAdapter != null) {
        summaryAdapter.clear();
     }

    setListView(month, year, dv);
    summaryList.addAll(Arrays.asList(summary_data));
    summaryAdapter = new SummaryAdapter(this.getActivity().getApplicationContext(), R.layout.listview_item_row, summaryList);


    summaryAdapter.notifyDataSetChanged();
    calendarSummary.setAdapter(summaryAdapter);
}

1 个答案:

答案 0 :(得分:6)

环顾一下,似乎用数组初始化适配器是个问题。请参阅UnsupportedOperationException with ArrayAdapter.removeUnable to modify ArrayAdapter in ListView: UnsupportedOperationException

尝试使用ArrayList代替array,如此

ArrayList<Weather> weather_data = new ArrayList<Weather>()
weather_data.add( new Weather(R.drawable.weather_cloudy, "Cloudy") );
// continue for the rest of your Weather items.

如果您感到懒惰,可以通过这种方式将array转换为ArrayList

ArrayList<Weather> weatherList = new ArrayList<Weather>();
weatherList.addAll(Arrays.asList(weather_data));

要完成ArrayList课程中WeatherAdapter的转换,您需要删除Weather data[] = null;及其所有引用(例如构造函数内部),因为ArrayAdapter为您保存数据,您可以使用getItem

访问它

因此,在getView函数内部,您需要将Weather weather = data[position];更改为Weather weather = getItem(position);

<强>更新 使用

修改您的新代码
private void setListViewAdapterToDate(int month, int year, int dv)
{
    setListView(month, year, dv); 
     if(summaryAdapter != null) {
        summaryAdapter.clear();
        summaryAdapter.addAll( summaryList );
        summaryAdapter.notifyDataSetChanged();
     } else {
         summaryList.addAll(Arrays.asList(summary_data));
         summaryAdapter = new SummaryAdapter(this.getActivity().getApplicationContext(), R.layout.listview_item_row, summaryList);
     }
    calendarSummary.setAdapter(summaryAdapter);
}