Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I have one edittext field and one "search" button. When I click on search, I have to display a list view with data corresponding to the values entered in the edittext. I have added a header to my list using addHeader(). When I do search first time, I am able to display data in List successfully. But when I do search again, I am getting the below error.

FATAL EXCEPTION: main
java.lang.IllegalStateException: Cannot add header view to list -- setAdapter has already been called.
at android.widget.ListView.addHeaderView(ListView.java:261)
at android.widget.ListView.addHeaderView(ListView.java:284)

I have assigned header to my list before setting the adapter.

Below is my code:

myList = (ListView) findViewById(R.id.searchResultsList);
View header = View.inflate(this, R.layout.search_results_header, null);
myList.addHeaderView(header, null, false);

dataAdapter = new MyCustomAdapter(this, R.layout.results_list_item, searchedResults);
myList.setAdapter(dataAdapter);

Where I am doing wrong?

like image 230
user2740599 Avatar asked Oct 25 '13 07:10

user2740599


3 Answers

Cannot add header view to list -- setAdapter has already been called. which you can see, the myList.addHeaderView(header) must be execute before myList.setAdapter(adapter);

like image 29
user2919006 Avatar answered Oct 22 '22 22:10

user2919006


On android 2.3, add header after setAdapter (even if you have added early, then removed) will throw an exception. To hide or show a header dynamically, use setVisibility(). How? You can see Hiding header views.

like image 86
ishitcno1 Avatar answered Oct 22 '22 20:10

ishitcno1


Try this..

dataAdapter = new MyCustomAdapter(this, R.layout.results_list_item, searchedResults);
myList.addHeaderView(header);
myList.setAdapter(dataAdapter);
dataAdapter.notifyDataSetChanged();
like image 28
Hariharan Avatar answered Oct 22 '22 21:10

Hariharan