2

I ve two ListFragments maganed by a tabhost. Firt time I switch between tab all is alright. The headerView is correctly added. The second time I switch between fragment I get this execption:

10-05 15:15:01.585: ERROR/AndroidRuntime(23263): java.lang.IllegalStateException: Cannot add header view to list -- setAdapter has already been called. 
10-05 15:15:01.585: ERROR/AndroidRuntime(23263):     at android.widget.ListView.addHeaderView(ListView.java:261) 
10-05 15:15:01.585: ERROR/AndroidRuntime(23263):     at android.widget.ListView.addHeaderView(ListView.java:284) 
10-05 15:15:01.585: ERROR/AndroidRuntime(23263):     at it.chiesacattolica.archive.ArchiveFragment.onActivityCreated(ArchiveFragment.java:199) 
10-05 15:15:01.585: ERROR/AndroidRuntime(23263):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:858) 
10-05 15:15:01.585: ERROR/AndroidRuntime(23263):     at android.support.v4.app.FragmentManagerImpl.attachFragment(FragmentManager.java:1183)

and the app crashes. The code I use to add the header view follows:

@Override
public void onActivityCreated(Bundle arg0) {
    super.onActivityCreated(arg0);      
    getListView().setOnScrollListener(this);
    getListView().addHeaderView(searchBox);
    setListAdapter(mAdapter);
}

what's wrong ? thanks in advance

Airon Tark
  • 8,900
  • 4
  • 23
  • 19
Blackbelt
  • 156,034
  • 29
  • 297
  • 305

2 Answers2

7

After a fleeting look at the android developers references, I'm guessing you can't do another call to addHeaderView after you've set the adapter. If there is such a thing, you can unload the adapter, add the new HeaderView and re-load the adapter. If not, all HeaderViews should be added before calling the setAdapter method.

see ListView.addHeaderView

Niels Doucet
  • 352
  • 5
  • 12
  • From the code he put up, it looks like he is calling setListAdapter after addHeaderView? – Alan Moore Oct 05 '11 at 13:39
  • clear does not exist in BaseAdapter. I had to call setListAdapter(null) – Blackbelt Oct 05 '11 at 13:51
  • @blackbelt Good that I could point you in the right direction :) – Niels Doucet Oct 05 '11 at 13:54
  • Setting adapter to NULL or clearing its items does not resolve the exception. – luben Nov 26 '13 at 13:19
  • from the link in my answer: > Note: When first introduced, this method could only be called before setting the adapter with setAdapter(ListAdapter). Starting with KITKAT, this method may be called at any time. So this should no longer be an issue if you use the latest – Niels Doucet Dec 05 '13 at 09:37
4

I think this might be the answer to your question, I can't say for sure since you haven't provided very much code:

Best place to addHeaderView in ListFragment

Community
  • 1
  • 1
Alan Moore
  • 6,525
  • 6
  • 55
  • 68