3

我正在尝试创建一个自定义 ListView 适配器(大致基于本教程,但示例很简单,我怀疑您是否需要查看它)。

NewsEntriesAdapter.java

public class NewsEntriesAdapter extends BaseAdapter {
    private static ArrayList<NewsEntries> newsEntriesArrayList;

    private final LayoutInflater mInflater;

    public NewsEntriesAdapter(Context context, ArrayList<NewsEntries> entries) {
        newsEntriesArrayList = entries;
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return newsEntriesArrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return newsEntriesArrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.assignment_list_row_view,
                    null);
            holder = new ViewHolder();
            holder.txtName = (TextView) convertView.findViewById(R.id.name);
            holder.txtCityState = (TextView) convertView
                    .findViewById(R.id.cityState);
            holder.txtPhone = (TextView) convertView.findViewById(R.id.phone);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.txtName.setText(newsEntriesArrayList.get(position).getName());
        holder.txtCityState.setText(newsEntriesArrayList.get(position)
                .getCityState());
        holder.txtPhone.setText(newsEntriesArrayList.get(position).getPhone());

        return convertView;
    }

    static class ViewHolder {
        TextView txtName;
        TextView txtCityState;
        TextView txtPhone;
    }

}

MainActivity.java(onCreate 方法)

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ArrayList<NewsEntries> results = new ArrayList<NewsEntries>();

    // I left the NewsEntries class out of this question; it's just a POJO with some get and set methods for Name, CityState, and Phone
    NewsEntries sr = new NewsEntries();
    sr.setName("Justin Schultz");
    sr.setCityState("San Francisco, CA");
    sr.setPhone("415-555-1234");
    results.add(sr);

    final ListView lv = (ListView) findViewById(R.id.list);

    System.out.println(results.get(0).getName());

    lv.setAdapter(new NewsEntriesAdapter(this, results));
}

但是,lv.setAdapter正上方的行会使应用程序崩溃,并出现空指针异常。

有任何想法吗?

4

1 回答 1

13

您没有在Activity. 您setContentView的. _addContentViewonCreate

因此,findViewById将无法找到视图,因为根本没有视图,并将返回null

于 2013-01-01T23:27:37.260 回答