2

I have a lookup relationship.

If I just do the following query it works fine:

Sobject c = [select field__r.fieldchild__c from custom_obj where Id = :someId];
system.debug('c:' + c);

However with the following I get an error:

Sobject c = [select field__r.fieldchild__c from custom_obj where Id = :someId];
String c2 = (String) r.getSobject('field__r').get('fieldchild__c');

Error message:

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

7

You need to add a null check. The only reason this would fail is if your parent record is null. One option may be to just get the value statically:

String text = record.Parent__r.TextField__c;

If you cannot use a static reference, I recommend a cross object getter like I shared here. First create this top-level class:

public with sharing class CrossObject
{
    public static Object get(SObject record, String field)
    {
        if (record == null) return null;
        if (!field.contains('.')) return record.get(field);
        return get(
            record.getSObject(field.substringBefore('.')),
            field.substringAfter('.')
        );
    }
}

Then instead of:

String text = (String)record.get('Parent__r').get('TextField__c');

You could use:

String text = (String)CrossObject.get(record, 'Parent__r.TextField__c');
|improve this answer|||||
  • How would you use your code? I copied your CrossObject code in developer console along with my code and getting this error only top-level class methods can be declared static – Nick Kahn Jun 11 '17 at 18:33
  • Yeah you would make this class top level. Then anywhere in your code base, you could call String parentField = (String)CrossObject.get(record, 'Parent__r.TextField__c'); instead of record.getSObject('Parent__r').get('TextField__c'). – Adrian Larson Jun 11 '17 at 18:35
  • I'm getting the null after I tried your approach, I'm not sure why getting the null value? – Nick Kahn Jun 11 '17 at 18:43
  • @NickKahn Because it doesn't have a parent record specified. That's the only reason you'd get the null pointer in the first place. Verify that Parent__c is not null. – Adrian Larson Jun 11 '17 at 18:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.