在我的Android应用中,我正在构建我的第一个自定义适配器。我现在遇到一个nullpointer在我膨胀convertView的行。请参阅以下代码:
private List<String> possibilitiesList = new ArrayList<String>();
public void setPossibilitiesList(List<String> possibilitiesList) {
for (String possibility : possibilitiesList) {
addItem(possibility);
}
}
public void addItem (final String item) {
possibilitiesList.add(item);
notifyDataSetChanged();
}
private LayoutInflater inflater;
@Override
public View getView(final int position, View convertView, ViewGroup viewGroup) {
Log.e(this, "is called here!!");
ViewHolder holder = new ViewHolder();
convertView = inflater.inflate(R.layout.list_item_posibility, viewGroup, false);
holder.possibilityTitle = (TextView) convertView.findViewById(R.id.text_possibility);
holder.possibilityTitle.setText(possibilitiesList.get(position));
return convertView;
}
在我的片段中,我按如下方式设置了possibilitiesList:
List<String> list = Arrays.asList(getResources().getStringArray(R.array.the_possibilities));
Log.e(this, new Integer(list.size()).toString()); // outputs 8
adapter.setPossibilitiesList(list);
我100%确定list_item_posibility.xml存在(Android Studio也突出显示存在),所以我很遗憾为什么这会给出一个nullpointer。
有人知道我在这里做错了吗?
答案 0 :(得分:5)
private LayoutInflater inflater;
刚刚声明未初始化
您需要将上下文传递给适配器类的构造函数,然后使用它来初始化inflater。
new Yourcustomadapter(ActivityName.this);
// pass the context here and other params
然后
private LayoutInflater inflater;
public Yourcustomadapterr(Context context)
{
inflater = LayoutInflater.from(context);
}
同时检查此
http://developer.android.com/reference/android/view/View.html#getContext()
答案 1 :(得分:2)
您的inflater为null,您需要将其设置为inflater的引用
private final LayoutInflater inflater;
public CustomAdapter(LayoutInflater inflater) {
this.inflater = inflater;
}
@Override
public View getView(final int position, View convertView, ViewGroup viewGroup) {
Log.e("this", "is called here!!");
ViewHolder holder = new ViewHolder();
convertView = inflater.inflate(R.layout.list_item_posibility, viewGroup, false);
holder.possibilityTitle = (TextView) convertView.findViewById(R.id.text_possibility);
holder.possibilityTitle.setText(possibilitiesList.get(position));
return convertView;
}
然后,在你新增适配器的地方,:(取决于你启动适配器的位置)
new CustomAdapter(LayoutInflater.from(this));
或
new CustomAdapter(LayoutInflater.from(context));
或
new CustomAdapter(getActivity().getLayoutInflater());
或
new CustomAdapter((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE));