运维开发网

Java inflater.inflate在Adapter getview方法中给出nullpointer.为什么?

运维开发网 https://www.qedev.com 2020-04-20 11:55 出处:网络 作者:运维开发网整理
在我的 Android应用程序中,我正在构建我的第一个自定义适配器我现在遇到一个nullpointer在我膨胀convertView的行.请参阅以下代码: private List<String> possibilitiesList = new ArrayList<String>(); public void setPossibilitiesList(List<String> possibili
在我的 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.

有谁知道我在这里做错了什么?

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()

0

精彩评论

暂无评论...
验证码 换一张
取 消