gpt4 book ai didi

java - 自定义 ListView 适配器抛出 UnsupportedOperationException

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:40:27 24 4
gpt4 key购买 nike

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);
}

最佳答案

环顾四周,问题似乎是用数组初始化适配器。参见 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));

要在 WeatherAdapter 类中完成到 ArrayList 的转换,您需要删除 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);
}

关于java - 自定义 ListView 适配器抛出 UnsupportedOperationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12494169/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com