Android Question [SOLVED] For...next remove many items from list problem

yfleury

Active Member
Licensed User
Longtime User
I all.
I have list with many items. And I have to remove some items and I use a for...next todo it. But when I remove an item, the size of list change to but the For...next run for the original list size and an error occur like
java.lang.IndexOutOfBoundsException: Index: 8, Size: 8

How can do it without error?

Example code:
B4X:
    Dim liste1 As List
    liste1.Initialize
    For x=0 To 10
        liste1.Add(x)
    Next
    
    For x=0 To liste1.Size-1
        Log (x & ") " & liste1.Get(x))
    Next
    Log ("size of liste1 = " & liste1.Size)
    For x=0 To liste1.Size-1
        
        If liste1.Get(x)= 3 Or liste1.Get(x)=5 Or liste1.Get(x)=8 Then
            Log( "remove " & x & " value " & liste1.Get(x))
            liste1.RemoveAt(x)
        End If
    Next
 

ac9ts

Active Member
Licensed User
Longtime User
When you remove something, it shifts up. Start at the end of the list and go to the beginning.

B4X:
   For x=liste1.Size-1 To 0 Step -1 
        
        If liste1.Get(x)= 3 Or liste1.Get(x)=5 Or liste1.Get(x)=8 Then
            Log( "remove " & x & " value " & liste1.Get(x))
            liste1.RemoveAt(x)
        End If
    Next
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…