gpt4 book ai didi

android - setAdapter() 上的空指针异常

转载 作者:太空宇宙 更新时间:2023-11-03 11:37:47 25 4
gpt4 key购买 nike

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

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 行使应用程序崩溃并出现空指针异常。

有什么想法吗?

最佳答案

您没有在 Activity 中设置任何内容.没有 setContentViewaddContentView调用你的onCreate .

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

关于android - setAdapter() 上的空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14115208/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com