4

这是我使用自定义 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);
}
4

1 回答 1

6

环顾四周,似乎用数组初始化适配器是问题所在。请参阅带有 ArrayAdapter.remove 的 UnsupportedOperationExceptionUnable to modify ArrayAdapter in ListView: UnsupportedOperationException

尝试使用 anArrayList而不是arraylike so

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.

如果你觉得懒惰,你可以将你的转换arrayArrayList这种方式

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);
}
于 2012-09-19T12:11:59.153 回答