I was using SimpleCursorAdapter with an xml file with some views defined in it:
<LinearLayout ...>
<ImageView android:id="@+id/listIcon" />
<TextView android:id="@+id/listText" />
</LinearLayout>
My aim was to set the text color of the TextView, and the background color of the LinearLayout (that is, each row in the ListView) programmatically; the color is returned from a database.
I was getting NPEs when trying to manipulate the TextView for example, after it had found it with no complaints:
TextView tv = (TextView) findViewById(R.id.listText);
tv.setTextColor(color); // NPE on this line
Which is fair; if there's multiple entries in the list, it's reasonable to assume that "R.id.listText" will not work. So I extended 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's 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:
- A similar NPE is thrown at "text.setTextColor(mTextColor)"
- If the lines with the ImageView are uncommented, I get a "ClassCastException: android.widget.TextView" where I am calling "row.findViewById(R.id.listIcon)"
For reference, I was trying to use Commonsware's sample code, applying it to my situation. link (pdf)
Changed to this:
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);
// If there's 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) {
convertView.setBackgroundColor(mBackgroundColor);
}
bindView(convertView, mContext, mCursor);
return(convertView);
}
Now I get a ClassCastException in the next activity (on list item click). Nothing has been modified in the next activity; it worked when using a SimpleListAdapter for the list which had entries (upon which clicking would lead to Activity2), so I think it's still something I'm doing wrong in the this extended class.