尝试使用自ArrayAdapter
派生的类中的自定义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)
错误在以下行中生成方法getView():
viewHolder.ivMaaloma.setImageResource(R.drawable.maaloma_bg_1);
viewHolder.tvMaaloma.setText(maaloma.getText());
为了更清楚地了解我尝试做什么,这是我的自定义ArrayAdapter
课程(我在评论时标记错误行):
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;
}
}
我认为错误仅存在于此类中,但我已准备好根据请求发布更多代码。感谢时间和精力。
答案 0 :(得分:1)
错误期间使用的布局是什么?
您使用的布局可能没有
R.id.iv_maaloma_bg
或R.id.tv_maaloma