[SalesForce] System.ListException: List index out of bounds: 0

I am working with webservice at below line i am getting error

System.ListException: List index out of bounds: 0

       res.resName = 'success';
       Database.SaveResult[] srList = Database.insert(accList, false);
       for(integer i = 0;i< req.accounts.size(); i++){
         if(srList[i].id !=null){
          for(integer j=0;j<req.accounts[i].contacts.size();j++)
          {
            con = new Contact();
            con.LastName = req.accounts[i].contacts[j].clName;
            con.FirstName =req.accounts[i].contacts[j].cfName; 
            con.Email = req.accounts[i].contacts[j].email;
            con.MobilePhone = req.accounts[i].contacts[j].mobile;             
            con.accountId = srList[i].id;
            contactList.add(con);  
          } 
           insert contactList;
        }
       }
       return res;

     }

Best Answer

Per your code above, only a subset of the req.accounts records actually get added to the accList (in the ELSE statement).

As such, you need to modify the for loop at the end to use a List that mirrors accList but contains the AccountWrapper objects instead of Accounts (in order to access the Contact records on that custom APEX class).

EDIT: Updated answer based on Chat.

Related Topic