4

I'm getting the null pointer exception in for loop

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

. Is there a way to filter null in Map.get()?

Map<ID,List<AccountPartner>>actIdPartnerMap= new Map<ID,List<AccountPartner>>();

// (populate map here...)

if (!actIdPartnerMap.isEmpty()) {
    if(null != p:actIdPartnerMap.get(usr.AccountId)) {
        for(AccountPartner p:actIdPartnerMap.get(usr.AccountId)) {
            AccountShare acp = new AccountShare();
            acp.AccountId=p.AccountFromId;
            acp.UserOrGroupId=usr.id;
            acp.AccountAccessLevel='Edit';
            acp.CaseAccessLevel='Edit';
            acp.OpportunityAccessLevel='Edit';
            sharingObjects.add(acp);
            system.debug(logginglevel.INFO,'InInnerLoop*******'+acp);
        }
    }
}
7
  • 1
    I presume you're populating the map between the first and second lines? Otherwise, I'd naturally expect this map to be empty.
    – sfdcfox
    Commented Jan 12, 2016 at 19:13
  • I'm actually populating my map in a different loop before specified loop, I didn't post entire code here. my scenario is when a user is not part of the Account sharing team then need to create the new sharing object for the insert. So, before creating the new object, i need to check in the map to make sure.
    – KrForce
    Commented Jan 12, 2016 at 19:25
  • If that's the case, sounds like you need to use a try-catch block to catch the null pointer exception.
    – crmprogdev
    Commented Jan 12, 2016 at 19:27
  • @crmprogdev No, try-catch definitely should not be used here. There's no reason for a try-catch block except to use it to mask the real problem.
    – sfdcfox
    Commented Jan 12, 2016 at 19:28
  • Sounded like he was trying to see if the sharing record existed in the map and was getting null returned for the value. If so, that would require a try-catch. But I may not be following all of the use case.
    – crmprogdev
    Commented Jan 12, 2016 at 19:30

1 Answer 1

4

First, your code could be simplified:

AccountPartner[] partners = actIdPartnerMap.get(usr.AccountId);
if(partners != null) {
    for(AccountPartner p: partners) {
        sharingObjects.add(
            new AccountShare(
                AccountId=p.AccountFromId,
                UserOrGroupId=usr.id,
                AccountAccessLevel='Edit',
                CaseAccessLevel='Edit',
                OpportunityAccessLevel='Edit')
        );
    }
}

Secondly, you'll want to make sure that usr is not null. There's no other way you could get a System.NullPointerException other than if that variable were null.

2
  • Yay for much cleaner code!
    – mkorman
    Commented Jan 12, 2016 at 19:35
  • Thank you All, It worked. Putting into the list and then checking the Null. resolved the issue.
    – KrForce
    Commented Jan 12, 2016 at 19:48

You must log in to answer this question.

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