2 * Copyright (C) 2008 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.android.calendar;
19 import static android.provider.Calendar.EVENT_BEGIN_TIME;
20 import static android.provider.Calendar.EVENT_END_TIME;
22 import android.app.Activity;
23 import android.app.AlertDialog;
24 import android.app.DatePickerDialog;
25 import android.app.ProgressDialog;
26 import android.app.TimePickerDialog;
27 import android.app.DatePickerDialog.OnDateSetListener;
28 import android.app.TimePickerDialog.OnTimeSetListener;
29 import android.content.AsyncQueryHandler;
30 import android.content.ContentResolver;
31 import android.content.ContentUris;
32 import android.content.ContentValues;
33 import android.content.Context;
34 import android.content.DialogInterface;
35 import android.content.Intent;
36 import android.content.SharedPreferences;
37 import android.content.DialogInterface.OnCancelListener;
38 import android.content.DialogInterface.OnClickListener;
39 import android.content.res.Resources;
40 import android.database.Cursor;
41 import android.net.Uri;
42 import android.os.Bundle;
43 import android.pim.EventRecurrence;
44 import android.preference.PreferenceManager;
45 import android.provider.Calendar.Calendars;
46 import android.provider.Calendar.Events;
47 import android.provider.Calendar.Reminders;
48 import android.text.TextUtils;
49 import android.text.format.DateFormat;
50 import android.text.format.DateUtils;
51 import android.text.format.Time;
52 import android.util.Log;
53 import android.view.KeyEvent;
54 import android.view.LayoutInflater;
55 import android.view.Menu;
56 import android.view.MenuItem;
57 import android.view.View;
58 import android.view.Window;
59 import android.widget.ArrayAdapter;
60 import android.widget.Button;
61 import android.widget.CheckBox;
62 import android.widget.CompoundButton;
63 import android.widget.DatePicker;
64 import android.widget.ImageButton;
65 import android.widget.LinearLayout;
66 import android.widget.ResourceCursorAdapter;
67 import android.widget.Spinner;
68 import android.widget.TextView;
69 import android.widget.TimePicker;
70 import android.widget.Toast;
72 import java.util.ArrayList;
73 import java.util.Arrays;
74 import java.util.Calendar;
75 import java.util.TimeZone;
77 public class EditEvent extends Activity implements View.OnClickListener,
78 DialogInterface.OnCancelListener, DialogInterface.OnClickListener {
80 * This is the symbolic name for the key used to pass in the boolean
81 * for creating all-day events that is part of the extra data of the intent.
82 * This is used only for creating new events and is set to true if
83 * the default for the new event should be an all-day event.
85 public static final String EVENT_ALL_DAY = "allDay";
87 private static final int MAX_REMINDERS = 5;
89 private static final int MENU_GROUP_REMINDER = 1;
90 private static final int MENU_GROUP_SHOW_OPTIONS = 2;
91 private static final int MENU_GROUP_HIDE_OPTIONS = 3;
93 private static final int MENU_ADD_REMINDER = 1;
94 private static final int MENU_SHOW_EXTRA_OPTIONS = 2;
95 private static final int MENU_HIDE_EXTRA_OPTIONS = 3;
97 private static final String[] EVENT_PROJECTION = new String[] {
100 Events.DESCRIPTION, // 2
101 Events.EVENT_LOCATION, // 3
103 Events.HAS_ALARM, // 5
104 Events.CALENDAR_ID, // 6
106 Events.DURATION, // 8
107 Events.EVENT_TIMEZONE, // 9
109 Events._SYNC_ID, // 11
110 Events.TRANSPARENCY, // 12
111 Events.VISIBILITY, // 13
113 private static final int EVENT_INDEX_ID = 0;
114 private static final int EVENT_INDEX_TITLE = 1;
115 private static final int EVENT_INDEX_DESCRIPTION = 2;
116 private static final int EVENT_INDEX_EVENT_LOCATION = 3;
117 private static final int EVENT_INDEX_ALL_DAY = 4;
118 private static final int EVENT_INDEX_HAS_ALARM = 5;
119 private static final int EVENT_INDEX_CALENDAR_ID = 6;
120 private static final int EVENT_INDEX_DTSTART = 7;
121 private static final int EVENT_INDEX_DURATION = 8;
122 private static final int EVENT_INDEX_TIMEZONE = 9;
123 private static final int EVENT_INDEX_RRULE = 10;
124 private static final int EVENT_INDEX_SYNC_ID = 11;
125 private static final int EVENT_INDEX_TRANSPARENCY = 12;
126 private static final int EVENT_INDEX_VISIBILITY = 13;
128 private static final String[] CALENDARS_PROJECTION = new String[] {
130 Calendars.DISPLAY_NAME, // 1
131 Calendars.TIMEZONE, // 2
133 private static final int CALENDARS_INDEX_DISPLAY_NAME = 1;
134 private static final int CALENDARS_INDEX_TIMEZONE = 2;
135 private static final String CALENDARS_WHERE = Calendars.ACCESS_LEVEL + ">=" +
136 Calendars.CONTRIBUTOR_ACCESS + " AND " + Calendars.SYNC_EVENTS + "=1";
138 private static final String[] REMINDERS_PROJECTION = new String[] {
140 Reminders.MINUTES, // 1
142 private static final int REMINDERS_INDEX_MINUTES = 1;
143 private static final String REMINDERS_WHERE = Reminders.EVENT_ID + "=%d AND (" +
144 Reminders.METHOD + "=" + Reminders.METHOD_ALERT + " OR " + Reminders.METHOD + "=" +
145 Reminders.METHOD_DEFAULT + ")";
147 private static final int DOES_NOT_REPEAT = 0;
148 private static final int REPEATS_DAILY = 1;
149 private static final int REPEATS_EVERY_WEEKDAY = 2;
150 private static final int REPEATS_WEEKLY_ON_DAY = 3;
151 private static final int REPEATS_MONTHLY_ON_DAY_COUNT = 4;
152 private static final int REPEATS_MONTHLY_ON_DAY = 5;
153 private static final int REPEATS_YEARLY = 6;
154 private static final int REPEATS_CUSTOM = 7;
156 private static final int MODIFY_UNINITIALIZED = 0;
157 private static final int MODIFY_SELECTED = 1;
158 private static final int MODIFY_ALL = 2;
159 private static final int MODIFY_ALL_FOLLOWING = 3;
161 private static final int DAY_IN_SECONDS = 24 * 60 * 60;
163 private int mFirstDayOfWeek; // cached in onCreate
165 private Cursor mEventCursor;
166 private Cursor mCalendarsCursor;
168 private Button mStartDateButton;
169 private Button mEndDateButton;
170 private Button mStartTimeButton;
171 private Button mEndTimeButton;
172 private Button mSaveButton;
173 private Button mDeleteButton;
174 private Button mDiscardButton;
175 private CheckBox mAllDayCheckBox;
176 private Spinner mCalendarsSpinner;
177 private Spinner mRepeatsSpinner;
178 private Spinner mAvailabilitySpinner;
179 private Spinner mVisibilitySpinner;
180 private TextView mTitleTextView;
181 private TextView mLocationTextView;
182 private TextView mDescriptionTextView;
183 private View mRemindersSeparator;
184 private LinearLayout mRemindersContainer;
185 private LinearLayout mExtraOptions;
186 private ArrayList<Integer> mOriginalMinutes = new ArrayList<Integer>();
187 private ArrayList<LinearLayout> mReminderItems = new ArrayList<LinearLayout>(0);
189 private EventRecurrence mEventRecurrence = new EventRecurrence();
190 private String mRrule;
191 private boolean mCalendarsQueryComplete;
192 private boolean mSaveAfterQueryComplete;
193 private ProgressDialog mLoadingCalendarsDialog;
194 private AlertDialog mNoCalendarsDialog;
195 private ContentValues mInitialValues;
198 * If the repeating event is created on the phone and it hasn't been
199 * synced yet to the web server, then there is a bug where you can't
200 * delete or change an instance of the repeating event. This case
201 * can be detected with mSyncId. If mSyncId == null, then the repeating
202 * event has not been synced to the phone, in which case we won't allow
203 * the user to change one instance.
205 private String mSyncId;
207 private ArrayList<Integer> mRecurrenceIndexes = new ArrayList<Integer> (0);
208 private ArrayList<Integer> mReminderValues;
209 private ArrayList<String> mReminderLabels;
211 private Time mStartTime;
212 private Time mEndTime;
213 private int mModification = MODIFY_UNINITIALIZED;
214 private int mDefaultReminderMinutes;
216 private DeleteEventHelper mDeleteEventHelper;
217 private QueryHandler mQueryHandler;
219 /* This class is used to update the time buttons. */
220 private class TimeListener implements OnTimeSetListener {
223 public TimeListener(View view) {
227 public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
228 // Cache the member variables locally to avoid inner class overhead.
229 Time startTime = mStartTime;
230 Time endTime = mEndTime;
232 // Cache the start and end millis so that we limit the number
233 // of calls to normalize() and toMillis(), which are fairly
237 if (mView == mStartTimeButton) {
238 // The start time was changed.
239 int hourDuration = endTime.hour - startTime.hour;
240 int minuteDuration = endTime.minute - startTime.minute;
242 startTime.hour = hourOfDay;
243 startTime.minute = minute;
244 startMillis = startTime.normalize(true);
246 // Also update the end time to keep the duration constant.
247 endTime.hour = hourOfDay + hourDuration;
248 endTime.minute = minute + minuteDuration;
249 endMillis = endTime.normalize(true);
251 // The end time was changed.
252 startMillis = startTime.toMillis(true);
253 endTime.hour = hourOfDay;
254 endTime.minute = minute;
255 endMillis = endTime.normalize(true);
257 // Do not allow an event to have an end time before the start time.
258 if (endTime.before(startTime)) {
259 endTime.set(startTime);
260 endMillis = startMillis;
264 setDate(mEndDateButton, endMillis);
265 setTime(mStartTimeButton, startMillis);
266 setTime(mEndTimeButton, endMillis);
270 private class TimeClickListener implements View.OnClickListener {
273 public TimeClickListener(Time time) {
277 public void onClick(View v) {
278 new TimePickerDialog(EditEvent.this, new TimeListener(v),
279 mTime.hour, mTime.minute,
280 DateFormat.is24HourFormat(EditEvent.this)).show();
284 private class DateListener implements OnDateSetListener {
287 public DateListener(View view) {
291 public void onDateSet(DatePicker view, int year, int month, int monthDay) {
292 // Cache the member variables locally to avoid inner class overhead.
293 Time startTime = mStartTime;
294 Time endTime = mEndTime;
296 // Cache the start and end millis so that we limit the number
297 // of calls to normalize() and toMillis(), which are fairly
301 if (mView == mStartDateButton) {
302 // The start date was changed.
303 int yearDuration = endTime.year - startTime.year;
304 int monthDuration = endTime.month - startTime.month;
305 int monthDayDuration = endTime.monthDay - startTime.monthDay;
307 startTime.year = year;
308 startTime.month = month;
309 startTime.monthDay = monthDay;
310 startMillis = startTime.normalize(true);
312 // Also update the end date to keep the duration constant.
313 endTime.year = year + yearDuration;
314 endTime.month = month + monthDuration;
315 endTime.monthDay = monthDay + monthDayDuration;
316 endMillis = endTime.normalize(true);
318 // If the start date has changed then update the repeats.
321 // The end date was changed.
322 startMillis = startTime.toMillis(true);
324 endTime.month = month;
325 endTime.monthDay = monthDay;
326 endMillis = endTime.normalize(true);
328 // Do not allow an event to have an end time before the start time.
329 if (endTime.before(startTime)) {
330 endTime.set(startTime);
331 endMillis = startMillis;
335 setDate(mStartDateButton, startMillis);
336 setDate(mEndDateButton, endMillis);
337 setTime(mEndTimeButton, endMillis); // In case end time had to be reset
341 private class DateClickListener implements View.OnClickListener {
344 public DateClickListener(Time time) {
348 public void onClick(View v) {
349 new DatePickerDialog(EditEvent.this, new DateListener(v), mTime.year,
350 mTime.month, mTime.monthDay).show();
354 private class CalendarsAdapter extends ResourceCursorAdapter {
355 public CalendarsAdapter(Context context, Cursor c) {
356 super(context, R.layout.calendars_item, c);
357 setDropDownViewResource(R.layout.calendars_dropdown_item);
361 public void bindView(View view, Context context, Cursor cursor) {
362 TextView name = (TextView) view.findViewById(R.id.calendar_name);
363 name.setText(cursor.getString(CALENDARS_INDEX_DISPLAY_NAME));
367 // This is called if the user clicks on one of the buttons: "Save",
368 // "Discard", or "Delete". This is also called if the user clicks
369 // on the "remove reminder" button.
370 public void onClick(View v) {
371 if (v == mSaveButton) {
378 if (v == mDeleteButton) {
379 long begin = mStartTime.toMillis(false /* use isDst */);
380 long end = mEndTime.toMillis(false /* use isDst */);
382 switch (mModification) {
383 case MODIFY_SELECTED:
384 which = DeleteEventHelper.DELETE_SELECTED;
386 case MODIFY_ALL_FOLLOWING:
387 which = DeleteEventHelper.DELETE_ALL_FOLLOWING;
390 which = DeleteEventHelper.DELETE_ALL;
393 mDeleteEventHelper.delete(begin, end, mEventCursor, which);
397 if (v == mDiscardButton) {
402 // This must be a click on one of the "remove reminder" buttons
403 LinearLayout reminderItem = (LinearLayout) v.getParent();
404 LinearLayout parent = (LinearLayout) reminderItem.getParent();
405 parent.removeView(reminderItem);
406 mReminderItems.remove(reminderItem);
407 updateRemindersVisibility();
410 // This is called if the user cancels a popup dialog. There are two
411 // dialogs: the "Loading calendars" dialog, and the "No calendars"
412 // dialog. The "Loading calendars" dialog is shown if there is a delay
413 // in loading the calendars (needed when creating an event) and the user
414 // tries to save the event before the calendars have finished loading.
415 // The "No calendars" dialog is shown if there are no syncable calendars.
416 public void onCancel(DialogInterface dialog) {
417 if (dialog == mLoadingCalendarsDialog) {
418 mSaveAfterQueryComplete = false;
419 } else if (dialog == mNoCalendarsDialog) {
424 // This is called if the user clicks on a dialog button.
425 public void onClick(DialogInterface dialog, int which) {
426 if (dialog == mNoCalendarsDialog) {
431 private class QueryHandler extends AsyncQueryHandler {
432 public QueryHandler(ContentResolver cr) {
437 protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
438 // If the Activity is finishing, then close the cursor.
439 // Otherwise, use the new cursor in the adapter.
441 stopManagingCursor(cursor);
444 mCalendarsCursor = cursor;
445 startManagingCursor(cursor);
448 getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
449 Window.PROGRESS_VISIBILITY_OFF);
451 // If there are no syncable calendars, then we cannot allow
452 // creating a new event.
453 if (cursor.getCount() == 0) {
454 // Cancel the "loading calendars" dialog if it exists
455 if (mSaveAfterQueryComplete) {
456 mLoadingCalendarsDialog.cancel();
459 // Create an error message for the user that, when clicked,
460 // will exit this activity without saving the event.
461 AlertDialog.Builder builder = new AlertDialog.Builder(EditEvent.this);
462 builder.setTitle(R.string.no_syncable_calendars)
463 .setIcon(android.R.drawable.ic_dialog_alert)
464 .setMessage(R.string.no_calendars_found)
465 .setPositiveButton(android.R.string.ok, EditEvent.this)
466 .setOnCancelListener(EditEvent.this);
467 mNoCalendarsDialog = builder.show();
471 // populate the calendars spinner
472 CalendarsAdapter adapter = new CalendarsAdapter(EditEvent.this, mCalendarsCursor);
473 mCalendarsSpinner.setAdapter(adapter);
474 mCalendarsQueryComplete = true;
475 if (mSaveAfterQueryComplete) {
476 mLoadingCalendarsDialog.cancel();
485 protected void onCreate(Bundle icicle) {
486 super.onCreate(icicle);
487 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
488 setContentView(R.layout.edit_event);
490 mFirstDayOfWeek = Calendar.getInstance().getFirstDayOfWeek();
492 mStartTime = new Time();
493 mEndTime = new Time();
495 Intent intent = getIntent();
496 mUri = intent.getData();
499 mEventCursor = managedQuery(mUri, EVENT_PROJECTION, null, null);
500 if (mEventCursor == null || mEventCursor.getCount() == 0) {
501 // The cursor is empty. This can happen if the event was deleted.
507 long begin = intent.getLongExtra(EVENT_BEGIN_TIME, 0);
508 long end = intent.getLongExtra(EVENT_END_TIME, 0);
510 boolean allDay = false;
511 if (mEventCursor != null) {
512 // The event already exists so fetch the all-day status
513 mEventCursor.moveToFirst();
514 allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
515 String rrule = mEventCursor.getString(EVENT_INDEX_RRULE);
516 String timezone = mEventCursor.getString(EVENT_INDEX_TIMEZONE);
517 long calendarId = mEventCursor.getInt(EVENT_INDEX_CALENDAR_ID);
519 // Remember the initial values
520 mInitialValues = new ContentValues();
521 mInitialValues.put(EVENT_BEGIN_TIME, begin);
522 mInitialValues.put(EVENT_END_TIME, end);
523 mInitialValues.put(Events.ALL_DAY, allDay ? 1 : 0);
524 mInitialValues.put(Events.RRULE, rrule);
525 mInitialValues.put(Events.EVENT_TIMEZONE, timezone);
526 mInitialValues.put(Events.CALENDAR_ID, calendarId);
528 // We are creating a new event, so set the default from the
529 // intent (if specified).
530 allDay = intent.getBooleanExtra(EVENT_ALL_DAY, false);
533 getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
534 Window.PROGRESS_VISIBILITY_ON);
536 // Start a query in the background to read the list of calendars
537 mQueryHandler = new QueryHandler(getContentResolver());
538 mQueryHandler.startQuery(0, null, Calendars.CONTENT_URI, CALENDARS_PROJECTION,
539 CALENDARS_WHERE, null /* selection args */, null /* sort order */);
542 // If the event is all-day, read the times in UTC timezone
545 String tz = mStartTime.timezone;
546 mStartTime.timezone = Time.TIMEZONE_UTC;
547 mStartTime.set(begin);
548 mStartTime.timezone = tz;
550 // Calling normalize to calculate isDst
551 mStartTime.normalize(true);
553 mStartTime.set(begin);
559 String tz = mStartTime.timezone;
560 mEndTime.timezone = Time.TIMEZONE_UTC;
562 mEndTime.timezone = tz;
564 // Calling normalize to calculate isDst
565 mEndTime.normalize(true);
571 // cache all the widgets
572 mTitleTextView = (TextView) findViewById(R.id.title);
573 mLocationTextView = (TextView) findViewById(R.id.location);
574 mDescriptionTextView = (TextView) findViewById(R.id.description);
575 mStartDateButton = (Button) findViewById(R.id.start_date);
576 mEndDateButton = (Button) findViewById(R.id.end_date);
577 mStartTimeButton = (Button) findViewById(R.id.start_time);
578 mEndTimeButton = (Button) findViewById(R.id.end_time);
579 mAllDayCheckBox = (CheckBox) findViewById(R.id.is_all_day);
580 mCalendarsSpinner = (Spinner) findViewById(R.id.calendars);
581 mRepeatsSpinner = (Spinner) findViewById(R.id.repeats);
582 mAvailabilitySpinner = (Spinner) findViewById(R.id.availability);
583 mVisibilitySpinner = (Spinner) findViewById(R.id.visibility);
584 mRemindersSeparator = findViewById(R.id.reminders_separator);
585 mRemindersContainer = (LinearLayout) findViewById(R.id.reminders_container);
586 mExtraOptions = (LinearLayout) findViewById(R.id.extra_options_container);
588 mAllDayCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
589 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
591 if (mEndTime.hour == 0 && mEndTime.minute == 0) {
593 long endMillis = mEndTime.normalize(true);
595 // Do not allow an event to have an end time before the start time.
596 if (mEndTime.before(mStartTime)) {
597 mEndTime.set(mStartTime);
598 endMillis = mEndTime.normalize(true);
600 setDate(mEndDateButton, endMillis);
601 setTime(mEndTimeButton, endMillis);
604 mStartTimeButton.setVisibility(View.GONE);
605 mEndTimeButton.setVisibility(View.GONE);
607 if (mEndTime.hour == 0 && mEndTime.minute == 0) {
609 long endMillis = mEndTime.normalize(true);
610 setDate(mEndDateButton, endMillis);
611 setTime(mEndTimeButton, endMillis);
614 mStartTimeButton.setVisibility(View.VISIBLE);
615 mEndTimeButton.setVisibility(View.VISIBLE);
621 mAllDayCheckBox.setChecked(true);
623 mAllDayCheckBox.setChecked(false);
626 mSaveButton = (Button) findViewById(R.id.save);
627 mSaveButton.setOnClickListener(this);
629 mDeleteButton = (Button) findViewById(R.id.delete);
630 mDeleteButton.setOnClickListener(this);
632 mDiscardButton = (Button) findViewById(R.id.discard);
633 mDiscardButton.setOnClickListener(this);
635 // Initialize the reminder values array.
636 Resources r = getResources();
637 String[] strings = r.getStringArray(R.array.reminder_minutes_values);
638 int size = strings.length;
639 ArrayList<Integer> list = new ArrayList<Integer>(size);
640 for (int i = 0 ; i < size ; i++) {
641 list.add(Integer.parseInt(strings[i]));
643 mReminderValues = list;
644 String[] labels = r.getStringArray(R.array.reminder_minutes_labels);
645 mReminderLabels = new ArrayList<String>(Arrays.asList(labels));
647 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
648 String durationString =
649 prefs.getString(CalendarPreferenceActivity.KEY_DEFAULT_REMINDER, "0");
650 mDefaultReminderMinutes = Integer.parseInt(durationString);
653 boolean hasAlarm = (mEventCursor != null)
654 && (mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0);
656 Uri uri = Reminders.CONTENT_URI;
657 long eventId = mEventCursor.getLong(EVENT_INDEX_ID);
658 String where = String.format(REMINDERS_WHERE, eventId);
659 ContentResolver cr = getContentResolver();
660 Cursor reminderCursor = cr.query(uri, REMINDERS_PROJECTION, where, null, null);
662 // First pass: collect all the custom reminder minutes (e.g.,
663 // a reminder of 8 minutes) into a global list.
664 while (reminderCursor.moveToNext()) {
665 int minutes = reminderCursor.getInt(REMINDERS_INDEX_MINUTES);
666 EditEvent.addMinutesToList(this, mReminderValues, mReminderLabels, minutes);
669 // Second pass: create the reminder spinners
670 reminderCursor.moveToPosition(-1);
671 while (reminderCursor.moveToNext()) {
672 int minutes = reminderCursor.getInt(REMINDERS_INDEX_MINUTES);
673 mOriginalMinutes.add(minutes);
674 EditEvent.addReminder(this, this, mReminderItems, mReminderValues,
675 mReminderLabels, minutes);
678 reminderCursor.close();
681 updateRemindersVisibility();
683 mDeleteEventHelper = new DeleteEventHelper(this, true /* exit when done */);
685 if (mEventCursor == null) {
686 // Allow the intent to specify the fields in the event.
687 // This will allow other apps to create events easily.
688 initFromIntent(intent);
692 private void initFromIntent(Intent intent) {
693 String title = intent.getStringExtra(Events.TITLE);
695 mTitleTextView.setText(title);
698 String location = intent.getStringExtra(Events.EVENT_LOCATION);
699 if (location != null) {
700 mLocationTextView.setText(location);
703 String description = intent.getStringExtra(Events.DESCRIPTION);
704 if (description != null) {
705 mDescriptionTextView.setText(description);
708 int availability = intent.getIntExtra(Events.TRANSPARENCY, -1);
709 if (availability != -1) {
710 mAvailabilitySpinner.setSelection(availability);
713 int visibility = intent.getIntExtra(Events.VISIBILITY, -1);
714 if (visibility != -1) {
715 mVisibilitySpinner.setSelection(visibility);
718 String rrule = intent.getStringExtra(Events.RRULE);
721 mEventRecurrence.parse(rrule);
726 protected void onResume() {
730 if (mEventCursor == null || mEventCursor.getCount() == 0) {
731 // The cursor is empty. This can happen if the event was deleted.
737 if (mEventCursor != null) {
738 Cursor cursor = mEventCursor;
739 cursor.moveToFirst();
741 mRrule = cursor.getString(EVENT_INDEX_RRULE);
742 String title = cursor.getString(EVENT_INDEX_TITLE);
743 String description = cursor.getString(EVENT_INDEX_DESCRIPTION);
744 String location = cursor.getString(EVENT_INDEX_EVENT_LOCATION);
745 int availability = cursor.getInt(EVENT_INDEX_TRANSPARENCY);
746 int visibility = cursor.getInt(EVENT_INDEX_VISIBILITY);
747 if (visibility > 0) {
748 // For now we the array contains the values 0, 2, and 3. We subtract one to match.
752 if (!TextUtils.isEmpty(mRrule) && mModification == MODIFY_UNINITIALIZED) {
753 // If this event has not been synced, then don't allow deleting
754 // or changing a single instance.
755 mSyncId = cursor.getString(EVENT_INDEX_SYNC_ID);
756 mEventRecurrence.parse(mRrule);
758 // If we haven't synced this repeating event yet, then don't
759 // allow the user to change just one instance.
761 CharSequence[] items;
762 if (mSyncId == null) {
763 items = new CharSequence[2];
765 items = new CharSequence[3];
766 items[itemIndex++] = getText(R.string.modify_event);
768 items[itemIndex++] = getText(R.string.modify_all);
769 items[itemIndex++] = getText(R.string.modify_all_following);
771 // Display the modification dialog.
772 new AlertDialog.Builder(this)
773 .setOnCancelListener(new OnCancelListener() {
774 public void onCancel(DialogInterface dialog) {
778 .setTitle(R.string.edit_event_label)
779 .setItems(items, new OnClickListener() {
780 public void onClick(DialogInterface dialog, int which) {
783 (mSyncId == null) ? MODIFY_ALL : MODIFY_SELECTED;
784 } else if (which == 1) {
786 (mSyncId == null) ? MODIFY_ALL_FOLLOWING : MODIFY_ALL;
787 } else if (which == 2) {
788 mModification = MODIFY_ALL_FOLLOWING;
791 // If we are modifying all the events in a
792 // series then disable and ignore the date.
793 if (mModification == MODIFY_ALL) {
794 mStartDateButton.setEnabled(false);
795 mEndDateButton.setEnabled(false);
796 } else if (mModification == MODIFY_SELECTED) {
797 mRepeatsSpinner.setEnabled(false);
799 // We could allow changing the Rrule for
800 // all following instances but we'll
801 // keep it simple for now.
802 mRepeatsSpinner.setEnabled(false);
809 mTitleTextView.setText(title);
810 mLocationTextView.setText(location);
811 mDescriptionTextView.setText(description);
812 mAvailabilitySpinner.setSelection(availability);
813 mVisibilitySpinner.setSelection(visibility);
815 // This is an existing event so hide the calendar spinner
816 // since we can't change the calendar.
817 View calendarSeparator = findViewById(R.id.calendar_separator);
818 View calendarLabel = findViewById(R.id.calendar_label);
819 calendarSeparator.setVisibility(View.GONE);
820 calendarLabel.setVisibility(View.GONE);
821 mCalendarsSpinner.setVisibility(View.GONE);
822 } else if (Time.isEpoch(mStartTime) && Time.isEpoch(mEndTime)) {
823 mStartTime.setToNow();
825 // Round the time to the nearest half hour.
826 mStartTime.second = 0;
827 int minute = mStartTime.minute;
828 if (minute > 0 && minute <= 30) {
829 mStartTime.minute = 30;
831 mStartTime.minute = 0;
832 mStartTime.hour += 1;
835 long startMillis = mStartTime.normalize(true /* ignore isDst */);
836 mEndTime.set(startMillis + DateUtils.HOUR_IN_MILLIS);
838 // New event - set the default reminder
839 if (mDefaultReminderMinutes != 0) {
840 addReminder(this, this, mReminderItems, mReminderValues,
841 mReminderLabels, mDefaultReminderMinutes);
844 // Hide delete button
845 mDeleteButton.setVisibility(View.GONE);
848 updateRemindersVisibility();
854 public boolean onCreateOptionsMenu(Menu menu) {
856 item = menu.add(MENU_GROUP_REMINDER, MENU_ADD_REMINDER, 0,
857 R.string.add_new_reminder);
858 item.setIcon(R.drawable.ic_menu_reminder);
859 item.setAlphabeticShortcut('r');
861 item = menu.add(MENU_GROUP_SHOW_OPTIONS, MENU_SHOW_EXTRA_OPTIONS, 0,
862 R.string.edit_event_show_extra_options);
863 item.setIcon(R.drawable.ic_menu_show_list);
864 item = menu.add(MENU_GROUP_HIDE_OPTIONS, MENU_HIDE_EXTRA_OPTIONS, 0,
865 R.string.edit_event_hide_extra_options);
866 item.setIcon(R.drawable.ic_menu_show_list);
868 return super.onCreateOptionsMenu(menu);
872 public boolean onPrepareOptionsMenu(Menu menu) {
873 if (mReminderItems.size() < MAX_REMINDERS) {
874 menu.setGroupVisible(MENU_GROUP_REMINDER, true);
875 menu.setGroupEnabled(MENU_GROUP_REMINDER, true);
877 menu.setGroupVisible(MENU_GROUP_REMINDER, false);
878 menu.setGroupEnabled(MENU_GROUP_REMINDER, false);
881 if (mExtraOptions.getVisibility() == View.VISIBLE) {
882 menu.setGroupVisible(MENU_GROUP_SHOW_OPTIONS, false);
883 menu.setGroupVisible(MENU_GROUP_HIDE_OPTIONS, true);
885 menu.setGroupVisible(MENU_GROUP_SHOW_OPTIONS, true);
886 menu.setGroupVisible(MENU_GROUP_HIDE_OPTIONS, false);
889 return super.onPrepareOptionsMenu(menu);
893 public boolean onOptionsItemSelected(MenuItem item) {
894 switch (item.getItemId()) {
895 case MENU_ADD_REMINDER:
896 // TODO: when adding a new reminder, make it different from the
897 // last one in the list (if any).
898 if (mDefaultReminderMinutes == 0) {
899 addReminder(this, this, mReminderItems, mReminderValues,
900 mReminderLabels, 10 /* minutes */);
902 addReminder(this, this, mReminderItems, mReminderValues,
903 mReminderLabels, mDefaultReminderMinutes);
905 updateRemindersVisibility();
907 case MENU_SHOW_EXTRA_OPTIONS:
908 mExtraOptions.setVisibility(View.VISIBLE);
910 case MENU_HIDE_EXTRA_OPTIONS:
911 mExtraOptions.setVisibility(View.GONE);
914 return super.onOptionsItemSelected(item);
918 public boolean onKeyDown(int keyCode, KeyEvent event) {
920 case KeyEvent.KEYCODE_BACK:
921 // If we are creating a new event, do not create it if the
922 // title, location and description are all empty, in order to
923 // prevent accidental "no subject" event creations.
924 if (mUri != null || !isEmpty()) {
926 // We cannot exit this activity because the calendars
927 // are still loading.
934 return super.onKeyDown(keyCode, event);
937 private void populateWhen() {
938 long startMillis = mStartTime.toMillis(false /* use isDst */);
939 long endMillis = mEndTime.toMillis(false /* use isDst */);
940 setDate(mStartDateButton, startMillis);
941 setDate(mEndDateButton, endMillis);
943 setTime(mStartTimeButton, startMillis);
944 setTime(mEndTimeButton, endMillis);
946 mStartDateButton.setOnClickListener(new DateClickListener(mStartTime));
947 mEndDateButton.setOnClickListener(new DateClickListener(mEndTime));
949 mStartTimeButton.setOnClickListener(new TimeClickListener(mStartTime));
950 mEndTimeButton.setOnClickListener(new TimeClickListener(mEndTime));
953 private void populateRepeats() {
954 Time time = mStartTime;
955 Resources r = getResources();
956 int resource = android.R.layout.simple_spinner_item;
958 String[] days = r.getStringArray(R.array.day_labels);
959 String[] ordinals = r.getStringArray(R.array.ordinal_labels);
961 // Only display "Custom" in the spinner if the device does not support the
962 // recurrence functionality of the event. Only display every weekday if
963 // the event starts on a weekday.
964 boolean isCustomRecurrence = isCustomRecurrence();
965 boolean isWeekdayEvent = isWeekdayEvent();
967 ArrayList<String> repeatArray = new ArrayList<String>(0);
968 ArrayList<Integer> recurrenceIndexes = new ArrayList<Integer>(0);
970 repeatArray.add(r.getString(R.string.does_not_repeat));
971 recurrenceIndexes.add(DOES_NOT_REPEAT);
973 repeatArray.add(r.getString(R.string.daily));
974 recurrenceIndexes.add(REPEATS_DAILY);
976 if (isWeekdayEvent) {
977 repeatArray.add(r.getString(R.string.every_weekday));
978 recurrenceIndexes.add(REPEATS_EVERY_WEEKDAY);
981 String format = r.getString(R.string.weekly);
982 repeatArray.add(String.format(format, time.format("%A")));
983 recurrenceIndexes.add(REPEATS_WEEKLY_ON_DAY);
985 // Calculate whether this is the 1st, 2nd, 3rd, 4th, or last appearance of the given day.
986 int dayNumber = (time.monthDay - 1) / 7;
987 format = r.getString(R.string.monthly_on_day_count);
988 repeatArray.add(String.format(format, ordinals[dayNumber], days[time.weekDay]));
989 recurrenceIndexes.add(REPEATS_MONTHLY_ON_DAY_COUNT);
991 format = r.getString(R.string.monthly_on_day);
992 repeatArray.add(String.format(format, time.monthDay));
993 recurrenceIndexes.add(REPEATS_MONTHLY_ON_DAY);
995 long when = time.toMillis(false);
996 format = r.getString(R.string.yearly);
998 if (DateFormat.is24HourFormat(this)) {
999 flags |= DateUtils.FORMAT_24HOUR;
1001 repeatArray.add(String.format(format, DateUtils.formatDateTime(this, when, flags)));
1002 recurrenceIndexes.add(REPEATS_YEARLY);
1004 if (isCustomRecurrence) {
1005 repeatArray.add(r.getString(R.string.custom));
1006 recurrenceIndexes.add(REPEATS_CUSTOM);
1008 mRecurrenceIndexes = recurrenceIndexes;
1010 int position = recurrenceIndexes.indexOf(DOES_NOT_REPEAT);
1011 if (mRrule != null) {
1012 if (isCustomRecurrence) {
1013 position = recurrenceIndexes.indexOf(REPEATS_CUSTOM);
1015 switch (mEventRecurrence.freq) {
1016 case EventRecurrence.DAILY:
1017 position = recurrenceIndexes.indexOf(REPEATS_DAILY);
1019 case EventRecurrence.WEEKLY:
1020 if (mEventRecurrence.repeatsOnEveryWeekDay()) {
1021 position = recurrenceIndexes.indexOf(REPEATS_EVERY_WEEKDAY);
1023 position = recurrenceIndexes.indexOf(REPEATS_WEEKLY_ON_DAY);
1026 case EventRecurrence.MONTHLY:
1027 if (mEventRecurrence.repeatsMonthlyOnDayCount()) {
1028 position = recurrenceIndexes.indexOf(REPEATS_MONTHLY_ON_DAY_COUNT);
1030 position = recurrenceIndexes.indexOf(REPEATS_MONTHLY_ON_DAY);
1033 case EventRecurrence.YEARLY:
1034 position = recurrenceIndexes.indexOf(REPEATS_YEARLY);
1039 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, resource, repeatArray);
1040 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
1041 mRepeatsSpinner.setAdapter(adapter);
1042 mRepeatsSpinner.setSelection(position);
1045 // Adds a reminder to the displayed list of reminders.
1046 // Returns true if successfully added reminder, false if no reminders can
1048 static boolean addReminder(Activity activity, View.OnClickListener listener,
1049 ArrayList<LinearLayout> items, ArrayList<Integer> values,
1050 ArrayList<String> labels, int minutes) {
1052 if (items.size() >= MAX_REMINDERS) {
1056 LayoutInflater inflater = activity.getLayoutInflater();
1057 LinearLayout parent = (LinearLayout) activity.findViewById(R.id.reminder_items_container);
1058 LinearLayout reminderItem = (LinearLayout) inflater.inflate(R.layout.edit_reminder_item, null);
1059 parent.addView(reminderItem);
1061 Spinner spinner = (Spinner) reminderItem.findViewById(R.id.reminder_value);
1062 Resources res = activity.getResources();
1063 int resource = android.R.layout.simple_spinner_item;
1064 ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity, resource, labels);
1065 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
1066 spinner.setAdapter(adapter);
1068 ImageButton reminderRemoveButton;
1069 reminderRemoveButton = (ImageButton) reminderItem.findViewById(R.id.reminder_remove);
1070 reminderRemoveButton.setOnClickListener(listener);
1072 int index = findMinutesInReminderList(values, minutes);
1073 spinner.setSelection(index);
1074 items.add(reminderItem);
1079 static void addMinutesToList(Context context, ArrayList<Integer> values,
1080 ArrayList<String> labels, int minutes) {
1081 int index = values.indexOf(minutes);
1086 // The requested "minutes" does not exist in the list, so insert it
1089 String label = constructReminderLabel(context, minutes, false);
1090 int len = values.size();
1091 for (int i = 0; i < len; i++) {
1092 if (minutes < values.get(i)) {
1093 values.add(i, minutes);
1094 labels.add(i, label);
1099 values.add(minutes);
1100 labels.add(len, label);
1104 * Finds the index of the given "minutes" in the "values" list.
1106 * @param values the list of minutes corresponding to the spinner choices
1107 * @param minutes the minutes to search for in the values list
1108 * @return the index of "minutes" in the "values" list
1110 private static int findMinutesInReminderList(ArrayList<Integer> values, int minutes) {
1111 int index = values.indexOf(minutes);
1113 // This should never happen.
1114 Log.e("Cal", "Cannot find minutes (" + minutes + ") in list");
1120 // Constructs a label given an arbitrary number of minutes. For example,
1121 // if the given minutes is 63, then this returns the string "63 minutes".
1122 // As another example, if the given minutes is 120, then this returns
1124 static String constructReminderLabel(Context context, int minutes, boolean abbrev) {
1125 Resources resources = context.getResources();
1128 if (minutes % 60 != 0) {
1131 resId = R.plurals.Nmins;
1133 resId = R.plurals.Nminutes;
1135 } else if (minutes % (24 * 60) != 0) {
1136 value = minutes / 60;
1137 resId = R.plurals.Nhours;
1139 value = minutes / ( 24 * 60);
1140 resId = R.plurals.Ndays;
1143 String format = resources.getQuantityString(resId, value);
1144 return String.format(format, value);
1147 private void updateRemindersVisibility() {
1148 if (mReminderItems.size() == 0) {
1149 mRemindersSeparator.setVisibility(View.GONE);
1150 mRemindersContainer.setVisibility(View.GONE);
1152 mRemindersSeparator.setVisibility(View.VISIBLE);
1153 mRemindersContainer.setVisibility(View.VISIBLE);
1157 private void setDate(TextView view, long millis) {
1158 int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR |
1159 DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_MONTH |
1160 DateUtils.FORMAT_ABBREV_WEEKDAY;
1161 view.setText(DateUtils.formatDateTime(this, millis, flags));
1164 private void setTime(TextView view, long millis) {
1165 int flags = DateUtils.FORMAT_SHOW_TIME;
1166 if (DateFormat.is24HourFormat(this)) {
1167 flags |= DateUtils.FORMAT_24HOUR;
1169 view.setText(DateUtils.formatDateTime(this, millis, flags));
1172 // Saves the event. Returns true if it is okay to exit this activity.
1173 private boolean save() {
1174 // If we are creating a new event, then make sure we wait until the
1175 // query to fetch the list of calendars has finished.
1176 if (mEventCursor == null) {
1177 if (!mCalendarsQueryComplete) {
1178 // Wait for the calendars query to finish.
1179 if (mLoadingCalendarsDialog == null) {
1180 // Create the progress dialog
1181 mLoadingCalendarsDialog = ProgressDialog.show(this,
1182 getText(R.string.loading_calendars_title),
1183 getText(R.string.loading_calendars_message),
1185 mSaveAfterQueryComplete = true;
1190 // Avoid creating a new event if the calendars cursor is empty. This
1191 // shouldn't ever happen since the setup wizard should ensure the user
1193 if (mCalendarsCursor == null || mCalendarsCursor.getCount() == 0) {
1194 Log.w("Cal", "The calendars table does not contain any calendars."
1195 + " New event was not created.");
1198 Toast.makeText(this, R.string.creating_event, Toast.LENGTH_SHORT).show();
1200 Toast.makeText(this, R.string.saving_event, Toast.LENGTH_SHORT).show();
1203 ContentResolver cr = getContentResolver();
1204 ContentValues values = getContentValuesFromUi();
1207 // For recurring events, we must make sure that we use duration rather
1210 // Create new event with new contents
1211 addRecurrenceRule(values);
1212 uri = cr.insert(Events.CONTENT_URI, values);
1214 } else if (mRrule == null) {
1215 // Modify contents of a non-repeating event
1216 addRecurrenceRule(values);
1217 checkTimeDependentFields(values);
1218 cr.update(uri, values, null, null);
1220 } else if (mInitialValues.getAsString(Events.RRULE) == null) {
1221 // This event was changed from a non-repeating event to a
1223 addRecurrenceRule(values);
1224 values.remove(Events.DTEND);
1225 cr.update(uri, values, null, null);
1227 } else if (mModification == MODIFY_SELECTED) {
1228 // Modify contents of the current instance of repeating event
1230 // Create a recurrence exception
1231 long begin = mInitialValues.getAsLong(EVENT_BEGIN_TIME);
1232 values.put(Events.ORIGINAL_EVENT, mEventCursor.getString(EVENT_INDEX_SYNC_ID));
1233 values.put(Events.ORIGINAL_INSTANCE_TIME, begin);
1234 boolean allDay = mInitialValues.getAsInteger(Events.ALL_DAY) != 0;
1235 values.put(Events.ORIGINAL_ALL_DAY, allDay ? 1 : 0);
1237 uri = cr.insert(Events.CONTENT_URI, values);
1239 } else if (mModification == MODIFY_ALL_FOLLOWING) {
1240 // Modify this instance and all future instances of repeating event
1241 addRecurrenceRule(values);
1243 if (mRrule == null) {
1244 // We've changed a recurring event to a non-recurring event.
1245 // If the event we are editing is the first in the series,
1246 // then delete the whole series. Otherwise, update the series
1247 // to end at the new start time.
1248 if (isFirstEventInSeries()) {
1249 cr.delete(uri, null, null);
1251 // Update the current repeating event to end at the new
1253 updatePastEvents(cr, uri);
1255 uri = cr.insert(Events.CONTENT_URI, values);
1257 if (isFirstEventInSeries()) {
1258 checkTimeDependentFields(values);
1259 values.remove(Events.DTEND);
1260 cr.update(uri, values, null, null);
1262 // Update the current repeating event to end at the new
1264 updatePastEvents(cr, uri);
1266 // Create a new event with the user-modified fields
1267 values.remove(Events.DTEND);
1268 uri = cr.insert(Events.CONTENT_URI, values);
1272 } else if (mModification == MODIFY_ALL) {
1274 // Modify all instances of repeating event
1275 addRecurrenceRule(values);
1277 if (mRrule == null) {
1278 // We've changed a recurring event to a non-recurring event.
1279 // Delete the whole series and replace it with a new
1280 // non-recurring event.
1281 cr.delete(uri, null, null);
1282 uri = cr.insert(Events.CONTENT_URI, values);
1284 checkTimeDependentFields(values);
1285 values.remove(Events.DTEND);
1286 cr.update(uri, values, null, null);
1291 long eventId = ContentUris.parseId(uri);
1292 ArrayList<Integer> reminderMinutes = reminderItemsToMinutes(mReminderItems,
1294 saveReminders(cr, eventId, reminderMinutes, mOriginalMinutes);
1299 private boolean isFirstEventInSeries() {
1300 int dtStart = mEventCursor.getColumnIndexOrThrow(Events.DTSTART);
1301 long start = mEventCursor.getLong(dtStart);
1302 return start == mStartTime.toMillis(true);
1305 private void updatePastEvents(ContentResolver cr, Uri uri) {
1306 long oldStartMillis = mEventCursor.getLong(EVENT_INDEX_DTSTART);
1307 String oldDuration = mEventCursor.getString(EVENT_INDEX_DURATION);
1308 boolean allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
1309 String oldRrule = mEventCursor.getString(EVENT_INDEX_RRULE);
1310 mEventRecurrence.parse(oldRrule);
1312 Time untilTime = new Time();
1313 long begin = mInitialValues.getAsLong(EVENT_BEGIN_TIME);
1314 ContentValues oldValues = new ContentValues();
1316 // The "until" time must be in UTC time in order for Google calendar
1317 // to display it properly. For all-day events, the "until" time string
1318 // must include just the date field, and not the time field. The
1319 // repeating events repeat up to and including the "until" time.
1320 untilTime.timezone = Time.TIMEZONE_UTC;
1322 // Subtract one second from the old begin time to get the new
1324 untilTime.set(begin - 1000); // subtract one second (1000 millis)
1327 untilTime.minute = 0;
1328 untilTime.second = 0;
1329 untilTime.allDay = true;
1330 untilTime.normalize(false);
1332 // For all-day events, the duration must be in days, not seconds.
1333 // Otherwise, Google Calendar will (mistakenly) change this event
1334 // into a non-all-day event.
1335 int len = oldDuration.length();
1336 if (oldDuration.charAt(0) == 'P' && oldDuration.charAt(len - 1) == 'S') {
1337 int seconds = Integer.parseInt(oldDuration.substring(1, len - 1));
1338 int days = (seconds + DAY_IN_SECONDS - 1) / DAY_IN_SECONDS;
1339 oldDuration = "P" + days + "D";
1342 mEventRecurrence.until = untilTime.format2445();
1344 oldValues.put(Events.DTSTART, oldStartMillis);
1345 oldValues.put(Events.DURATION, oldDuration);
1346 oldValues.put(Events.RRULE, mEventRecurrence.toString());
1347 cr.update(uri, oldValues, null, null);
1350 private void checkTimeDependentFields(ContentValues values) {
1351 long oldBegin = mInitialValues.getAsLong(EVENT_BEGIN_TIME);
1352 long oldEnd = mInitialValues.getAsLong(EVENT_END_TIME);
1353 boolean oldAllDay = mInitialValues.getAsInteger(Events.ALL_DAY) != 0;
1354 String oldRrule = mInitialValues.getAsString(Events.RRULE);
1355 String oldTimezone = mInitialValues.getAsString(Events.EVENT_TIMEZONE);
1357 long newBegin = values.getAsLong(Events.DTSTART);
1358 long newEnd = values.getAsLong(Events.DTEND);
1359 boolean newAllDay = values.getAsInteger(Events.ALL_DAY) != 0;
1360 String newRrule = values.getAsString(Events.RRULE);
1361 String newTimezone = values.getAsString(Events.EVENT_TIMEZONE);
1363 // If none of the time-dependent fields changed, then remove them.
1364 if (oldBegin == newBegin && oldEnd == newEnd && oldAllDay == newAllDay
1365 && TextUtils.equals(oldRrule, newRrule)
1366 && TextUtils.equals(oldTimezone, newTimezone)) {
1367 values.remove(Events.DTSTART);
1368 values.remove(Events.DTEND);
1369 values.remove(Events.DURATION);
1370 values.remove(Events.ALL_DAY);
1371 values.remove(Events.RRULE);
1372 values.remove(Events.EVENT_TIMEZONE);
1376 if (oldRrule == null || newRrule == null) {
1380 // If we are modifying all events then we need to set DTSTART to the
1381 // start time of the first event in the series, not the current
1382 // date and time. If the start time of the event was changed
1383 // (from, say, 3pm to 4pm), then we want to add the time difference
1384 // to the start time of the first event in the series (the DTSTART
1385 // value). If we are modifying one instance or all following instances,
1386 // then we leave the DTSTART field alone.
1387 if (mModification == MODIFY_ALL) {
1388 long oldStartMillis = mEventCursor.getLong(EVENT_INDEX_DTSTART);
1389 if (oldBegin != newBegin) {
1390 // The user changed the start time of this event
1391 long offset = newBegin - oldBegin;
1392 oldStartMillis += offset;
1394 values.put(Events.DTSTART, oldStartMillis);
1398 static ArrayList<Integer> reminderItemsToMinutes(ArrayList<LinearLayout> reminderItems,
1399 ArrayList<Integer> reminderValues) {
1400 int len = reminderItems.size();
1401 ArrayList<Integer> reminderMinutes = new ArrayList<Integer>(len);
1402 for (int index = 0; index < len; index++) {
1403 LinearLayout layout = reminderItems.get(index);
1404 Spinner spinner = (Spinner) layout.findViewById(R.id.reminder_value);
1405 int minutes = reminderValues.get(spinner.getSelectedItemPosition());
1406 reminderMinutes.add(minutes);
1408 return reminderMinutes;
1411 static void saveReminders(ContentResolver cr, long eventId,
1412 ArrayList<Integer> reminderMinutes, ArrayList<Integer> originalMinutes) {
1413 // If the reminders have not changed, then don't update the database
1414 if (reminderMinutes.equals(originalMinutes)) {
1418 // Delete all the existing reminders for this event
1419 String where = Reminders.EVENT_ID + "=?";
1420 String[] args = new String[] { Long.toString(eventId) };
1421 cr.delete(Reminders.CONTENT_URI, where, args);
1423 // Update the "hasAlarm" field for the event
1424 ContentValues values = new ContentValues();
1425 int len = reminderMinutes.size();
1426 values.put(Events.HAS_ALARM, (len > 0) ? 1 : 0);
1427 Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, eventId);
1428 cr.update(uri, values, null /* where */, null /* selection args */);
1430 // Insert the new reminders, if any
1431 for (int i = 0; i < len; i++) {
1432 int minutes = reminderMinutes.get(i);
1435 values.put(Reminders.MINUTES, minutes);
1436 values.put(Reminders.METHOD, Reminders.METHOD_ALERT);
1437 values.put(Reminders.EVENT_ID, eventId);
1438 cr.insert(Reminders.CONTENT_URI, values);
1442 private void addRecurrenceRule(ContentValues values) {
1443 updateRecurrenceRule();
1445 if (mRrule == null) {
1449 values.put(Events.RRULE, mRrule);
1450 long end = mEndTime.toMillis(true /* ignore dst */);
1451 long start = mStartTime.toMillis(true /* ignore dst */);
1454 boolean isAllDay = mAllDayCheckBox.isChecked();
1456 long days = (end - start + DateUtils.DAY_IN_MILLIS - 1) / DateUtils.DAY_IN_MILLIS;
1457 duration = "P" + days + "D";
1459 long seconds = (end - start) / DateUtils.SECOND_IN_MILLIS;
1460 duration = "P" + seconds + "S";
1462 values.put(Events.DURATION, duration);
1465 private void updateRecurrenceRule() {
1466 int position = mRepeatsSpinner.getSelectedItemPosition();
1467 int selection = mRecurrenceIndexes.get(position);
1469 if (selection == DOES_NOT_REPEAT) {
1472 } else if (selection == REPEATS_CUSTOM) {
1473 // Keep custom recurrence as before.
1475 } else if (selection == REPEATS_DAILY) {
1476 mEventRecurrence.freq = EventRecurrence.DAILY;
1477 } else if (selection == REPEATS_EVERY_WEEKDAY) {
1478 mEventRecurrence.freq = EventRecurrence.WEEKLY;
1480 int[] byday = new int[dayCount];
1481 int[] bydayNum = new int[dayCount];
1483 byday[0] = EventRecurrence.MO;
1484 byday[1] = EventRecurrence.TU;
1485 byday[2] = EventRecurrence.WE;
1486 byday[3] = EventRecurrence.TH;
1487 byday[4] = EventRecurrence.FR;
1488 for (int day = 0; day < dayCount; day++) {
1492 mEventRecurrence.byday = byday;
1493 mEventRecurrence.bydayNum = bydayNum;
1494 mEventRecurrence.bydayCount = dayCount;
1495 } else if (selection == REPEATS_WEEKLY_ON_DAY) {
1496 mEventRecurrence.freq = EventRecurrence.WEEKLY;
1497 int[] days = new int[1];
1499 int[] dayNum = new int[dayCount];
1501 days[0] = EventRecurrence.timeDay2Day(mStartTime.weekDay);
1502 // not sure why this needs to be zero, but set it for now.
1505 mEventRecurrence.byday = days;
1506 mEventRecurrence.bydayNum = dayNum;
1507 mEventRecurrence.bydayCount = dayCount;
1508 } else if (selection == REPEATS_MONTHLY_ON_DAY) {
1509 mEventRecurrence.freq = EventRecurrence.MONTHLY;
1510 mEventRecurrence.bydayCount = 0;
1511 mEventRecurrence.bymonthdayCount = 1;
1512 int[] bymonthday = new int[1];
1513 bymonthday[0] = mStartTime.monthDay;
1514 mEventRecurrence.bymonthday = bymonthday;
1515 } else if (selection == REPEATS_MONTHLY_ON_DAY_COUNT) {
1516 mEventRecurrence.freq = EventRecurrence.MONTHLY;
1517 mEventRecurrence.bydayCount = 1;
1518 mEventRecurrence.bymonthdayCount = 0;
1520 int[] byday = new int[1];
1521 int[] bydayNum = new int[1];
1522 // Compute the week number (for example, the "2nd" Monday)
1523 int dayCount = 1 + ((mStartTime.monthDay - 1) / 7);
1524 if (dayCount == 5) {
1527 bydayNum[0] = dayCount;
1528 byday[0] = EventRecurrence.timeDay2Day(mStartTime.weekDay);
1529 mEventRecurrence.byday = byday;
1530 mEventRecurrence.bydayNum = bydayNum;
1531 } else if (selection == REPEATS_YEARLY) {
1532 mEventRecurrence.freq = EventRecurrence.YEARLY;
1535 // Set the week start day.
1536 mEventRecurrence.wkst = EventRecurrence.calendarDay2Day(mFirstDayOfWeek);
1537 mRrule = mEventRecurrence.toString();
1540 private ContentValues getContentValuesFromUi() {
1541 String title = mTitleTextView.getText().toString();
1542 boolean isAllDay = mAllDayCheckBox.isChecked();
1543 String location = mLocationTextView.getText().toString();
1544 String description = mDescriptionTextView.getText().toString();
1546 ContentValues values = new ContentValues();
1548 String timezone = null;
1553 // Reset start and end time, increment the monthDay by 1, and set
1554 // the timezone to UTC, as required for all-day events.
1555 timezone = Time.TIMEZONE_UTC;
1556 mStartTime.hour = 0;
1557 mStartTime.minute = 0;
1558 mStartTime.second = 0;
1559 mStartTime.timezone = timezone;
1560 startMillis = mStartTime.normalize(true);
1563 mEndTime.minute = 0;
1564 mEndTime.second = 0;
1565 mEndTime.monthDay++;
1566 mEndTime.timezone = timezone;
1567 endMillis = mEndTime.normalize(true);
1569 if (mEventCursor == null) {
1570 // This is a new event
1571 calendarId = mCalendarsSpinner.getSelectedItemId();
1573 calendarId = mInitialValues.getAsLong(Events.CALENDAR_ID);
1576 startMillis = mStartTime.toMillis(true);
1577 endMillis = mEndTime.toMillis(true);
1578 if (mEventCursor != null) {
1579 // This is an existing event
1580 timezone = mEventCursor.getString(EVENT_INDEX_TIMEZONE);
1582 // The timezone might be null if we are changing an existing
1583 // all-day event to a non-all-day event. We need to assign
1584 // a timezone to the non-all-day event.
1585 if (TextUtils.isEmpty(timezone)) {
1586 timezone = TimeZone.getDefault().getID();
1588 calendarId = mInitialValues.getAsLong(Events.CALENDAR_ID);
1590 // This is a new event
1591 calendarId = mCalendarsSpinner.getSelectedItemId();
1593 // The timezone for a new event is the currently displayed
1594 // timezone, NOT the timezone of the containing calendar.
1595 timezone = TimeZone.getDefault().getID();
1599 values.put(Events.CALENDAR_ID, calendarId);
1600 values.put(Events.EVENT_TIMEZONE, timezone);
1601 values.put(Events.TITLE, title);
1602 values.put(Events.ALL_DAY, isAllDay ? 1 : 0);
1603 values.put(Events.DTSTART, startMillis);
1604 values.put(Events.DTEND, endMillis);
1605 values.put(Events.DESCRIPTION, description);
1606 values.put(Events.EVENT_LOCATION, location);
1607 values.put(Events.TRANSPARENCY, mAvailabilitySpinner.getSelectedItemPosition());
1609 int visibility = mVisibilitySpinner.getSelectedItemPosition();
1610 if (visibility > 0) {
1611 // For now we the array contains the values 0, 2, and 3. We add one to match.
1614 values.put(Events.VISIBILITY, visibility);
1619 private boolean isEmpty() {
1620 String title = mTitleTextView.getText().toString();
1621 if (title.length() > 0) {
1625 String location = mLocationTextView.getText().toString();
1626 if (location.length() > 0) {
1630 String description = mDescriptionTextView.getText().toString();
1631 if (description.length() > 0) {
1638 private boolean isCustomRecurrence() {
1640 if (mEventRecurrence.until != null || mEventRecurrence.interval != 0) {
1644 if (mEventRecurrence.freq == 0) {
1648 switch (mEventRecurrence.freq) {
1649 case EventRecurrence.DAILY:
1651 case EventRecurrence.WEEKLY:
1652 if (mEventRecurrence.repeatsOnEveryWeekDay() && isWeekdayEvent()) {
1654 } else if (mEventRecurrence.bydayCount == 1) {
1658 case EventRecurrence.MONTHLY:
1659 if (mEventRecurrence.repeatsMonthlyOnDayCount()) {
1661 } else if (mEventRecurrence.bydayCount == 0 && mEventRecurrence.bymonthdayCount == 1) {
1665 case EventRecurrence.YEARLY:
1672 private boolean isWeekdayEvent() {
1673 if (mStartTime.weekDay != Time.SUNDAY && mStartTime.weekDay != Time.SATURDAY) {