ListView custom adapter throws UnsupportedOperationException

This is the guide I followed to use the custom list adapter. The problem I am facing is that when I try to clean the adapter, the application crashes and throws a 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); } 
+4
source share
1 answer

Looking back a bit, it seems that initializing an adapter with an array is a problem. See UnsupportedOperationException with ArrayAdapter.remove and Cannot Modify ArrayAdapter in ListView: UnsupportedOperationException

Try using an ArrayList instead of array so that

 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 feel lazy, you can convert your array to ArrayList this way

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

To complete the conversion to ArrayList in the WeatherAdapter class, you will want to remove Weather data[] = null; and all its links (for example, inside the constructor), because the ArrayAdapter contains data for you, and you can access it using getItem

So, inside your getView function getView you can change Weather weather = data[position]; on Weather weather = getItem(position);

Update Change 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); } 
+6
source

Source: https://habr.com/ru/post/1435050/


All Articles