0

I'm deleting my ArrayList data using for loop but the loop only deletes the last index of my list. What's wrong with this? I think this would be easy but I'm taking an hour an still cannot solve this.

 for (int i = 0; i < selectedRowFile.size() - 1; i++) {
     imagesFileName.remove(i);
         mylist.remove(i);
     adapter.notifyDataSetChanged();
     Toast.makeText(getApplicationContext(),"" + selectedRowFile.size() , Toast.LENGTH_LONG).show();
}
JREN
  • 3,572
  • 3
  • 27
  • 45
NewDroidDev
  • 1,656
  • 5
  • 19
  • 33

2 Answers2

4

You should remove an element from a List using an Iterator.

        Iterator<YourDataType> it = YourList.iterator();
        while (it.hasNext()) 
               it.remove();

With this you can use if-else to specify the element, which should be removed.

This should give you some hints, why you should use an Iterator.

Community
  • 1
  • 1
Steve Benett
  • 12,843
  • 7
  • 59
  • 79
2

I don't know why you're using a for loop, but you can also clear an ArrayList object by using clear.

List myList = new ArrayList<Object>();
myList.clear();

Using a for loop to clear an ArrayList seems dubious to me.

JREN
  • 3,572
  • 3
  • 27
  • 45