简体   繁体   中英

Custom ListView Adapter throws UnsupportedOperationException

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM