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
Quang Bui 15Quang Bui 15 

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

Hi,

I try to upload an apex class from the sandbox to the prod. and receiving following error:

System.NullPointerException: Attempt to de-reference a null object
Stack Trace: Class.ClsApplicationTrainingRequestController.getPickValues: line 57, column 1 Class.ClsAppTrainRequestController_Test.myUnitTest: line 52, column 1

The person who has created the custom code has left the company years ago and I have no apex skills. Can anyone please help me with this?

Apex Class
public class ClsApplicationTrainingRequestController {

    public Application_Training_Request__c appRequest {get;set;}
    public Id trainRecordType;
    
    public ClsApplicationTrainingRequestController(ApexPages.StandardController stdController){
        Id oppyId = System.currentPageReference().getParameters().get('oppyId');
        Opportunity oppy = [Select OwnerId,AccountId,Market_sub_Segment__c,Market_Segment__c,Id,Business_Unit__c,BNG_Strategic_Market__c 
                        From Opportunity where id=:oppyId];
        appRequest = new Application_Training_Request__c();
        if(oppyId != null){
            appRequest.opportunity_name__c = oppyId;
            //appRequest.market_segment__c = oppy.market_segment__c;
            //appRequest.market_subsegment__c = oppy.market_sub_segment__c;
            appRequest.business_unit__c = oppy.business_unit__c;
            appRequest.opportunity_owner__c = oppy.ownerid;
            //appRequest.bng_strategic_market__c = oppy.bng_strategic_market__c;
            appRequest.account_name__c = oppy.accountid;    
            
            List<OpportunityCompetitor> oppyCompetitorList = [SELECT OpportunityId, Id, CompetitorName FROM OpportunityCompetitor 
                        where OpportunityId =:oppyId];
            String competitors = '';
            Map<String,String> resutlMap = new Map<String,String>();
            System.debug('---oppyCompetitorList');
            for(OpportunityCompetitor oppyComp : oppyCompetitorList){
                System.debug(resutlMap + '---resutlMap' + oppyComp.competitorname);
                if(!resutlMap.containsKey(oppyComp.competitorname)){
                    if(competitors != ''){
                        competitors += ';'; 
                    }
                    competitors += oppyComp.competitorname; 
                    resutlMap.put(oppyComp.competitorname,oppyComp.competitorname);
                    System.debug(competitors + '----' + oppyComp.competitorname);
                }
            }
            appRequest.competitor__c = competitors;
        }
    }
    
    public List<RecordType> getRecordTypeList(){
        List<RecordType> recordList = [Select Name,Id,Description,developername From RecordType where SobjectType='Application_Training_Request__c'];
        for(RecordType rt : recordList){
            if('Training_Request'.equals(rt.developername)){
                trainRecordType = rt.id;    
            }
        }
        return recordList;
    }
    public List<selectOption> getPickValues(Sobject object_name, String field_name, String first_val) {
        List<selectOption> options = new List<selectOption>(); //new list for holding all of the picklist options
        if (first_val != null) { //if there is a first value being provided
           options.add(new selectOption(first_val, first_val)); //add the first option
        }
        Schema.sObjectType sobject_type = object_name.getSObjectType(); //grab the sobject that was passed
        Schema.DescribeSObjectResult sobject_describe = sobject_type.getDescribe(); //describe the sobject
        Map<String, Schema.SObjectField> field_map = sobject_describe.fields.getMap(); //get a map of fields for the passed sobject
        List<Schema.PicklistEntry> pick_list_values = field_map.get(field_name).getDescribe().getPickListValues(); //grab the list of picklist values for the passed field on the sobject
        for (Schema.PicklistEntry a : pick_list_values) { //for all values in the picklist list
                      
             options.add(new selectOption(a.getValue(), a.getLabel())); //add the value and label to our final list
        }
        System.debug('--options' + options);
        return options; //return the List
        
    }

    public PageReference saveRequest(){
        try{
            system.debug('www saveRequet appRequest : ' + appRequest);
            if(appRequest.recordtypeid != trainRecordType){
                //appRequest.request_type__c = 'Sample Analysis';
                //appRequest.permission_on_sample_preparation__c = 'permitted';
                //appRequest.sample_status_indicator__c = 'received';
            }
            insert appRequest;
            System.debug('--appRequest---' + appRequest);
            PageReference requestPage = new ApexPages.StandardController(appRequest).view();
            requestPage.setRedirect(true);
            return requestPage;
        }catch(Exception ex){
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error, ex.getStackTraceString()));
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage()));
            System.debug('Method---:saveRequest-- linenumber :' + ex.getLineNumber() + '---message:' + ex.getMessage());
            return null;
        }
    }
}



Test Class
/**
 * This class contains unit tests for validating the behavior of Apex classes
 * and triggers.
 *
 * Unit tests are class methods that verify whether a particular piece
 * of code is working properly. Unit test methods take no arguments,
 * commit no data to the database, and are flagged with the testMethod
 * keyword in the method definition.
 *
 * All test methods in an organization are executed whenever Apex code is deployed
 * to a production organization to confirm correctness, ensure code
 * coverage, and prevent regressions. All Apex classes are
 * required to have at least 75% code coverage in order to be deployed
 * to a production organization. In addition, all triggers must have some code coverage.
 * 
 * The @isTest class annotation indicates this class only contains test
 * methods. Classes defined with the @isTest annotation do not count against
 * the organization size limit for all Apex scripts.
 *
 * See the Apex Language Reference for more information about Testing and Code Coverage.
 */
@isTest
private class ClsAppTrainRequestController_Test {

    /*static testMethod void myUnitTest() {
        Account acc = new Account();
        acc.Name = 'jinbo test accoutn13';
        insert acc;
        
        Opportunity oppy = new Opportunity();
        oppy.AccountId = acc.Id;
        oppy.StageName = 'Closed Lost';
        oppy.Name = 'test oppy name';
        oppy.CloseDate = system.today();
        insert oppy;
        OpportunityCompetitor oppyComp = new OpportunityCompetitor();
        oppyComp.competitorname = 'Atominstitut Wien';
        oppyComp.opportunityid = oppy.id;
        insert oppyComp;
        
        OpportunityCompetitor oppyComp2 = new OpportunityCompetitor();
        oppyComp2.competitorname = 'Bowman';
        oppyComp2.opportunityid = oppy.id;
        insert oppyComp2;
        
        List<RecordType> recordList = [Select Name,Id,Description,developername From RecordType where SobjectType='Application_Training_Request__c' and developername='Application_Request'];
        System.currentPageReference().getParameters().put('oppyId',oppy.id);
        ApexPages.StandardController extController = new ApexPages.StandardController(new Application_Training_Request__c());
        ClsApplicationTrainingRequestController contr = new ClsApplicationTrainingRequestController(extController);
        contr.getRecordTypeList();
        contr.saveRequest();
        contr.getPickValues(new Application_Training_Request__c(),'request_type__c',null);
        if(recordList != null && !recordList.isEmpty())
            contr.appRequest.recordtypeid = recordList.get(0).id;
    }*/
}

Thanks in advance!


 
Best Answer chosen by Quang Bui 15
Devi ChandrikaDevi Chandrika (Salesforce Developers) 
If you remove 52nd line from test class then your code coverage will decrease.If there is any other picklist field in that object pass that field instead of request_type__c.

Hope this helps you
Let me know if this helps you. Kindly mark it as solved so that it may help others in future.

Thanks and Regards​​​​​​​

All Answers

Devi ChandrikaDevi Chandrika (Salesforce Developers) 
Hi Quang,
Error might be because there is no picklist field called request_type__c ,that is why when fetching for picklist values in this field getting null pointer exception.
Please check if there is request_type__c  picklist field on Application_Training_Request__c object 

Hope this helps you
Let me know if this helps you. Kindly mark it as solved so that it may help others in future.

Thanks and Regards​​​​​​​
Quang Bui 15Quang Bui 15
Hi Devi,

thanks for your quick response!

You are right, there is no picklist request_type_c. Shall I remove ",'request_type__c',null)" from line 52?

Thanks,
Quang
Devi ChandrikaDevi Chandrika (Salesforce Developers) 
If you remove 52nd line from test class then your code coverage will decrease.If there is any other picklist field in that object pass that field instead of request_type__c.

Hope this helps you
Let me know if this helps you. Kindly mark it as solved so that it may help others in future.

Thanks and Regards​​​​​​​
This was selected as the best answer
Quang Bui 15Quang Bui 15
Thanks, Devi. It works. Is there a way to increase the code coverage? I getting this message from salesforce:

Your code coverage is 73%. You need at least 75% coverage to complete this deployment.