I used a SimpleCursorAdapter with an XML file with the views defined in it:
<LinearLayout ...> <ImageView android:id="@+id/listIcon" /> <TextView android:id="@+id/listText" /> </LinearLayout>
My goal was to programmatically adjust the text color of the TextView and the background color of the LinearLayout (that is, each row in the ListView); color is returned from the database.
I got NPE when trying to manipulate a TextView, for example, after finding it without complaint:
TextView tv = (TextView) findViewById(R.id.listText); tv.setTextColor(color); // NPE on this line
This is true; if there are several entries in the list, it is reasonable to assume that "R.id.listText" will not work. Therefore, I expanded the SimpleCursor adapter:
public View getView(int position, View convertView, ViewGroup parent) { View row = super.getView(position, convertView, parent); TextView text = (TextView) row.findViewById(R.id.listText); // ImageView icon = (ImageView) row.findViewById(R.id.listIcon); // If there an icon defined if (mIcon_id != 0) { // icon.setImageResource(mIcon_id); } // If text color defined if (mTextColor != 0) { text.setTextColor(mTextColor); } // If background color set if (mBackgroundColor != 0) { row.setBackgroundColor(mBackgroundColor); } return(row); }
And I get two different errors:
- Similar NPE "Text.setTextColor (mTextColor)"
- If the rows with ImageView are unhurt, I get a "ClassCastException: android.widget.TextView" where I am calling "Row.findViewById (R.id.listIcon)"
For reference, I tried to use the Commonsware sample code, applying it to my situation. link (pdf)
Modified by:
public View getView(int position, View convertView, ViewGroup parent) { convertView = super.getView(position, convertView, parent); if (convertView == null) convertView = View.inflate(mContext, R.layout.theme_item, null); TextView text = (TextView) convertView.findViewById(R.id.listText_tv); ImageView icon = (ImageView) convertView.findViewById(R.id.listIcon_iv);
Now I get a ClassCastException in the next action (when I click on a list item). Nothing was changed in the next action; it worked when using the SimpleListAdapter for the list in which there were entries (after which clicking will result in Activity2), so I think that this is still something that I am doing wrong in this extended class.