Custom ListView Adapter throws UnsupportedOperationException

匆匆过客 提交于 2019-12-19 09:08:10

问题


This is the tutorial that I followed to use a custom Listview Adapter. The problem I am having is that when I try to clear the adapter, the app crashes and throws java.lang.UnsupportedOperationException

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

UPDATED CODE:

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:


Looking around a bit, it would seem that initializing the adapter with an array is the problem. See UnsupportedOperationException with ArrayAdapter.remove and Unable to modify ArrayAdapter in ListView: UnsupportedOperationException

Try using an ArrayList instead of an array like 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.

If you're feeling lazy, you can convert your array to an ArrayList this way

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

To finish the conversion to ArrayList in your WeatherAdapter class you will want to remove the Weather data[] = null; and all of it's references (such as inside the constructor) because ArrayAdapter holds the data for you and you can access it with getItem

So inside of your getView function you would change Weather weather = data[position]; to Weather weather = getItem(position);

Update Modify your udated code with

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


来源:https://stackoverflow.com/questions/12494169/custom-listview-adapter-throws-unsupportedoperationexception

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