+ Start a Discussion
GC_00001GC_00001 

Getting substring of a field produces error message Attempt to de-reference a null object. What have I missed?

Not experienced in apex code so would appreciate some help.
Within a controller I am trying to retrieve the first 3 characters of a field to either store or just query on direct.

I have the following two fields defined:

    public String orderHeaderReason {get; set;}
    public String orderHeaderReasonFirst3 {get; set;}

and then want to use them as follows:
              // Save the reason specified on the OrderHeader - this works OK
              orderHeaderReason = orderHeader.Reason_for_Order_FOC__c;

              // Save the first 3 characters of the same field   - this fails
              orderHeaderReasonFirst3 = orderHeader.Reason_for_Order_FOC__c.substring(0,2);

              //This also fails
              orderHeaderReasonFirst3= orderHeaderReason.substring(0,2);

I am assuming that I have not correctly defined the fields orderHeaderReason and  orderHeaderReasonFirst3 but cannot see what I should be doing - I need to instantiate them in some way?

Thanks
Best Answer chosen by GC_00001
Michael WelburnMichael Welburn
If your field is null (i.e. no value has ever been set for it), it is not considered a String. In that sense, you can't execute methods to manipulate the text (which is where the "de-reference a null object" comes into play). What you'll want to do is first check if the value exists before doing any manipulation using String.isNotBlank() or String.isNotEmpty().

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_string.htm

You might also notice that you could use the left(3) method in that documentation instead of substring(0,2);
 
String orderHeaderReason = orderHeaderReason_for_Order_FOC__c;
if (String.isNotBlank(orderHeaderReason)) {
  orderHeaderReasonFirst3 = orderHeaderReason.left(3);
}

 

All Answers

Michael WelburnMichael Welburn
If your field is null (i.e. no value has ever been set for it), it is not considered a String. In that sense, you can't execute methods to manipulate the text (which is where the "de-reference a null object" comes into play). What you'll want to do is first check if the value exists before doing any manipulation using String.isNotBlank() or String.isNotEmpty().

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_string.htm

You might also notice that you could use the left(3) method in that documentation instead of substring(0,2);
 
String orderHeaderReason = orderHeaderReason_for_Order_FOC__c;
if (String.isNotBlank(orderHeaderReason)) {
  orderHeaderReasonFirst3 = orderHeaderReason.left(3);
}

 
This was selected as the best answer
GC_00001GC_00001
Perfect thank you.