0
public class AccwithLLContactsClass {
    list<Account> lstaccount=new list<Account>();
    list<Contact> lstContact=new list<Contact>();
    public list<Contact> getconrecords(){
        lstcontact.clear();
        accId.clear();
        lstaccount.clear();
        system.debug('****Accname text value is'+accname);
        lstaccount=[Select id,name from Account where name=:accname];
        if(lstaccount.size()>0){
            for(integer i=0;i<=lstaccount.size();i++)
            {
                accId.add(lstaccount[i].Id);
            }
        }  
        lstcontact=[Select id,name,accountId from contact where accountId in:accId];
        system.debug('**** List of Contact for test is'+lstcontact);
        return lstcontact;        
    }
    set<string> accid=new set<string>();
    public pageReference showcontact(){
        return null;
    }

    public string accname{set;get;}
}

2 Answers 2

2

In this line:

for(integer i=0;i<=lstaccount.size();i++)

you probably meant to write:

for(integer i=0;i<lstaccount.size();i++)

This is because the greatest offset that you can reference is one less than the number of elements in the list.

1

An alternate way to code your getter is as follows:

public list<Contact> lstContact{
  get{
      if (this.lstContact == null) {
          this.lstContact = new List<Contact>();
          for (Account a: [select id,
                             (select id, name,accountId from Contacts)
                            from Account where name = :this.accName]) 
             this.lstContact.addAll(a.Contacts);
      }
      return this.lstcontact;
  private set;
}

One SOQL statement, no side effects by updating other variables, and efficiently reusable. If the cached value needs to be requeried, some actionMethod need merely set this.lstContact to null.

1
  • solid​​​​​​​​​​
    – martin
    Commented Jan 25, 2016 at 9:27

You must log in to answer this question.

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