我正在尝试创建一个自定义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
行会因空指针异常而崩溃应用程序。
有什么想法吗?
答案 0 :(得分:13)
您未在Activity
中设置任何内容。您的setContentView
中没有addContentView
或onCreate
来电。
因此,findViewById
将无法找到视图,因为根本没有没有视图,并且会返回null
。