CreateEventDialogFragment.java revision 38fc457abe8028f0a2fd71091b8cc71184e9f6db
1/* Copyright (C) 2012 The Android Open Source Project
2
3     Licensed under the Apache License, Version 2.0 (the "License");
4     you may not use this file except in compliance with the License.
5     You may obtain a copy of the License at
6
7          http://www.apache.org/licenses/LICENSE-2.0
8
9     Unless required by applicable law or agreed to in writing, software
10     distributed under the License is distributed on an "AS IS" BASIS,
11     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12     See the License for the specific language governing permissions and
13     limitations under the License.
14*/
15
16package com.android.calendar.event;
17
18import android.app.Activity;
19import android.app.AlertDialog;
20import android.app.Dialog;
21import android.app.DialogFragment;
22import android.content.Context;
23import android.content.DialogInterface;
24import android.content.Intent;
25import android.database.Cursor;
26import android.os.Bundle;
27import android.provider.CalendarContract;
28import android.provider.CalendarContract.Calendars;
29import android.provider.Settings;
30import android.text.Editable;
31import android.text.TextWatcher;
32import android.text.format.DateUtils;
33import android.text.format.Time;
34import android.view.LayoutInflater;
35import android.view.View;
36import android.widget.Button;
37import android.widget.EditText;
38import android.widget.TextView;
39import android.widget.Toast;
40
41import com.android.calendar.AsyncQueryService;
42import com.android.calendar.CalendarController;
43import com.android.calendar.CalendarController.EventType;
44import com.android.calendar.CalendarEventModel;
45import com.android.calendar.GeneralPreferences;
46import com.android.calendar.R;
47import com.android.calendar.Utils;
48
49
50/**
51 * Allows the user to quickly create a new all-day event from the calendar's month view.
52 */
53public class CreateEventDialogFragment extends DialogFragment implements TextWatcher {
54
55    private static final int TOKEN_CALENDARS = 1 << 3;
56
57    private static final String KEY_DATE_STRING = "date_string";
58    private static final String KEY_DATE_IN_MILLIS = "date_in_millis";
59    private static final String EVENT_DATE_FORMAT = "%a, %b %d, %Y";
60
61    private AlertDialog mAlertDialog;
62
63    private CalendarQueryService mService;
64
65    private EditText mEventTitle;
66    private View mColor;
67
68    private TextView mCalendarName;
69    private TextView mAccountName;
70    private TextView mDate;
71    private Button mButtonAddEvent;
72
73    private CalendarController mController;
74    private EditEventHelper mEditEventHelper;
75
76    private String mDateString;
77    private long mDateInMillis;
78
79    private CalendarEventModel mModel;
80    private long mCalendarId = -1;
81    private String mCalendarOwner;
82
83    private class CalendarQueryService extends AsyncQueryService {
84
85        /**
86         * @param context
87         */
88        public CalendarQueryService(Context context) {
89            super(context);
90        }
91
92        @Override
93        public void onQueryComplete(int token, Object cookie, Cursor cursor) {
94            setDefaultCalendarView(cursor);
95            if (cursor != null) {
96                cursor.close();
97            }
98        }
99    }
100
101    public CreateEventDialogFragment() {
102        // Empty constructor required for DialogFragment.
103    }
104
105    public CreateEventDialogFragment(Time day) {
106        setDay(day);
107    }
108
109    public void setDay(Time day) {
110        mDateString = day.format(EVENT_DATE_FORMAT);
111        mDateInMillis = day.toMillis(true);
112    }
113
114    @Override
115    public void onCreate(Bundle savedInstanceState) {
116        super.onCreate(savedInstanceState);
117        if (savedInstanceState != null) {
118            mDateString = savedInstanceState.getString(KEY_DATE_STRING);
119            mDateInMillis = savedInstanceState.getLong(KEY_DATE_IN_MILLIS);
120        }
121    }
122
123    @Override
124    public Dialog onCreateDialog(Bundle savedInstanceState) {
125        final Activity activity = getActivity();
126        final LayoutInflater layoutInflater = (LayoutInflater) activity
127                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
128        View view = layoutInflater.inflate(R.layout.create_event_dialog, null);
129
130        mColor = view.findViewById(R.id.color);
131        mCalendarName = (TextView) view.findViewById(R.id.calendar_name);
132        mAccountName = (TextView) view.findViewById(R.id.account_name);
133
134        mEventTitle = (EditText) view.findViewById(R.id.event_title);
135        mEventTitle.addTextChangedListener(this);
136
137        mDate = (TextView) view.findViewById(R.id.event_day);
138        if (mDateString != null) {
139            mDate.setText(mDateString);
140        }
141
142        mAlertDialog = new AlertDialog.Builder(activity)
143            .setTitle(R.string.new_event_dialog_label)
144            .setView(view)
145            .setPositiveButton(R.string.create_event_dialog_save,
146                    new DialogInterface.OnClickListener() {
147
148                        @Override
149                        public void onClick(DialogInterface dialog, int which) {
150                            createAllDayEvent();
151                            dismiss();
152                        }
153                    })
154            .setNeutralButton(R.string.edit_label,
155                    new DialogInterface.OnClickListener() {
156
157                        @Override
158                        public void onClick(DialogInterface dialog, int which) {
159                            mController.sendEventRelatedEventWithExtraWithTitleWithCalendarId(this,
160                                    EventType.CREATE_EVENT, -1, mDateInMillis,
161                                    mDateInMillis + DateUtils.DAY_IN_MILLIS, 0, 0,
162                                    CalendarController.EXTRA_CREATE_ALL_DAY, -1,
163                                    mEventTitle.getText().toString(),
164                                    mCalendarId);
165                            dismiss();
166                        }
167                    })
168            .setNegativeButton(android.R.string.cancel, null)
169            .create();
170
171        return mAlertDialog;
172    }
173
174    @Override
175    public void onResume() {
176        super.onResume();
177        if (mButtonAddEvent == null) {
178            mButtonAddEvent = mAlertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
179            mButtonAddEvent.setEnabled(mEventTitle.getText().toString().length() > 0);
180        }
181    }
182
183    @Override
184    public void onSaveInstanceState(Bundle outState) {
185        super.onSaveInstanceState(outState);
186        outState.putString(KEY_DATE_STRING, mDateString);
187        outState.putLong(KEY_DATE_IN_MILLIS, mDateInMillis);
188    }
189
190    @Override
191    public void onActivityCreated(Bundle args) {
192        super.onActivityCreated(args);
193        final Context context = getActivity();
194        mController = CalendarController.getInstance(getActivity());
195        mEditEventHelper = new EditEventHelper(context);
196        mModel = new CalendarEventModel(context);
197        mService = new CalendarQueryService(context);
198        mService.startQuery(TOKEN_CALENDARS, null, Calendars.CONTENT_URI,
199                EditEventHelper.CALENDARS_PROJECTION,
200                EditEventHelper.CALENDARS_WHERE_WRITEABLE_VISIBLE, null,
201                null);
202    }
203
204    private void createAllDayEvent() {
205        mModel.mStart = mDateInMillis;
206        mModel.mEnd = mDateInMillis + DateUtils.DAY_IN_MILLIS;
207        mModel.mTitle = mEventTitle.getText().toString();
208        mModel.mAllDay = true;
209        mModel.mCalendarId = mCalendarId;
210        mModel.mOwnerAccount = mCalendarOwner;
211
212        if (mEditEventHelper.saveEvent(mModel, null, 0)) {
213            Toast.makeText(getActivity(), R.string.creating_event, Toast.LENGTH_SHORT).show();
214        }
215    }
216
217    @Override
218    public void afterTextChanged(Editable s) {
219        // Do nothing.
220    }
221
222    @Override
223    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
224        // Do nothing.
225    }
226
227    @Override
228    public void onTextChanged(CharSequence s, int start, int before, int count) {
229        if (mButtonAddEvent != null) {
230            mButtonAddEvent.setEnabled(s.length() > 0);
231        }
232    }
233
234    // Find the calendar position in the cursor that matches calendar in
235    // preference
236    private void setDefaultCalendarView(Cursor cursor) {
237        if (cursor == null || cursor.getCount() == 0) {
238            // Create an error message for the user that, when clicked,
239            // will exit this activity without saving the event.
240            dismiss();
241            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
242            builder.setTitle(R.string.no_syncable_calendars).setIconAttribute(
243                    android.R.attr.alertDialogIcon).setMessage(R.string.no_calendars_found)
244                    .setPositiveButton(R.string.add_account, new DialogInterface.OnClickListener() {
245
246                        @Override
247                        public void onClick(DialogInterface dialog, int which) {
248                                Intent nextIntent = new Intent(Settings.ACTION_ADD_ACCOUNT);
249                                final String[] array = {"com.android.calendar"};
250                                nextIntent.putExtra(Settings.EXTRA_AUTHORITIES, array);
251                                nextIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
252                                        Intent.FLAG_ACTIVITY_NEW_TASK);
253                                getActivity().startActivity(nextIntent);
254                        }
255                    })
256                    .setNegativeButton(android.R.string.no, null);
257            builder.show();
258            return;
259        }
260
261        String defaultCalendar = Utils.getSharedPreference(
262                getActivity(), GeneralPreferences.KEY_DEFAULT_CALENDAR, (String) null);
263
264        int calendarOwnerIndex = cursor.getColumnIndexOrThrow(Calendars.OWNER_ACCOUNT);
265        int accountNameIndex = cursor.getColumnIndexOrThrow(Calendars.ACCOUNT_NAME);
266        int accountTypeIndex = cursor.getColumnIndexOrThrow(Calendars.ACCOUNT_TYPE);
267
268        int position = 0;
269        cursor.moveToPosition(-1);
270        while (cursor.moveToNext()) {
271            String calendarOwner = cursor.getString(calendarOwnerIndex);
272            if (defaultCalendar == null) {
273                // There is no stored default upon the first time running.  Use a primary
274                // calendar in this case.
275                if (calendarOwner != null &&
276                        calendarOwner.equals(cursor.getString(accountNameIndex)) &&
277                        !CalendarContract.ACCOUNT_TYPE_LOCAL.equals(
278                                cursor.getString(accountTypeIndex))) {
279                    setCalendarFields(cursor);
280                    return;
281                }
282            } else if (defaultCalendar.equals(calendarOwner)) {
283                // Found the default calendar.
284                setCalendarFields(cursor);
285                return;
286            }
287        }
288        cursor.moveToFirst();
289        setCalendarFields(cursor);
290    }
291
292    private void setCalendarFields(Cursor cursor) {
293        int calendarIdIndex = cursor.getColumnIndexOrThrow(Calendars._ID);
294        int colorIndex = cursor.getColumnIndexOrThrow(Calendars.CALENDAR_COLOR);
295        int calendarNameIndex = cursor.getColumnIndexOrThrow(Calendars.CALENDAR_DISPLAY_NAME);
296        int accountNameIndex = cursor.getColumnIndexOrThrow(Calendars.ACCOUNT_NAME);
297        int calendarOwnerIndex = cursor.getColumnIndexOrThrow(Calendars.OWNER_ACCOUNT);
298
299        mCalendarId = cursor.getLong(calendarIdIndex);
300        mCalendarOwner = cursor.getString(calendarOwnerIndex);
301        mColor.setBackgroundColor(Utils.getDisplayColorFromColor(cursor
302                .getInt(colorIndex)));
303        String accountName = cursor.getString(accountNameIndex);
304        String calendarName = cursor.getString(calendarNameIndex);
305        mCalendarName.setText(calendarName);
306        if (calendarName.equals(accountName)) {
307            mAccountName.setVisibility(View.GONE);
308        } else {
309            mAccountName.setVisibility(View.VISIBLE);
310            mAccountName.setText(accountName);
311        }
312    }
313}
314