IDmikael IDmikael - 1 month ago 16
Android Question

problems with assignment Calendar values

i have such problem:

i have Calendar object in Main activity:

public static Calendar today = Calendar.getInstance();


in my second activity i need to set several alarms, so i did next:

for(int i = 0; i < alarmCounter; i++){
Calendar calendar = MainActivity.today;

calendar.set(Calendar.HOUR_OF_DAY, alarmHours.get(i));
calendar.set(Calendar.MINUTE, alarmMinutes.get(i));
calendar.set(Calendar.SECOND, 0);

if (calendar.getTimeInMillis() <= System.currentTimeMillis()) {
calendar.add(Calendar.DAY_OF_YEAR, 7);
}
}


but when if condition is satisfied and 7 days are added to
calendar
, these 7 days are also added to
MainActivity.today
. Why it happens? How can i solve it?

It's important for me to save values of
MainActivity.today
because i change it's values in another method and it's not always equals current date.

Answer

This is a memory pointer problem.

Both calendar and MainActivity.today are pointing at the same Calendar istance.

If you want to keep them separated you can use the clone() method:

Calendar calendar = (Calendar)MainActivity.today.clone();