How to display only the even position items in ListView?

advertisements

I am getting data from Database and displaying using a custom list adapter in a ListView. I need to display only even position items in ListView.

i am able to solve this in two ways.

1. sorting data before attaching to adapter, but i want to do those task in getView() method of adapter/by using other available methods in adapter.

2.

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
   if( position%2 == 0 ) {
      // display
   } else {
      // not display
   }
return view;

in this i am getting alternate view's are empty view's.. i want to avoid these empty view.

i ant to do those all calculations in getView() method, without empty view in the ListView. How i can do this?


I will suggest you to create new List with filtered data and use it in your adapter. Still if you want an alternate solution you can try below code:

@Override
public int getCount() {
     int halfCountOfList = itemList.size()/2;
     // Add +1 in halfCountOfList if itemList size is odd.
     int finalCount = halfCountOfList + itemList.size()%2;
     return finalCount;
}

@Override
public View getView(int position, View convertView, ViewGroup parent)  {

    Item item = getItem(position*2);
    //No need to to check for even item

    return view;
}