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
Anish SinghAnish Singh 

System.NullPointerException | Apex script unhanded exception

I am getting NullPointerException for the below code. At second line(highlighted) the code is giving me exception.
Can anyone please suggest if there is any other way around or if I am missing anything. I can post the further code if required.

------------------------------------------------------------------------------------


public List<objectHistoryLine> getObjectHistory(){
    Id myObjectId = String.valueOf(myObject.get('Id'));
    //String myObjectIdString = String.valueOf(myObject.get('Id'));
    String myObjectAPIName;
    //String contactIdPrefix = Contact.SObjectType.getDescribe().getKeyPrefix();
    Schema.DescribeSObjectResult objectDescription = myObject.getSObjectType().getDescribe();
    
    myObjectFieldMap = objectDescription.fields.getMap();
    objectLabel = String.valueOf(objectDescription.getLabel());

-------------------------------------------------------------------------------------------   
    
Thanks in advance.
Agustin BAgustin B
HI, that means that myObject is null when you try to retrieve the get field.
Verify how are you filling the myObject, you can also use system.debug(myObject); to see if you have any data on the first line.

If it helps please mark as correct.

If you are still with issues please post entire code.
Ram Chand HeerekarRam Chand Heerekar
Hi Anish,

please post the code.
Anish SinghAnish Singh
Thank you Agustin & Ram for your response. I even tried to catch in debug but it couldnt help.
I am sharing my rest of the code may be you could suggest some more.

-------------------------------------------------------------------------
public List<objectHistoryLine> getObjectHistory(){
    
    Id myObjectId = String.valueOf(myObject.get('Id'));
    //String myObjectIdString = String.valueOf(myObject.get('Id'));
    String myObjectAPIName;
    //String contactIdPrefix = Contact.SObjectType.getDescribe().getKeyPrefix();
    Schema.DescribeSObjectResult objectDescription = myObject.getSObjectType().getDescribe();
    
    myObjectFieldMap = objectDescription.fields.getMap();
    objectLabel = String.valueOf(objectDescription.getLabel());
    if(myObjectId != null){
         myObjectAPIName = myObjectId.getSObjectType().getDescribe().getName();
         String doubleUnderscoreC = '__c';
    
        if(myObjectAPIName.endsWith(doubleUnderscoreC)){
           mySObject = 'ParentId';
        }else{
            mySObject = myObjectAPIName+'Id';
        }
    }
    //Get the name of thew history table
    String objectHistoryTableName = objectDescription.getName();
    //if we have a custom object we need to drop the 'c' off the end before adding 'History' to get the history tables name
    if (objectDescription.isCustom()){
        objectHistoryTableName = objectHistoryTableName.substring(0, objectHistoryTableName.length()-1);
    }
    objectHistoryTableName = objectHistoryTableName + 'History';
    
    Schema.DescribeFieldResult objectHistoryFieldField = mySObjectTypeMap.get(objectHistoryTableName).getDescribe().fields.getMap().get('Field').getDescribe();
    historyFieldPicklistValues = objectHistoryFieldField.getPickListValues();
    
    list<objectHistoryLine> objectHistory = new list<objectHistoryLine>();
    
    String prevDate = '';
    
    if (recordLimit== null){
        recordLimit = 100;
    }
    list<sObject> historyList = new list<sObject>();
    if(myObjectId != null){
        historyList = Database.query( 'SELECT CreatedDate,'+
                                               'CreatedById,'+
                                               'CreatedBy.Name,'+
                                               'Field,'+
                                               'NewValue,'+
                                               'OldValue ' +
                                               'FROM ' + objectHistoryTableName + ' ' +
                                               'WHERE ' + mySObject + ' =\'' + myObjectId + '\' ' +
                                               'ORDER BY CreatedDate DESC '+
                                               'LIMIT ' + String.valueOf(recordLimit));
        system.debug('### '+historyList.size()+' '+historyList);
    }
     
    if(Test.isRunningTest()){  
        Id accountRT = Schema.SObjectType.Account.RecordTypeInfosByName.get('Client').RecordTypeId;
        objAccount = new Account();
        objAccount.RecordTypeId = accountRT;
        AccessSecurity.insertAsUser(objAccount,null);            
        Client_Territory_Detail__c ct= new Client_Territory_Detail__c(CMS_Contract_Number__c='H3305',PBP__c='015',Client__c=objAccount.id);
        AccessSecurity.insertAsUser(ct,null);
        historyList = new List<sObject>{}; //OldValue, NewValue not writeable
        historyList.add(new Client_Territory_Detail__History(parentId=ct.id, Field='CMS_Contract_Number__c'));
        historyList.add(new Client_Territory_Detail__History(parentId=ct.id, Field='created'));
        //insert historyList;
     //   System.debug('@@History'+historyList);   
    }
    for(Integer i = 0; i < historyList.size(); i++){
        sObject historyLine = historyList.get(i);
        Boolean isSFId = historyLine.get('oldValue') instanceof Id || historyLine.get('newValue') instanceof Id;
        if (((historyLine.get('newValue') != null && !(string.valueOf(historyLine.get('newValue')).startsWith('005') || string.valueOf(historyLine.get('newValue')).startsWith('00G')))
            || (historyLine.get('oldValue') != null && !(string.valueOf(historyLine.get('oldValue')).startsWith('005') || string.valueOf(historyLine.get('oldValue')).startsWith('00G')))
            ||(historyLine.get('newValue') == null && historyLine.get('oldValue') == null)) && !isSFId){
                objectHistoryLine tempHistory = new objectHistoryLine();
                // Set the Date and who performed the action
                if (null!=historyLine.get('CreatedDate') && String.valueOf(historyLine.get('CreatedDate')) != prevDate){
                    tempHistory.theDate = Datetime.valueOf(historyLine.get('CreatedDate')).format();
                    tempHistory.userId = String.valueOf(historyLine.get('CreatedById'));
                    //tempHistory.who = String.valueOf(historyLine.get('CreatedById'));
                    tempHistory.who = (String) historyLine.getSobject('CreatedBy').get('Name');
                }
                else{
                    tempHistory.theDate = '';
                    tempHistory.who = '';
                    tempHistory.userId = String.valueOf(historyLine.get('CreatedById'));
                }
                if(null!=historyLine.get('CreatedDate'))
                    prevDate = Datetime.valueOf(historyLine.get('CreatedDate')).format();
                
                // Get the field label
                String fieldLabel = GenericHistoryComponentController.returnFieldLabel(String.valueOf(historyLine.get('Field')));
                
                // Set the Action value
                if (String.valueOf(historyLine.get('Field')) == 'created') { // on Creation
                    tempHistory.action = 'Created.';
                }
                else if (historyLine.get('oldValue') != null && historyLine.get('newValue') == null){ // when deleting a value from a field
                    // Format the Date and if there's an error, catch it and re
                    try {
                        tempHistory.action = 'Deleted ' + Date.valueOf(historyLine.get('oldValue')).format() + ' in <b>' + fieldLabel + '</b>.';
                    } catch (Exception e){
                        tempHistory.action = 'Deleted ' + String.valueOf(historyLine.get('oldValue')) + ' in <b>' + fieldLabel + '</b>.';
                    }
                }
                else{ // all other scenarios
                    String fromText = '';
                    if (historyLine.get('oldValue') != null || Test.isRunningTest()) {
                        try {
                            fromText = ' from ' + Date.valueOf(historyLine.get('oldValue')).format();
                        } catch (Exception e) {
                            fromText = ' from ' + String.valueOf(historyLine.get('oldValue'));
                            
                        }
                    }
                    
                    String toText = '';
                    if (historyLine.get('newValue') != null|| Test.isRunningTest()) {
                        try {
                            toText = Date.valueOf(historyLine.get('newValue')).format();
                        } catch (Exception e) { 
                            toText = String.valueOf(historyLine.get('newValue'));
                            
                        }
                    }
                    if (toText != ''){
                       system.debug('###tempHistory###' +tempHistory);
                        tempHistory.action = 'Changed <b>' + fieldLabel + '</b>' + fromText + ' to <b>' + toText + '</b>.';
                    }
                    else {
                        tempHistory.action = 'Changed <b>' + fieldLabel;
                    }
                }
                
                // Add to the list
                objectHistory.add(tempHistory);
            }
    }
public class objectHistoryLine {
    
    public String theDate {get; set;}
    public String who {get; set;}
    public Id userId {get; set;} 
    public String action {get; set;}
}