1

I'm having some trouble with my code using 2 dimensional lists.

Here's where I create the list and fill it in (not necessarily will the query return something):

List<List<Task>> Tareas_Servicio = new List<List<Task>>();
    For (User Us : Servicio){
        List <Task> ta = [Select Id, ActivityDate, Who.name, subject, status, OwnerId From task Where ActivityDate=:Date.today() and OwnerId=:us.id and status!='Completed'];
        Tareas_Servicio.add(ta);           
    }  

The issue is when there are no elements that match the query (which can be very likely) I get an error in the following code:

If (!Tareas_Comercial.isEmpty()){
            string subject = 'Tareas Incompletas Departamento Comercial<br/><br/>';
            for (integer k = 0;k < Tareas_Comercial.size();k++){
                string nombre = Tareas_Comercial[K][0].who.name;
                subject = subject + nombre + ': ' + Tareas_Comercial[k].size()+'<br/>';                
          }}

The error I receive is

System.ListException: List index out of bounds: 0

I'm assuming because the list is empty and therefore can't access any data there. That's why I added the if statement to check if the list was empty before trying to do anything with it but I keep receiving the error.

How can I avoid this error if the list is empty?

  • 1
    Your Tareas_Servicio loop has a query withn a loop. This may cause governor limits to be hit if there are enough Users in the Servicio collection. Consider refactoring your code to use a Map instead. – sfdcfox Aug 16 '17 at 4:37
6

The inner list appears to be empty, not the outer list. That is, the array at [0] has no elements. A simple modification should work:

string subject = 'Tareas Incompletas Departamento Comercial<br/><br/>';
for (integer k = 0;k < Tareas_Comercial.size(); k++){
    if(Tareas_Comercial[k].size()>0) {
        string nombre = Tareas_Comercial[K][0].who.name;
        subject = subject + nombre + ': ' + Tareas_Comercial[k].size()+'<br/>';                
    }
}

The first if statement is not actually necessary, because if k is less than Tareas_Comercial.size(), the loop will not execute at all.

0

add it to the List only when ta is not empty. Here it adds an empty List at index [0] of list Tareas_Servicio.

List<List<Task>> Tareas_Servicio = new List<List<Task>>();
    For (User Us : Servicio){
    List <Task> ta = [Select Id, ActivityDate, Who.name, subject, status, 
                      OwnerId From task Where ActivityDate=:Date.today() and OwnerId=:us.id 
                      and 
                      status!='Completed'];
    if(!ta.isEmpty()){
    Tareas_Servicio.add(ta);
    }           
 }  

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.