4

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

2 Answers 2

9

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');
4
  • 1
    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
    Commented Jun 11, 2017 at 18:33
  • 1
    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
    Commented Jun 11, 2017 at 18:35
  • 1
    I'm getting the null after I tried your approach, I'm not sure why getting the null value?
    – Nick
    Commented Jun 11, 2017 at 18:43
  • 1
    @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
    Commented Jun 11, 2017 at 18:46
0

Hello Everyone sharing with you my code. This resolve only custom lookut relations modified code for objects that don't have '__r'.

    //==============================================
   // Criado por: Rodrigo Chiarato Domingues
   // Data: 18/04/2020
   // Propósito: dá um powerUp para o get do sObject. Exemplo Retorna qualquer campo na estrutura 'Objeto1__r.Objeto2__r.Campo__c'
   // Descrição: na função get do sObject ele só tras o campo do objeto não traz os lookups/relacionamentos/foreing key
   //            para essa função vc passa o sobject que quer pegar o campo e no string o caminho completo do campo.
   //==============================================
   public static Object sObjectPowerGet(sObject objSObject, String NomeDoCampo)
   {
      System.debug('sObjectPowerGet');
      String[] arrNomeDoCampo = NomeDoCampo.split('\\.');
      Integer NroDeCampos = arrNomeDoCampo.size();
      Object objValorOuSObject = objSObject;
      Object objValor ;
      for (Integer I = 0 ; i < NroDeCampos ;  i++)
      {
         if(I+1 == NroDeCampos) //Se for o ultimo
         {
            try
            {
               objValorOuSObject = ((sObject)objValorOuSObject).get(arrNomeDoCampo[i]);
            }
            catch(Exception objException)
            {
               System.debug(objException.getMessage());
               if(objException.getMessage().indexOfIgnoreCase('Invalid field') != -1)
               {
                  objValorOuSObject = ((sObject)objValorOuSObject).getSObject(arrNomeDoCampo[i]);
               }
               else
               {
                  throw objException;
               }
            }
         }
         else
         {
            objValorOuSObject = ((sObject)objValorOuSObject).getSObject(arrNomeDoCampo[i]);
         }
      }
      return objValorOuSObject;
   }

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .