function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Lisa Haigy 37Lisa Haigy 37 

System. NullPointerException: Attempt to de-reference a null object


So I am in a jam.  I am trying to deploy a few classes and a visual force page and I am getting the following errors.  I'm new to the "developer" side of Salesforce and need at least a starting point to try and figure out what is going on. 
The full error I receive is:
System.NullPointerException: Attempt to de-reference a null object 
Stack Trace: Class.Utilities.readFieldSet: line 111, column 1 Class.Fulfillment.SendToFulfillment: line 70, column 1

global class Fulfillment {
    public static final String USER_ID = 'fulfillmentSvc VE';
    public static final String CREATE_ORDER_METHOD = 'legacyorders';
    
    @future (callout=true)
    global static void SendToFulfillment(string kitOrderId, Boolean isTest){
        Access_Service_Token__c tokenRecord = Utilities.getAccessToken(Utilities.FULFILLMENT_SERVICE_INTERFACE_NAME);
        String accessToken = tokenRecord.Access_Token__c;
        
        // querying all fields because the Custom Fields are configurable
        // which means any Kit Order field could potentially be added
        String queryFields = Utilities.getSOQLFields('Fulfillment_Order__c');
        String query = 'SELECT ' + queryFields + ' FROM Fulfillment_Order__c WHERE Id = \'' + kitOrderId + '\' LIMIT 1';
        system.debug('query: ' + query);
        Fulfillment_Order__c ko = (Fulfillment_Order__c)Database.query(query);
        System.debug('query: ' + query);
        
        
        //only process if valid ship to information was entered
        /* This is not currently used
* */
        
        if(ko.Ship_To_First_Name__c != null && ko.Ship_To_First_Name__c == 'Contact' &&
           ko.Ship_To_Last_Name__c != null && ko.Ship_To_Last_Name__c == 'Placeholder'){
               system.debug('shipping to contact placeholder');
               return;
           }
        
        Utilities.APIMapping apiMap = Utilities.getAPIMappings(Utilities.FULFILLMENT_SERVICE_INTERFACE_NAME);
        
        NewOrderRequest req = new NewOrderRequest();
        req.OrderBatchId = ko.Order_Batch__c == null ? 0 : Integer.valueOf(ko.Order_Batch__c);
        req.PlacementReference = ko.ID;
        req.ShipToFirstName = ko.Ship_To_First_Name__c == null ? ko.Contact_First_Name__c : ko.Ship_To_First_Name__c; // BC
        req.ShipToMiddle = '';
        req.ShipToLastName = ko.Ship_To_Last_Name__c == null ? ko.Contact_Last_Name__c : ko.Ship_To_Last_Name__c; // BC
        req.ShipToAddress1 = ko.Ship_To_Attention__c == null ? ko.Ship_To_Address__c : 'Attn: ' + ko.Ship_To_Attention__c;
        // if attention is populated then address 2 should be the address
        req.ShipToAddress2 = ko.Ship_To_Attention__c == null ? '' :  ko.Ship_To_Address__c;
        req.ShipToCity = ko.Ship_To_City__c == null ? '' : ko.Ship_To_City__c;
        req.ShipToState = ko.Ship_To_State__c == null ? '' : ko.Ship_To_State__c;
        req.ShipToZip = ko.Ship_To_Zip__c == null ? '' : ko.Ship_To_Zip__c;
        req.SiteName = ko.SiteName__c == null ? '': ko.SiteName__c;
        req.ShipToCountry = ko.Ship_To_Country__c == null ? '' : ko.Ship_To_Country__c;
        req.UserId = USER_ID; // this will always be static
        req.IsTestMode = false;
        req.KitsRequired = ko.Quantity__c == null ? 1 : Integer.valueOf(ko.Quantity__c);
        req.Details.SourceSystem = '5';
        
        system.debug('req' + req);
        
        // custom fields uses a fieldset to populate
        // update the Custom_Fields field set to modify the fields/values sent in the customfields
        // field in the request body
        List<String> customFields = new List<String>();
        List<Schema.FieldSetMember> fieldSetMemberList =  Utilities.readFieldSet('Custom_Fields','Fulfillment_Order__c');
        for(Schema.FieldSetMember fieldSetMemberObj : fieldSetMemberList) {
            customFields.add((String)ko.get(fieldSetMemberObj.getFieldPath()));
        }
        req.Details.CustomFields = customFields;
        
        string CallEndPoint = apiMap.EndPoint + '/' + CREATE_ORDER_METHOD;
        system.debug('CallEndPoint:' + CallEndPoint);  
        
        string requestBody = JSON.serializePretty(req);
        
        system.debug(requestBody);
        
        HttpRequest webreq = new HttpRequest();
        HttpResponse webresp = new HttpResponse();
        Http http = new Http();
        
        
        webreq.setEndpoint(CallEndPoint);
        webreq.setMethod('POST');
        webreq.setCompressed(false);
        webreq.setHeader('Content-Type', 'application/json');
        webreq.setTimeout(20000);
        webreq.setHeader('Accept', 'application/json');
        webreq.setHeader('Authorization', 'Bearer ' + accessToken);
        if (apiMap.Prod == False)    
            webreq.setHeader('x-tc-userid', '9MZ_QGFAwueYN8dV_IQj8g~~'); //uat
        else 
            webreq.setHeader('x-tc-userid', '8CeFr9rb7DZ43Pom76kMxA~~'); //prod
        
        webreq.setBody(requestBody);
        System.debug('apiMap.Prod = ' + apiMap.Prod);
        System.debug('Access Token requestBody: '+ requestBody);        
        
        try {
            webresp = http.send(webreq);
            system.debug('successfully sent to fulfillment service' + webresp);
        }
        catch(Exception e){
            system.debug('Exception to fulfillment service: ' + e.getMessage());
            Utilities.logErrors('Exception to fulfillment service: ' + e.getMessage());
        }
        
        //string jsonResponse = '';
        string jsonResponse = webresp.getBody();
        System.debug('Fulfillment jsonResponse: '+ jsonResponse);
        
        //deserialize json into the response object
        NewOrderResponse orderResp = (NewOrderResponse)JSON.deserialize(jsonResponse, NewOrderResponse.class);
        
        system.debug('orderResp' + orderResp);
        
        if(orderResp.Success){
            Integer orderId = orderResp.Data;
            
            //Fulfillment_Order__c ko = req.kitOrder;
            ko.Order_Id__c = String.valueOf(orderId);
            //update the address so we know where it shipped to
            ko.Ship_To_First_Name__c = req.ShipToFirstName;
            ko.Ship_To_Last_Name__c = req.ShipToLastName;
            ko.Ship_To_Attention__c = req.ShipToAddress2 == '' ? '' : req.ShipToAddress1;
            ko.Ship_To_Address__c = req.ShipToAddress2 == '' ? req.ShipToAddress1 : req.ShipToAddress2;
            ko.Ship_To_City__c = req.ShipToCity;
            ko.Ship_To_State__c = req.ShipToState;
            ko.Ship_To_Zip__c = req.ShipToZip;
            ko.SiteName__c = req.SiteName;
            ko.Ship_To_Country__c = req.ShipToCountry;
            
            try{
                Database.update(ko, false);
            }
            catch(Exception ex){
                system.debug('Exception updating kit order after being sent to fulfillment: ' + ex.getMessage());
                Utilities.logErrors('Exception updating kit order after being sent to fulfillment:\n' + ex.getMessage());
            }   
        }
        else{
            //return 'Fail|' + orderResp.Messages[0];
        }
        AccessService.accesssTokenCleanup(tokenRecord);
    }
    global static void GetOrderStatus(string orderId){
        
        HttpRequest webreq = new HttpRequest();
        HttpResponse webresp = new HttpResponse();
        Http http = new Http();
        
        Utilities.APIMapping apiMap = Utilities.getAPIMappings(Utilities.FULFILLMENT_SERVICE_INTERFACE_NAME);
        String endPoint = apiMap.EndPoint + '/' +CREATE_ORDER_METHOD +'/'+ orderId;
        Access_Service_Token__c tokenRecord = Utilities.getAccessToken(Utilities.FULFILLMENT_SERVICE_INTERFACE_NAME);
        String accessToken = tokenRecord.Access_Token__c;
        
        System.debug('Fulfillment.GetOrderStatus: Endpoint ' + endpoint );
        webreq.setEndpoint(endPoint);
        webreq.setMethod('GET');
        webreq.setCompressed(false);
        webreq.setHeader('Content-Type', 'application/json');
        webreq.setTimeout(20000);
        webreq.setHeader('Accept', 'application/json');
        if (apiMap.Prod == False)    
            webreq.setHeader('x-tc-userid', '9MZ_QGFAwueYN8dV_IQj8g~~'); //uat
        else 
            webreq.setHeader('x-tc-userid', '8CeFr9rb7DZ43Pom76kMxA~~'); //prod
        webreq.setHeader('Authorization', 'Bearer ' + accessToken);
        
        try{
            webresp = http.send(webreq);
            system.debug('successfully call order status service'+ webreq);
        }
        catch(Exception e){
            system.debug('Exception to fulfillment service: ' + e.getMessage());
            Utilities.logErrors('Exception to fulfillment service (GetOrders): ' + e.getMessage());
        }
        
        string jsonResponse = webresp.getBody();
        system.debug('jsonResponse: ' + jsonResponse);
        
        if(jsonResponse != null && jsonResponse != ''){
            //deserialize json into the response object
            OrderStatusResponse orderResp = (OrderStatusResponse)JSON.deserialize(jsonResponse, OrderStatusResponse.class);
            
            system.debug('orderResp ' + orderResp);
            
            if(orderResp.Success){
                system.debug('orderResp.Success' + orderResp.Success);   
                //update related order record with status info
                Fulfillment_Order__c ko = [select Id, Is_Acknowledged__c, Status__c, Is_Shipped__c, Ship_Date__c, Tracking_Number__c from Fulfillment_Order__c where Order_Id__c = :orderId];
                
                ko.Order_Id__c = String.valueOf(orderId);
                ko.Is_Acknowledged__c = orderResp.Data.IsAcknowledged;
                ko.Is_Shipped__c = orderResp.Data.IsShipped;
                ko.Status__c = orderResp.Data.OrderStatus;
                //parse dates since they come in as: May 21 2015 3:29PM
                ko.Ship_Date__c = orderResp.Data.ShipDate != null ? Utilities.FormatDate(orderResp.Data.ShipDate): null;
                ko.Tracking_Number__c = orderResp.Data.TrackingNumber;
                
                Database.update(ko, false);
                //return success message
                system.debug('Success' + ko);
            }
            else{
                system.debug(orderResp.Messages[0]);
            }
        }
        else{
            system.debug('Fail|No data was returned from order status service');
        }
        AccessService.accesssTokenCleanup(tokenRecord);
    }
    
    
    global class NewOrderRequest{
        public Integer OrderBatchId {get; set;}
        public string PlacementReference {get; set;}
        public string ShipToFirstName {get; set;}
        public string ShipToMiddle {get; set;}
        public string ShipToLastName {get; set;}
        public string ShipToAddress1 {get; set;}
        public string ShipToAddress2 {get; set;}
        public string ShipToCity {get; set;}
        public string ShipToState {get; set;}
        public string ShipToCountry {get; set;}
        public string ShipToZip {get; set;}
        public string ShipToPhone {get; set;}
        public string ShipToFax {get; set;}
        public string SiteName {get; set;}
        public string UserId {get; set;}
        public Boolean IsTestMode {get; set;}
        public Integer KitsRequired {get; set;}
        public Fulfillment_Order__c kitOrder {get; set;}
        public OrderDetails Details {get; set;}
        
        public NewOrderRequest(){
            Details = new OrderDetails();
        }
    }
    
    global class OrderDetails{
        public string SourceSystem {get; set;}
        public List<string> CustomFields {get; set;}
        
        public OrderDetails(){
        }
    }
    global class OrderStatusResponseData {
        public Boolean IsAcknowledged {get; set;}
        public Integer OrderStatusId {get; set;}
        public String OrderStatus {get; set;}
        public String VendorName {get; set;}
        public String CaseNumber {get; set;}
        public Boolean IsShipped {get; set;}
        public String ShipDate {get; set;}
        public String TrackingNumber {get; set;}
        public Integer OrderId {get; set;}
        public Integer VendorId {get; set;}
        public Integer OrderFulfillmentDetailsId {get; set;}
        
        public OrderStatusResponseData (){
            
        }
    }
    
    global class NewOrderResponse{
        public Boolean Success {get; set;}
        public List<string> Messages {get; set;}
        public Integer Data {get; set;}
        public NewOrderResponse(){
            
        }
    }
    
    global class OrderStatusResponse{
        public Boolean Success {get; set;}
        public List<String> Messages {get; set;}
        public OrderStatusResponseData Data {get;set;}
        public OrderStatusResponse(){
            
        }
    }
    
    
}


Test Class:

@isTest
private class Fulfillment_Test {
    
    // static final Id patientRecordTypeId = [Select Id From RecordType Where SObjectType = 'Account' and DeveloperName = 'IndustriesIndividual'].Id;
    
    static string Kit_Order_Id;
    
    @testSetup static void setup() {
        
        APIEndpointURLMapping__c apiRecord = new APIEndpointURLMapping__c();
        apiRecord.Name = 'FulfillmentService';
        apiRecord.InterfaceName__c = 'FulfillmentService';
        apiRecord.NonProdEndPoint__c = 'https://fulfillment-uat.trialcard.com/api/v2';
        apiRecord.ProdEndPoint__c = 'https://fulfillment-uat.trialcard.com/api/v2';
        apiRecord.NonProdPassword__c = '12345';
        apiRecord.NonProdUserName__c =  'fulfillmentSvc VE';
        apiRecord.Prod__c =  False;
        insert apiRecord;
        
        Program__c program = new Program__c(Name = 'Test Program');
        insert program;
        
        Account patientAcct = new Account(Name = 'Test Patient', Program__c = program.Id);
        insert patientAcct;
        
        Contact patientContact = new Contact(LastName = 'Patient', FirstName = 'Test', AccountId = patientAcct.Id);
        insert patientContact;
        
        Fulfillment_Order__c ko = new Fulfillment_Order__c();
        ko.Contact__c = patientContact.Id;
        ko.Order_Code__c = '123';
        ko.Order_Id__c = '1';
        ko.Ship_To_First_Name__c = 'Bob';
        ko.Ship_To_Last_Name__c = 'Bobberson';
        ko.SiteName__c = 'Lisa Haigy';
        ko.Ship_To_Address__c = '12 Main St.';
        ko.Ship_To_City__c = 'little Town';
        ko.Ship_To_State__c = 'NC';
        ko.Ship_To_Zip__c = '12345';
        ko.Ship_To_Country__c = 'US';
        ko.Status__c='Open';
        insert ko;
        
        Kit_Order_Id =ko.Id;                
    }
    
    static testMethod void testSendToFulfillment() {
        
        Test.startTest();
        
        // Get Kit Order id created in test class
        Fulfillment_Order__c ko1 = [Select Status__c From Fulfillment_Order__c Where Order_Id__c = '1'];
        Kit_Order_Id  = ko1.Id;
        
        //Fulfillment.SendToFulfillment(Kit_Order_Id, False); 
        Map<String, String> responseHeaders = new Map<String, String>();
        responseHeaders.put('Content-Type', 'application/json');
        Fulfillment.NewOrderResponse resp = new Fulfillment.NewOrderResponse();
        resp.Success = True;
        resp.Data = 1;
        string responseBody = JSON.serializePretty(resp);
        
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator(200, 'Success', responseBody, responseHeaders));
        
        system.debug('Kit_Order_Id: ' + Kit_Order_Id);
        Fulfillment.SendToFulfillment(Kit_Order_Id, False);
        Test.stopTest();
        Fulfillment_Order__c ko = [Select Status__c From Fulfillment_Order__c Where Order_Id__c = '1'];
        system.assertEquals(1 , resp.Data);
    }

    static testMethod void testGetOrderStatus() {

        Map<String, String> responseHeaders = new Map<String, String>();
        responseHeaders.put('Content-Type', 'application/json');
        
        Fulfillment.OrderStatusResponse resp = new Fulfillment.OrderStatusResponse();
        resp.Success = True;
        resp.Data = new Fulfillment.OrderStatusResponseData();
        resp.Data.IsAcknowledged = True;
        resp.Data.OrderStatusId= 1;
        resp.Data.OrderStatus='Open';
        resp.Data.VendorName='TCFax';
        resp.Data.CaseNumber ='';
        resp.Data.IsShipped=False;
        resp.Data.ShipDate = '';
        resp.Data.TrackingNumber = '';
        resp.Data.OrderId= 1;
        resp.Data.VendorId = 86;
        resp.Data.OrderFulfillmentDetailsId = 1;
        string responseBody = JSON.serializePretty(resp);
        
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator(200, 'Success', responseBody, responseHeaders));
        Test.startTest();
        Fulfillment.GetOrderStatus('1');
        Test.stopTest();
        
        Fulfillment_Order__c ko = [Select Status__c From Fulfillment_Order__c Where Order_Id__c = '1'];
        system.assertEquals('Open', ko.Status__c);
        
    }
}
Alain CabonAlain Cabon
@Lisa Haigy 37 

System.NullPointerException: Attempt to de-reference a null object 
Stack Trace: Class.Utilities.readFieldSet: line 111, column 1 Class.Fulfillment.SendToFulfillment: line 70, column 1

You should give at least these lines in your question.

Attempt to de-reference a null object => that means that you want to use a field of an object never initialized (so the object is still null itself while you want to use a field of it).

The common case of this error is when you forgot to declare the object with a "new ()" or when the initialization of an object with a method is still null (for instance an empty result for a SOQL query).