androidpositionconvertviewgetview

Wrong 'convertView' object while scrolling a list view


My problem is that when I'm scrolling a list view I'm getting wrong convertView, but the position is right.

I have 3 items in my Listview, on load 'position' parameter is called with index '0' and convertView is null.

When I scroll one by one, to the next item 'position' is '1' and convertView is null also.

The problem is on item 3, the 'position' is '2' BUT the 'convertView' is not null, it is populated by the first item convertView.

Why is that ?

 public View getView(final int position, View convertView, ViewGroup parent) {
        View itemView = convertView;
        if (itemView == null) {
            itemView = getLayoutInflater().inflate(R.layout.post_layout, parent, false);

            postViewHolder                              = new PostViewHolder();
            postViewHolder.commentsImageButton          = (ImageButton) itemView.findViewById(R.id.postAddCommentsImageButton);

            itemView.setTag(postViewHolder);
        }else{
            postViewHolder = (PostViewHolder) itemView.getTag();
        }

}


Solution

  • Try This

    public View getView(final int position, View convertView, ViewGroup parent) {
            View itemView = convertView;
            PostViewHolder postViewHolder = null;
            if (itemView == null) {
                itemView = getLayoutInflater().inflate(R.layout.post_layout, parent, false);
                postViewHolder                              = new PostViewHolder();
                postViewHolder.commentsImageButton          = (ImageButton) itemView.findViewById(R.id.postAddCommentsImageButton);
    
                itemView.setTag(postViewHolder);
            }else{
                postViewHolder = (PostViewHolder) itemView.getTag();
            }
            postViewHolder.position    = position;
            :do your stuff with postViewHolder
            :
            return itemView;
    }