I have a requirement where I need to compare Child object records of one parent and update values based on that. Parent Record -> Contact

Child Record 1 -> Driver (has lookup to contact)

Child Record 2 -> Vehicle (has lookup to contact)

I have to update matched__c field on Driver__c object, if Vehicle State__c matches with Driver State__c

When I am trying to get map value it is throwing

Null pointer error Attempt to de-reference a null object.

Using below logic to perform update:

Set<Id> ConIds = new Set<ID>();
for(Driver__c d : [Select Id, Contact__c,Status__c, Matched__c from Driver__c where Status__c ='Active']){

Map<Id, Vehicle__c> mapStateVehicle = new Map<ID,Vehicle__c>([Select ID, Vstate__c, Contact__c from Vehicle__c where Contact__c IN: ConIds]);

for(Driver__c d : [select Id, Name, dState__c, Contact__c from Driver__c where Name like 'XYZ%']){
    if(d.dState__c == 'IL' && mapStateVehicle.get(d.Contact__c).Vstate__c  == 'IL' ) // mapStateVehicle.get(d.Contact__c).Vstate__c receiving null pointer expcetion
        Matched__c = true;
  • 1
    There is a possibility that you have a driver record without a Contact__c field populated. In the if condition before accessinga VState__c , add a check if the map contains contact field populated: mapStateVehicle.containsKey(d.Contact__c)
    – Raul
    Oct 21, 2019 at 20:09
  • @Raul mapStateVehicle.containsKey(d.Contact__c) is returning false .How to get Contact ID from MAP? Oct 21, 2019 at 20:22
  • mapStateVehicle.containsKey(d.Contact__c) false means your key is not found in a map, thus means mapStateVehicle.get(d.Contact__c) is null and the error is because you are performing a dot operation against a null value.
    – Raul
    Oct 21, 2019 at 20:47

1 Answer 1


welcome to our forum.

I think that your query is probably giving you more than one result. Try something like this:

Set<ID> ConIds = new Set<ID>();

for(List<Driver__c> d : [SELECT Id, Contact__c,Status__c, Matched__c FROM Driver__c WHERE Status__c = 'Active]) {
          for(Driver__c driver : d) {
            if (driver.Contact__c != null) {


// Rest of your code.. you maybe need to make changes there as well.

This should populate the Set if any Driver__c is found on you query.

  • thanks for your response, ConIds are getting values, the problem is mapStateVehicle.get(d.Contact__c).Vstate__c . I am not sure how to get Contact Id and State from Vehicle__c. Oct 21, 2019 at 20:17

You must log in to answer this question.

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