ClassCastException with ListView when executing notifyDataSetChanged

大城市里の小女人 提交于 2019-11-28 06:44:35

It seems that whenever you use header/footer views in a listview, your ListView gets wrapped with a HeaderViewListAdapter. You can fix this using the below code:

((YourAdapter)((HeaderViewListAdapter)lv.getAdapter()).getWrappedAdapter()).notifyDataSetChanged();

API 18 and lower is confused about what it is wrapping. To help it, set your header and/or footer PRIOR to assigning the adapter. That way the correct wrapping takes place under the covers. Then remove the header/footer immediately after (if that is what you want).

myList.addFooterView(myFooterView);
myList.setAdapter(adapter);
myList.removeFooterView(myFooterView);

As written in http://stanllysong.blogspot.ru/2013/08/javalangclasscastexception.html it should be done so:

HeaderViewListAdapter hlva = (HeaderViewListAdapter)l.getAdapter();
YourListAdapter postAdapter = (YourListAdapter) hlva.getWrappedAdapter();
postAdapter.notifyDataSetChanged();

@mussharapp's answer is perfectly right and it works! However I find more convenient to simply cache your adapter on a member variable for later use before you do setAdapter():

mAdapter = new YourAdapter(ctx, items);
listView.addFooterView(v);
listView.setAdapter(mAdapter);

The reason for class cast exception is that the listview did't wrapped to headerlistview. So we can't add footers or header to listview directly. So before setting adapter to listview, add dummy view as header or footer view. Then set adapter to listview. This makes listview to instance of headerviewslist. Then you can add and remove footers easily from listview as normal.

listview.addFooterView(new View(mContext));listview.setAdapter(yourAdapter): 

After setting adapter, you can add or remove footer listview.addFooterView(yourFooter); or listview.removeFooterView(yourFooter);

Charly Baquero Murillo
public class YourOwnList extends ListActivity {
    private EfficientAdapter mAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        mAdapter = new EfficientAdapter(/*your parameters for the adapter*/);
    }

    private void yourMethod () {
        mAdapter.notifyDataSetChanged();
    }

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