Reputation: 183
I am trying to display a list from current year plus five year in a Spinner item. But getting error java.lang.IndexOutOfBoundsException: Invalid index 2014, size is 0
I used this code,
ArrayList<String> years=new ArrayList<String>();
Calendar cal=Calendar.getInstance();
int curYear= cal.get(Calendar.YEAR);
for(int i=0;i<6;i++)
{
years.add(curYear+i, null);
}
Spinner spnYear= (Spinner) findViewById(R.id.spnYear);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, years);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnYear.setAdapter(adapter);
Please help.
Thanks.
Upvotes: 0
Views: 116
Reputation: 157457
here is your issue
for(int i=0;i<6;i++) {
years.add(curYear+i, null);
}
you are using the add method that takes a first paramter the index and as second the object. The documentation states that it throws
IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size()).
At the first iteration size()
returns 0, and you are try to put the element at position 2014
Change it in
for(int i=0;i<6;i++) {
years.add(String.valueOf(curYear+i));
}
Upvotes: 0
Reputation: 7663
It's how you're adding things to your ArrayList
. For one, you're trying to add an int curYear + i to an ArrayList<String>
. That won't work. Second you're adding them in such a way that you're not actually passing an object to the list. The version of add you're using add(int index, E object) takes the index as its first argument - not what you want to add to the list. Your second argument, which is what you actually want to add, is null. That explains why you're getting list size of 0. You should just add your values normally and know that index 0, 1, 2, 3, 4 will be the next 5 years.
Upvotes: 0
Reputation: 10974
When you use add()
with two parameters, the first is the index you would like to add it at. You'll want to just call years.add(String.valueOf(currYear + 1))
. I've also added the String.valueOf()
around the item you're adding, because you have an ArrayList<String>
Upvotes: 2