ListView如果设置页脚之后(addFooterView),在更新数据的时候有可能会报错;
报错内容大致如下:cannot be cast to android.widget.HeaderViewListAdapter
网上找到报错资料
查看代码发现:确实是在ListView 添加adapter之前设置过了页脚。
继续查到资料:java.lang.ClassCastException: android.widget.HeaderViewListAdapter cannot be cast to com.android.mms
根据资料修改代码:
if (foodValue != null ) {
foodValue.addAll(result);
if(foodListView.getAdapter() instanceof HeaderViewListAdapter) {
HeaderViewListAdapter listAdapter=(HeaderViewListAdapter)foodListView.getAdapter();
adapter = (FoodDateAdapter) listAdapter.getWrappedAdapter();
}else{
adapter = (FoodDateAdapter) foodListView.getAdapter();
}
adapter.notifyDataSetChanged();
}
之后,问题解决问题。
---------------------------------------------------------------------------------------
知其然要知其所以然,之所以会这样是因为:
ListView增加HeaderView之后,将原来的Adapter包装成HeaderViewListAdapter,看看HeaderViewListAdapter的文档说明:
ListAdapter used when a ListView has header views. This ListAdapter wraps another one and also keeps track of the header views and their associated data objects.
This is intended as a base class; you will probably not need to use this class directly in your own code.
HeaderViewListAdapter有个方法getWrappedAdapter,该方法能返回被包装的HeaderViewListAdapter的ListAdapter。
到了这里就明白为什么会报ClassCastException异常了。因为ListView的getAdapter方法返回的是HeaderViewListAdapter的实例,而将其转换成BaseAdapter的子类的实例,肯定是不对的。