Search code examples
androidlistviewsimpleadapter

ListView adapter, prevent updates


I've extended the SimpleAdapter with date grouping for items, which is working properly at creation time. List items contains the grouping view, and my adapter is hiding this view if the item belongs to the current date group as such:

TextView Title (2012-10-08) - visible
TextView Name  (Foo)        - visible

TextView Title (2012-10-08) - hidden
TextView Name  (Bar)        - visible

TextView Title (2012-10-07) - visible
TextView Name  (Baz)        - visible

TextView Title (2012-10-07) - hidden
TextView Name  (Etc)        - visible

Now, if I where to scroll down below the 2nd item on a fully populated list, the hidden view would become visible when scrolling up again. Why is this happening and how do I prevent it?

I do not alter the adapter after onCreate so I have no clue as to why my ListView or Adapter changes view states.

DateAdapter:

public class DateAdapter extends SimpleAdapter
{
    protected   ArrayList<HashMap<String, String>>  items;
    private     String                  prevDate = "";
    private     SimpleDateFormat            dateFormat = new SimpleDateFormat("EEEE, dd/MM yyyy", Locale.getDefault());

    public DateAdapter (Context context, ArrayList<HashMap<String, String>> items, int resource, String[] from, int[] to)
    {
        super(context, items, resource, from, to);
        this.items = items;
    }

    @Override
    public View getView (int position, View convertView, ViewGroup parent)
    {
        View view = super.getView(position, convertView, parent);

        try
        {
            HashMap<String, String> item = this.items.get(position);
            Long itemTime = Long.parseLong(item.get("timedate")) * 1000;

            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(itemTime);
            String dateString = dateFormat.format(calendar.getTime());

            TextView section = (TextView) view.findViewById(R.id.sectionTitle);

            if (!dateString.equals(this.prevDate))
            {
                this.prevDate = dateString;
                section.setText(dateFormat.format(calendar.getTime()));
                section.setVisibility(View.VISIBLE);
            }
        }
        catch (Exception e) { Debug.e(e); }

        return view;
    }
}

Solution

  • View view = super.getView(position, convertView, parent);

    This line returns newly created view, only if the provided convertView is null, if convertView is not null, same view will be returned. So when it return the same convertView instance then, there is the possibility that the view having visibility VISIBLE will remain visible. So, what you have to do is fill the else of this condition

        if (!dateString.equals(this.prevDate)){} 
    

    where you will be setting view visibility to INVISIBLE. Tell me is it helpful?