0

I have below code where the Map is not getting populated and throws Null Pointer error.

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

Code:

for(Business_Plan_abv__c obj : [select Id,Account_abv__c,Territory_abv__c,First_Name_abv__c,Last_Name_abv__c from Business_Plan_abv__c where Territory_abv__c=:terr]) {
    if(!accMap.containsKey(obj.Territory_abv__c)){
         accMap.put(obj.Territory_abv__c, new List<Business_Plan_abv__c>{obj});

    }else{
         accMap.get(obj.Territory_abv__c).add(obj);
    }

    system.debug('accmap@@@'+accMap);
}

Error throws elsewhere when i try getting the map values as below.

for(Business_Plan_abv__c j: accMap.get(BpToInsert[i].Territory_Name__c))
{.......
}

The map is as below.

 Public Map<String, List<Business_Plan_abv__c>> accMap = new Map<String, List<Business_Plan_abv__c>>(); 
  • Please specify the Map type. – Ankita Jul 20 '17 at 10:18
  • Public Map<String, List<Business_Plan_abv__c>> accMap = new Map<String, List<Business_Plan_abv__c>>(); – Testing_SFDC Jul 20 '17 at 10:19
  • select Id,Account_abv__c,Territory_abv__c,First_Name_abv__c,Last_Name_abv__c from Business_Plan_abv__c where Territory_abv__c=:terr Does it have values – bharath Jul 20 '17 at 10:31
1

Try to populate the map in this way:

Code:

for(Business_Plan_abv__c obj : [select Id,Account_abv__c,Territory_abv__c,First_Name_abv__c,Last_Name_abv__c from Business_Plan_abv__c where Territory_abv__c=:terr]) {
    if(!accMap.containsKey(obj.Territory_abv__c)){
         accMap.put(obj.Territory_abv__c, new List<Business_Plan_abv__c>{obj});

    }else{
         List<Business_Plan_abv__c> tempList = accMap.get(obj.Territory_abv__c)
         tempList.add(obj);
         accMap.put(obj.Territory_abv__c, tempList);
    }

    system.debug('accmap@@@'+accMap);
}

If the key is not present in the Map, then get() ,ethod returns null. Here accMap.get(BpToInsert[i].Territory_Name__c) will return null if the key is does not exist and you are trying to iterate over a null value.

Add a null check. Try this.

if(accMap.get(BpToInsert[i].Territory_Name__c) != null && accMap.get(BpToInsert[i].Territory_Name__c).size() > 0){
    for(Business_Plan_abv__c j: accMap.get(BpToInsert[i].Territory_Name__c))
    {
     .......
    }
}
  • But here the problem is accMap itself is not at all getting populated although BpToInsert[i].Territory_Name__c === has value – Testing_SFDC Jul 20 '17 at 10:26
  • Do check your SQOL because Territory_abv__c is a String and in your query you have where clause as Territory_abv__c=:terr which means you are doing case sensitive check – Ankita Jul 20 '17 at 11:49
0

Added to Ankita. IT's googd to check with containksKey()

if(accMap.ContainsKey(BpToInsert[i].Territory_Name__c){
  //   Your for loop
}

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.