Reputation: 1486
While i am trying to get value from arraylist,i got the following errors.My sample code is below.test is the name of my array list
String s = test.get(1);
04-05 11:51:42.525: E/AndroidRuntime(901): java.lang.IndexOutOfBoundsException: Invalid location 1, size is 1
04-05 11:51:42.525: E/AndroidRuntime(901): at java.util.ArrayList.get(ArrayList.java:341)
) 04-05 11:51:42.525: E/AndroidRuntime(901): at android.app.Activity.onMenuItemSelected(Activity.java:2170)
Upvotes: 2
Views: 7970
Reputation: 34765
Firstly your arraylist size is one you can get by using test.size();
so now as we all know array indexing starts with zero you can fetch test.get(0); to retrive first element in arraylist and if you try to fetch next element that is test.get(1) you will get IndexOutBound Exception...
Upvotes: 0
Reputation: 2889
Your string array is size of 1, that means it only has one string and at 0. What are you trying to get from the string array? I think the code you want is
if(test.size() >=1)
String s = test.get(0);//magical numbers are evil by the way the good book told me so
Please not that this is very bad practice, and you should really post more of your code so we know why you need the first or second string of that array.
Upvotes: 2
Reputation: 109247
Just check for test.size()
in your case its 1 that's why use String s = test.get(0);
Always first check the size of your list
or array's length
. And then get the values according to it. Remember all array and list always start with 0 in this case you last element is always your list's size() - 1.
Upvotes: 2
Reputation: 992
Invalid location 1, size is 1
means that the ArrayList starts with index[0]. If you use get(1)
you will receive the second entry.
Upvotes: 2
Reputation: 32232
your ArrayList size is 1 so its position will be 0
try this code
String s= test.get(0);
Upvotes: 0