I'm attempting to create a custom ListView adapter (roughly based on this tutorial, but the example is simple enough I doubt you need to look at it).
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 method)
@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));
}
However, the lv.setAdapter line right above this crashes the app with a null pointer exception.
Any ideas?
You are not setting any content in your Activity. There is no setContentView or addContentView call in your onCreate.
Hence, findViewById will not be able to find a view since there are no views at all, and will return null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With