+ Start a Discussion
Vincent van Drunen LittelVincent van Drunen Littel 

Need some help with Error Attempt to de-reference a null object ?

Hi, Im trying with this controller that when a record has been selected and when you add target it should actually add the record to the target object.
For some reason i get this error... could anyone give me a hand on thsi one?
 
public with sharing class CustomPaginationController 
{

    public Contact acc {get;set;}   
    public ApexPages.StandardSetController con{get; set;} 
    public string selectedlstAccounts {get; set;} 
    Map<Id, Account> contactMap {get; set;}
    string parentAccountId;
    public CustomPaginationController ()
    {
       acc = new Contact();
       lstAccount = new List<Contact>();
    }
    public List<Contact> lstAccount 
    {  
        get  
        {  
            if(con != null)  
                return (List<Contact>)con.getRecords();  
            else  
                return null ;  
        }  
        set;
    }  
    
    
    //added by me to test
     public PageReference addTargets() {
     
     system.debug('jjjjj');
     
        List<String> lstAccountsIds = selectedlstAccounts.split(',');
        List<Target__c> Target = new List<Target__c>();
        system.debug('oooo');
        for (string s : lstAccountsIds )
        {
            
            Target__c newtarget = new Target__c (Target__c = parentAccountId, Name = contactMap.get(s).Name);
            Target.add(newtarget);
        }
        system.debug('yyyyyyy');
        if (Target.size() > 0)
        {
            system.debug('ppppppp');
            insert Target;
        }
        string strPageRef = '"javascript:window.close();"';
        return new PageReference(strPageRef);
    }   
    
    
    public PageReference Search()
    {
        String query= '';
        String strFilter = '';
        if(acc.Name != null && (acc.Name ).trim() !='')
        {
           strFilter  = strFilter  +  ' where Name Like \''+acc.Name+'%\'' ;
        }
        if(acc.Account.Name != null && (acc.Account.Name).trim() !='' )
        {
            strFilter  = strFilter  +  ' where Name Like \''+acc.Account.Name+'%\'' ;
           
        }
        if(strFilter != '')
        {
            query = 'Select name ,id, Account.Name, Cargo__c from Contact '+strFilter+ ' limit 1000';
            System.debug('Query ---->'+ query );
            con = new ApexPages.StandardSetController(Database.getQueryLocator(query)); 
            con.setPageSize(10);
        }
        else
        {
        }
       return null;
    }
    public Boolean hasNext  
    {  
        get  
        {  
            return con.getHasNext();  
        }  
        set;  
    }  
    public Boolean hasPrevious  
    {  
        get  
        {  
            return con.getHasPrevious();  
        }  
        set;  
    }  
    public Integer pageNumber  
    {  
        get  
        {  
            return con.getPageNumber();  
        }  
        set;  
    }  
    public void previous()  
    {  
        con.previous();  
    }  
    public void next()  
    {  
        con.next();  
    }  
   
}

 
Best Answer chosen by Vincent van Drunen Littel
Amit Chaudhary 8Amit Chaudhary 8
Please try below code:-
public with sharing class CustomPaginationController 
{

    public Contact acc {get;set;}   
    public ApexPages.StandardSetController con{get; set;} 
    public string selectedlstAccounts {get; set;} 
    Map<Id, Account> contactMap {get; set;}
    string parentAccountId;
	string parentContactId;

    public CustomPaginationController ()
    {
       acc = new Contact();
       lstAccount = new List<Contact>();
	   selectedlstAccounts='';
	   contactMap = new Map<Id, Contact>([select Id, Name from Contact]);
       parentContactId = ApexPages.currentPage().getParameters().get('ContID');

    }
    public List<Contact> lstAccount 
    {  
        get  
        {  
            if(con != null)  
                return (List<Contact>)con.getRecords();  
            else  
                return null ;  
        }  
        set;
    }  
    
    
    //added by me to test
     public PageReference addTargets() {
     
     system.debug('jjjjj');
     
        List<String> lstAccountsIds = selectedlstAccounts.split(',');
        List<Target__c> Target = new List<Target__c>();
        system.debug('oooo');
        for (string s : lstAccountsIds )
        {
            Target__c newtarget = new Target__c (Target__c = parentContactId, Name = contactMap.get(s).Name);
            Target.add(newtarget);
        }
        system.debug('yyyyyyy');
        if (Target.size() > 0)
        {
            system.debug('ppppppp');
            insert Target;
        }
        string strPageRef = '"javascript:window.close();"';
        return new PageReference(strPageRef);
    }   
    
    
    public PageReference Search()
    {
        String query= '';
        String strFilter = '';
        if(acc.Name != null && (acc.Name ).trim() !='')
        {
           strFilter  = strFilter  +  ' where Name Like \''+acc.Name+'%\'' ;
        }
        if(acc.Account.Name != null && (acc.Account.Name).trim() !='' )
        {
            strFilter  = strFilter  +  ' where Name Like \''+acc.Account.Name+'%\'' ;
           
        }
        if(strFilter != '')
        {
            query = 'Select name ,id, Account.Name, Cargo__c from Contact '+strFilter+ ' limit 1000';
            System.debug('Query ---->'+ query );
            con = new ApexPages.StandardSetController(Database.getQueryLocator(query)); 
            con.setPageSize(10);
        }
        else
        {
        }
       return null;
    }
    public Boolean hasNext  
    {  
        get  
        {  
            return con.getHasNext();  
        }  
        set;  
    }  
    public Boolean hasPrevious  
    {  
        get  
        {  
            return con.getHasPrevious();  
        }  
        set;  
    }  
    public Integer pageNumber  
    {  
        get  
        {  
            return con.getPageNumber();  
        }  
        set;  
    }  
    public void previous()  
    {  
        con.previous();  
    }  
    public void next()  
    {  
        con.next();  
    }  
   
}

NOTE:- you need to pass ContID in URL like below :-
https://ap1.salesforce.com/apex/YOUR_PAGE_NAME?ContID=0039000001Z5QEU

Please pass ID and base URL according to your org
Please mark this as solution if this will solved ur issue.

Thanks
Amit chaudhary
amit.salesforce21@gmail.com

All Answers

Shrikant BagalShrikant Bagal
Please check "selectedlstAccounts" not null before using it:

line 32: List<String> lstAccountsIds = selectedlstAccounts.split(',');

should be :
List<String> lstAccountsIds = new List<String>();
if(String.isNotBlank(selectedlstAccounts))
                     lstAccountsIds = selectedlstAccounts.split(',');


Hope its help!!
 
Vincent van Drunen LittelVincent van Drunen Littel
Hi Shrikant, 
I do not get an error anymore, but it does not add the selected record to object Target!? 

I did debug but doesnt show any errors to, :/ 

Would you have any idea why its not adding the selected records to Target?

Thanks
Amit Chaudhary 8Amit Chaudhary 8
Please try below code :-
public with sharing class CustomPaginationController 
{

    public Contact acc {get;set;}   
    public ApexPages.StandardSetController con{get; set;} 
    public string selectedlstAccounts {get; set;} 
    Map<Id, Account> contactMap {get; set;}
    string parentAccountId;
    public CustomPaginationController ()
    {
       acc = new Contact();
       lstAccount = new List<Contact>();
	   selectedlstAccounts='';
	   contactMap = new Map<Id, Account>();
    }
    public List<Contact> lstAccount 
    {  
        get  
        {  
            if(con != null)  
                return (List<Contact>)con.getRecords();  
            else  
                return null ;  
        }  
        set;
    }  
    
    
    //added by me to test
     public PageReference addTargets() {
     
     system.debug('jjjjj');
     
        List<String> lstAccountsIds = selectedlstAccounts.split(',');
        List<Target__c> Target = new List<Target__c>();
        system.debug('oooo');
        for (string s : lstAccountsIds )
        {
            
            Target__c newtarget = new Target__c (Target__c = parentAccountId, Name = contactMap.get(s).Name);
            Target.add(newtarget);
        }
        system.debug('yyyyyyy');
        if (Target.size() > 0)
        {
            system.debug('ppppppp');
            insert Target;
        }
        string strPageRef = '"javascript:window.close();"';
        return new PageReference(strPageRef);
    }   
    
    
    public PageReference Search()
    {
        String query= '';
        String strFilter = '';
        if(acc.Name != null && (acc.Name ).trim() !='')
        {
           strFilter  = strFilter  +  ' where Name Like \''+acc.Name+'%\'' ;
        }
        if(acc.Account.Name != null && (acc.Account.Name).trim() !='' )
        {
            strFilter  = strFilter  +  ' where Name Like \''+acc.Account.Name+'%\'' ;
           
        }
        if(strFilter != '')
        {
            query = 'Select name ,id, Account.Name, Cargo__c from Contact '+strFilter+ ' limit 1000';
            System.debug('Query ---->'+ query );
            con = new ApexPages.StandardSetController(Database.getQueryLocator(query)); 
            con.setPageSize(10);
        }
        else
        {
        }
       return null;
    }
    public Boolean hasNext  
    {  
        get  
        {  
            return con.getHasNext();  
        }  
        set;  
    }  
    public Boolean hasPrevious  
    {  
        get  
        {  
            return con.getHasPrevious();  
        }  
        set;  
    }  
    public Integer pageNumber  
    {  
        get  
        {  
            return con.getPageNumber();  
        }  
        set;  
    }  
    public void previous()  
    {  
        con.previous();  
    }  
    public void next()  
    {  
        con.next();  
    }  
   
}

Please let us know if that will help you
 
Vincent van Drunen LittelVincent van Drunen Littel
Amit, with you code i got the following error 
Invalid id:
Error is in expression '{!addTargets}' in component <apex:commandButton> in page custompaginationvf: External entry point

Any suggestions?
Vincent van Drunen LittelVincent van Drunen Littel
<apex:page controller="CustomPaginationController" sidebar="false">

//I added this
<apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" />
<script type="text/javascript">
    $ = jQuery.noConflict();
    function Select1stAccounts(chk, contactId, Account.Name)
        {
            alert( '1' );
            var lstAccounts = $('input[id$="lstAccounts"]');
            var selectedlstAccounts = lstAccounts.val();
            
            if (chk.checked == true)
            {
                alert( '2A' );
                if (selectedlstAccounts == '')
                {
                    alert( '2A1' );
                    selectedlstAccounts = lstAccounts;
                } 
                else
                {
                    alert( '2A2' );
                    selectedlstAccounts = selectedlstAccounts + ',' + lstAccounts;
                }
            }
            else 
            {
                alert( '2B' );
                var accountIndex = selectedlstAccounts.indexOf(contactId);
                var accountToRemove = '';

                if (selectedlstAccounts.length == lstAccounts.length) {
                    accountToRemove = lstAccounts;
                }
                else {
                    if (accountIndex == 0){
                        accountToRemove = lstAccounts+ ',';
                    }
                    else{
                        accountToRemove = ',' + lstAccounts;
                    }
                }
            
                selectedlstAccounts = selectedlstAccounts.replace(accountToRemove, '');
            }
            alert( 'B' );
            lstAccounts.val(selectedlstAccounts);
            alert (lstAccounts.val());
    }
</script>
//Orignal Code
    <apex:form >
        <apex:inputHidden value="{!selectedlstAccounts}" id="lstAccountsIds"/>
        <apex:pageBlock >
            <apex:pageMessages ></apex:pageMessages>
            <apex:pageBlockButtons >
                <apex:commandButton action="{!Search}" value="Search" />
            </apex:pageBlockButtons>
            
            <apex:pageblockSection >
                <apex:inputText value="{!acc.Name}" label="Name"/> 
                
            </apex:pageblockSection>
        </apex:pageBlock>
        <apex:pageBlock id="resultId" rendered="{!if(lstAccount != null && lstAccount.size > 0, true,false )}">
            <apex:pageBlockButtons >
                <div style="text-align:right"> 
                  Total Records Found: {!Con.resultSize}  
      <apex:image url="/img/search_prevarrow_disabled.gif" styleClass="prevArrow" rendered="{!NOT(Con.HasPrevious)}"/>  
      <apex:image url="/img/search_prevarrow.gif" title="Previous Page" styleClass="prevArrow" rendered="{!Con.HasPrevious}"/>  
      <apex:commandLink action="{!Previous}" title="Previous Page" value="Previous Page" rendered="{!Con.HasPrevious}"/>  
      <apex:outputPanel styleClass="pShowLess noLink" style="color:grey" rendered="{!NOT(Con.HasPrevious)}">Previous Page</apex:outputPanel>           
      <apex:outputPanel styleClass="pShowLess noLink" style="color:grey" rendered="{!NOT(Con.HasNext)}">Next Page</apex:outputPanel>           
      <apex:commandLink title="Next Page" value="Next Page" rendered="{!Con.HasNext}" action="{!Next}"/>&nbsp;  
      <apex:image url="/img/search_nextarrow.gif" title="Next Page" styleClass="nextArrow" rendered="{!Con.HasNext}"/>  
      <apex:image url="/img/search_nextarrow_disabled.gif" rendered="{!NOT(Con.HasNext)}"/> 
      <img src="/s.gif" title="Last Page" alt="Last Page" class="last"/>         
                </div>
            </apex:pageBlockButtons>                
            <apex:pageBlockSection columns="1">
                <apex:pageBlockTable value="{!lstAccount}" var="acc" >
                <apex:column headerValue="Select" width="100px;">
                    <apex:inputCheckbox onclick="javascript:SelectAccounts(this, '{!acc.Id}');"/>
                    </apex:column>
                    <apex:column value="{!acc.Name}"/>
                    <apex:column value="{!acc.Account.Name}"/>
                    <apex:column value="{!acc.Cargo__c}"/>
                </apex:PageblockTable>
                <apex:commandButton value="Add Target" action="{!addTargets}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Thanks!
Shrikant BagalShrikant Bagal
Please change
var lstAccounts = $('input[id$="lstAccounts"]');

TO 

var lstAccounts = $('input[id$="lstAccountsIds"]');

 
Vincent van Drunen LittelVincent van Drunen Littel
Hi Amit, 

Still the same error
Invalid id:
Error is in expression '{!addTargets}' in component <apex:commandButton> in page custompaginationvf: External entry point
 
Vincent van Drunen LittelVincent van Drunen Littel

Correct, the error is after clicking the button.

I used the code from your blog to create this search box (thanks) altough i needed to make my customizations, therefore have checkbox and "add target" button, I used another code i already in place (working) to try to make the button to work. 
I guess merging the 2 is creating some problem.
The thoughts and needs behind all this is to be able to search contacts, with account name then to be able to select them and add them to a custom object called Target.

to answer you question of parentAccountId,  this comes from the code below.. but not sure what significance it has.


This is the "original code" that i used (very basic), but the add target button works

public class ContactsController {

    public String selectedContactsIds { get; set; }

    public PageReference addContact() {
        return null;
    }


    public List<Contact> contacts {get; set;}
    Map<Id, Contact> contactMap {get; set;}
     public string selectedContactIds {get; set;}
    string parentContactId;
    public ContactsController() // CHANGE THIS (SelectConcorrenteController TO ConcorrenteController)
    {
        parentContactId = ApexPages.currentPage().getParameters().get('accId');
        contactMap = new Map<Id, Contact>([select Id, Name from Contact]);
        contacts = contactMap.Values();
    }
    
     public PageReference addTargets() {
        List<string> contactIds = selectedContactIds.split(',');
        List<Target__c> Targets = new List<Target__c>();
        
        for (string s : contactIds)
        {
            Target__c Target = new Target__c(Target__c = parentContactId, Name = contactMap.get(s).Name); 
            Targets.add(target);
        }
        if (Targets.size() > 0)
        {
            insert Targets;
        }
        string strPageRef = '"javascript:window.close();"';
        return new PageReference(strPageRef);
    }
}
<apex:page controller="ContactsController" sidebar="false" showHeader="false">
<apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" />
<script type="text/javascript">
    $ = jQuery.noConflict();
    function SelectContact(chk, contactId)
        {
            var contactIds = $('input[id$="contactIds"]');
            var selectedContacts = contactIds.val();
            if (chk.checked == true)
            {
                if (selectedContacts == '')
                {
                    selectedContacts = contactId;
                }
                else
                {
                    selectedContacts = selectedContacts + ',' + contactId;
                }
            }
            else 
            {
                var contactIndex = selectedContacts.indexOf(contactId);
                var contactToRemove = '';

                if (selectedContacts.length == contactId.length) {
                    contactToRemove = contactId;
                }
                else {
                    if (contactIndex == 0){
                        contactToRemove = contactId+ ',';
                    }
                    else{
                        contactToRemove = ',' + contactId;
                    }
                }
            
                selectedContacts = selectedContacts.replace(contactToRemove, '');
            }
            
        contactIds.val(selectedContacts);
       // alert (contactIds.val());
    }
</script>
    <apex:form >
        <apex:inputHidden value="{!selectedContactsIds}" id="contactIds"/>
        <apex:pageBlock title="Select Contacts">
            <apex:pageBlockTable value="{!contacts}" var="con">
                <apex:column headerValue="Select" width="100px;">
                    <apex:inputCheckbox onclick="javascript:SelectContacts(this, '{!con.Id}');"/>
                </apex:column>
                <apex:column headerValue="Contact Name" value="{!con.Name}"/>
            </apex:pageBlockTable>
            <apex:commandButton value="Add Contact" action="{!addContact}"/>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Hope this helps..


 
Shrikant BagalShrikant Bagal
Change the 

string parentContactId

To 

public String parentContactId { get; set; }
Amit Chaudhary 8Amit Chaudhary 8
Can you Please share the screen shot of Target__c object with all fields ?
Are you want to use Account or Contact Object ?

Please check code on below post. That will help you.
https://developer.salesforce.com/page/Wrapper_Class

 
Vincent van Drunen LittelVincent van Drunen Littel
Hi Amit,
Here is a screenshot of all fields..  
User-added image

you are pointing to create a wrapper class, right? 
I believed it was not necesarry as i have pretty much the same controllers/vfpages for 3 other objects..
I have a trigger that creates a "target" upon creation of a contact --> Also i have a function code that creates a new "target" when added on a related list on for example contact, which is then shown in the related list on contact and account.
(i used target to make it easier to explain)
I just wanted to make the VFpage more accessible by using a searchbox (from your blog) So I wanted to combine my old code (funcioning) with your code of searchbox to have this.
i posted above my functioning code which has no searchbox
Amit Chaudhary 8Amit Chaudhary 8
Please try below code:-
public with sharing class CustomPaginationController 
{

    public Contact acc {get;set;}   
    public ApexPages.StandardSetController con{get; set;} 
    public string selectedlstAccounts {get; set;} 
    Map<Id, Account> contactMap {get; set;}
    string parentAccountId;
	string parentContactId;

    public CustomPaginationController ()
    {
       acc = new Contact();
       lstAccount = new List<Contact>();
	   selectedlstAccounts='';
	   contactMap = new Map<Id, Contact>([select Id, Name from Contact]);
       parentContactId = ApexPages.currentPage().getParameters().get('ContID');

    }
    public List<Contact> lstAccount 
    {  
        get  
        {  
            if(con != null)  
                return (List<Contact>)con.getRecords();  
            else  
                return null ;  
        }  
        set;
    }  
    
    
    //added by me to test
     public PageReference addTargets() {
     
     system.debug('jjjjj');
     
        List<String> lstAccountsIds = selectedlstAccounts.split(',');
        List<Target__c> Target = new List<Target__c>();
        system.debug('oooo');
        for (string s : lstAccountsIds )
        {
            Target__c newtarget = new Target__c (Target__c = parentContactId, Name = contactMap.get(s).Name);
            Target.add(newtarget);
        }
        system.debug('yyyyyyy');
        if (Target.size() > 0)
        {
            system.debug('ppppppp');
            insert Target;
        }
        string strPageRef = '"javascript:window.close();"';
        return new PageReference(strPageRef);
    }   
    
    
    public PageReference Search()
    {
        String query= '';
        String strFilter = '';
        if(acc.Name != null && (acc.Name ).trim() !='')
        {
           strFilter  = strFilter  +  ' where Name Like \''+acc.Name+'%\'' ;
        }
        if(acc.Account.Name != null && (acc.Account.Name).trim() !='' )
        {
            strFilter  = strFilter  +  ' where Name Like \''+acc.Account.Name+'%\'' ;
           
        }
        if(strFilter != '')
        {
            query = 'Select name ,id, Account.Name, Cargo__c from Contact '+strFilter+ ' limit 1000';
            System.debug('Query ---->'+ query );
            con = new ApexPages.StandardSetController(Database.getQueryLocator(query)); 
            con.setPageSize(10);
        }
        else
        {
        }
       return null;
    }
    public Boolean hasNext  
    {  
        get  
        {  
            return con.getHasNext();  
        }  
        set;  
    }  
    public Boolean hasPrevious  
    {  
        get  
        {  
            return con.getHasPrevious();  
        }  
        set;  
    }  
    public Integer pageNumber  
    {  
        get  
        {  
            return con.getPageNumber();  
        }  
        set;  
    }  
    public void previous()  
    {  
        con.previous();  
    }  
    public void next()  
    {  
        con.next();  
    }  
   
}

NOTE:- you need to pass ContID in URL like below :-
https://ap1.salesforce.com/apex/YOUR_PAGE_NAME?ContID=0039000001Z5QEU

Please pass ID and base URL according to your org
Please mark this as solution if this will solved ur issue.

Thanks
Amit chaudhary
amit.salesforce21@gmail.com
This was selected as the best answer