kimkevin
kimkevin

Reputation: 2222

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?

Upvotes: 1

Views: 3783

Answers (3)

Suresh Maidaragi
Suresh Maidaragi

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

ref : https://developer.android.com/reference/android/widget/ListView.html#addFooterView(android.view.View,%20java.lang.Object,%20boolean)

Upvotes: 0

kimkevin
kimkevin

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

CommonsWare
CommonsWare

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

Related Questions