Reputation: 2222
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?
Upvotes: 1
Views: 3783
Reputation: 2308
To explain in details, as per Android guidelines. When addHeader/addFooter
introduced before KITKAT version, developer should call setAdapter only after adding Header/Footer. After release Kitkat means Android Versions>=Kitkat
developers can call setAdapter anytime
Upvotes: 0
Reputation: 2222
Actually I solved this problem by using LinearLayout in HeaderView.
I added LinearLayout to HeaderView and if I want to make header invisible, I set GONE to setVisibility method of LinearLayout.
It doesn't make IllegalStateException at all.
Thank you.
Upvotes: 0
Reputation: 1006819
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".
Upvotes: 5