Search code examples
salesforceapex-codeapexforce.com

null pointer exception in adding element to list


I am getting a nut pointer exception when adding an element to the list. Error is System.NullPointerException: Attempt to de-reference a null object on out.add(Time.newInstance(17,00,00,00));

public class BusScheduleCache 
{   //Variable
private Cache.OrgPartition part;

//Constructor 
public BusScheduleCache()
{
    Cache.OrgPartition newobj = Cache.Org.getPartition('local.BusSchedule');
    part = newobj;
}

//methods
public void putSchedule(String busLine, Time[] schedule)
{
    part.put(busline, schedule);
}

public Time[] getSchedule (String busline)
{
    Time[] out = new List<Time>();

    out = (Time[]) part.get(busline);
    if (out == null)
    {
        out.add(Time.newInstance(8, 00, 00, 00));
        out.add(Time.newInstance(17,00,00,00));

    }

        return out;

}

}


Solution

  • The problem is that you are checking if the list out is null:

    if (out == null) { }
    

    Inside that condition you are then adding to a null list.

    Also review these two lines:

    Time[] out = new List<Time>();
    
    out = (Time[]) part.get(busline);
    

    First you instantiate the variable out with a new list, but then you assign null reference to it again.

    It might be useful doing something like this:

    Time[] out = part.containsKey(busline) ? 
                         (Time[]) part.get(busline) : new List<Time>();
    if (out.isEmpty())
    {
        out.add(Time.newInstance(8, 00, 00, 00));
        out.add(Time.newInstance(17,00,00,00));
    }
    
    return out;