Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
658 views
in Technique[技术] by (71.8m points)

exception - Android ListView addHeaderView() nullPointerException for predefined Views defined in XML

Trying to use addHeaderView() and addFooterView() for a ListView. If I try to use a View that I've predefined in XML for either the header or footer, I get a null pointer exception. However, if I dynamically create a View using code, it works fine...

// This doesn't work... nullPointerException
ListView lv = (ListView) findViewById(R.id.my_list_view);
TextView header = (TextView) findViewById(R.id.my_header);
lv.addHeaderView(header);

// This works fine
ListView lv = (ListView) findViewById(R.id.my_list_view);
TextView header = new TextView(this);
TextView.setHeight(30);
TextView.setText("my header text!");
lv.addHeaderView(header);

My stack trace:

Caused by: java.lang.NullPointerException
    at android.widget.ListView.clearRecycledState(ListView.java:522)
    at android.widget.ListView.resetList(ListView.java:508)
    at android.widget.ListView.setAdapter(ListView.java:440)
    at com.company.myapp.MyActivity.refreshList(MyActivity.java:85)
    at com.company.myapp.MyActivity.onCreate(MyActivity.java:37)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
    ... 11 more

Any clues?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

EDIT:

you simply cannot do

View header = findViewById(R.layout.headerView);
lst.addHeaderView(header);

This will NOT work because the view which is being passed in has to be inflated. In a nutshell when you do setContentView at the beginning of your activity the android framework automatically inflates the view and puts it to use. In order to inflate your header view, all you have to do is

View header = (View)getLayoutInflater().inflate(R.layout.headerView,null);
ls.addHeaderView(header);

lastly, add your adapter after you’ve set the header view and run the application. You should see your header view with the content you put into your adapter.

In my case, this works

View header = getLayoutInflater().inflate(R.layout.header, null); 
View footer = getLayoutInflater().inflate(R.layout.footer, null); 

ListView listView = getListView();  

listView.addHeaderView(header); 
listView.addFooterView(footer);     

setListAdapter(new ArrayAdapter<String(this,android.R.layout.simple_list_item_single_choice,android.R.id.text1, names)); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...