+ Start a Discussion
Suhas GB 4Suhas GB 4 

Apex trigger using AggregateResult

Here is my code:

trigger AggregateResult on Contact (after insert, after update) {

if((trigger.isinsert && trigger.isafter) || (trigger.isupdate && trigger.isafter))
{
contact c=trigger.new[0];
if(c.accountid!=null)
{

AggregateResult[] ar=[select SUM(Contact_Amount__c) ss from contact where accountid=:c.accountid];

Integer d=(Integer)ar[0].get('ss');

account ac=new account(id=c.accountid);
  ac.Total_Amount_of_Contacts__c=decimal.valueOf(String.valueOf(ar[0].get('ss')));
  update ac;
}
}

}

I want the sum of Amount field in Contact to appear on Account field. But I'm getting this error:
Apex trigger AggregateResult caused an unexpected exception, contact your administrator: AggregateResult: execution of AfterUpdate caused by: System.TypeException: Invalid conversion from runtime type Decimal to Integer: Trigger.AggregateResult: line 11, column 1

Please provide me a solution for this.
Best Answer chosen by Suhas GB 4
Shiva RajendranShiva Rajendran

Hi Suhas GB 4,
I believe the type of  Contact_Amount__c be either a decimal or double. 
You can't convert decimal or double to Integer in that way.

You have to use Integer.valueOf(ar[0].get('ss')); 
This should work , let me know if you face any further issues 
Thanks and Regards,
Shiva RV

All Answers

Deepak Maheshwari 7Deepak Maheshwari 7

Hi,

 

Please use Double instead of Integer

Deepak Maheshwari 7Deepak Maheshwari 7

Hi,

 

Did you try to change Integer to Double?

 

Hope the above solution worked for you.

 

Thanks

Deepak

Shiva RajendranShiva Rajendran

Hi Suhas GB 4,
I believe the type of  Contact_Amount__c be either a decimal or double. 
You can't convert decimal or double to Integer in that way.

You have to use Integer.valueOf(ar[0].get('ss')); 
This should work , let me know if you face any further issues 
Thanks and Regards,
Shiva RV

This was selected as the best answer
Suhas GB 4Suhas GB 4
Thanks Deepak and Shiva. Now it works. Thanks a lot guys.