khalid alqahtani khalid alqahtani - 1 month ago 6
Android Question

How to store years of type Calendar into an array?

I'm trying to create an array and populate it with currentYear+1 to max of 15 Calendar [] years = {2016, 2017, 2018, 2019,.......2031} and I want to display it in a numberpicker. So far I was able to get the currentYear and add 1 year to it but I'm facing a problem when I try to store the results into an array in a for loop.

my code so far

Calendar cal;
Calendar [] years = new Calendar[15];
public Calendar [] getYears(){


cal = Calendar.getInstance();
cal.get(Calendar.YEAR);
//cal.add(Calendar.YEAR, 1);
for(int i = 1; i < years.length; i ++){

Calendar temp = cal.add(Calendar.YEAR, 1);
years [i] = temp ;

}


return years;
}

Answer

First of all, if the array holds 15 years then it would be from 2016 until 2030, not 31.

Secondly if you just add the cal field to all of the places of the array years then you will have 15 references pointing to the exact same Object. What you want to do is create cloned objects and point to them, which you can do with the clone() method.

So try changing the method to something like:

public Calendar[] getYears() {
    cal = Calendar.getInstance();
    for (int index = 0; index < years.length;) {
        years[index++] = (Calendar) cal.clone();
        cal.add(Calendar.YEAR, 1);
    }
    return years;
}

But if all you want is to store the years I would recommend changing your code to something like:

Calendar cal;
int[] years = new int[15];

public int[] getYears() {
    cal = Calendar.getInstance();
    int year = cal.get(Calendar.YEAR);
    for (int index = 0; index < years.length;) {
        years[index++] = year + index;
    }
    return years;
}