Explanation
The issue occurs because you set the inflated layout only once, when your condition of convertView
is null
. However, after the first time itemView
ins't null
. Your items are not updated except the first one. Also, you need to return all the views (itemView) for the list items.
Solution
In your adapter, the getView
method needs to inflate a layout (once) and returns this layout:
// inflate the layout to the row (items)
View itemView = convertView;
if(null == itemView) {
itemView = getLayoutInflater().inflate(R.layout.item_crossroad, parent, false);
}
// Then return the inflated view and all its stuff
return itemView;
Also, you need to attach all the item's views to the layout as follows:
// itemView.findViewById(...) to retrieve the id which is on the inflated layout
TextView name = (TextView) itemView.findViewById(R.id.item_crossroadName);
Finally, to improve the performance of your Adapter
, you should use a ViewHolder
. This will avoid you to call ever and ever all the findViewById
methods. Here's a great tutorial and a simple example. Then, your method might be:
// Init your variables
public ViewHolder {
TextView name, redLight, greenLight
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
// create the ViewHolder variable
ViewHolderItem viewHolder;
if(itemView == null) {
itemView = getLayoutInflater().inflate(R.layout.item_crossroad, parent, false);
// create a new ViewHolder
viewHolder = new ViewHolderItem();
// get your views with the ViewHolder and attached to the inflated layout
viewHolder.name = (TextView) itemView.findViewById(R.id.item_crossroadName);
viewHolder.redLight = (TextView) itemView.findViewById(R.id.item_redLightDuration);
viewHolder.greenLight = (TextView) itemView.findViewById(R.id.item_greenLightDuration);
// store the ViewHolder
itemView.setTag(viewHolder);
}else{
// this is not the first, reuse the stored ViewHolder
viewHolder = (ViewHolderItem) convertView.getTag();
}
// do your stuff...
Crossroad currentCrossroad = crossroads.get(position);
try {
viewHolder.name.setText(currentCrossroad.getName());
viewHolder.redLight.setText("" + currentCrossroad.getRedLight());
viewHolder.greenLight.setText("" + currentCrossroad.getGreenLight());
} catch (Exception e) { }
// return the layout inflated
return itemView;
}