-2

I am adding to an array list every SATURDAY and SUNDAY date of the month, for the first 3 months.

However, when I iterate through the array, to check if the values are actually correct, I seem to get only a few elements (with the size of the array still being correct though -> E.g. only two elements in the array, while the size is 26).

Any help?

info.setContentView(R.layout.calendar_dialog);
        CalendarView calendarView = info.findViewById(R.id.calendarView);

        Calendar currentDate = Calendar.getInstance();
        Calendar max = Calendar.getInstance();
        max.add(Calendar.MONTH,3);
        calendarView.setMinimumDate(currentDate);
        calendarView.setMaximumDate(max);


        Calendar temp = Calendar.getInstance();
        ArrayList<Calendar> calendars = new ArrayList<>();
        calendars.add(temp);

        while(temp.get(Calendar.MONTH) < max.get(Calendar.MONTH)) {

            temp.add(Calendar.DATE, 1);

            if(temp.get(Calendar.DAY_OF_WEEK) == 1 || temp.get(Calendar.DAY_OF_WEEK) == 7) {
                calendars.add(temp);
            }
        }

        calendarView.setDisabledDays(calendars);

        info.findViewById(R.id.calendar_ok).setOnClickListener(v -> info.dismiss());
        info.show();
Zoe
  • 27,060
  • 21
  • 118
  • 148
user9927059
  • 63
  • 2
  • 8

3 Answers3

0

You are adding the same object (temp) to the arraylist over and over again. Do this instead:

calendars.add(temp.clone());
Ridcully
  • 23,362
  • 7
  • 71
  • 86
0

You have two mistakes there:

1) The condition while(temp.get(Calendar.MONTH) < max.get(Calendar.MONTH)) is not taking into account the change of the year if the period is close the final/beginning of a new year. Comparing November 2018 and February 2019 will fail with that condition.

2) You should not add the same instance of the calendar over and over again: calendars.add(temp);. Instead, make a deep clone of the instance (temp.clone()), and add to the list a new instance with the proper values every time.

thelawnmowerman
  • 11,956
  • 2
  • 23
  • 36
0

The problem is that You use only single instance of Calendar in temp variable. You modify it in each iteration of Your while loop and store the same reference in calendars list.

In the end, calendars list contains many (You say 26) items but all of them refers exactly the same Calendar instance which was modified in each iteration.

Solution is to build completely new Calendar instance before adding it to the list:

...
if(temp.get(Calendar.DAY_OF_WEEK) == 1 || temp.get(Calendar.DAY_OF_WEEK) == 7){
    calendars.add((Calendar)temp.clone());
}
...
zolv
  • 1,720
  • 2
  • 19
  • 36