Android Custom ArrayAdapter NullPointerException

时间:2014-02-09 18:41:30

标签: android android-layout android-arrayadapter

目前正在尝试为列表视图创建自定义ArrayAdapter

public class FilesArrayAdapter extends ArrayAdapter<String> {
private String[] _objects;

public FilesArrayAdapter(Context context, int resource, String[] objects) {
    super(context, resource, objects);
    this._objects = objects;
}

@Override
public View getView(int position, View convertView, ViewGroup parent){
    if(convertView == null){
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.entry_layout, null); 
    }

    String string = _objects[position];

    if(string != null){
        TextView fNameView = (TextView) convertView.findViewById(R.id.mTextView);

        if(fNameView != null){
            fNameView.setText(string);
        }
    }

    return convertView;
}

}

这是布局R.layout.entry_layout

<?xml version="1.0" encoding="utf-8"?>

<TextView 
    android:id="@+id/mTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

我正在绑定主要活动的列表,但它正在抛出NullPointerException这一行:

TextView fNameView = (TextView) convertView.findViewById(R.id.mTextView);

文本视图存在于上述布局中,布局文件没有问题。

由于

2 个答案:

答案 0 :(得分:0)

getView()方法中,你必须这样做:

convertView = inflater.inflate(R.layout.entry_layout, null);

答案 1 :(得分:0)

你应该添加:

convertView = inflater.inflate(R.layout.entry_layout, null);

如下:

public View getView(int position, View convertView, ViewGroup parent){
if(convertView == null){
    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    inflater.inflate(R.layout.entry_layout, null); 
    convertView = inflater.inflate(R.layout.entry_layout, null);
}

String string = _objects[position];

if(string != null){
    TextView fNameView = (TextView) convertView.findViewById(R.id.mTextView);

    if(fNameView != null){
        fNameView.setText(string);
    }
}

return convertView;

}