1

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?

kimkevin
  • 2,202
  • 1
  • 26
  • 48
  • Try my answer here at http://stackoverflow.com/a/31181366/4489494 hope this will helpful to you.. – Kishan Soni Jul 02 '15 at 10:00
  • Try my answer here at http://stackoverflow.com/a/31181366/4489494 hope this will helpful to you.. – Kishan Soni Jul 02 '15 at 10:02
  • You can check my answer for more details https://stackoverflow.com/questions/19583961/cannot-add-header-view-to-list-setadapter-has-already-been-called/54529452#54529452 – Manmohan Soni Feb 05 '19 at 08:06

3 Answers3

5

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".

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • I changed my question, so I tried another way, but it still has a space. – kimkevin Nov 25 '14 at 12:40
  • The reason for the crash is mentioned in android api documentation also. Please check the answer for more details :https://stackoverflow.com/questions/19583961/cannot-add-header-view-to-list-setadapter-has-already-been-called/54529452#54529452 – Manmohan Soni Feb 05 '19 at 08:09
0

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.

kimkevin
  • 2,202
  • 1
  • 26
  • 48
0

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)

Suresh Maidaragi
  • 2,173
  • 18
  • 25