0

How can I solve the List index out of bounds: 0 issue .

  ID Accid;

  Account[] acc = [Select id,name from account where name ='test']; -->1
  if(acc.size() >0){
     Accid = acc[0].id;
   }else {
    Account[] acc1 =[Select id,name from Account where name = 'test 1'];-->2
    if(acc1.size()>0){
       Accid = acc1[0].id;
     }
   }

  User[] u = [Select id,Name from User Where Accountid=:Accid];-->3 
  if(u.size() >0){ //here throw the error like List index out of bounds: 0
    //some logic here
    //
   }

  ------some code---------
  --- some code-----------
  ---- some code----------

Here i got issue that is 1 query executed then 3 query executed size 0 after iI am not get any error executed next lines that's work fine. but 2 query executed then 3 query executed size 0 now next lines not executed that's throw the error like List index out of bounds: 0

  • Are you sure the second Account query returns a value? – Mike Chale Mar 15 '13 at 11:52
  • @Kittu : did your issue got sorted? – user10727 Apr 9 '15 at 13:22
1

You're referencing the wrong array in the second if statement, see the BAD LINE comment in the code below

ID Accid;

Account[] acc = [Select id,name from account where name ='test']; -->1
if (acc.size() > 0) {
    Accid = acc[0].id;
} else {
    Account[] acc1 =[Select id,name from Account where name = 'test 1'];-->2
    if (acc1.size() > 0) {
        Accid = acc[0].id; // BAD LINE, should be Accid = acc1[0].id
    }
}

User[] u = [Select id,Name from User Where Accountid=:Accid];-->3
  • hi Ralph thanks for your response actually my post is wrong this is actual code. pls help... ID Accid; Account[] acc = [Select id,name from account where name ='test']; -->1 if (acc.size() > 0) { Accid = acc[0].id; } else { Account[] acc1 =[Select id,name from Account where name = 'test 1'];-->2 if (acc1.size() > 0) { Accid = acc1[0].id; } } User[] u = [Select id,Name from User Where Accountid=:Accid];-->3 – Kittu Mar 15 '13 at 5:23
  • 1
    might i suggest actually formatting a bit? you're braces don't even match – Ralph Callaway Mar 15 '13 at 5:24
  • 2
    also, edit your question, commenting code just doesn't work – Ralph Callaway Mar 15 '13 at 5:25
1

you should do like below. In else condition you should do acc1[0].id but you are doing acc[0].id where acc is not has any vaue thats why you are getting this Out Of bound exception.

List<Account> acc = [Select id,name from account where name ='test'];
if(acc.size() >0){ 
Accid = acc[0].id; 
} else { 
List<Account> acc1 =[Select id,name from Account where name = 'test 1'];
 if(acc1.size()>0){ 
Accid = acc1[0].id; } 
}
  • Thanks for your response pramod now you look at my question i edited some lines ..pls give any suggestions... – Kittu Mar 15 '13 at 5:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.