Cyph3rCod3r
Cyph3rCod3r

Reputation: 2088

Remove items from listview on its ItemClickListener

I am using a collection of ArrayList to fill my Listview. My ListView contains two separate rows types.

Header and Footer.

I am trying to achieve the ExpandableListView Functionality on my Listview from which I am trying to remove some items on click of header till next header. I am using this function to loop through items and removing items

private void removeItems(int value)
{   Log.e(Constant.LOG, items.size()+"");
    for (int i = value;i < items.size(); i++) {
        if(!items.get(i).isSection())
            items.remove(i);
    }
    Log.e(Constant.LOG, items.size()+"");
    adapter = new EntryAdapter(this, items, this);
    mListView.setAdapter(adapter);
}

QUESTION IS : I am not able to remove all items from the list in one shot, some stays there !

I have tried looping through adapter.count(); but no luck

My List : SECTION 1 ITEM 1 ITEM 2 Item N Section 2 But when I click on Section 1 not all ITEMS get deleted in one shot WHY! I am not able to use Expandable Listview at this stage because activity contains many more complex functionality on List. Please help me where I am going wrong!

Upvotes: 1

Views: 585

Answers (2)

hemantsb
hemantsb

Reputation: 2059

Create a new ArrayList<Collection> , Then add your item in it and then use removeAll(collection).

TRY THIS:

  private void removeItems(int value)
  {   Log.e(Constant.LOG, items.size()+"");
   ArrayList<Collection> deleteItems= new ArrayList<Collection>();

  for (int i = value;i < items.size(); i++) {
    if(!items.get(i).isSection())
       deleteItems.add(items.get(i));
}
 items.removeAll(deleteItems);
 Log.e(Constant.LOG, items.size()+"");
 adapter = new EntryAdapter(this, items, this);
 mListView.setAdapter(adapter);
 }

EDIT

Every time you are deleting an item, you are changing the index of the elements inside .

e.g : let suppose you are deleting list1 , then list[2] becomes list1 and hence your code will skip list1 next time because now your counter would be moved to 2.

Here are other ways by which you can achieve this also, Removing item while iterating it

Upvotes: 1

Cyph3rCod3r
Cyph3rCod3r

Reputation: 2088

So what exactly I did now. Instead of looping through items again I did like this :

I created another list and parallely populate it with the main array.

items.add(user);
// after populating items did this
newItems.addAll(items);  // same collection ArrayList

and finally I can play with the main array by using removeAll and addAll methods.

items.removeAll(newItems);  // remove items
items.addAll(afterPosition,newItems); // add items after position

Upvotes: 0

Related Questions