Getting List Index out of bounds error even after null check. below sample workable code.
Apex Demo Code
String order = 'asc';
String usrId = '<userid>';
String query = 'SELECT Id, Name FROM Opportunity WHERE OwnerId =: usrId Order By Name '+order;
List<Opportunity> oppManOwner = database.query(query );
List<Opportunity> oppFiltered = new List<Opportunity>();
Integer maxRecNo = 15;
Integer pageNumber =3;
Integer indexStart = (pageNumber*maxRecNo) - (maxRecNo);
for(integer i=0; i< maxRecNo; i++){
if(oppManOwner[indexStart] != null){ // List index getting out of bounds
oppFiltered.add(oppManOwner[indexStart++]);
}
else
break;
}
In Page number 3 less than 15 records are left. So when it reaches that point I assume
oppManOwner[indexStart] != null
will break the loop, but still giving the List Index out of bounds error. What is going wrong here?