I get an error when I try to run the code for my app after trying to add a list view using a custom ArrayAdapter in a class derived from ListFragment.
Logcat:
09-12 02:21:27.818 31354-31354/com.example.anas.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.anas.myapplication, PID: 31354
java.lang.NullPointerException
at com.example.anas.myapplication.adapter.MaalomaListAdapter.getView(MaalomaListAdapter.java:74)
The error is produced in the following line the method getView():
viewHolder.ivMaaloma.setImageResource(R.drawable.maaloma_bg_1);
viewHolder.tvMaaloma.setText(maaloma.getText());
To get a clearer idea of what I'm trying to do, this is my custom ArrayAdapter class (I marked error line with a comment):
MaalomaListAdapter.java:
public class MaalomaListAdapter extends ArrayAdapter<Maaloma> {
private Context context;
private int resource;
private List<Maaloma> maalomaList;
public MaalomaListAdapter(Context context, int resource, List<Maaloma> maalomaList) {
super(context, resource, maalomaList);
this.context = context;
this.resource = resource;
this.maalomaList = maalomaList;
}
public static int getResId(String resName, Class<?> c) {
try {
Field idField = c.getDeclaredField(resName);
return idField.getInt(idField);
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView == null) {
// inflate item layout
LayoutInflater inflater = ((Activity) this.context).getLayoutInflater();
convertView = inflater.inflate(this.resource, parent, false);
// init view holder
viewHolder = new ViewHolder();
viewHolder.ivMaaloma = (ImageView) convertView.findViewById(R.id.iv_maaloma_bg);
viewHolder.tvMaaloma = (TextView) convertView.findViewById(R.id.tv_maaloma);
convertView.setTag(viewHolder);
} else {
// recycling already inflated views
viewHolder = (ViewHolder) convertView.getTag();
}
Maaloma maaloma = maalomaList.get(position);
//int imageResId = getResId(maaloma.getImage(), Drawable.class);
/**** ERROR COMES FROM THE FOLLOWING TWO LINES (WHICHEVER WAS FIRST) *****/
viewHolder.ivMaaloma.setImageResource(R.drawable.maaloma_bg_1);
viewHolder.tvMaaloma.setText(maaloma.getText());
return convertView;
}
private static class ViewHolder {
private ImageView ivMaaloma;
private TextView tvMaaloma;
}
}
I suppose the error resides in this class only but I'm ready to post more code upon request. Appreciate the time and effort guys.
viewHolder.ivMaaloma.setImageResource(R.drawable.maaloma_bg_1). I marked it with an all caps/* */comment in the class code. (Out of topic: If there's a trick I can use on SO for that you could let me know please)