Monday 25 January 2016

Attempt to de-reference a null object Issue in SOQL Querry

Attempt to de-reference a null object is common issue, this issue occurs when particular value will be null and we are trying get that value.

I am sharing one scenario where i also faced same issue.

 String MSORecordTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Managed Sales Opportunity').getRecordTypeId();  

map<Id,Opportunity> map_Opportunity = new map<id,Opportunity>([SELECT id,Stagename FROM Opportunity WHERE name = 'test Oppty'  AND recordtypeid = :MSORecordTypeId.substring(0,15)]); 
System.debug('Printing map==='+)map_Opportunity ;
 if(map_Opportunity ! = null){
   
    Opportunity oppty = map_Opportunity.get('OpportynityId');
}

I got error on the line (Opportunity oppty = map_Opportunity.get('OpportynityId');) Because map_Opportunity is having empty value when query filter condition got unsatisfied which is not null so obliviously if condition satisfied. 

To avoid such issue we need to add condition below 

 if(map_Opportunity.keyset().size() > 0){
}

Keep Exploring and sharing more and more .. :)

No comments: