在CustomAdapter

时间:2016-03-16 12:15:48

标签: android listview nullpointerexception

我使用以下代码在getView方法中设置文字。

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    view = convertView;

    if (convertView == null) {
        //inflate the view for each row of listview
        view = layoutInflater.inflate(R.layout.rating_item, null);
        mViewHolder = new ViewHolder();
        mViewHolder.mstatus = (TextView) view.findViewById(R.id.status);
        mViewHolder.mCheckBox = (CheckBox) view.findViewById(R.id.checkBox);
        view.setTag(mViewHolder);
    } else {
        mViewHolder = (ViewHolder) view.getTag();
    }

    mViewHolder.mstatus.setText("Statius");
    return view;
}

但是引发了以下错误

java.lang.NullPointerException 
at com.vaighai.adapters.RatingAdapter.getView(RatingAdapter.java:71)
at android.widget.AbsListView.obtainView(AbsListView.java:2627)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1259)
at android.widget.ListView.onMeasure(ListView.java:1171)
at android.view.View.measure(View.java:16831)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5245)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1410)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)

这指向我将文本设置为mViewHolder.mstatus.setText("Statius");

的行

为什么抛出空指针异常虽然我已经初始化了ViewHolder

1 个答案:

答案 0 :(得分:1)

您需要检查mViewHolder.mstatus是否为空。     (TextView)view.findViewById(R.id.status); 可能会返回null。