function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Ramkumar MurugesanRamkumar Murugesan 

Visualforce/Apex Error: Attempt to de-reference a null object

Visualforce/Apex Error: Attempt to de-reference a null object

When a user trying to attempt to open the visual force tab, he is getting the as ' Visualforce/Apex Error: Attempt to de-reference a null object '
I dont know where is getting null point expection the below visiual force pagecontroller. Please try to helpme to resolve this issue.

public with sharing class EntitySelectionController {

   public List<SelectOption> availableOptions {
        get{
            List<SelectOption> options = new List<SelectOption>();
            for(Territory territory : availableTerritories.values()){
                options.add(new SelectOption(territory.Id, territory.Name));
            }
            options.sort();
            return options;
        }
    }

    public List<SelectOption> selectedOptions { get{
        List<SelectOption> options = new List<SelectOption>();
            for(Territory territory : selectedTerritories.values()){
                options.add(new SelectOption(territory.Id, territory.Name));
            }
            options.sort();
            return options;
        }
    }

    public Map<Id, Territory> territoriesMap {get;set;}

    public Map<Id, Territory> availableTerritories {get;set;}

    public Map<Id, Territory> selectedTerritories {get;set;}

    public Set<String> existingTerritories {get;set;}

    public Set<String> totalTerritoriesToRemove {get;set;}

    public List<String> territoriesToAdd {get;set;}
    public List<String> territoriesToRemove {get;set;}

    public Integer entityCount {get;set;}

    public Territories_Synced__c territoriesSynced {get;set;}

    public Boolean selectionHasChanged {get;set;}

    public Boolean underSyncLimit {
        get{
            _Settings__c settings = _Settings__c.getInstance();
            if(settings.Entity_Sync_Limit__c != null){
                return entityCount <= Integer.valueOf(settings.Entity_Sync_Limit__c);
            } else{
                return true;
            }
        }
    }

    public EntitySelectionController() {
        territoriesMap = new Map<Id, Territory>([select Id, ParentTerritoryID, Name from Territory]);
        selectedTerritories = new Map<Id, Territory>();
        availableTerritories = new Map<Id, Territory>();
        //existingTerritories = new Set<String>();
        territoriesToAdd = new List<String>();
        territoriesToRemove= new List<String>();
        //totalTerritoriesToRemove = new Set<String>();
        entityCount = 0;
        selectionHasChanged = false;
        loadWrappedTerritories();
    }

    public void loadWrappedTerritories(){
        List<UserTerritory> userTerritories = [select TerritoryId From UserTerritory where isActive=true and userId =:UserInfo.getUserId()];

        List<Territory> territories = new List<Territory>();

        for(UserTerritory userTerritory : userTerritories){
            territories.addAll(getTerritoryHierarchy(userTerritory.TerritoryId));
        }
      
        for(Territory territory : territories){
            availableTerritories.put(territory.Id, territory);
        }

        territoriesSynced = Territories_Synced__c.getValues(UserInfo.getUserId());
        if(territoriesSynced == null){
            territoriesSynced = new Territories_Synced__c();
            territoriesSynced.Name = UserInfo.getUserId();
            territoriesSynced.Territory_Names__c = '';
        }
        for(Territory territory : availableTerritories.values()){
            if(territoriesSynced.Territory_Names__c.contains(territory.Name)){
                availableTerritories.remove(territory.Id);
                selectedTerritories.put(territory.Id, territory);
                //existingTerritories.add(territory);
            }
        }
        calculateEntitiesCount(selectedTerritories);
    }

    public List<Territory> getTerritoryHierarchy(Id topTerrId){
        List<Territory> territories = new List<Territory>();

        Territory currentTerr = territoriesMap.get(topTerrId);

        territories.add(currentTerr);

        List<Territory> childTerrs = new List<Territory>();

        for(Territory childTerr : territoriesMap.values()){
            if(childTerr.ParentTerritoryId == currentTerr.Id){
                childTerrs.add(childTerr);
            }
        }

        if(!childTerrs.isEmpty()){
            for(Territory childTerr : childTerrs){
                territories.addAll(getTerritoryHierarchy(childTerr.Id));
            }
        } else{
            return territories;
        }

        return territories;
    }

    public void selectTerritories(){
        if(!territoriesToAdd.isEmpty()){
            for(String territory : territoriesToAdd){
                selectedTerritories.put(territory, availableTerritories.remove(territory));
            }
            calculateEntitiesCount(selectedTerritories);
            territoriesToAdd = new List<String>();
            selectionHasChanged = true;
        }
    }

    public void selectAllTerritories(){
        selectedTerritories.putAll(availableTerritories);
        calculateEntitiesCount(selectedTerritories);
        availableTerritories.clear();
        selectionHasChanged = true;
    }

    public void deselectAllTerritories(){
        availableTerritories.putAll(selectedTerritories);
        entityCount = 0;
        selectedTerritories.clear();
        selectionHasChanged = true;
    }

    public void deselectTerritories(){
        if(!territoriesToRemove.isEmpty()){
            for(String territory : territoriesToRemove){
                availableTerritories.put(territory, selectedTerritories.remove(territory));
            }
            if(!selectedTerritories.isEmpty()){
                calculateEntitiesCount(selectedTerritories);
            } else{
                entityCount = 0;          
            }
            territoriesToRemove = new List<String>();
            selectionHasChanged = true;
        }
    }

    public void calculateEntitiesCount(Map<Id, Territory> territories){
        Map<Id, Group> territoryGroups = new Map<Id, Group>([select Id from Group where RelatedId in :territories.keySet() AND Type='Territory']);
      
        Integer count = [select count() from AccountShare where UserOrGroupId in :territoryGroups.keySet()];
      
        entityCount = count;
    }

    public void updateFilters(){
        /*List<String> tsfsToAdd = new List<String>();
        for(String territory : selectedTerritories){
            if(!existingTerritories.contains(territory)){
                tsfsToAdd.add(territory);
            }
        }*/
        List<String> territoryNames = new List<String>();
        for(Territory territory : selectedTerritories.values()){
            territoryNames.add(territory.Name);
        }

        territoriesSynced.Territory_Names__c = String.join(territoryNames, ',');
        upsert territoriesSynced;

        //First, remove all Entity Sync records for user
        List<Entity_Sync___c> existingSyncs = [select Id from Entity_Sync___c where User___c = :UserInfo.getUserId()];

        delete existingSyncs;

        List<Group> territoryGroups = [select Id from Group where RelatedId in :selectedTerritories.keySet() AND Type='Territory'];
        List<Id> accountIds = new List<Id>();
        if(territoryGroups != null){
            List<Id> territoryGroupIds = new List<Id>();
            for(Group territoryGroup : territorygroups){
                territoryGroupIds.add(territoryGroup.Id);
            }
            List<AccountShare> accountShares = [select AccountId from AccountShare where UserOrGroupId in :territoryGroupIds];
            for(AccountShare accountShare : accountShares){
                accountIds.add(accountShare.AccountId);
            }
        }

        List<Entity_Sync___c> newEntitySyncs = new List<Entity_Sync___c>();
        for(Id accountId : accountIds){
            Entity_Sync___c newEntitySync = new Entity_Sync___c();
            newEntitySync.User___c = UserInfo.getUserId();
            newEntitySync.Entity___c = accountId;
            newEntitySyncs.add(newEntitySync);
        }

        insert newEntitySyncs;
        /*

        List<TSF_vod__c> tsfRecordsToAdd = [select Id, Account_vod__c from TSF_vod__c where Territory_vod__c in :tsfsToAdd];

        for(TSF_vod__c tsf : tsfRecordsToAdd){
            tsf.Sync_Entity___c = true;
        }

        update tsfRecordsToAdd;

        List<TSF_vod__c> tsfRecordsToRemove = [select Id, Territory_vod__c, Sync_Entity___c from TSF_vod__c where Territory_vod__c in :totalTerritoriesToRemove];

        for(TSF_vod__c tsf : tsfRecordsToRemove){
            tsf.Sync_Entity___c = false;
        }

        update tsfRecordsToRemove;
      
        List<Territories_Synced__c> territoriesToRemove = [select Id from Territories_Synced__c where Name in :totalTerritoriesToRemove];

        delete territoriesToRemove;*/
    }
}
Ramu_SFDCRamu_SFDC
One advice I can give you is to always check the list size before accessing the content of it. For example the first two methods in your code where they are returning Options. Before returning Options check if Options is not null else return null.

Hope this helps !!
Ramkumar MurugesanRamkumar Murugesan
Can we modify the code like this as below mentioned

if(options!=null)
	return options;
else
	return null;
Please advise who to check this whether returning null or not?
Edwin VijayEdwin Vijay
The first step is to figure out the line number which causes the error. If you enable debug logs for the running user, it would show you the specific error line. You can then add a null check as suggested to prevent the error.
Ramkumar MurugesanRamkumar Murugesan

hello ,

The below method from is getting error, like  Available options are getting null in this case.

public with sharing class EntitySelectionController {

   public List<SelectOption> availableOptions {
        get{
            List<SelectOption> options = new List<SelectOption>();
            for(Territory territory : availableTerritories.values()){
                options.add(new SelectOption(territory.Id, territory.Name));
            }
            options.sort();
            return options;
        }
    }

Please advise how to prevent this.