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
Patrick G. BrownPatrick G. Brown 

Simple trigger getting List index out of bounds error

Everyone, I have the most basic trigger and am getting a silly testing error that I can't shake.  Ironically, when I manually fire this trigger, it works perfectly.  But when I test it, I receive this error: "System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, SetAccountField: execution of BeforeInsert caused by: System.ListException: List index out of bounds: 0  Trigger.SetAccountField: line 6, column 1: []"  

This trigger simply looks at a "location_ID" field on my Monthly Outreach object, which coorelates to a "location_ID" field on my Account object, then associates the Account ID to my Monthly Outreach record.  I continue to get the dreaded List Out of Bounds error.  After much research, it appears that I'm supposed to be checking to see if my account variable is null.  I thought I was doing that by adding:"if(account != null)".  Can anyone tell me what I'm doing wrong?

My trigger:
trigger SetAccountField on Monthly_Outreaches__c (before insert, before update) {
    for (Monthly_Outreaches__c mo : {
        String accid = mo.Location_ID__c;
        List<Account> account = [SELECT Id FROM Account WHERE Location_ID__c = :accid];
        if(account != null){
            account[0].Id = mo.Account__c;} else {

Here is my test class.  Again, very basic:
private class AddMonthlyOutreachesTestClass {
    static testMethod void validateMonthlyOutreaches() {
        Monthly_Outreaches__c m = new Monthly_Outreaches__c(
        // Insert Monthly Outreaches
        insert m;
        ApexPages.StandardController sc = new ApexPages.standardController(m);
        MonthlyOutreachesRedirect e = new MonthlyOutreachesRedirect(sc);
        String nextPage = e.saveAndCongrat().getURL();
        // Verify that the Congratulations page displays
        System.assertEquals('/apex/congratulations', nextPage);
Best Answer chosen by Patrick G. Brown
Bhaswanthnaga vivek vutukuriBhaswanthnaga vivek vutukuri
use if(account.size()>0) instead of account!=null

All Answers

Bhaswanthnaga vivek vutukuriBhaswanthnaga vivek vutukuri
use if(account.size()>0) instead of account!=null
This was selected as the best answer
Patrick G. BrownPatrick G. Brown
I knew it had to be something simple.  Thanks so much, Bhaswanthnaga.  This worked.
Bhaswanthnaga vivek vutukuriBhaswanthnaga vivek vutukuri
haha you are welcome :)