+ Start a Discussion
balraj singh 33balraj singh 33 

displaying null for system.debug(accountids) but accountid has value

list<id> accountids;
for(contact con1 : [select id,accountid From contact where lastname = 'TEST'and birthdate = 2019-04-15 and firstname = 'TEST'])

{
   system.debug(con1.accountid);
      
}

system.debug(accountids);
 
Khan AnasKhan Anas (Salesforce Developers) 
Hi Balraj,

Greetings to you!

You need to add values to accountids list. Please try below code:
 
List<Id> accountids = new List<Id>();
for(Contact con1 : [SELECT Id, AccountId FROM Contact WHERE LastName = 'TEST'AND Birthdate = 2019-04-15 AND FirstName = 'TEST']){
    System.debug(con1.AccountId);
    accountids.add(con1.AccountId);
}
System.debug(accountids);

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
Raj VakatiRaj Vakati
Keep the Account Ids in Set .. because you no need to store the duplicate Id in list 
 
Set<id> accountids =new Set<Id>()
for(contact con1 : [select id,accountid From contact where lastname = 'TEST'and birthdate = 2019-04-15 and firstname = 'TEST'])

{
   accountids.add(con1.accountid);
      
}

system.debug(accountids);

 
Ajay K DubediAjay K Dubedi
Hi Balraj,

Firstly keep the Id in the Set and ensure that this contact has Account as a parent, if yes then try the below code it is working for me:
public static void check(){
        Set<Id> accountids=new Set<Id>();
        for(contact con1 : [select Id,AccountId From contact where lastname = 'TEST'and birthdate = 2019-04-15 and firstname = 'TEST']){
           system.debug(con1.Id);    
            if(con1.AccountId!=NULL){
        accountids.add(con1.AccountId);         
            }
      }
      if(accountids.size()>0){
         system.debug(accountids);
        }
    }
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks,
Ajay Dubedi