Search code examples
androidandroid-listviewandroid-adapter

Cannot add header view to list - setAdapter has already been called


FATAL EXCEPTION: main java.lang.IllegalStateException: Cannot add header view to list -- setAdapter has already been called.

I got this crash, but It didn't always happen! Actually my test phones have no problem. below is my codes.

Constructor

public MyListView(Context context) {        
    super(context);

    adapter = new MytListAdapter(context);
    setAdapter(adapter);
}

and I called 'addHeaderView' after getting data from server. so I tried calling addHeaderView before setAdapter and I using visibility of attribute of view. but even if i set the view gone, but it still has a space.

any idea to solve this?


Solution

  • Do not call setAdapter() until after you have called addHeaderView(). In your case, that would mean not calling addHeaderView() or setAdapter() until "after getting data from server".

    Or, do not use addHeaderView(), but instead modify the adapter to have an additional row, in the 0th position, after you have retrieved your server data, where the 0th position is your virtual "header".