问题
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