[SalesForce] Custom CSV file uploading using apex getting this “Error List index out of bounds: 5

I am uploading a csv using apex programming to upload data to my custom object. I am getting this error while uploading csv file. Some the same is uploading correctly. Can one tell how to resolve this. I tried a lot but i couldn't resolve this.

Error: List index out of bounds: 5 Error is in expression '{!ReadFile}' in page

for (Integer i=1;i < filelines.size();i++)
{
     String[] inputconvalues = new String[]{};
     inputconvalues = filelines[i].split(',');
     Contact con = new Contact();
     for(Account a: accstoupload)
     {
          con.AccountId =accstoupload[i-1].id;
     } 
     if(con.AccountId!= null)
     {
          con.Lastname = inputconvalues[36];
          con.Email = inputconvalues[37];
          con.Phone = inputconvalues[38];
          contoupload.add(con);
     }
}
try
{
     insert contoupload;
}
catch (Exception e1)
{
    ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.INFO,'Account Name associate with this Contact already exist ');
    ApexPages.addMessage(errormsg);
}
return null;

Best Answer

This error occurs when you try to reference by index something in a list that does not exist. You have two lists in the sample code above 'inputconvalues' and 'accstoupload'.

inputconvalues. To receive this kind of error when using inputconvalues[] it would likely be due to one of the rows in your CSV file not having the correct number of columns in it. You can resolve this by correcting your CSV file and/or by adding some defensive code to check the size of the inputconvalues list via the size() method before accessing elements by index via inputconvalues[].

accstoupload. This looks like your code is assuming this list has the same number of items in it as the rows in your CSV file. Are you 100% sure this is the case, if not you would receive this error when your code started to process CSV rows towards the end of the file. Try giving a file with one row to test this theory.

Debug Tips:

  • Read this first. Debugging general docs.
  • ApexPage Messages. Rather than reading through large Debug Logs, I've sometimes used ApexPages.addMessage to output debug info. Try adding some of these to check the size of your two lists, you will need to comment out the lines of code accessing them to avoid the error temporarily.
  • Stack Dumps via Developer Mode.. A quick way to get some clarity on which line number is causing the error is to move to Developer Mode via the Developer Mode field on your User record (I don't recommend staying in this for long, its to slow on your VF pages). This will surface in the browser when the error occurs the line number in your code.
Related Topic