Tom Finet Tom Finet - 2 months ago 10
Android Question

How to add an extra list item to list view?

I need my listview to always have a trailing list item different to the other list items, even when the adapter is empty.

I have tried adding a null item at the end of the dataset in the adapter constructor:

mDataset.add(null);


In the getView method I distinguish between the last item and the others and inflate different layouts accordingly.

When the user adds a new list item, I need to delete the null item in the dataset, add the new data the end of the dataset and then add another null item in the last index of the dataset:

public void addData(String data) {
mDataset.remove(mDataset.indexOf(null));
mDataset.add(data);
mDataset.add(null);
notifyDataSetChanged();
}


This is of course called within the adapter. When I run the app I get the following error:

java.lang.NullPointerException: Attempt to read from field 'android.widget.TextView com.neutronstar.revu.DataAdapter$DataViewHolder.mDataTextView' on a null object reference


Which maps to this line in the getView() method of my adapter:

holder.mDataTextView.setText(mDataset.get(position));


Here is the getView() method in the adapter:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
long viewType = getItemId(position);

Log.i("SPECS ADAPTER", viewType + "");

if (getCount() == 0)
convertView = LayoutInflater.from(mContext).inflate(R.layout.item_add_spec, null);
else if (viewType == NOT_LAST_ITEM) {
SpecViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.item_spec, null);
holder = new SpecViewHolder(convertView);
convertView.setTag(holder);
} else
holder = (SpecViewHolder) convertView.getTag();

holder.mSpecTextView.setText(mSpecs.get(position));

} else {
if (convertView == null)
convertView = LayoutInflater.from(mContext).inflate(R.layout.item_add_spec, null);
}
return convertView;
}

public void addSpec(String spec) {
mSpecs.remove(mSpecs.indexOf(null));
mSpecs.add(spec);
mSpecs.add(null);
notifyDataSetChanged();
}

static class SpecViewHolder {
@BindView(R.id.spec_text_view) TextView mSpecTextView;

SpecViewHolder(View view) {
ButterKnife.bind(this, view);
}
}


How do I fix this error?

Thanks

Answer

As @Rotwang said. Stop adding null item and attach a footer view to the listview as below in the activity/fragment.

View v = getLayoutInflater().inflate(R.layout.footer, null);
listView.addFooterView(v); //IMPORTANT: make sure you call this before setAdapter
listView.setAdapter(adapter);

And dont forget to create a footer layout.

Comments