I have been getting null returns from findViewbyID for some hours now. I’ve been through all the solutions, checking my xml, etc. I found that if I try to pull out two views in a row, the second has the expected results of the first. So I fixed my app by just adding 1 to the R.id.xxx value… what is going on?
product_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="@+id/product_name" xmlns:android="http://schemas.android.com/apk/res/android"
style="@android:style/TextAppearance.Large"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageView android:id="@+id/cart_icon"
android:layout_width="wrap_content"
android:paddingLeft="4dip"
android:paddingRight="4dip"
android:layout_alignParentRight="true"
android:layout_marginLeft="10px"
android:layout_height="wrap_content"
android:src="@drawable/ic_menu_shopping"/>
</RelativeLayout>
This is the newView method of my CursorAdapter class that doesn’t work. productName is null and icon gets assigned a TextView Object. They are only created here for debugging, getting the findViewbyId as close to the view creation as possible.
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final View view=mInflater.inflate(R.layout.product_row,parent,false);
View productName=(View)view.findViewById(R.id.product_name);
View icon = (View) view.findViewById(R.id.cart_icon);
return view;
The following code with the additions +1’s actually works. Why?!?!
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final View view=mInflater.inflate(R.layout.product_row,parent,false);
View productName=(View)view.findViewById(R.id.product_name+1);
View icon = (View) view.findViewById(R.id.cart_icon+1);
return view;
}
I have had issues in the past with the generated R.java file not being updated correctly – in one case the resource ids were mixed up and all my text labels got confused..
A project clean has always fixed that for me though.