findViewById returns null in new Intent
I am having a problem where in the started Intent, the findViewById returns null.
Is there anything special I should 开发者_StackOverflowknow about starting a new intent?
It goes something like this for me:
//in the MainList class
Intent stuffList = new Intent(this, StuffList.class);
then in the new Stuff's constructor:
public class StuffList extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.stuff_list);
...
this.setListAdapter(new StuffAdapter(this, my_cursor));
and in the StuffAdapter I do my usual view and data retrieval.
Note the line where findViewById returns null:
class ViewWrapper{
View base;
TextView label = null;
ViewWrapper(View base){
this.base = base; }
TextView getLabel(){
if(label == null){
label = (TextView)base.findViewById(R.id.my_label); // returns NULL
}
return label;}
}
class StuffAdapter extends CursorAdapter{
StuffAdapter(Context context, Cursor cursor){
super(context, cursor);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.stuff_list, parent, false);
ViewWrapper wrapper = new ViewWrapper(row);
row.setTag(wrapper);
return(row);
}
@Override
public void bindView(View row, Context context, Cursor cursor) {
ViewWrapper wrapper = (ViewWrapper)row.getTag();
TextView label = wrapper.getLabel(); // also NULL
//this throws exception of course
label.setText(cursor.getString("title"));
}
}
The curious thing is that in the class that calls intent (MainList class), I do Exactly the same thing (i list a bunch of objects), and it Works! however when I try to do it in an Intent - it can't seem to find the view by id.
For completeness I wanted to add that my list resource file is call "stuff_list.xml" and my row layout file is called "stuff_row.xml".
Ok, the lesson is - don't copy and paste your code. The problem was precisely in the newView function, where I was trying to inflate a list instead of a row!
View row = inflater.inflate(R.layout.stuff_list, parent, false);
but it should be:
View row = inflater.inflate(R.layout.stuff_row, parent, false);
You are probably using different content views for your Main and StuffList activity (I cannot tell since you didn't post the setContentView
-line of your Main activity).
Are you sure the element R.id.my_label is actually in the xml of R.layout.stuff_list
? Probably not.
精彩评论