0

I have below code in apex constructor of the controller where it shows null pointer exception. Can someone please let me know if I have issues with declaration and also the workaround.

 for(Userterritory ut: [select territoryid from userterritory where userid in : resultIds])
        { system.debug(ut.territoryid);
        userterrsIds.add(ut.territoryid);}

Please userterrsids is a set of Id which is public and declared with gettter setter as below.

public set<ID> userterrsids {get;set;}
1

You could define the property in the following way to avoid getting a null pointer exception -

public set<Id> userterrsids {
    get {
        if(userterrsids == null) {
            userterrsids = new Set<Id>();
        }
        return userterrsids;
    }
    set;        
}
1

You have to initialize a variable somehow before you use it. In this case, userterrsIds is null, so "add" doesn't have anywhere to add the values to. The easiest way to do so from where you're at is to simply initialize it right before the loop:

userterrsids = new Set<Id>();
for(...) {

If you have a constructor for the class, consider initializing it there, since that's the point of a constructor. A proper constructor will make sure that all variables are set to a not-null value, if appropriate.

1
  • Can you please let me know how to initialize in the get set while declaring the Set<ID> as public. I remember such a thing I found earlier but can't find it now over google search. – Testing_SFDC Dec 4 '16 at 9:00

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.