From 1e9c3328cfdd84789dabdb2dd1098d4dd1f1d652 Mon Sep 17 00:00:00 2001 From: Alex Baker Date: Fri, 2 Aug 2013 00:08:52 -0500 Subject: [PATCH] Reformat code and optimize imports --- api/AndroidManifest.xml | 8 +- api/res/layout/status_preference.xml | 73 +- api/res/values-ca/strings.xml | 203 +- api/res/values-cs/strings.xml | 231 +- api/res/values-da/strings.xml | 174 +- api/res/values-de/strings.xml | 487 +- api/res/values-es/strings.xml | 488 +- api/res/values-fr/strings.xml | 490 +- api/res/values-it/strings.xml | 489 +- api/res/values-iw/strings.xml | 480 +- api/res/values-ja/strings.xml | 483 +- api/res/values-ko/strings.xml | 478 +- api/res/values-nb/strings.xml | 200 +- api/res/values-nl/strings.xml | 483 +- api/res/values-pl/strings.xml | 485 +- api/res/values-pt-rBR/strings.xml | 488 +- api/res/values-pt/strings.xml | 164 +- api/res/values-ru/strings.xml | 484 +- api/res/values-sv/strings.xml | 486 +- api/res/values-th/strings.xml | 148 +- api/res/values-tr/strings.xml | 480 +- api/res/values-zh-rCN/strings.xml | 478 +- api/res/values-zh-rTW/strings.xml | 478 +- api/res/values/colors.xml | 10 +- api/res/values/keys.xml | 14 +- api/res/values/strings.xml | 485 +- .../todoroo/andlib/data/AbstractDatabase.java | 50 +- .../todoroo/andlib/data/AbstractModel.java | 187 +- .../andlib/data/ContentResolverDao.java | 47 +- .../com/todoroo/andlib/data/DatabaseDao.java | 79 +- api/src/com/todoroo/andlib/data/Property.java | 66 +- api/src/com/todoroo/andlib/data/Table.java | 11 +- .../todoroo/andlib/data/TodorooCursor.java | 47 +- .../service/AbstractDependencyInjector.java | 21 +- .../com/todoroo/andlib/service/Autowired.java | 5 +- .../andlib/service/ContextManager.java | 8 +- .../service/DependencyInjectionService.java | 46 +- .../andlib/service/ExceptionService.java | 48 +- .../andlib/service/HttpRestClient.java | 32 +- .../service/HttpUnavailableException.java | 1 - .../andlib/service/NotificationManager.java | 5 +- .../todoroo/andlib/service/RestClient.java | 6 +- api/src/com/todoroo/andlib/sql/DBObject.java | 7 +- api/src/com/todoroo/andlib/sql/Field.java | 8 +- api/src/com/todoroo/andlib/sql/Functions.java | 6 +- api/src/com/todoroo/andlib/sql/Operator.java | 6 +- api/src/com/todoroo/andlib/sql/Order.java | 10 +- api/src/com/todoroo/andlib/sql/Query.java | 65 +- .../com/todoroo/andlib/sql/QueryTemplate.java | 7 +- api/src/com/todoroo/andlib/sql/SqlTable.java | 2 +- .../todoroo/andlib/sql/UnaryCriterion.java | 6 +- .../andlib/utility/AndroidUtilities.java | 310 +- .../todoroo/andlib/utility/DateUtilities.java | 87 +- .../andlib/utility/DialogUtilities.java | 103 +- api/src/com/todoroo/andlib/utility/Pair.java | 3 +- .../todoroo/andlib/utility/Preferences.java | 50 +- .../utility/TodorooPreferenceActivity.java | 26 +- api/src/com/todoroo/astrid/api/Addon.java | 5 +- .../astrid/api/AstridApiConstants.java | 4 +- .../astrid/api/CustomFilterCriterion.java | 11 +- api/src/com/todoroo/astrid/api/Filter.java | 56 +- .../todoroo/astrid/api/FilterCategory.java | 15 +- .../api/FilterCategoryWithNewButton.java | 15 +- .../todoroo/astrid/api/FilterListHeader.java | 5 +- .../todoroo/astrid/api/FilterListItem.java | 1 - .../astrid/api/FilterWithCustomIntent.java | 6 +- .../todoroo/astrid/api/FilterWithUpdate.java | 4 +- .../com/todoroo/astrid/api/IntentFilter.java | 7 +- .../astrid/api/MultipleSelectCriterion.java | 5 +- api/src/com/todoroo/astrid/api/PermaSql.java | 67 +- .../com/todoroo/astrid/api/SyncAction.java | 15 +- .../com/todoroo/astrid/api/TaskAction.java | 7 +- .../todoroo/astrid/api/TaskDecoration.java | 14 +- .../astrid/api/TextInputCriterion.java | 5 +- .../com/todoroo/astrid/core/SearchFilter.java | 4 +- .../com/todoroo/astrid/core/SortHelper.java | 65 +- api/src/com/todoroo/astrid/data/History.java | 60 +- api/src/com/todoroo/astrid/data/Metadata.java | 65 +- .../todoroo/astrid/data/MetadataApiDao.java | 13 +- .../com/todoroo/astrid/data/RemoteModel.java | 64 +- .../com/todoroo/astrid/data/StoreObject.java | 55 +- .../astrid/data/StoreObjectApiDao.java | 9 +- api/src/com/todoroo/astrid/data/TagData.java | 161 +- .../com/todoroo/astrid/data/TagMetadata.java | 52 +- .../todoroo/astrid/data/TagOutstanding.java | 12 +- api/src/com/todoroo/astrid/data/Task.java | 337 +- .../com/todoroo/astrid/data/TaskApiDao.java | 73 +- .../todoroo/astrid/data/TaskAttachment.java | 87 +- .../data/TaskAttachmentOutstanding.java | 12 +- .../todoroo/astrid/data/TaskListMetadata.java | 62 +- .../data/TaskListMetadataOutstanding.java | 12 +- .../todoroo/astrid/data/TaskOutstanding.java | 12 +- api/src/com/todoroo/astrid/data/Update.java | 86 +- api/src/com/todoroo/astrid/data/User.java | 73 +- .../com/todoroo/astrid/data/UserActivity.java | 66 +- .../astrid/data/UserActivityOutstanding.java | 12 +- .../com/todoroo/astrid/data/WaitingOnMe.java | 20 +- .../astrid/data/WaitingOnMeOutstanding.java | 12 +- .../astrid/sync/SyncBackgroundService.java | 54 +- .../todoroo/astrid/sync/SyncContainer.java | 12 +- .../com/todoroo/astrid/sync/SyncProvider.java | 113 +- .../astrid/sync/SyncProviderPreferences.java | 75 +- .../astrid/sync/SyncProviderUtilities.java | 60 +- .../astrid/sync/SyncResultCallback.java | 2 + .../sync/SyncResultCallbackAdapter.java | 4 +- .../astrid/sync/SyncV2BackgroundService.java | 54 +- .../todoroo/astrid/sync/SyncV2Provider.java | 16 +- astrid/AndroidManifest.xml | 1390 ++-- .../commonsware/cwac/tlv/TouchListView.java | 831 +-- .../com/localytics/android/Constants.java | 14 +- .../localytics/android/DatapointHelper.java | 218 +- .../localytics/android/ExceptionHandler.java | 21 +- .../com/localytics/android/JsonObjects.java | 148 +- .../android/LocalyticsProvider.java | 485 +- .../localytics/android/LocalyticsSession.java | 1360 ++-- .../localytics/android/ReflectionUtils.java | 74 +- .../mdimension/jchronic/AstridChronic.java | 321 +- .../mobile/android/imagecache/DiskCache.java | 59 +- .../android/imagecache/DrawableMemCache.java | 1 + .../mobile/android/imagecache/ImageCache.java | 166 +- .../mobile/android/imagecache/KeyedLock.java | 7 +- .../com/timsu/astrid/GCMIntentService.java | 83 +- .../astrid/actfm/ActFmBackgroundService.java | 4 +- .../astrid/actfm/ActFmCameraModule.java | 43 +- .../astrid/actfm/ActFmGoogleAuthActivity.java | 13 +- .../astrid/actfm/ActFmLoginActivity.java | 128 +- .../astrid/actfm/ActFmPreferences.java | 16 +- .../astrid/actfm/ActFmSyncActionExposer.java | 6 +- .../astrid/actfm/CommentsActivity.java | 8 +- .../astrid/actfm/CommentsFragment.java | 56 +- .../astrid/actfm/EditPeopleControlSet.java | 116 +- .../astrid/actfm/TagCommentsFragment.java | 5 +- .../astrid/actfm/TagSettingsActivity.java | 85 +- .../todoroo/astrid/actfm/TagViewFragment.java | 107 +- .../astrid/actfm/WaitingOnMeFragment.java | 8 +- .../astrid/actfm/sync/ActFmInvoker.java | 102 +- .../actfm/sync/ActFmPreferenceService.java | 51 +- .../actfm/sync/ActFmServiceException.java | 5 +- .../astrid/actfm/sync/ActFmSyncMonitor.java | 1 + .../astrid/actfm/sync/ActFmSyncService.java | 68 +- .../astrid/actfm/sync/ActFmSyncThread.java | 56 +- .../actfm/sync/ActFmSyncV2Provider.java | 17 +- .../actfm/sync/ActFmSyncWaitingPool.java | 8 +- .../actfm/sync/AstridNewSyncMigrator.java | 48 +- .../EmptyTitleOutstandingEntryMigration.java | 36 +- .../actfm/sync/SyncDatabaseListener.java | 1 + .../astrid/actfm/sync/SyncUpgradePrompt.java | 32 +- .../sync/messages/AcknowledgeChange.java | 12 +- .../astrid/actfm/sync/messages/BriefMe.java | 12 +- .../actfm/sync/messages/ChangesHappened.java | 68 +- .../sync/messages/ClientToServerMessage.java | 9 +- ...structOutstandingTableFromMasterTable.java | 2 +- .../astrid/actfm/sync/messages/Debug.java | 4 +- .../actfm/sync/messages/FetchHistory.java | 25 +- .../messages/JSONChangeToPropertyVisitor.java | 8 +- .../sync/messages/JSONPayloadBuilder.java | 6 +- .../actfm/sync/messages/MakeChanges.java | 19 +- .../astrid/actfm/sync/messages/NameMaps.java | 140 +- .../actfm/sync/messages/NowBriefed.java | 8 +- .../messages/ReplayOutstandingEntries.java | 2 +- .../sync/messages/RequestDoubleCheck.java | 6 +- .../sync/messages/ServerToClientMessage.java | 4 +- .../TaskListMetadataChangesHappened.java | 6 +- .../astrid/actfm/sync/messages/UserData.java | 4 +- .../actfm/sync/messages/UserMigrated.java | 4 +- .../astrid/alarms/AlarmControlSet.java | 17 +- .../astrid/alarms/AlarmDetailExposer.java | 21 +- .../todoroo/astrid/alarms/AlarmFields.java | 21 +- .../todoroo/astrid/alarms/AlarmService.java | 44 +- .../alarms/AlarmTaskRepeatListener.java | 14 +- .../todoroo/astrid/backup/BackupActivity.java | 18 +- .../astrid/backup/BackupConstants.java | 24 +- .../astrid/backup/BackupDateUtilities.java | 6 +- .../astrid/backup/BackupPreferences.java | 21 +- .../todoroo/astrid/backup/BackupService.java | 21 +- .../astrid/backup/FilePickerBuilder.java | 8 +- .../astrid/backup/TasksXmlExporter.java | 103 +- .../astrid/backup/TasksXmlImporter.java | 175 +- .../astrid/calls/MissedCallActivity.java | 56 +- .../calls/PhoneStateChangedReceiver.java | 24 +- .../astrid/core/CoreFilterExposer.java | 37 +- .../astrid/core/CustomFilterActivity.java | 195 +- .../astrid/core/CustomFilterAdapter.java | 72 +- .../astrid/core/CustomFilterExposer.java | 37 +- .../astrid/core/DefaultsPreferences.java | 36 +- .../com/todoroo/astrid/core/FilterView.java | 1 - .../astrid/core/LinkActionExposer.java | 19 +- .../astrid/core/OldTaskPreferences.java | 41 +- .../todoroo/astrid/core/PluginServices.java | 7 +- .../com/todoroo/astrid/core/SavedFilter.java | 39 +- .../astrid/files/AACRecordingActivity.java | 6 +- .../com/todoroo/astrid/files/FileExplore.java | 383 +- .../todoroo/astrid/files/FileMetadata.java | 6 +- .../todoroo/astrid/files/FileUtilities.java | 13 +- .../todoroo/astrid/files/FilesControlSet.java | 60 +- .../astrid/gcal/CalendarAlarmListCreator.java | 22 +- .../astrid/gcal/CalendarAlarmReceiver.java | 22 +- .../astrid/gcal/CalendarAlarmScheduler.java | 10 +- .../astrid/gcal/CalendarReminderActivity.java | 58 +- .../com/todoroo/astrid/gcal/Calendars.java | 332 +- .../todoroo/astrid/gcal/GCalControlSet.java | 39 +- .../com/todoroo/astrid/gcal/GCalHelper.java | 40 +- .../astrid/gcal/GCalTaskCompleteListener.java | 6 +- .../gtasks/GtasksBackgroundService.java | 5 +- .../GtasksCustomFilterCriteriaExposer.java | 10 +- .../astrid/gtasks/GtasksDetailExposer.java | 22 +- .../astrid/gtasks/GtasksFilterExposer.java | 26 +- .../com/todoroo/astrid/gtasks/GtasksList.java | 17 +- .../astrid/gtasks/GtasksListAdder.java | 12 +- .../astrid/gtasks/GtasksListFragment.java | 51 +- .../astrid/gtasks/GtasksListService.java | 31 +- .../todoroo/astrid/gtasks/GtasksMetadata.java | 19 +- .../astrid/gtasks/GtasksMetadataService.java | 46 +- .../gtasks/GtasksPreferenceService.java | 25 +- .../astrid/gtasks/GtasksPreferences.java | 13 +- .../gtasks/GtasksSyncActionExposer.java | 6 +- .../astrid/gtasks/GtasksTaskListUpdater.java | 57 +- .../astrid/gtasks/api/CreateRequest.java | 7 +- .../gtasks/api/GoogleTasksException.java | 4 +- .../astrid/gtasks/api/GtasksApiUtilities.java | 5 +- .../astrid/gtasks/api/GtasksInvoker.java | 12 +- .../astrid/gtasks/api/MoveListRequest.java | 5 +- .../astrid/gtasks/api/MoveRequest.java | 5 +- .../astrid/gtasks/api/PushRequest.java | 9 +- .../astrid/gtasks/api/UpdateRequest.java | 6 +- .../astrid/gtasks/auth/AccountChooser.java | 168 +- .../astrid/gtasks/auth/AuthManager.java | 90 +- .../gtasks/auth/GtasksLoginActivity.java | 19 +- .../gtasks/auth/GtasksTokenValidator.java | 14 +- .../astrid/gtasks/auth/ModernAuthManager.java | 344 +- .../gtasks/sync/GtasksLegacyMigrator.java | 29 +- .../astrid/gtasks/sync/GtasksSyncService.java | 37 +- .../gtasks/sync/GtasksSyncV2Provider.java | 82 +- .../gtasks/sync/GtasksTaskContainer.java | 15 +- .../astrid/locale/LocaleEditAlerts.java | 103 +- .../todoroo/astrid/locale/LocaleReceiver.java | 16 +- .../astrid/notes/EditNoteActivity.java | 99 +- .../todoroo/astrid/notes/NoteMetadata.java | 29 +- .../astrid/notes/NotesDecorationExposer.java | 9 +- .../astrid/notes/NotesDetailExposer.java | 19 +- .../com/todoroo/astrid/notes/NotesPlugin.java | 4 +- .../astrid/opencrx/OpencrxControlSet.java | 97 +- .../astrid/opencrx/OpencrxCoreUtils.java | 24 +- .../astrid/people/PeopleFilterAdapter.java | 2 +- .../astrid/people/PeopleFilterExposer.java | 12 +- .../astrid/people/PeopleFilterMode.java | 4 +- .../astrid/people/PersonViewFragment.java | 31 +- .../reminders/NotificationFragment.java | 59 +- .../astrid/reminders/Notifications.java | 143 +- .../reminders/ReengagementReceiver.java | 14 +- .../astrid/reminders/ReengagementService.java | 6 +- .../ReminderDebugContextActions.java | 10 +- .../astrid/reminders/ReminderDialog.java | 29 +- .../astrid/reminders/ReminderPreferences.java | 48 +- .../reminders/ReminderSchedulingService.java | 6 +- .../astrid/reminders/ReminderService.java | 166 +- .../reminders/ReminderStartupReceiver.java | 1 - .../astrid/repeats/RepeatControlSet.java | 159 +- .../astrid/repeats/RepeatDetailExposer.java | 67 +- .../repeats/RepeatTaskCompleteListener.java | 100 +- .../AstridOrderedListFragmentHelper.java | 52 +- .../subtasks/AstridOrderedListUpdater.java | 20 +- .../OrderedListFragmentHelperInterface.java | 9 +- .../OrderedMetadataListFragmentHelper.java | 54 +- .../subtasks/OrderedMetadataListUpdater.java | 91 +- .../astrid/subtasks/SubtasksHelper.java | 11 +- .../astrid/subtasks/SubtasksListFragment.java | 5 +- .../astrid/subtasks/SubtasksMetadata.java | 9 +- .../subtasks/SubtasksMetadataMigration.java | 4 +- .../subtasks/SubtasksTagListFragment.java | 2 +- .../astrid/subtasks/SubtasksTagUpdater.java | 4 +- .../astrid/subtasks/SubtasksUpdater.java | 9 +- .../todoroo/astrid/tags/TagCaseMigrator.java | 25 +- .../tags/TagCustomFilterCriteriaExposer.java | 28 +- .../todoroo/astrid/tags/TagDetailExposer.java | 7 +- .../todoroo/astrid/tags/TagFilterExposer.java | 55 +- .../com/todoroo/astrid/tags/TagService.java | 86 +- .../todoroo/astrid/tags/TagsControlSet.java | 66 +- .../com/todoroo/astrid/tags/TagsPlugin.java | 1 + .../astrid/tags/TaskToTagMetadata.java | 17 +- .../reusable/FeaturedListFilterAdapter.java | 2 +- .../reusable/FeaturedListFilterExposer.java | 18 +- .../tags/reusable/FeaturedListFilterMode.java | 4 +- .../reusable/FeaturedTaskListFragment.java | 7 +- .../tags/reusable/ReusableTaskAdapter.java | 14 +- .../astrid/timers/TimerActionControlSet.java | 13 +- .../astrid/timers/TimerControlSet.java | 9 +- .../astrid/timers/TimerDecorationExposer.java | 7 +- .../astrid/timers/TimerFilterExposer.java | 5 +- .../todoroo/astrid/timers/TimerPlugin.java | 11 +- .../timers/TimerTaskCompleteListener.java | 4 +- astrid/res/anim/slide_bottom_in.xml | 5 +- astrid/res/anim/slide_bottom_out.xml | 5 +- astrid/res/anim/slide_left_in.xml | 5 +- astrid/res/anim/slide_left_out.xml | 5 +- astrid/res/anim/slide_none.xml | 5 +- astrid/res/anim/slide_right_in.xml | 5 +- astrid/res/anim/slide_right_out.xml | 5 +- astrid/res/color/new_list_button_text.xml | 10 +- .../color/task_edit_toggle_button_text.xml | 10 +- .../res/drawable-v11/importance_title_1.xml | 10 +- .../res/drawable-v11/importance_title_2.xml | 10 +- .../res/drawable-v11/importance_title_3.xml | 10 +- .../res/drawable-v11/importance_title_4.xml | 10 +- .../res/drawable-v11/importance_title_5.xml | 10 +- .../res/drawable-v11/importance_title_6.xml | 10 +- astrid/res/drawable/astrid_com_gradient.xml | 16 +- astrid/res/drawable/btn_add.xml | 4 +- astrid/res/drawable/btn_check.xml | 4 +- astrid/res/drawable/btn_check_small.xml | 10 +- astrid/res/drawable/btn_clone.xml | 6 +- astrid/res/drawable/btn_dismiss.xml | 4 +- astrid/res/drawable/camera_button.xml | 2 +- astrid/res/drawable/comment_blue.xml | 2 +- astrid/res/drawable/comment_blue_alt.xml | 2 +- astrid/res/drawable/comment_blue_filled.xml | 2 +- .../res/drawable/comment_blue_filled_alt.xml | 2 +- astrid/res/drawable/comment_dark_blue.xml | 2 +- .../res/drawable/comment_dark_blue_filled.xml | 2 +- astrid/res/drawable/comment_red.xml | 2 +- astrid/res/drawable/comment_red_filled.xml | 2 +- astrid/res/drawable/custom_tab_indicator.xml | 4 +- .../res/drawable/custom_tab_indicator_alt.xml | 6 +- .../drawable/custom_tab_indicator_dark.xml | 4 +- .../custom_tab_indicator_dark_blue.xml | 4 +- ...tab_indicator_dark_blue_selected_layer.xml | 2 +- ...stom_tab_indicator_dark_selected_layer.xml | 4 +- ...ustom_tab_indicator_selected_alt_layer.xml | 2 +- .../custom_tab_indicator_selected_layer.xml | 2 +- astrid/res/drawable/edit_title_background.xml | 21 +- .../drawable/edit_title_background_dark.xml | 21 +- astrid/res/drawable/file_type_background.xml | 4 +- astrid/res/drawable/filter_count.xml | 18 +- astrid/res/drawable/footer_editbutton.xml | 4 +- astrid/res/drawable/header_button.xml | 4 +- astrid/res/drawable/header_button_white.xml | 4 +- astrid/res/drawable/importance_1.xml | 4 +- astrid/res/drawable/importance_2.xml | 4 +- astrid/res/drawable/importance_3.xml | 4 +- astrid/res/drawable/importance_4.xml | 4 +- .../importance_background_selected.xml | 15 +- .../importance_background_selected_dark.xml | 15 +- astrid/res/drawable/importance_check_1.xml | 4 +- astrid/res/drawable/importance_check_2.xml | 4 +- astrid/res/drawable/importance_check_3.xml | 4 +- astrid/res/drawable/importance_check_4.xml | 4 +- .../drawable/importance_check_repeat_1.xml | 4 +- .../drawable/importance_check_repeat_2.xml | 4 +- .../drawable/importance_check_repeat_3.xml | 4 +- .../drawable/importance_check_repeat_4.xml | 4 +- astrid/res/drawable/lists_disclosure_blue.xml | 2 +- .../drawable/lists_disclosure_blue_alt.xml | 2 +- .../drawable/lists_disclosure_dark_blue.xml | 2 +- astrid/res/drawable/lists_disclosure_red.xml | 2 +- astrid/res/drawable/menu_button_blue.xml | 2 +- astrid/res/drawable/menu_button_blue_alt.xml | 2 +- astrid/res/drawable/menu_button_dark_blue.xml | 2 +- astrid/res/drawable/menu_button_red.xml | 2 +- astrid/res/drawable/mic_button_blue.xml | 2 +- astrid/res/drawable/mic_button_dark_blue.xml | 2 +- astrid/res/drawable/mic_button_red.xml | 2 +- .../res/drawable/people_menu_button_blue.xml | 2 +- .../drawable/people_menu_button_dark_blue.xml | 2 +- .../res/drawable/people_menu_button_red.xml | 2 +- astrid/res/drawable/plus_button_blue.xml | 2 +- astrid/res/drawable/plus_button_dark_blue.xml | 2 +- astrid/res/drawable/plus_button_red.xml | 2 +- .../drawable/reminder_dialog_background.xml | 12 +- .../reminder_dialog_inset_background.xml | 8 +- astrid/res/drawable/task_edit_background.xml | 20 +- ...task_edit_background_transparent_black.xml | 20 +- ...task_edit_background_transparent_white.xml | 20 +- .../drawable/task_edit_background_white.xml | 20 +- astrid/res/drawable/task_row_bg_dark.xml | 16 +- astrid/res/drawable/task_row_bg_white.xml | 16 +- astrid/res/drawable/timepicker_down_btn.xml | 10 +- astrid/res/drawable/timepicker_input.xml | 10 +- astrid/res/drawable/timepicker_up_btn.xml | 10 +- astrid/res/drawable/vertical_separator.xml | 8 +- astrid/res/drawable/widget_body_legacy.xml | 14 +- astrid/res/drawable/widget_header_legacy.xml | 20 +- .../drawable/wom_edit_background_white.xml | 20 +- .../res/layout-land/actfm_login_activity.xml | 245 +- astrid/res/layout-land/astrid_dialog_view.xml | 159 +- .../res/layout-land/astrid_reminder_view.xml | 177 +- astrid/res/layout-land/date_time_picker.xml | 107 +- .../date_time_picker_no_shortcuts.xml | 109 +- .../res/layout-land/filter_list_activity.xml | 69 +- .../filter_list_fragment_alternative.xml | 29 +- .../layout-land/main_menu_popover_body.xml | 61 +- astrid/res/layout-land/share_activity.xml | 138 +- .../task_list_wrapper_activity_3pane.xml | 70 +- astrid/res/layout-land/widget_initialized.xml | 93 +- .../layout-xlarge-land/widget_initialized.xml | 87 +- astrid/res/layout-xlarge/help_popover.xml | 52 +- astrid/res/layout/aac_record_activity.xml | 10 +- astrid/res/layout/actfm_login_activity.xml | 222 +- astrid/res/layout/addon_adapter_row.xml | 144 +- astrid/res/layout/addon_list_container.xml | 42 +- astrid/res/layout/alarm_edit_row.xml | 71 +- astrid/res/layout/assigned_adapter_row.xml | 48 +- .../astrid_calendar_list_creator_view.xml | 164 +- .../layout/astrid_calendar_reminder_view.xml | 164 +- astrid/res/layout/astrid_dialog_view.xml | 119 +- .../layout/astrid_dialog_view_portrait.xml | 119 +- astrid/res/layout/astrid_missed_call_view.xml | 183 +- .../res/layout/astrid_record_audio_view.xml | 101 +- astrid/res/layout/astrid_reminder_view.xml | 137 +- .../layout/astrid_reminder_view_portrait.xml | 137 +- astrid/res/layout/astrid_speech_bubble.xml | 79 +- astrid/res/layout/astrid_time_picker.xml | 146 +- .../layout/astrid_time_picker_horizontal.xml | 169 +- astrid/res/layout/backup_activity.xml | 36 +- .../res/layout/beast_mode_pref_activity.xml | 58 +- astrid/res/layout/billing_activity.xml | 170 +- astrid/res/layout/calendar.xml | 49 +- .../layout/calendar_alarm_list_creator.xml | 10 +- .../res/layout/calendar_reminder_activity.xml | 10 +- astrid/res/layout/contact_adapter_row.xml | 73 +- astrid/res/layout/contact_edit_row.xml | 70 +- astrid/res/layout/control_dialog_ok.xml | 24 +- astrid/res/layout/control_set_alarms.xml | 67 +- astrid/res/layout/control_set_assigned.xml | 95 +- .../res/layout/control_set_collaborators.xml | 239 +- astrid/res/layout/control_set_deadline.xml | 11 +- .../layout/control_set_deadline_display.xml | 65 +- .../layout/control_set_default_display.xml | 66 +- astrid/res/layout/control_set_files.xml | 38 +- .../res/layout/control_set_files_display.xml | 67 +- astrid/res/layout/control_set_gcal.xml | 40 +- .../res/layout/control_set_gcal_display.xml | 68 +- astrid/res/layout/control_set_hide.xml | 17 +- astrid/res/layout/control_set_importance.xml | 75 +- astrid/res/layout/control_set_notes.xml | 103 +- .../res/layout/control_set_notes_display.xml | 57 +- astrid/res/layout/control_set_opencrx.xml | 109 +- .../layout/control_set_opencrx_display.xml | 54 +- astrid/res/layout/control_set_reminders.xml | 204 +- astrid/res/layout/control_set_repeat.xml | 128 +- .../res/layout/control_set_repeat_display.xml | 75 +- astrid/res/layout/control_set_tags.xml | 62 +- astrid/res/layout/control_set_timers.xml | 106 +- astrid/res/layout/control_set_title.xml | 60 +- astrid/res/layout/custom_filter_activity.xml | 142 +- astrid/res/layout/custom_filter_row.xml | 82 +- astrid/res/layout/date_time_dialog.xml | 70 +- astrid/res/layout/date_time_picker.xml | 101 +- .../layout/date_time_picker_no_shortcuts.xml | 123 +- astrid/res/layout/deadline_number_picker.xml | 61 +- astrid/res/layout/feedback_prompt.xml | 66 +- astrid/res/layout/file_display_row.xml | 47 +- astrid/res/layout/file_row.xml | 70 +- astrid/res/layout/filter_adapter_row.xml | 119 +- astrid/res/layout/filter_list_activity.xml | 69 +- .../res/layout/filter_list_activity_3pane.xml | 69 +- .../filter_list_fragment_alternative.xml | 29 +- ...filter_list_fragment_alternative_3pane.xml | 29 +- astrid/res/layout/fla_separator.xml | 6 +- astrid/res/layout/gtasks_login_activity.xml | 55 +- astrid/res/layout/header_nav_views.xml | 137 +- astrid/res/layout/header_title_view.xml | 16 +- astrid/res/layout/help_popover.xml | 52 +- astrid/res/layout/list_dropdown_popover.xml | 40 +- astrid/res/layout/list_header.xml | 16 +- astrid/res/layout/locale_edit_alerts.xml | 64 +- astrid/res/layout/main_menu_popover.xml | 57 +- astrid/res/layout/main_menu_popover_body.xml | 53 +- .../layout/main_menu_popover_body_tablet.xml | 61 +- ..._menu_popover_body_tablet_phone_layout.xml | 61 +- .../res/layout/main_menu_popover_tablet.xml | 55 +- .../main_menu_popover_tablet_phone_layout.xml | 55 +- astrid/res/layout/main_menu_row.xml | 54 +- astrid/res/layout/main_menu_row_tablet.xml | 58 +- astrid/res/layout/missed_call_activity.xml | 10 +- astrid/res/layout/n_number_picker_dialog.xml | 12 +- astrid/res/layout/no_members_text_view.xml | 18 +- astrid/res/layout/note_decoration.xml | 30 +- astrid/res/layout/notes_view_dialog.xml | 61 +- astrid/res/layout/number_picker.xml | 31 +- astrid/res/layout/number_picker_dialog.xml | 10 +- astrid/res/layout/oauth_login_activity.xml | 17 +- .../res/layout/preference_draggable_row.xml | 53 +- astrid/res/layout/quick_add_bar.xml | 185 +- astrid/res/layout/repeat_until_dialog.xml | 73 +- .../res/layout/reusable_task_adapter_row.xml | 47 +- astrid/res/layout/share_activity.xml | 138 +- ...imple_list_item_multiple_choice_themed.xml | 20 +- astrid/res/layout/snooze_dialog.xml | 48 +- astrid/res/layout/sort_selection_dialog.xml | 178 +- astrid/res/layout/tag_edit_row.xml | 36 +- astrid/res/layout/tag_settings_activity.xml | 344 +- astrid/res/layout/tag_updates_activity.xml | 8 +- astrid/res/layout/tag_updates_fragment.xml | 161 +- astrid/res/layout/tag_updates_header.xml | 92 +- astrid/res/layout/task_adapter_row.xml | 231 +- astrid/res/layout/task_adapter_row_simple.xml | 285 +- .../layout/task_adapter_row_title_only.xml | 99 +- astrid/res/layout/task_edit_activity.xml | 369 +- astrid/res/layout/task_edit_more_controls.xml | 8 +- astrid/res/layout/task_edit_when_controls.xml | 57 +- .../res/layout/task_edit_wrapper_activity.xml | 21 +- astrid/res/layout/task_list_activity.xml | 46 +- .../layout/task_list_body_featured_list.xml | 73 +- .../layout/task_list_body_reengagement.xml | 131 +- astrid/res/layout/task_list_body_standard.xml | 44 +- astrid/res/layout/task_list_body_subtasks.xml | 48 +- astrid/res/layout/task_list_body_tag.xml | 115 +- astrid/res/layout/task_list_body_user.xml | 64 +- .../res/layout/task_list_wrapper_activity.xml | 11 +- .../task_list_wrapper_activity_3pane.xml | 68 +- .../task_list_wrapper_activity_no_swipe.xml | 10 +- astrid/res/layout/time_picker_dialog.xml | 32 +- astrid/res/layout/timer_decoration.xml | 64 +- astrid/res/layout/update_adapter_row.xml | 156 +- astrid/res/layout/update_message_link.xml | 40 +- .../layout/update_message_speech_bubble.xml | 81 +- astrid/res/layout/update_message_view.xml | 57 +- astrid/res/layout/web_service_amazon_row.xml | 159 +- astrid/res/layout/web_service_row.xml | 93 +- .../res/layout/web_services_load_button.xml | 20 +- astrid/res/layout/welcome_walkthrough.xml | 84 +- .../layout/welcome_walkthrough_login_page.xml | 214 +- .../res/layout/welcome_walkthrough_page.xml | 71 +- .../welcome_walkthrough_simple_login.xml | 74 +- astrid/res/layout/widget_config_activity.xml | 50 +- astrid/res/layout/widget_initialized.xml | 87 +- astrid/res/layout/widget_initialized_dark.xml | 87 +- .../widget_initialized_dark_transparent.xml | 87 +- .../res/layout/widget_initialized_legacy.xml | 87 +- astrid/res/layout/widget_initialized_red.xml | 87 +- .../layout/widget_initialized_transparent.xml | 87 +- astrid/res/layout/widget_loading.xml | 107 +- astrid/res/layout/widget_row.xml | 20 +- astrid/res/layout/widget_separator.xml | 10 +- astrid/res/values-ca/strings.xml | 1606 ++--- astrid/res/values-cs/strings.xml | 1806 ++--- astrid/res/values-da/strings.xml | 1272 ++-- astrid/res/values-de/strings.xml | 5760 ++++++++-------- astrid/res/values-es/strings.xml | 5762 ++++++++-------- astrid/res/values-fr/strings.xml | 5791 +++++++++-------- astrid/res/values-it/strings.xml | 5777 ++++++++-------- astrid/res/values-iw/strings.xml | 5620 ++++++++-------- astrid/res/values-ja/strings.xml | 5679 ++++++++-------- astrid/res/values-ko/strings.xml | 5442 ++++++++-------- astrid/res/values-nb/strings.xml | 1303 ++-- astrid/res/values-nl/strings.xml | 5720 ++++++++-------- astrid/res/values-pl/strings.xml | 5718 ++++++++-------- astrid/res/values-pt-rBR/strings.xml | 5718 ++++++++-------- astrid/res/values-pt/strings.xml | 1072 +-- astrid/res/values-ru/strings-opencrx.xml | 93 +- astrid/res/values-ru/strings.xml | 5724 ++++++++-------- astrid/res/values-sv/strings.xml | 5704 ++++++++-------- astrid/res/values-th/strings.xml | 1019 +-- astrid/res/values-tr/strings.xml | 5698 ++++++++-------- astrid/res/values-zh-rCN/strings.xml | 5396 +++++++-------- astrid/res/values-zh-rTW/strings.xml | 5376 +++++++-------- astrid/res/values/attrs.xml | 98 +- astrid/res/values/colors.xml | 12 +- astrid/res/values/cwac_touchlist_attrs.xml | 38 +- astrid/res/values/keys-opencrx.xml | 12 +- astrid/res/values/keys.xml | 899 +-- astrid/res/values/strings-actfm.xml | 804 +-- astrid/res/values/strings-alarms.xml | 16 +- astrid/res/values/strings-backup.xml | 153 +- astrid/res/values/strings-core.xml | 2110 +++--- astrid/res/values/strings-defaults.xml | 178 +- astrid/res/values/strings-filters.xml | 62 +- astrid/res/values/strings-gcal.xml | 66 +- astrid/res/values/strings-gtasks.xml | 120 +- astrid/res/values/strings-intro.xml | 102 +- astrid/res/values/strings-locale.xml | 65 +- astrid/res/values/strings-opencrx.xml | 88 +- astrid/res/values/strings-ppack.xml | 32 +- astrid/res/values/strings-premium.xml | 119 +- astrid/res/values/strings-reminders.xml | 820 +-- astrid/res/values/strings-repeat.xml | 253 +- astrid/res/values/strings-subtasks.xml | 16 +- astrid/res/values/strings-tags.xml | 196 +- astrid/res/values/strings-timers.xml | 26 +- astrid/res/values/strings-updates.xml | 19 +- astrid/res/values/strings-voice.xml | 88 +- astrid/res/values/strings-welcome.xml | 102 +- astrid/res/values/strings-widget.xml | 89 +- astrid/res/values/styles-locale.xml | 44 +- astrid/res/values/styles.xml | 322 +- astrid/res/xml/filter_list_searchable.xml | 4 +- astrid/res/xml/preferences.xml | 383 +- astrid/res/xml/preferences_actfm.xml | 80 +- astrid/res/xml/preferences_backup.xml | 54 +- astrid/res/xml/preferences_blank.xml | 4 +- astrid/res/xml/preferences_defaults.xml | 66 +- astrid/res/xml/preferences_gtasks.xml | 60 +- astrid/res/xml/preferences_misc.xml | 64 +- astrid/res/xml/preferences_oldtasks.xml | 48 +- astrid/res/xml/preferences_opencrx.xml | 108 +- astrid/res/xml/preferences_reminders.xml | 84 +- astrid/res/xml/widget_provider_info.xml | 10 +- .../com/timsu/astrid/activities/TaskList.java | 4 +- .../com/timsu/astrid/data/Identifier.java | 10 +- .../astrid/data/LegacyAbstractController.java | 13 +- .../astrid/data/LegacyAbstractModel.java | 119 +- .../com/timsu/astrid/data/alerts/Alert.java | 56 +- .../astrid/data/alerts/AlertController.java | 62 +- .../timsu/astrid/data/enums/Importance.java | 76 +- .../astrid/data/enums/RepeatInterval.java | 32 +- .../astrid/data/sync/SyncDataController.java | 68 +- .../timsu/astrid/data/sync/SyncMapping.java | 63 +- .../astrid/data/tag/AbstractTagModel.java | 87 +- .../timsu/astrid/data/tag/TagController.java | 205 +- .../astrid/data/tag/TagModelForView.java | 33 +- .../astrid/data/tag/TagToTaskMapping.java | 52 +- .../astrid/data/task/AbstractTaskModel.java | 405 +- .../astrid/data/task/TaskController.java | 299 +- .../astrid/data/task/TaskModelForEdit.java | 39 +- .../data/task/TaskModelForHandlers.java | 48 +- .../astrid/data/task/TaskModelForList.java | 107 +- .../astrid/data/task/TaskModelForNotify.java | 27 +- .../data/task/TaskModelForProvider.java | 23 +- .../data/task/TaskModelForReminder.java | 21 +- .../astrid/data/task/TaskModelForSync.java | 49 +- .../astrid/data/task/TaskModelForWidget.java | 23 +- .../astrid/data/task/TaskModelForXml.java | 70 +- .../utilities/LegacyTasksXmlExporter.java | 32 +- .../commonsware/cwac/merge/MergeAdapter.java | 669 +- .../cwac/merge/MergeSpinnerAdapter.java | 143 +- .../astrid/activity/AboutActivity.java | 12 +- .../astrid/activity/AddOnActivity.java | 34 +- .../astrid/activity/AstridActivity.java | 52 +- .../astrid/activity/BeastModePreferences.java | 7 +- .../astrid/activity/DefaultFilterMode.java | 2 +- .../astrid/activity/EditPreferences.java | 150 +- .../src/com/todoroo/astrid/activity/Eula.java | 19 +- .../activity/ExpandableListFragment.java | 53 +- .../astrid/activity/FilterListFragment.java | 72 +- .../astrid/activity/FilterModeSpec.java | 5 + .../activity/FilterShortcutActivity.java | 4 +- .../astrid/activity/ShareLinkActivity.java | 8 +- .../astrid/activity/ShortcutActivity.java | 86 +- .../activity/SortSelectionActivity.java | 88 +- .../astrid/activity/TaskEditActivity.java | 42 +- .../astrid/activity/TaskEditFragment.java | 226 +- .../astrid/activity/TaskEditViewPager.java | 4 +- .../astrid/activity/TaskListActivity.java | 137 +- .../astrid/activity/TaskListFragment.java | 289 +- .../todoroo/astrid/adapter/AddOnAdapter.java | 18 +- .../todoroo/astrid/adapter/FilterAdapter.java | 149 +- .../todoroo/astrid/adapter/TaskAdapter.java | 402 +- .../adapter/TaskListFragmentPagerAdapter.java | 7 +- .../todoroo/astrid/adapter/UpdateAdapter.java | 144 +- .../astrid/api/TaskContextActionExposer.java | 8 +- .../astrid/api/TaskDecorationExposer.java | 5 +- .../billing/AstridPurchaseObserver.java | 95 +- .../com/todoroo/astrid/billing/Base64.java | 989 +-- .../billing/Base64DecoderException.java | 14 +- .../astrid/billing/BillingActivity.java | 67 +- .../astrid/billing/BillingConstants.java | 4 +- .../astrid/billing/BillingReceiver.java | 11 +- .../astrid/billing/BillingService.java | 83 +- .../astrid/billing/PurchaseObserver.java | 59 +- .../astrid/billing/ResponseHandler.java | 50 +- .../com/todoroo/astrid/billing/Security.java | 11 +- .../todoroo/astrid/dao/ABTestEventDao.java | 16 +- .../astrid/dao/DaoReflectionHelpers.java | 4 +- .../src/com/todoroo/astrid/dao/Database.java | 580 +- .../com/todoroo/astrid/dao/HistoryDao.java | 2 +- .../com/todoroo/astrid/dao/MetadataDao.java | 64 +- .../todoroo/astrid/dao/RemoteModelDao.java | 13 +- .../todoroo/astrid/dao/StoreObjectDao.java | 27 +- .../com/todoroo/astrid/dao/TagDataDao.java | 18 +- .../todoroo/astrid/dao/TagMetadataDao.java | 37 +- .../todoroo/astrid/dao/TaskAttachmentDao.java | 18 +- .../src/com/todoroo/astrid/dao/TaskDao.java | 247 +- .../astrid/dao/TaskListMetadataDao.java | 10 +- .../src/com/todoroo/astrid/dao/UpdateDao.java | 8 +- .../todoroo/astrid/dao/UserActivityDao.java | 2 +- .../src/com/todoroo/astrid/dao/UserDao.java | 5 +- .../com/todoroo/astrid/data/ABTestEvent.java | 33 +- astrid/src/com/todoroo/astrid/data/AddOn.java | 3 +- .../todoroo/astrid/helper/AsyncImageView.java | 12 +- .../astrid/helper/DueDateTimeMigrator.java | 7 +- .../todoroo/astrid/helper/MetadataHelper.java | 2 +- .../helper/ProgressBarSyncResultCallback.java | 12 +- .../astrid/helper/SyncActionHelper.java | 34 +- .../helper/TaskAdapterAddOnManager.java | 58 +- .../astrid/helper/TaskEditControlSet.java | 8 +- .../TaskListContextMenuExtensionLoader.java | 6 +- .../com/todoroo/astrid/helper/UUIDHelper.java | 3 +- .../todoroo/astrid/legacy/AlarmDatabase.java | 9 +- .../astrid/legacy/LegacyAlertModel.java | 4 +- .../astrid/legacy/LegacyImportance.java | 10 +- .../astrid/legacy/LegacyRepeatInfo.java | 38 +- .../todoroo/astrid/legacy/LegacyTagModel.java | 4 +- .../astrid/legacy/LegacyTaskModel.java | 12 +- .../astrid/legacy/TransitionalAlarm.java | 37 +- .../astrid/provider/Astrid2TaskProvider.java | 399 +- .../provider/Astrid3ContentProvider.java | 206 +- .../astrid/provider/SqlContentProvider.java | 18 +- .../todoroo/astrid/service/AddOnService.java | 62 +- .../service/Astrid2To3UpgradeHelper.java | 84 +- .../service/AstridDependencyInjector.java | 9 +- .../astrid/service/GlobalEventReceiver.java | 5 +- .../astrid/service/MarketStrategy.java | 36 +- .../astrid/service/MetadataService.java | 39 +- .../astrid/service/StartupService.java | 116 +- .../astrid/service/StatisticsService.java | 30 +- .../service/SyncResultCallbackWrapper.java | 5 + .../todoroo/astrid/service/SyncV2Service.java | 25 +- .../astrid/service/TagDataService.java | 54 +- .../todoroo/astrid/service/TaskService.java | 81 +- .../todoroo/astrid/service/ThemeService.java | 170 +- .../service/UpdateMessagePreference.java | 8 +- .../astrid/service/UpdateMessageService.java | 76 +- .../astrid/service/UpdateScreenFlow.java | 4 +- .../astrid/service/UpgradeService.java | 429 +- .../astrid/service/abtesting/ABChooser.java | 10 +- .../ABTestEventReportingService.java | 18 +- .../service/abtesting/ABTestInvoker.java | 37 +- .../astrid/service/abtesting/ABTests.java | 44 +- .../todoroo/astrid/ui/AstridTimePicker.java | 7 +- .../com/todoroo/astrid/ui/CalendarDialog.java | 72 +- .../com/todoroo/astrid/ui/CalendarView.java | 362 +- .../todoroo/astrid/ui/CheckableImageView.java | 2 +- .../todoroo/astrid/ui/ContactListAdapter.java | 35 +- .../astrid/ui/ContactsAutoComplete.java | 6 +- .../astrid/ui/CustomBorderDrawable.java | 15 +- .../todoroo/astrid/ui/DateAndTimeDialog.java | 1 + .../todoroo/astrid/ui/DateAndTimePicker.java | 14 +- .../todoroo/astrid/ui/DateChangedAlerts.java | 66 +- .../todoroo/astrid/ui/DeadlineControlSet.java | 2 +- .../astrid/ui/DeadlineTimePickerDialog.java | 42 +- .../todoroo/astrid/ui/DraggableListView.java | 128 +- .../astrid/ui/EditDialogOkBackground.java | 4 +- .../astrid/ui/EditNotesControlSet.java | 10 +- .../astrid/ui/EditTitleControlSet.java | 6 +- .../astrid/ui/ErrorCatchingEditText.java | 18 +- .../astrid/ui/FeedbackPromptDialogs.java | 43 +- .../todoroo/astrid/ui/FragmentPopover.java | 10 +- .../astrid/ui/HideUntilControlSet.java | 34 +- .../astrid/ui/ImportanceControlSet.java | 23 +- .../todoroo/astrid/ui/MainMenuPopover.java | 1 + .../astrid/ui/NNumberPickerDialog.java | 45 +- .../todoroo/astrid/ui/NestableViewPager.java | 4 +- .../com/todoroo/astrid/ui/NestedListView.java | 2 +- .../com/todoroo/astrid/ui/NumberPicker.java | 94 +- .../todoroo/astrid/ui/NumberPickerButton.java | 2 +- .../todoroo/astrid/ui/NumberPickerDialog.java | 4 +- .../todoroo/astrid/ui/PeopleContainer.java | 93 +- .../todoroo/astrid/ui/PopupControlSet.java | 1 + .../com/todoroo/astrid/ui/QuickAddBar.java | 30 +- .../astrid/ui/RandomReminderControlSet.java | 19 +- .../todoroo/astrid/ui/ReminderControlSet.java | 23 +- .../astrid/ui/TaskListFragmentPager.java | 3 + .../ui/TextViewWithMeasureListener.java | 2 +- .../astrid/ui/TimeDurationControlSet.java | 32 +- .../astrid/utility/AstridPreferenceSpec.java | 1 + .../astrid/utility/AstridPreferences.java | 27 +- .../com/todoroo/astrid/utility/Constants.java | 16 +- .../com/todoroo/astrid/utility/Entities.java | 783 ++- .../astrid/utility/ResourceDrawableCache.java | 72 +- .../astrid/utility/StringEscapeUtils.java | 31 +- .../astrid/utility/SyncMetadataService.java | 77 +- .../todoroo/astrid/utility/TitleParser.java | 125 +- .../voice/Api6VoiceOutputAssistant.java | 13 +- .../astrid/voice/VoiceInputAssistant.java | 44 +- .../astrid/voice/VoiceOutputService.java | 10 +- .../todoroo/astrid/voice/VoiceRecognizer.java | 8 +- .../astrid/welcome/HelpInfoPopover.java | 15 +- .../welcome/tutorial/WelcomePagerAdapter.java | 78 +- .../welcome/tutorial/WelcomeWalkthrough.java | 27 +- .../todoroo/astrid/widget/TasksWidget.java | 40 +- .../astrid/widget/WidgetConfigActivity.java | 21 +- tests-sync/AndroidManifest.xml | 17 +- tests-sync/res/layout/main.xml | 12 +- .../todoroo/astrid/gtasks/GtasksApiTest.java | 38 +- .../astrid/gtasks/GtasksNewSyncTest.java | 64 +- .../astrid/gtasks/GtasksSyncOnSaveTest.java | 34 +- .../sync/repeats/AbstractSyncRepeatTests.java | 42 +- .../sync/repeats/RepeatTestsActFmSync.java | 39 +- .../repeats/RepeatTestsActFmSyncRemote.java | 12 +- .../sync/repeats/RepeatTestsGtasksSync.java | 38 +- .../repeats/RepeatTestsGtasksSyncRemote.java | 9 +- .../todoroo/astrid/test/DatabaseTestCase.java | 58 +- .../astrid/test/TestDependencyInjector.java | 1 + .../todoroo/astrid/test/TestUtilities.java | 1 - .../todoroo/astrid/test/TodorooTestCase.java | 25 +- .../test/TodorooTestCaseWithInjector.java | 23 +- .../junitreport/JUnitReportListener.java | 28 +- .../junitreport/JUnitReportTestRunner.java | 2 +- tests/AndroidManifest.xml | 11 +- .../service/DependencyInjectionTests.java | 18 +- .../service/TestDependencyInjector.java | 1 + .../andlib/sql/QueryTemplateHelperTest.java | 5 +- .../andlib/test/SimpleAndroidTest.java | 9 +- .../todoroo/andlib/test/TestUtilities.java | 1 - .../todoroo/andlib/test/TodorooTestCase.java | 25 +- .../test/TodorooTestCaseWithInjector.java | 23 +- .../todoroo/andlib/test/TranslationTests.java | 69 +- .../andlib/utility/DateUtilitiesTest.java | 12 +- tests/src/com/todoroo/astrid/AllTests.java | 27 +- .../astrid/backup/BackupServiceTests.java | 32 +- .../todoroo/astrid/dao/MetadataDaoTests.java | 4 +- .../com/todoroo/astrid/dao/TaskDaoTests.java | 8 +- .../gtasks/GtasksDetailExposerTest.java | 11 +- .../astrid/gtasks/GtasksIndentActionTest.java | 15 +- .../gtasks/GtasksMetadataServiceTest.java | 7 +- .../gtasks/GtasksTaskListUpdaterTest.java | 47 +- .../astrid/gtasks/GtasksTaskMovingTest.java | 45 +- .../com/todoroo/astrid/model/TaskTests.java | 18 +- .../astrid/provider/Astrid3ProviderTests.java | 32 +- .../astrid/reminders/NotificationTests.java | 21 +- .../reminders/ReminderServiceTests.java | 55 +- .../astrid/repeats/AdvancedRepeatTests.java | 56 +- .../astrid/repeats/NewRepeatTests.java | 31 +- .../repeats/RepeatAfterCompleteTests.java | 60 +- .../astrid/service/ABTestingServiceTest.java | 17 +- .../AstridDependencyInjectorTests.java | 14 +- .../astrid/service/QuickAddMarkupTest.java | 8 +- .../astrid/service/TitleParserTest.java | 380 +- .../service/UpdateMessageServiceTest.java | 24 +- .../astrid/subtasks/SubtasksHelperTest.java | 3 +- .../subtasks/SubtasksMigrationTest.java | 2 +- .../astrid/subtasks/SubtasksTestCase.java | 2 +- .../sync/AstridNewSyncMigrationTest.java | 286 +- .../ConstructOutstandingFromMasterTest.java | 66 +- .../todoroo/astrid/sync/NewSyncTestCase.java | 88 +- .../todoroo/astrid/sync/SyncMessageTest.java | 303 +- .../todoroo/astrid/sync/SyncModelTest.java | 182 +- .../astrid/test/AstridTranslationTests.java | 12 +- .../todoroo/astrid/test/DatabaseTestCase.java | 70 +- .../android/junitreport/Compatibility.java | 13 +- .../junitreport/JUnitReportListener.java | 70 +- .../junitreport/JUnitReportTestRunner.java | 7 +- 832 files changed, 79761 insertions(+), 73497 deletions(-) diff --git a/api/AndroidManifest.xml b/api/AndroidManifest.xml index c084e7d72..d63ccf83e 100644 --- a/api/AndroidManifest.xml +++ b/api/AndroidManifest.xml @@ -5,10 +5,10 @@ ** See the file "LICENSE" for the full license governing this code. --> + package="com.todoroo.astrid.api" + android:versionCode="1" + android:versionName="1.0"> - + \ No newline at end of file diff --git a/api/res/layout/status_preference.xml b/api/res/layout/status_preference.xml index c8be5f06a..9435355e7 100644 --- a/api/res/layout/status_preference.xml +++ b/api/res/layout/status_preference.xml @@ -16,46 +16,49 @@ - + android:id="@+id/status" + android:layout_width="fill_parent" + android:layout_height="wrap_content" + android:minHeight="?android:attr/listPreferredItemHeight" + android:gravity="center_vertical" + android:paddingRight="?android:attr/scrollbarSize"> + - - - - + android:layout_marginLeft="20dip" + android:layout_marginRight="6dip" + android:layout_marginTop="6dip" + android:layout_marginBottom="6dip" + android:layout_weight="1"> + + + + - + - + diff --git a/api/res/values-ca/strings.xml b/api/res/values-ca/strings.xml index 88c3b39be..6da4721d7 100644 --- a/api/res/values-ca/strings.xml +++ b/api/res/values-ca/strings.xml @@ -1,101 +1,108 @@ - - 1 any - %d anys - - - 1 mes - %d mesos - - - 1 setmana - %d setmanes - - - 1 dia - %d dies - - - 1 Weekday - %d Weekdays - - - 1 hora - %d Hores - - - 1 minut - %d Minuts - - - 1 segon - %d Segons - - - 1 Hr - %d Hrs - - - 1 Min - %d Min - - - 1 Seg - %d Seg - - - 1 tasca - %d tasques - - - 1 person - %d people - - Avui - Demà - Ahir - Confirmar? - Pregunta: - Informació - S\'ha produït un error - Desar - - No - Tancar - Fet - ¡Ui, sembla que hi ha hagut un problema! Això es el que ha passat:\n\n%s - ¡Ui, sembla que hi ha hagut un problema! - Si us plau, espera... - Sincronitzant les seves tasques... - S\'està sincronitzant... - Error de conexió! Verifiqui la conexió d\'internet. - Estat - Sincronització en curs... - Última sincronització:\n%s - Fallida el: %s - Última sincronització correcte: %s - Mai sincronitzat! - Opcions - Sincronitzar en segon pla - Desactivada la sincronització en segon pla - Actualment configurat en: %s - La sincronització en segon pla només funciona amb el Wifi activat. - Sempre es produirà la sincronització en segon pla - Accions - Surt - Esborra tota la informació de sincronització - Tancar sessió / esborra la informació de sincronització? - - desactivat - cada quince minuts - cada trenta minuts - cada hora - cada tres hores - cada sis hores - cada dotze hores - diàriament - cada tres dies - setmanalment - + + 1 any + %d anys + + + 1 mes + %d mesos + + + 1 setmana + %d setmanes + + + 1 dia + %d dies + + + 1 Weekday + %d Weekdays + + + 1 hora + %d Hores + + + 1 minut + %d Minuts + + + 1 segon + %d Segons + + + 1 Hr + %d Hrs + + + 1 Min + %d Min + + + 1 Seg + %d Seg + + + 1 tasca + %d tasques + + + 1 person + %d people + + Avui + Demà + Ahir + Confirmar? + Pregunta: + Informació + S\'ha produït un error + Desar + + No + Tancar + Fet + ¡Ui, sembla que hi ha hagut un problema! Això es el que ha + passat:\n\n%s + + ¡Ui, sembla que hi ha hagut un problema! + Si us plau, espera... + Sincronitzant les seves tasques... + S\'està sincronitzant... + Error de conexió! Verifiqui la conexió d\'internet. + Estat + Sincronització en curs... + Última sincronització:\n%s + Fallida el: %s + Última sincronització correcte: %s + Mai sincronitzat! + Opcions + Sincronitzar en segon pla + Desactivada la sincronització en segon pla + + Actualment configurat en: %s + La sincronització en segon pla només funciona amb el + Wifi activat. + + Sempre es produirà la sincronització en segon pla + + Accions + Surt + Esborra tota la informació de sincronització + Tancar sessió / esborra la informació de sincronització? + + + desactivat + cada quince minuts + cada trenta minuts + cada hora + cada tres hores + cada sis hores + cada dotze hores + diàriament + cada tres dies + setmanalment + diff --git a/api/res/values-cs/strings.xml b/api/res/values-cs/strings.xml index 855555168..c53eae2ae 100644 --- a/api/res/values-cs/strings.xml +++ b/api/res/values-cs/strings.xml @@ -1,116 +1,121 @@ - - 1 rok - %d Roky - - - 1 měsíc - %d Měsíce - - - 1 týden - %d Týdny - - - 1 den - %d Dnů - - - 1 pracovní den - %d pracovních dnů - - - 1 hodina - %d hodin - - - 1 minuta - %d minut - - - 1 vteřina - %d vteřin - - - 1 hod. - %d hod. - - - 1 min. - %d min. - - - 1 s - %d s - - - 1 úkol - %d úkolů - - - 1 osoba - %d lidí - - Dnes - Zítra - Včera - Zítra - Včera - Potvrdit? - Otázka: - Informace - Chyba! - Uložit - Ano - Ne - Zavřít - Hotovo - Jejda, vypadá to, že se vyskytla chyba! Tady je co se stalo:\n\n%s - Jejda, vypadá to, že se vyskytla chyba! - Čekejte prosím... - Probíhá synchronizace Vašich úkolů... - Sychronizuji... - Synchronizace - Astrid.com, Google Tasks, uložená data, lokální záloha - Chyba připojení! Zkontrolujte vaše internetové připojení. - Stav - Stav: %s - Nepřihlášen - Probíhá synchronizace... - Poslední synchronizace:\n%s - Selhalo: %s - Sync w/ chyby: %s - Poslední úspěšná synchronizace: %s - Nikdo nesynchronizováno! - Nastavení - Synchronizace na pozadí - Synchronizace na pozadí je zakázána - Současně nastaveno na: %s - Nastavení jen pro Wifi - Synchronizovat na pozadí se bude pouze při zapnuté Wifi - Synchronizovat na pozadí se bude vždy - Akce - Synchronizovat nyní - Přihlásit se & Synchronizovat! - Přihlášen jako: - Stavové hlášení - Klepnutím odešlete zprávu týmu Astrid - Odeslat zprávu - Odhlásit se - Smazat všechny synchronizační data - Odhlásit se / vymazat synchronizační data? - Během posledního pokusu o synchronizaci se službou %s nastal problém s připojením k síti. Zkuste to prosím později. - - zakázat - každých patnáct minut - každých třicet minut - každou hodinu - každé tři hodiny - každých šest hodin - každých dvanáct hodin - každý den - každé tři dny - každý týden - + + 1 rok + %d Roky + + + 1 měsíc + %d Měsíce + + + 1 týden + %d Týdny + + + 1 den + %d Dnů + + + 1 pracovní den + %d pracovních dnů + + + 1 hodina + %d hodin + + + 1 minuta + %d minut + + + 1 vteřina + %d vteřin + + + 1 hod. + %d hod. + + + 1 min. + %d min. + + + 1 s + %d s + + + 1 úkol + %d úkolů + + + 1 osoba + %d lidí + + Dnes + Zítra + Včera + Zítra + Včera + Potvrdit? + Otázka: + Informace + Chyba! + Uložit + Ano + Ne + Zavřít + Hotovo + Jejda, vypadá to, že se vyskytla chyba! Tady je co se stalo:\n\n%s + + Jejda, vypadá to, že se vyskytla chyba! + Čekejte prosím... + Probíhá synchronizace Vašich úkolů... + Sychronizuji... + Synchronizace + Astrid.com, Google Tasks, uložená data, lokální záloha + Chyba připojení! Zkontrolujte vaše internetové připojení. + Stav + Stav: %s + Nepřihlášen + Probíhá synchronizace... + Poslední synchronizace:\n%s + Selhalo: %s + Sync w/ chyby: %s + Poslední úspěšná synchronizace: %s + Nikdo nesynchronizováno! + Nastavení + Synchronizace na pozadí + Synchronizace na pozadí je zakázána + Současně nastaveno na: %s + Nastavení jen pro Wifi + Synchronizovat na pozadí se bude pouze při zapnuté + Wifi + + Synchronizovat na pozadí se bude vždy + Akce + Synchronizovat nyní + Přihlásit se & Synchronizovat! + Přihlášen jako: + Stavové hlášení + Klepnutím odešlete zprávu týmu Astrid + Odeslat zprávu + Odhlásit se + Smazat všechny synchronizační data + Odhlásit se / vymazat synchronizační data? + Během posledního pokusu o synchronizaci se službou %s nastal + problém s připojením k síti. Zkuste to prosím později. + + + zakázat + každých patnáct minut + každých třicet minut + každou hodinu + každé tři hodiny + každých šest hodin + každých dvanáct hodin + každý den + každé tři dny + každý týden + diff --git a/api/res/values-da/strings.xml b/api/res/values-da/strings.xml index f9be3ad99..67d833194 100644 --- a/api/res/values-da/strings.xml +++ b/api/res/values-da/strings.xml @@ -1,89 +1,91 @@ - - 1 år - %d År - - - 1 måned - %d måneder - - - 1 uge - %d uger - - - 1 dag - %d dage - - - 1 Weekday - %d Weekdays - - - 1 time - %d timer - - - 1 minut - %d minutter - - - 1 sekund - %d sekunder - - - 1 time - %d timer - - - 1 min. - %d min. - - - 1 sek. - %d sek. - - - 1 opgave - %d opgaver - - - 1 person - %d people - - I dag - I morgen - I går - Bekræft? - Spørsmål: - Gem - Ja - Nej - Luk - Færdig - Vent venligst... - Synkroniserer... - Synkronisering - Forbindelsesfejl! Tjek din internetforbindelse. - Indstillinger - Baggrunds Synk - Baggrunds synkronisering er slået fra - Baggrunds synkronisering sker kun ved Wifi - Baggrunds synkronisering sker uanset forbindelsestype - Handlinger - Log af - Sletter al synkroniserings data - - disable - every fifteen minutes - every thirty minutes - hver time - hver 3. time - hver 6. time - hver 12. time - hver dag - hver 3. dag - hver uge - + + 1 år + %d År + + + 1 måned + %d måneder + + + 1 uge + %d uger + + + 1 dag + %d dage + + + 1 Weekday + %d Weekdays + + + 1 time + %d timer + + + 1 minut + %d minutter + + + 1 sekund + %d sekunder + + + 1 time + %d timer + + + 1 min. + %d min. + + + 1 sek. + %d sek. + + + 1 opgave + %d opgaver + + + 1 person + %d people + + I dag + I morgen + I går + Bekræft? + Spørsmål: + Gem + Ja + Nej + Luk + Færdig + Vent venligst... + Synkroniserer... + Synkronisering + Forbindelsesfejl! Tjek din internetforbindelse. + Indstillinger + Baggrunds Synk + Baggrunds synkronisering er slået fra + Baggrunds synkronisering sker kun ved Wifi + Baggrunds synkronisering sker uanset + forbindelsestype + + Handlinger + Log af + Sletter al synkroniserings data + + disable + every fifteen minutes + every thirty minutes + hver time + hver 3. time + hver 6. time + hver 12. time + hver dag + hver 3. dag + hver uge + diff --git a/api/res/values-de/strings.xml b/api/res/values-de/strings.xml index 45dff2116..205001822 100755 --- a/api/res/values-de/strings.xml +++ b/api/res/values-de/strings.xml @@ -4,243 +4,252 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - - - - - - - 1 Jahr - - %d Jahre - - - - 1 Monat - - %d Monate - - - - Eine Woche - - %d Wochen - - - - Ein Tag - - %d Tage - - - - Ein Wochentag - - %d Wochentage - - - - Eine Stunde - - %d Stunden - - - - Eine Minute - - %d Minuten - - - - Eine Sekunde - - %d Sekunden - - - - 1 Std - - %d Std - - - - 1 Min - - %d min - - - - 1 Sek - - %d Sek - - - - 1 Aufgabe - - %d Aufgaben - - - - Eine Person - - %d Personen - - - - Heute - - - Morgen - - - Gestern - - - Morg. - - - Gest. - - - - - Bestätigen? - - - Frage: - - - Informationen - - - Fehler! - - - Speichern - - - Ja - - - Nein - - - Schließen - - - Erledigt - - - Ups, sieht aus, als ob ein Fehler aufgetreten ist! Folgendes ist passiert:\n\n%s - - - Ups, sieht aus, als ob ein Fehler aufgetreten ist! - - - Bitte warten... - - - - - Synchronisiere deine Aufgaben - - - Synchronisiere… - - - Synchronisation - - - Jetzt synchronisieren - - - Astrid.com, Google Tasks, gespeicherte Daten, lokale Backups - - - Verbindungsfehler! Überprüfen Sie Ihre Internetverbindung. - - - - - Status - - - Status: %s - - Nicht angemeldet - - Synchronisierung läuft... - - Letzte Synchronisierung:\n%s - - Fehlgeschlagen am: %s - - Synchronisation m. Fehler: %s - - Letzte erfolgreiche Synchronisierung: %s - - Noch nie synchronisiert! - - - Einstellungen - - - Hintergrund-Synchronisierung - - Hintergrund-Synchronisierung ist deaktiviert - - Gesetzt auf: %s - - - WLAN-Einstellungen - - Hintergrund-Synchronisierung nur bei WLAN-Verbindung - - Hintergrund-Synchronisierung findet immer statt - - - Aktionen - - - Jetzt synchronisieren - - Einloggen & synchronisieren! - - - Angemeldet als: - - - Statusbericht - - - Klicke um einen Bericht ans Astrid-Team zu senden - - Bericht senden - - - Abmelden - - Alle Synchronisationsdaten löschen - - - Ausloggen/synchronisierte Daten löschen? - - - Es gab ein Problem mit der Netzwerkverbindung während der letzten Synchronisation mit %s. Versuche es bitte später noch einmal. - - - - deaktivieren - alle 15 Minuten - alle 30 Minuten - stündlich - alle 3 Stunden - alle 6 Stunden - alle 12 Stunden - täglich - jeden dritten Tag - wöchentlich - - + + + + + + + 1 Jahr + + %d Jahre + + + + 1 Monat + + %d Monate + + + + Eine Woche + + %d Wochen + + + + Ein Tag + + %d Tage + + + + Ein Wochentag + + %d Wochentage + + + + Eine Stunde + + %d Stunden + + + + Eine Minute + + %d Minuten + + + + Eine Sekunde + + %d Sekunden + + + + 1 Std + + %d Std + + + + 1 Min + + %d min + + + + 1 Sek + + %d Sek + + + + 1 Aufgabe + + %d Aufgaben + + + + Eine Person + + %d Personen + + + + Heute + + + Morgen + + + Gestern + + + Morg. + + + Gest. + + + + + Bestätigen? + + + Frage: + + + Informationen + + + Fehler! + + + Speichern + + + Ja + + + Nein + + + Schließen + + + Erledigt + + + Ups, sieht aus, als ob ein Fehler aufgetreten ist! Folgendes ist + passiert:\n\n%s + + + + Ups, sieht aus, als ob ein Fehler aufgetreten ist! + + + Bitte warten... + + + + + Synchronisiere deine Aufgaben + + + Synchronisiere… + + + Synchronisation + + + Jetzt synchronisieren + + + Astrid.com, Google Tasks, gespeicherte Daten, lokale Backups + + + Verbindungsfehler! Überprüfen Sie Ihre Internetverbindung. + + + + + Status + + + Status: %s + + Nicht angemeldet + + Synchronisierung läuft... + + Letzte Synchronisierung:\n%s + + Fehlgeschlagen am: %s + + Synchronisation m. Fehler: %s + + Letzte erfolgreiche Synchronisierung: %s + + Noch nie synchronisiert! + + + Einstellungen + + + Hintergrund-Synchronisierung + + Hintergrund-Synchronisierung ist deaktiviert + + + Gesetzt auf: %s + + + WLAN-Einstellungen + + Hintergrund-Synchronisierung nur bei + WLAN-Verbindung + + + Hintergrund-Synchronisierung findet immer statt + + + + Aktionen + + + Jetzt synchronisieren + + Einloggen & synchronisieren! + + + Angemeldet als: + + + Statusbericht + + + Klicke um einen Bericht ans Astrid-Team zu senden + + + Bericht senden + + + Abmelden + + Alle Synchronisationsdaten löschen + + + Ausloggen/synchronisierte Daten löschen? + + + Es gab ein Problem mit der Netzwerkverbindung während der + letzten Synchronisation mit %s. Versuche es bitte später noch einmal. + + + + + deaktivieren + alle 15 Minuten + alle 30 Minuten + stündlich + alle 3 Stunden + alle 6 Stunden + alle 12 Stunden + täglich + jeden dritten Tag + wöchentlich + + diff --git a/api/res/values-es/strings.xml b/api/res/values-es/strings.xml index ca543ccbc..ccd1a4522 100755 --- a/api/res/values-es/strings.xml +++ b/api/res/values-es/strings.xml @@ -4,243 +4,253 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - - - - - - - 1 año - - %d años - - - - 1 mes - - %d meses - - - - 1 semana - - %d semanas - - - - Un día - - %d días - - - - 1 día laborable - - %d días laborables - - - - 1 hora - - %d horas - - - - 1 minuto - - %d minutos - - - - 1 segundo - - %d segundos - - - - 1 hr - - %d hrs - - - - 1 min - - %d min - - - - 1 seg - - %d seg - - - - 1 tarea - - %d tareas - - - - 1 persona - - %d personas - - - - Hoy - - - Mañana - - - Ayer - - - Mañana - - - Ayer - - - - - ¿Confirmar? - - - Pregunta: - - - Información - - - ¡Error! - - - Guardar - - - - - - No - - - Cerrar - - - Terminado - - - ¡Uy, parece que ocurró un error! Esto es lo que pasó:\n\n%s - - - ¡Uy, parece que ocurrió un error! - - - Espere un momento... - - - - - Sincronizando sus tareas... - - - Sincronizando... - - - Sincronización & copia de seguridad - - - Sincronizar ahora - - - Astrid.com, Google Tasks, información guardada, copia de seguridad local - - - ¡Error de conexión! Verifique su conexión a internet. - - - - - Estado - - - Estado: %s - - Sesión no iniciada - - Sincronización en marcha - - Ultima sincronización:\n%s - - Falló en: %s - - Sincronización c/ errores: %s - - Última sincronización correcta: %s - - ¡Nunca sincronizado! - - - Opciones - - - Sincronización en segundo plano - - Sincronización en segundo plano deshabilitada - - Actualmente configurado a: %s - - - Configuración solo wifi - - La sincronización en segundo plano sólo funciona con el Wifi activado - - La sincronización en segundo plano siempre funcionará - - - Acciones - - - Sincronizar ahora - - Iniciar sesión & sincronizar! - - - Sesión iniciada como: - - - Reporte de estado - - - Click para enviar un reporte al equipo de Astrid - - Enviar reporte - - - Cerrar sesión - - Limpia todos los datos de la sincronización - - - Cerrar sesión/Limpiar datos de sincronización? - - - Ha ocurrido un problema conectando a la red durante la última sincronización con %s. Por favor inténtelo nuevamente después. - - - - deshabilitar - cada quince minutos - cada treinta minutos - cada hora - cada tres horas - cada seis horas - cada doce horas - cada día - cada tres días - cada semana - - + + + + + + + 1 año + + %d años + + + + 1 mes + + %d meses + + + + 1 semana + + %d semanas + + + + Un día + + %d días + + + + 1 día laborable + + %d días laborables + + + + 1 hora + + %d horas + + + + 1 minuto + + %d minutos + + + + 1 segundo + + %d segundos + + + + 1 hr + + %d hrs + + + + 1 min + + %d min + + + + 1 seg + + %d seg + + + + 1 tarea + + %d tareas + + + + 1 persona + + %d personas + + + + Hoy + + + Mañana + + + Ayer + + + Mañana + + + Ayer + + + + + ¿Confirmar? + + + Pregunta: + + + Información + + + ¡Error! + + + Guardar + + + + + + No + + + Cerrar + + + Terminado + + + ¡Uy, parece que ocurró un error! Esto es lo que pasó:\n\n%s + + + ¡Uy, parece que ocurrió un error! + + + Espere un momento... + + + + + Sincronizando sus tareas... + + + Sincronizando... + + + Sincronización & copia de seguridad + + + Sincronizar ahora + + + Astrid.com, Google Tasks, información guardada, copia de seguridad + local + + + + ¡Error de conexión! Verifique su conexión a internet. + + + + + Estado + + + Estado: %s + + Sesión no iniciada + + Sincronización en marcha + + Ultima sincronización:\n%s + + Falló en: %s + + Sincronización c/ errores: %s + + Última sincronización correcta: %s + + ¡Nunca sincronizado! + + + Opciones + + + Sincronización en segundo plano + + Sincronización en segundo plano deshabilitada + + + Actualmente configurado a: %s + + + Configuración solo wifi + + La sincronización en segundo plano sólo funciona con + el Wifi activado + + + La sincronización en segundo plano siempre + funcionará + + + + Acciones + + + Sincronizar ahora + + Iniciar sesión & sincronizar! + + + Sesión iniciada como: + + + Reporte de estado + + + Click para enviar un reporte al equipo de Astrid + + + Enviar reporte + + + Cerrar sesión + + Limpia todos los datos de la sincronización + + + Cerrar sesión/Limpiar datos de sincronización? + + + Ha ocurrido un problema conectando a la red durante la última + sincronización con %s. Por favor inténtelo nuevamente después. + + + + + deshabilitar + cada quince minutos + cada treinta minutos + cada hora + cada tres horas + cada seis horas + cada doce horas + cada día + cada tres días + cada semana + + diff --git a/api/res/values-fr/strings.xml b/api/res/values-fr/strings.xml index 1a191e5e1..a7b1e5cb8 100755 --- a/api/res/values-fr/strings.xml +++ b/api/res/values-fr/strings.xml @@ -4,243 +4,255 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - - - - - - - 1 an - - %d ans - - - - 1 mois - - %d mois - - - - 1 semaine - - %d semaines - - - - 1 jour - - %d jours - - - - 1 jour de la semaine - - %d jours de la semaine - - - - 1 heure - - %d heures - - - - 1 minute - - %d minutes - - - - 1 seconde - - %d secondes - - - - 1 h - - %d h - - - - 1 min - - %d min - - - - 1 s - - %d s - - - - 1 tâche - - %d tâches - - - - 1 personne - - %d personnes - - - - Aujourd\'hui - - - Demain - - - Hier - - - Demain - - - Hier - - - - - Confirmer ? - - - Question : - - - Information - - - Erreur ! - - - Enregistrer - - - Oui - - - Non - - - Fermer - - - Fnalizado - - - Oups, une erreur est survenue ! Voici ce qu\'il s\'est passé :\n\n%s - - - Oups, une erreur est survenue ! - - - Veuillez patienter... - - - - - Synchronisation de vos tâches... - - - Synchronisation... - - - Synchronisation - - - Sync now - - - Astrid.com, Tâches Google, données enregistrées, sauvegarde locale - - - Erreur de connexion ! Veuillez vérifier votre connexion Internet. - - - - - Statut - - - État : %s - - Non connecté - - Synchronisation en cours... - - Dernière synchro. :\n%s - - Échec sur : %s - - Synchro avec Erreurs: %s - - Dernière synchro. réussie : %s - - Jamais synchronisé ! - - - Options - - - Synchro. en arrière-plan - - Synchronisation en arrière-plan désactivée - - Actuellement configuré sur : %s - - - Paramètre Wifi seul - - La synchronisation en arrière-plan ne s\'effectue uniquement sous Wifi - - La synchronisation en arrière-plan s\'effectuera toujours - - - Actions - - - Synchroniser maintenant - - Se connecter et synchroniser ! - - - Connecté en tant que : - - - Rapport d\'état - - - Cliquez pour envoyer un rapport à l\'équipe Astrid - - Envoyer le rapport - - - Se déconnecter - - Purger toutes les données de synchronisation - - - Se déconnecter/purger les données de synchronisation ? - - - Un problème de connexion réseau est survenu lors de la dernière synchronisation avec %s. Merci de réessayer plus tard. - - - - désactiver - toutes les quinze minutes - toutes les trente minutes - toutes les heures - toutes les trois heures - toutes les six heures - toutes les douze heures - tous les jours - tous les trois jours - toutes les semaines - - + + + + + + + 1 an + + %d ans + + + + 1 mois + + %d mois + + + + 1 semaine + + %d semaines + + + + 1 jour + + %d jours + + + + 1 jour de la semaine + + %d jours de la semaine + + + + 1 heure + + %d heures + + + + 1 minute + + %d minutes + + + + 1 seconde + + %d secondes + + + + 1 h + + %d h + + + + 1 min + + %d min + + + + 1 s + + %d s + + + + 1 tâche + + %d tâches + + + + 1 personne + + %d personnes + + + + Aujourd\'hui + + + Demain + + + Hier + + + Demain + + + Hier + + + + + Confirmer ? + + + Question : + + + Information + + + Erreur ! + + + Enregistrer + + + Oui + + + Non + + + Fermer + + + Fnalizado + + + Oups, une erreur est survenue ! Voici ce qu\'il s\'est passé :\n\n%s + + + + Oups, une erreur est survenue ! + + + Veuillez patienter... + + + + + Synchronisation de vos tâches... + + + Synchronisation... + + + Synchronisation + + + Sync now + + + Astrid.com, Tâches Google, données enregistrées, sauvegarde locale + + + + Erreur de connexion ! Veuillez vérifier votre connexion Internet. + + + + + + Statut + + + État : %s + + Non connecté + + Synchronisation en cours... + + Dernière synchro. :\n%s + + Échec sur : %s + + Synchro avec Erreurs: %s + + Dernière synchro. réussie : %s + + Jamais synchronisé ! + + + Options + + + Synchro. en arrière-plan + + Synchronisation en arrière-plan désactivée + + + Actuellement configuré sur : %s + + + Paramètre Wifi seul + + La synchronisation en arrière-plan ne s\'effectue + uniquement sous Wifi + + + La synchronisation en arrière-plan s\'effectuera + toujours + + + + Actions + + + Synchroniser maintenant + + Se connecter et synchroniser ! + + + Connecté en tant que : + + + Rapport d\'état + + + Cliquez pour envoyer un rapport à l\'équipe Astrid + + + Envoyer le rapport + + + Se déconnecter + + Purger toutes les données de synchronisation + + + Se déconnecter/purger les données de synchronisation ? + + + + Un problème de connexion réseau est survenu lors de la + dernière synchronisation avec %s. Merci de réessayer plus tard. + + + + + désactiver + toutes les quinze minutes + toutes les trente minutes + toutes les heures + toutes les trois heures + toutes les six heures + toutes les douze heures + tous les jours + tous les trois jours + toutes les semaines + + diff --git a/api/res/values-it/strings.xml b/api/res/values-it/strings.xml index eaed227c2..295caded3 100755 --- a/api/res/values-it/strings.xml +++ b/api/res/values-it/strings.xml @@ -4,243 +4,254 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - - - - - - - 1 Anno - - %d Anni - - - - 1 Mese - - %d mesi - - - - 1 Settimana - - %d settimane - - - - 1 Giorno - - %d Giorni - - - - 1 giorno della settimana - - %d giorni della settimana - - - - 1 ora - - %d ore - - - - 1 minuto - - %d minuti - - - - 1 secondo - - %d secondi - - - - 1 ora - - %d ore - - - - 1 min - - %d min - - - - 1 sec - - %d sec - - - - 1 attività - - %d attività - - - - 1 persona - - %d persone - - - - Oggi - - - Domani - - - Ieri - - - Domani - - - Ieri - - - - - Confermi? - - - Domanda: - - - Informazione - - - Errore! - - - Salva - - - - - - No - - - Chiudi - - - Completata - - - Oops, sembra che ci sia stato un errore! E\' successo questo:\n\n%s - - - Oops, sembra che ci sia stato un errore! - - - Attendi... - - - - - Sincronizzando le tue attività... - - - Sincronizzando... - - - Sincronizza & archivia - - - Sync now - - - Astrid.com, Attività Google, dati salvati, backup locale - - - Errore di Connessione! Controlla la tua connessione Internet. - - - - - Stato - - - Stato: %s - - Non connesso - - Sincronizzazione in corso... - - Ultima Sincronizzazione:\n%s - - Fallita Su: %s - - Sincronizza con gli errori: %s - - Ultima sincronizzazione eseguita con successo in data: %s - - Mai sincronizzato! - - - Preferenze - - - Sincronizzazione eseguita in background - - La sincronizzazione in background è disattivata - - Attualmente impostata su: %s - - - Unica Impostazione Wifi - - La sincronizzazione in background avviene solo con rete Wifi attiva - - La sincronizzazione in background avviene sempre - - - Azioni - - - Sincronizza ora - - Esegui l\'accesso & Sincronizza! - - - Accesso come: - - - Status report - - - "Clicca per inviare un rapporto al team Astrid" - - Invia rapporto - - - Esci - - Cancella tutti i dati di sincronizzazione - - - Esci / cancella i file di sincronizzazione? - - - Problema di connessione alla rete durante l\'ultima sincronizzazione con %s. Riprova dopo. - - - - disabilita - ogni quindici minuti - ogni trenta minuti - ogni ora - ogni tre ore - ogni sei ore - ogni dodici ore - ogni giorno - ogni tre giorni - Ogni settimana - - + + + + + + + 1 Anno + + %d Anni + + + + 1 Mese + + %d mesi + + + + 1 Settimana + + %d settimane + + + + 1 Giorno + + %d Giorni + + + + 1 giorno della settimana + + %d giorni della settimana + + + + 1 ora + + %d ore + + + + 1 minuto + + %d minuti + + + + 1 secondo + + %d secondi + + + + 1 ora + + %d ore + + + + 1 min + + %d min + + + + 1 sec + + %d sec + + + + 1 attività + + %d attività + + + + 1 persona + + %d persone + + + + Oggi + + + Domani + + + Ieri + + + Domani + + + Ieri + + + + + Confermi? + + + Domanda: + + + Informazione + + + Errore! + + + Salva + + + + + + No + + + Chiudi + + + Completata + + + Oops, sembra che ci sia stato un errore! E\' successo questo:\n\n%s + + + + Oops, sembra che ci sia stato un errore! + + + Attendi... + + + + + Sincronizzando le tue attività... + + + Sincronizzando... + + + Sincronizza & archivia + + + Sync now + + + Astrid.com, Attività Google, dati salvati, backup locale + + + Errore di Connessione! Controlla la tua connessione Internet. + + + + + + Stato + + + Stato: %s + + Non connesso + + Sincronizzazione in corso... + + Ultima Sincronizzazione:\n%s + + Fallita Su: %s + + Sincronizza con gli errori: %s + + Ultima sincronizzazione eseguita con successo in + data: %s + + + Mai sincronizzato! + + + Preferenze + + + Sincronizzazione eseguita in background + + La sincronizzazione in background è disattivata + + + Attualmente impostata su: %s + + + Unica Impostazione Wifi + + La sincronizzazione in background avviene solo con + rete Wifi attiva + + + La sincronizzazione in background avviene sempre + + + + Azioni + + + Sincronizza ora + + Esegui l\'accesso & Sincronizza! + + + Accesso come: + + + Status report + + + "Clicca per inviare un rapporto al team Astrid" + + + Invia rapporto + + + Esci + + Cancella tutti i dati di sincronizzazione + + + Esci / cancella i file di sincronizzazione? + + + Problema di connessione alla rete durante l\'ultima + sincronizzazione con %s. Riprova dopo. + + + + + disabilita + ogni quindici minuti + ogni trenta minuti + ogni ora + ogni tre ore + ogni sei ore + ogni dodici ore + ogni giorno + ogni tre giorni + Ogni settimana + + diff --git a/api/res/values-iw/strings.xml b/api/res/values-iw/strings.xml index 8cc08ef1c..f5d80f358 100755 --- a/api/res/values-iw/strings.xml +++ b/api/res/values-iw/strings.xml @@ -4,243 +4,245 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - - - - - - - שנה - - %d שנים - - - - חודש - - %d חודשים - - - - שבוע אחד - - %d שבועות - - - - יום אחד - - %d ימים - - - - יום עבודה אחד - - %d ימי עבודה - - - - שעה אחת - - %d שעות - - - - דקה אחת - - %d דקות - - - - שנייה אחת - - %d שניות - - - - שעה - - %d שע\' - - - - דקה - - %d דק׳ - - - - שנייה - - %d שנ\' - - - - משימה אחת - - %d משימות - - - - שותף אחד - - %d שותפים - - - - היום - - - מחר - - - אתמול - - - מחר - - - אתמול - - - - - האם לאשר? - - - שאלה: - - - פרטים - - - שגיאה! - - - שמור - - - כן - - - לא - - - סגור - - - בוצע - - - אוּפְּס, נראה שארעה שגיאה! הנה מה שקה:\n\n%s - - - אוּפְּס, נראה שארעה שגיאה! - - - אנא המתן... - - - - - מסנכרן את המשימות שלך... - - - מסנכרנת... - - - סינכרון וגיבוי - - - סנכרני כעת - - - אתר אסטריד, ״משימות גוגל״, מידע שמור, גיבוי מקומי - - - שגיאה בחיבור! בדוק את חיבור הַמִּרְשֶׁתֶת שלך - - - - - מצב - - - מצב: %s - - לא מחובר - - הסינכרון מתבצע - - סנכרון אחרון:\n%s - - נכשל ב: %s - - סנכרון עם שגיאות: %s - - סנכרון מוצלח אחרון: %s - - לעולם לא סונכרן! - - - אפשרויות - - - סנכרון ברקע - - סנכרון ברקע אינו מופעל - - כרגע מוגדר ל: %s - - - הגדרת WiFi בלבד - - סנכרון רקע מתרחש רק כאשר על WiFi - - סנכרון רקע יתבצע תמיד - - - פעולות - - - מסנכרן כעת - - התחבר וסנכרן! - - - מחובר לחשבון בתור: - - - דו"ח מצב - - - הקלק כדי לשלוח דוח לצוות של אסטריד - - שלח דו"ח - - - התנתק - - מסיר את כל נתוני הסנכרון - - - צא מהחשבון \\ הסר נתוני סנכרון? - - - נתקלתי בבעית חיבור לרשת בזמן הסינכרון האחרון עם %s. אנא נסה מאוחר יותר. - - - - מִנְעִי - כל רבע שעה - כל חצי שעה - כל שעה - כל שלוש שעות - כל שש שעות - כל שתים עשרה שעות - כל יום - כל שלושה ימים - כל שבוע - - + + + + + + + שנה + + %d שנים + + + + חודש + + %d חודשים + + + + שבוע אחד + + %d שבועות + + + + יום אחד + + %d ימים + + + + יום עבודה אחד + + %d ימי עבודה + + + + שעה אחת + + %d שעות + + + + דקה אחת + + %d דקות + + + + שנייה אחת + + %d שניות + + + + שעה + + %d שע\' + + + + דקה + + %d דק׳ + + + + שנייה + + %d שנ\' + + + + משימה אחת + + %d משימות + + + + שותף אחד + + %d שותפים + + + + היום + + + מחר + + + אתמול + + + מחר + + + אתמול + + + + + האם לאשר? + + + שאלה: + + + פרטים + + + שגיאה! + + + שמור + + + כן + + + לא + + + סגור + + + בוצע + + + אוּפְּס, נראה שארעה שגיאה! הנה מה שקה:\n\n%s + + + אוּפְּס, נראה שארעה שגיאה! + + + אנא המתן... + + + + + מסנכרן את המשימות שלך... + + + מסנכרנת... + + + סינכרון וגיבוי + + + סנכרני כעת + + + אתר אסטריד, ״משימות גוגל״, מידע שמור, גיבוי מקומי + + + שגיאה בחיבור! בדוק את חיבור הַמִּרְשֶׁתֶת שלך + + + + + מצב + + + מצב: %s + + לא מחובר + + הסינכרון מתבצע + + סנכרון אחרון:\n%s + + נכשל ב: %s + + סנכרון עם שגיאות: %s + + סנכרון מוצלח אחרון: %s + + לעולם לא סונכרן! + + + אפשרויות + + + סנכרון ברקע + + סנכרון ברקע אינו מופעל + + כרגע מוגדר ל: %s + + + הגדרת WiFi בלבד + + סנכרון רקע מתרחש רק כאשר על WiFi + + סנכרון רקע יתבצע תמיד + + + פעולות + + + מסנכרן כעת + + התחבר וסנכרן! + + + מחובר לחשבון בתור: + + + דו"ח מצב + + + הקלק כדי לשלוח דוח לצוות של אסטריד + + שלח דו"ח + + + התנתק + + מסיר את כל נתוני הסנכרון + + + צא מהחשבון \\ הסר נתוני סנכרון? + + + נתקלתי בבעית חיבור לרשת בזמן הסינכרון האחרון עם %s. אנא נסה + מאוחר יותר. + + + + + מִנְעִי + כל רבע שעה + כל חצי שעה + כל שעה + כל שלוש שעות + כל שש שעות + כל שתים עשרה שעות + כל יום + כל שלושה ימים + כל שבוע + + diff --git a/api/res/values-ja/strings.xml b/api/res/values-ja/strings.xml index 5c76a6b6c..77bf8f013 100755 --- a/api/res/values-ja/strings.xml +++ b/api/res/values-ja/strings.xml @@ -4,244 +4,247 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - - - - - - - 1年 - - %d 年 - - - - 1か月 - - %d か月 - - - - 1週間 - - %d 週間 - - - - 1 日 - - %d 日 - - - - 1 Weekday - - %d Weekdays - - - - 1 時間 - - %d 時間 - - - - 1 分 - - %d 分 - - - - 1 秒 - - %d 秒 - - - - 1 時間 - - %d 時間 - - - - 1 分 - - %d 分 - - - - 1 秒 - - %d 秒 - - - - タスク 1 件 - - タスク %d 件 - - - - 1人 - - %d人 - - - - Today - - - Tomorrow - - - 昨日 - - - 明日 - - - 昨日 - - - - - 確認 - - - 確認 - - - インフォメーション - - - エラー - - - 保存 - - - はい - - - いいえ - - - 閉じる - - - 完了 - - - Oops, looks like an error occurred! Here\'s what happened:\n\n%s - - - Oops, looks like an error occurred! - - - お待ちください - - - - - タスクの同期中... - - - 同期中... - - - 同期 - - - Sync now - - - Astrid.com, Google Tasks, saved data, local backup - - - 接続エラー!インターネットに接続できるか確認してください。 - - - - - 状況 - - - Status: %s - - Not logged in - - 同期中 - - 前回の同期:\n%s - - 失敗: %s - - Sync w/ errors: %s - - 最後の同期: %s - - 同期していません - - - オプション - - - バックグラウンド同期 - - バックグラウンド同期は無効になっています - - 現在の設定: %s - - - Wi-Fi のみ - - Wi-Fi が有効なときだけバックグラウンドで同期する - - Background synchronization will always occur - - - アクション - - - Synchronize now - - ログインと同期 - - - ログインアカウント: - - - Status report - - - Click to send a report to the Astrid team - - Send report - - - ログアウト - - すべての同期データを消去します - - - ログアウトと同期データを消去しますか? - - - There was a problem connecting to the network - during the last sync with %s. Please try again later. - - - - 無効 - 15分毎 - 30分毎 - 1時間毎 - 3時間毎 - 6時間毎 - 12時間毎 - 毎日 - 3日に一度 - 毎週 - - + + + + + + + 1年 + + %d 年 + + + + 1か月 + + %d か月 + + + + 1週間 + + %d 週間 + + + + 1 日 + + %d 日 + + + + 1 Weekday + + %d Weekdays + + + + 1 時間 + + %d 時間 + + + + 1 分 + + %d 分 + + + + 1 秒 + + %d 秒 + + + + 1 時間 + + %d 時間 + + + + 1 分 + + %d 分 + + + + 1 秒 + + %d 秒 + + + + タスク 1 件 + + タスク %d 件 + + + + 1人 + + %d人 + + + + Today + + + Tomorrow + + + 昨日 + + + 明日 + + + 昨日 + + + + + 確認 + + + 確認 + + + インフォメーション + + + エラー + + + 保存 + + + はい + + + いいえ + + + 閉じる + + + 完了 + + + Oops, looks like an error occurred! Here\'s what happened:\n\n%s + + + + Oops, looks like an error occurred! + + + お待ちください + + + + + タスクの同期中... + + + 同期中... + + + 同期 + + + Sync now + + + Astrid.com, Google Tasks, saved data, local backup + + + 接続エラー!インターネットに接続できるか確認してください。 + + + + + 状況 + + + Status: %s + + Not logged in + + 同期中 + + 前回の同期:\n%s + + 失敗: %s + + Sync w/ errors: %s + + 最後の同期: %s + + 同期していません + + + オプション + + + バックグラウンド同期 + + バックグラウンド同期は無効になっています + + 現在の設定: %s + + + Wi-Fi のみ + + Wi-Fi が有効なときだけバックグラウンドで同期する + + Background synchronization will always occur + + + + アクション + + + Synchronize now + + ログインと同期 + + + ログインアカウント: + + + Status report + + + Click to send a report to the Astrid team + + Send report + + + ログアウト + + すべての同期データを消去します + + + ログアウトと同期データを消去しますか? + + + There was a problem connecting to the network + during the last sync with %s. Please try again later. + + + + + 無効 + 15分毎 + 30分毎 + 1時間毎 + 3時間毎 + 6時間毎 + 12時間毎 + 毎日 + 3日に一度 + 毎週 + + diff --git a/api/res/values-ko/strings.xml b/api/res/values-ko/strings.xml index f1164f5ad..873e5888a 100755 --- a/api/res/values-ko/strings.xml +++ b/api/res/values-ko/strings.xml @@ -4,243 +4,243 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - - - - - - - 1년 - - %d년 - - - - 1개월 - - %d개월 - - - - 1주 - - %d주 - - - - 1일 - - %d일 - - - - 주중 1일 - - 주중 %d일 - - - - 1시간 - - %d시간 - - - - 1분 - - %d분 - - - - 1초 - - %d초 - - - - 1시간 - - %d시간 - - - - 1분 - - %d분 - - - - 1초 - - %d초 - - - - 1 일정 - - %d 일정 - - - - 1 사람 - - %d 사람 - - - - 오늘 - - - 내일 - - - 어제 - - - 내일 - - - 어제 - - - - - 확인? - - - 질문: - - - 정보 - - - 에러! - - - 저장 - - - - - - 아니요 - - - 닫기 - - - 마침 - - - 에러가 발생한 것 같습니다! 발생한 에러는 다음과 같습니다:\n\n%s - - - 에러가 발생한 것 같습니다! - - - 잠시 기다리세요... - - - - - 일정을 동기화 중입니다... - - - 동기화하는 중... - - - 동기화 & 백업 - - - 지금 동기화하기 - - - Astrid.com, 구글 일정, 저장한 자료, 로컬 백업 - - - 연결 오류! 인터넷 연결을 확인하세요. - - - - - 상태 - - - 상태: %s - - 로그인 안 됨 - - 동기화 진행 중... - - 마지막 동기화: \n%s - - 실패: %s - - 동기화 중 에러: %s - - 마지막 동기화 성공시간: %s - - 동기화 한 적이 없습니다! - - - 설정 - - - 백그라운드 동기화 - - 백그라운드 동기화를 사용하지 않습니다. - - 현재 설정: %s - - - WiFi 설정 - - 백그라운드 동기화는 WiFi 지역에서만 작동합니다. - - 백그라운드 동기화는 항상 작동합니다. - - - 동작 - - - 지금 동기화하기 - - 로그인 & 동기화! - - - 로그인하기: - - - 상태 보고 - - - 아스트리드 팀에게 보고서를 보내려면 클릭하세요 - - 보고서 보내기 - - - 로그아웃 - - 모든 동기화 자료 삭제 - - - 로그아웃 / 모든 동기화 데이터 삭제? - - - %s 과 마지막 동기화 중에 네트워크 연결 문제가 있었습니다.나중에 다시 시도해 주세요. - - - - 사용안함 - 15분마다 - 30분마다 - 매시간 - 3시간마다 - 6시간마다 - 12시간마다 - 매일 - 3일마다 - 일주일마다 - - + + + + + + + 1년 + + %d년 + + + + 1개월 + + %d개월 + + + + 1주 + + %d주 + + + + 1일 + + %d일 + + + + 주중 1일 + + 주중 %d일 + + + + 1시간 + + %d시간 + + + + 1분 + + %d분 + + + + 1초 + + %d초 + + + + 1시간 + + %d시간 + + + + 1분 + + %d분 + + + + 1초 + + %d초 + + + + 1 일정 + + %d 일정 + + + + 1 사람 + + %d 사람 + + + + 오늘 + + + 내일 + + + 어제 + + + 내일 + + + 어제 + + + + + 확인? + + + 질문: + + + 정보 + + + 에러! + + + 저장 + + + + + + 아니요 + + + 닫기 + + + 마침 + + + 에러가 발생한 것 같습니다! 발생한 에러는 다음과 같습니다:\n\n%s + + + 에러가 발생한 것 같습니다! + + + 잠시 기다리세요... + + + + + 일정을 동기화 중입니다... + + + 동기화하는 중... + + + 동기화 & 백업 + + + 지금 동기화하기 + + + Astrid.com, 구글 일정, 저장한 자료, 로컬 백업 + + + 연결 오류! 인터넷 연결을 확인하세요. + + + + + 상태 + + + 상태: %s + + 로그인 안 됨 + + 동기화 진행 중... + + 마지막 동기화: \n%s + + 실패: %s + + 동기화 중 에러: %s + + 마지막 동기화 성공시간: %s + + 동기화 한 적이 없습니다! + + + 설정 + + + 백그라운드 동기화 + + 백그라운드 동기화를 사용하지 않습니다. + + 현재 설정: %s + + + WiFi 설정 + + 백그라운드 동기화는 WiFi 지역에서만 작동합니다. + + 백그라운드 동기화는 항상 작동합니다. + + + 동작 + + + 지금 동기화하기 + + 로그인 & 동기화! + + + 로그인하기: + + + 상태 보고 + + + 아스트리드 팀에게 보고서를 보내려면 클릭하세요 + + 보고서 보내기 + + + 로그아웃 + + 모든 동기화 자료 삭제 + + + 로그아웃 / 모든 동기화 데이터 삭제? + + + %s 과 마지막 동기화 중에 네트워크 연결 문제가 있었습니다.나중에 다시 시도해 주세요. + + + + 사용안함 + 15분마다 + 30분마다 + 매시간 + 3시간마다 + 6시간마다 + 12시간마다 + 매일 + 3일마다 + 일주일마다 + + diff --git a/api/res/values-nb/strings.xml b/api/res/values-nb/strings.xml index 57bb8a460..983f6b81a 100644 --- a/api/res/values-nb/strings.xml +++ b/api/res/values-nb/strings.xml @@ -1,102 +1,104 @@ - - 1 år - %d år - - - 1 måned - %d måneder - - - 1 uke - %d uker - - - 1 dag - %d dager - - - 1 ukesdag - %d Weekdays - - - 1 time - %d timer - - - 1 minutt - %d minutter - - - 1 sekund - %d sekunder - - - 1 t - %d t - - - 1 min - %d min - - - 1 s - %d s - - - 1 oppgave - %d oppgaver - - - 1 person - %d people - - I dag - I morgen - I går - Bekreft? - Spørsmål: - Informasjon - Feil! - Lagre - Ja - Nei - Lukk - Utført - Oi, det oppstod en feil! Dette skjedde:\n\n%s - Oi, det oppstod en feil! - Vennligst vent... - Synkroniserer oppgavene dine... - Synkroniserer... - Tilkoblingsfeil! Kontroller tilkoblingen til Internett - Synkronisering pågår... - Siste synkronisering:\n%s - Mislykket: %s - Siste vellykkede synkronisering: %s - Aldri synkronisert! - Alternativer - Bakgrunnssynkronisering - Bakgrunnssynkronisering er deaktivert - Aktuell innstilling: %s - Bare Wifi Innstilling - Bakgrunnssynkronisering skjer kun med Wifi-tilkobling - Bakgrunnssynkronisering skjer alltid - Handlinger - Logg inn & Synkroniser! - Logg ut - Sletter all synkroniseringsdata - Logg ut / slett synkroniseringsdata? - - deaktiver - hvert kvarter - hver halvtime - hver time - hver tredje time - hver sjette time - hver tolvte time - daglig - hver tredje dag - hver uke - + + 1 år + %d år + + + 1 måned + %d måneder + + + 1 uke + %d uker + + + 1 dag + %d dager + + + 1 ukesdag + %d Weekdays + + + 1 time + %d timer + + + 1 minutt + %d minutter + + + 1 sekund + %d sekunder + + + 1 t + %d t + + + 1 min + %d min + + + 1 s + %d s + + + 1 oppgave + %d oppgaver + + + 1 person + %d people + + I dag + I morgen + I går + Bekreft? + Spørsmål: + Informasjon + Feil! + Lagre + Ja + Nei + Lukk + Utført + Oi, det oppstod en feil! Dette skjedde:\n\n%s + Oi, det oppstod en feil! + Vennligst vent... + Synkroniserer oppgavene dine... + Synkroniserer... + Tilkoblingsfeil! Kontroller tilkoblingen til Internett + Synkronisering pågår... + Siste synkronisering:\n%s + Mislykket: %s + Siste vellykkede synkronisering: %s + Aldri synkronisert! + Alternativer + Bakgrunnssynkronisering + Bakgrunnssynkronisering er deaktivert + Aktuell innstilling: %s + Bare Wifi Innstilling + Bakgrunnssynkronisering skjer kun med + Wifi-tilkobling + + Bakgrunnssynkronisering skjer alltid + Handlinger + Logg inn & Synkroniser! + Logg ut + Sletter all synkroniseringsdata + Logg ut / slett synkroniseringsdata? + + deaktiver + hvert kvarter + hver halvtime + hver time + hver tredje time + hver sjette time + hver tolvte time + daglig + hver tredje dag + hver uke + diff --git a/api/res/values-nl/strings.xml b/api/res/values-nl/strings.xml index 50f5c74f8..144096d17 100755 --- a/api/res/values-nl/strings.xml +++ b/api/res/values-nl/strings.xml @@ -4,243 +4,248 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - - - - - - - 1 jaar - - %d jaren - - - - 1 maand - - %d maanden - - - - 1 week - - %d weken - - - - 1 dag - - %d dagen - - - - 1 weekdag - - %d weekdagen - - - - 1 uur - - %d uren - - - - 1 minuut - - %d minuten - - - - 1 seconde - - %d seconden - - - - 1 u. - - %d u. - - - - 1 m. - - %d m. - - - - 1 s. - - %d s. - - - - 1 taak - - %d taken - - - - 1 persoon - - %d personen - - - - Vandaag - - - Morgen - - - Gisteren - - - mrgn - - - gisteren - - - - - OK? - - - Vraag: - - - Informatie - - - Fout! - - - Opslaan - - - Ja - - - Nee - - - Sluit - - - Gedaan - - - Er is een fout opgetreden:\n\n%s - - - Er is een fout opgetreden! - - - Even geduld a.u.b. - - - - - Taken synchroniseren... - - - Synchroniseren… - - - Synchronisatie - - - Nu synchroniseren - - - Astrid.com, Google Taken, opgeslagen data, lokale back-up - - - Verbindingsfout! Controleer de internetverbinding - - - - - Status - - - Status: %s - - Niet aangemeld - - Synchronisatie bezig... - - Vorige:\n%s - - Mislukt op: %s - - Gesync. met fouten: %s - - Gelukt op: %s - - Nooit gesynct! - - - Opties - - - Achtergrond synchronisatie - - Achtergrond synchronisatie uitgeschakeld - - Huidige instelling: %s - - - Alleen via WiFi - - Achtergrond synchronisatie alleen met WiFi aan - - Achtergrond synchronisatie altijd aan - - - Acties - - - Nu synchroniseren - - Aanmelden & Sync. - - - Aangemeld als: - - - Statusrapport - - - Klik om een rapport naar het Astrid team te versturen - - Rapport verzenden - - - Afmelden - - Alle synchronisatie gegevens verwijderen - - - Afmelden / synchronisatie gegevens verwijderen? - - - Er was een probleem met de netwerkverbinding tijdens de laatste synchronisatie met %s. Probeer het a.u.b. later nog eens. - - - - uitschakelen - elke 15 min. - elke 30 min. - elk uur - elke 3 uur - elke 6 uur - elke 12 uur - elke dag - elke 3 dagen - elke week - - + + + + + + + 1 jaar + + %d jaren + + + + 1 maand + + %d maanden + + + + 1 week + + %d weken + + + + 1 dag + + %d dagen + + + + 1 weekdag + + %d weekdagen + + + + 1 uur + + %d uren + + + + 1 minuut + + %d minuten + + + + 1 seconde + + %d seconden + + + + 1 u. + + %d u. + + + + 1 m. + + %d m. + + + + 1 s. + + %d s. + + + + 1 taak + + %d taken + + + + 1 persoon + + %d personen + + + + Vandaag + + + Morgen + + + Gisteren + + + mrgn + + + gisteren + + + + + OK? + + + Vraag: + + + Informatie + + + Fout! + + + Opslaan + + + Ja + + + Nee + + + Sluit + + + Gedaan + + + Er is een fout opgetreden:\n\n%s + + + Er is een fout opgetreden! + + + Even geduld a.u.b. + + + + + Taken synchroniseren... + + + Synchroniseren… + + + Synchronisatie + + + Nu synchroniseren + + + Astrid.com, Google Taken, opgeslagen data, lokale back-up + + + Verbindingsfout! Controleer de internetverbinding + + + + + Status + + + Status: %s + + Niet aangemeld + + Synchronisatie bezig... + + Vorige:\n%s + + Mislukt op: %s + + Gesync. met fouten: %s + + Gelukt op: %s + + Nooit gesynct! + + + Opties + + + Achtergrond synchronisatie + + Achtergrond synchronisatie uitgeschakeld + + Huidige instelling: %s + + + Alleen via WiFi + + Achtergrond synchronisatie alleen met WiFi aan + + + Achtergrond synchronisatie altijd aan + + + Acties + + + Nu synchroniseren + + Aanmelden & Sync. + + + Aangemeld als: + + + Statusrapport + + + Klik om een rapport naar het Astrid team te + versturen + + + Rapport verzenden + + + Afmelden + + Alle synchronisatie gegevens verwijderen + + + Afmelden / synchronisatie gegevens verwijderen? + + + Er was een probleem met de netwerkverbinding tijdens de + laatste synchronisatie met %s. Probeer het a.u.b. later nog eens. + + + + + uitschakelen + elke 15 min. + elke 30 min. + elk uur + elke 3 uur + elke 6 uur + elke 12 uur + elke dag + elke 3 dagen + elke week + + diff --git a/api/res/values-pl/strings.xml b/api/res/values-pl/strings.xml index 93e29ee4d..5fce6eaba 100755 --- a/api/res/values-pl/strings.xml +++ b/api/res/values-pl/strings.xml @@ -4,243 +4,250 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - - - - - - - 1 rok - - %d lat - - - - 1 miesiąc - - %d miesięcy - - - - 1 tydzień - - %d tygodni - - - - 1 dzień - - %d dni - - - - 1 dzień roboczy - - %d dni roboczych - - - - 1 godzina - - %d godzin - - - - 1 minuta - - %d minut - - - - 1 sekunda - - %d sekund - - - - 1 godz. - - %d godz. - - - - 1 min. - - %d min. - - - - 1 sek. - - %d sek. - - - - 1 zadanie - - %d zadań - - - - 1 osoba - - %d osób - - - - Dzisiaj - - - Jutro - - - Wczoraj - - - jtr - - - wcz - - - - - Potwierdzić? - - - Pytanie: - - - Informacja - - - Błąd! - - - Zapisz - - - Tak - - - Nie - - - Zamknij - - - Ukończone - - - Ups! Wygląda na to, że wystąpił jakiś błąd! Oto, co się stało:\n\n%s - - - Ups! Wygląda na to, że wystąpił jakiś błąd! - - - Proszę czekać... - - - - - Synchronizowanie Twoich zadań... - - - Synchronizacja... - - - Synchronizacja - - - Zsynchronizuj - - - Astrid.com, Zadania Google, zapisane dane, lokalna kopia zapasowa - - - Błąd połączenia! Sprawdź swoje połączenie z Internetem! - - - - - Stan - - - Status: %s - - Niezalogowany - - Synchronizacja trwa... - - Ostatnia synchronizacja:\n%s - - Nieudana: %s - - Synch w/ Błędy: %s - - Ostatnia udana synchronizacja: %s - - Nigdy nie synchronizowano! - - - Opcje - - - Synchronizacja w tle - - Synchronizacja w tle wyłączona - - Aktualnie ustawione na: %s - - - Tylko połączenie Wi-Fi - - Synchronizacja w tle przebiega tylko poprzez Wi-Fi - - Synchronizowanie w tle zawsze, niezależnie od rodzaju połączenia - - - Działania - - - Synchronizuj teraz - - Zaloguj & Synchronizuj! - - - Zalogowany jako: - - - Raport statusu - - - Kliknij by wysłać raport do zespłu Astrid - - Wyślij raport - - - Wyloguj - - Czyści wszystkie dane synchronizacji - - - Wyloguj / wyczyść dane synchronizacji? - - - Wystąpił problem łączenia się z siecią w trakcie ostatniej synchronizacji z %s. Spróbuj później. - - - - Wyłączone - co 15 minut - co 30 minut - co godzinę - co 3 godziny - co 6 godzin - co 12 godzin - raz dziennie - co 3 dni - co tydzień - - + + + + + + + 1 rok + + %d lat + + + + 1 miesiąc + + %d miesięcy + + + + 1 tydzień + + %d tygodni + + + + 1 dzień + + %d dni + + + + 1 dzień roboczy + + %d dni roboczych + + + + 1 godzina + + %d godzin + + + + 1 minuta + + %d minut + + + + 1 sekunda + + %d sekund + + + + 1 godz. + + %d godz. + + + + 1 min. + + %d min. + + + + 1 sek. + + %d sek. + + + + 1 zadanie + + %d zadań + + + + 1 osoba + + %d osób + + + + Dzisiaj + + + Jutro + + + Wczoraj + + + jtr + + + wcz + + + + + Potwierdzić? + + + Pytanie: + + + Informacja + + + Błąd! + + + Zapisz + + + Tak + + + Nie + + + Zamknij + + + Ukończone + + + Ups! Wygląda na to, że wystąpił jakiś błąd! Oto, co się stało:\n\n%s + + + + Ups! Wygląda na to, że wystąpił jakiś błąd! + + + Proszę czekać... + + + + + Synchronizowanie Twoich zadań... + + + Synchronizacja... + + + Synchronizacja + + + Zsynchronizuj + + + Astrid.com, Zadania Google, zapisane dane, lokalna kopia zapasowa + + + + Błąd połączenia! Sprawdź swoje połączenie z Internetem! + + + + + Stan + + + Status: %s + + Niezalogowany + + Synchronizacja trwa... + + Ostatnia synchronizacja:\n%s + + Nieudana: %s + + Synch w/ Błędy: %s + + Ostatnia udana synchronizacja: %s + + Nigdy nie synchronizowano! + + + Opcje + + + Synchronizacja w tle + + Synchronizacja w tle wyłączona + + Aktualnie ustawione na: %s + + + Tylko połączenie Wi-Fi + + Synchronizacja w tle przebiega tylko poprzez Wi-Fi + + + Synchronizowanie w tle zawsze, niezależnie od + rodzaju połączenia + + + + Działania + + + Synchronizuj teraz + + Zaloguj & Synchronizuj! + + + Zalogowany jako: + + + Raport statusu + + + Kliknij by wysłać raport do zespłu Astrid + + Wyślij raport + + + Wyloguj + + Czyści wszystkie dane synchronizacji + + + Wyloguj / wyczyść dane synchronizacji? + + + Wystąpił problem łączenia się z siecią w trakcie ostatniej + synchronizacji z %s. Spróbuj później. + + + + + Wyłączone + co 15 minut + co 30 minut + co godzinę + co 3 godziny + co 6 godzin + co 12 godzin + raz dziennie + co 3 dni + co tydzień + + diff --git a/api/res/values-pt-rBR/strings.xml b/api/res/values-pt-rBR/strings.xml index 93d77a5f4..147ac9bf1 100755 --- a/api/res/values-pt-rBR/strings.xml +++ b/api/res/values-pt-rBR/strings.xml @@ -4,243 +4,253 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - - - - - - - 1 ano - - %d anos - - - - 1 mês - - %d meses - - - - 1 semana - - %d semanas - - - - 1 dia - - %d dias - - - - 1 dia útil - - %d dias úteis - - - - 1 hora - - %d horas - - - - 1 minuto - - %d minutos - - - - 1 segundo - - %d segundos - - - - 1 h - - %d h - - - - 1 min - - %d min - - - - 1 s - - %d s - - - - 1 tarefa - - %d tarefas - - - - 1 pessoa - - %d pessoas - - - - Hoje - - - Amanhã - - - Ontem - - - amanhã - - - ontem - - - - - Confirmar? - - - Pergunta: - - - Informações - - - Erro! - - - Salvar - - - Sim - - - Não - - - Fechar - - - Feito - - - Opa, parece que ocorreu um erro! Aqui está o que aconteceu:\n\n%s - - - Opa, parece que ocorreu um erro! - - - Por favor, aguarde... - - - - - Sincronizando suas tarefas... - - - Sincronizando... - - - Sincronização - - - Sync now - - - Astrid.com, Google Tasks, dados salvos, backup local - - - Erro na Conexão! Verifique sua conexão com a internet. - - - - - Estado - - - Status: %s - - Não Registrado - - Sincronizando... - - Última sincronização:\n%s - - Falhou em: %s - - Sicronizou com erros: %s - - Última sincronização com sucesso: %s - - Nunca sincronizado! - - - Opções - - - Sincronização em segundo plano - - O serviço de sincronização em segundo plano está desativado - - Atualmente definido para: %s - - - Configuração Somente Wifi - - Sincronização em segundo plano só ocorre se conectado ao Wifi - - Sincronização em segundo plano sempre ocorre - - - Ações - - - Sincronizar agora - - Conectar e sincronizar! - - - Conectado como: - - - Relatório de status - - - Clique para enviar um relatório para a equipe do Astrid - - Enviar relatório - - - Desconectar - - Limpar todos os dados de sincronização - - - Desconectar / limpar dados de sincronização? - - - Houve um problema na conexão durante a última sincronia com %s. Por favor tente novamente mais tarde. - - - - desabilitar - a cada quinze minutos - a cada trinta minutos - a cada hora - a cada três horas - a cada seis horas - a cada doze horas - diariamente - a cada três dias - semanalmente - - + + + + + + + 1 ano + + %d anos + + + + 1 mês + + %d meses + + + + 1 semana + + %d semanas + + + + 1 dia + + %d dias + + + + 1 dia útil + + %d dias úteis + + + + 1 hora + + %d horas + + + + 1 minuto + + %d minutos + + + + 1 segundo + + %d segundos + + + + 1 h + + %d h + + + + 1 min + + %d min + + + + 1 s + + %d s + + + + 1 tarefa + + %d tarefas + + + + 1 pessoa + + %d pessoas + + + + Hoje + + + Amanhã + + + Ontem + + + amanhã + + + ontem + + + + + Confirmar? + + + Pergunta: + + + Informações + + + Erro! + + + Salvar + + + Sim + + + Não + + + Fechar + + + Feito + + + Opa, parece que ocorreu um erro! Aqui está o que aconteceu:\n\n%s + + + + Opa, parece que ocorreu um erro! + + + Por favor, aguarde... + + + + + Sincronizando suas tarefas... + + + Sincronizando... + + + Sincronização + + + Sync now + + + Astrid.com, Google Tasks, dados salvos, backup local + + + Erro na Conexão! Verifique sua conexão com a internet. + + + + + Estado + + + Status: %s + + Não Registrado + + Sincronizando... + + Última sincronização:\n%s + + Falhou em: %s + + Sicronizou com erros: %s + + Última sincronização com sucesso: %s + + Nunca sincronizado! + + + Opções + + + Sincronização em segundo plano + + O serviço de sincronização em segundo plano está + desativado + + + Atualmente definido para: %s + + + Configuração Somente Wifi + + Sincronização em segundo plano só ocorre se + conectado ao Wifi + + + Sincronização em segundo plano sempre ocorre + + + + Ações + + + Sincronizar agora + + Conectar e sincronizar! + + + Conectado como: + + + Relatório de status + + + Clique para enviar um relatório para a equipe do + Astrid + + + Enviar relatório + + + Desconectar + + Limpar todos os dados de sincronização + + + Desconectar / limpar dados de sincronização? + + + Houve um problema na conexão durante a última sincronia com + %s. Por favor tente novamente mais tarde. + + + + + desabilitar + a cada quinze minutos + a cada trinta minutos + a cada hora + a cada três horas + a cada seis horas + a cada doze horas + diariamente + a cada três dias + semanalmente + + diff --git a/api/res/values-pt/strings.xml b/api/res/values-pt/strings.xml index 4a32bbc53..23f4ae240 100644 --- a/api/res/values-pt/strings.xml +++ b/api/res/values-pt/strings.xml @@ -1,85 +1,85 @@ - - 1 Ano - %d Anos - - - 1 Mês - %d Meses - - - 1 Semana - %d Semanas - - - 1 Dia - %d Dias - - - 1 Weekday - %d Weekdays - - - 1 Hora - %d Horas - - - 1 Minuto - %d Minutos - - - 1 Segundo - %d Segundos - - - 1 h - %d h - - - 1 min - %d min - - - 1 s - %d s - - - 1 tarefa - %d tarefas - - - 1 person - %d people - - Hoje - Amanhã - Ontem - Confirma? - Pergunta: - Informação - Guardar - Sim - Não - Fechar - Concluído - Por favor aguarde... - A Sincronizar... - Sincronização - Estado - Opções - Acções - Terminar sessão - - desactivar - every fifteen minutes - every thirty minutes - every hour - every three hours - every six hours - every twelve hours - every day - every three days - every week - + + 1 Ano + %d Anos + + + 1 Mês + %d Meses + + + 1 Semana + %d Semanas + + + 1 Dia + %d Dias + + + 1 Weekday + %d Weekdays + + + 1 Hora + %d Horas + + + 1 Minuto + %d Minutos + + + 1 Segundo + %d Segundos + + + 1 h + %d h + + + 1 min + %d min + + + 1 s + %d s + + + 1 tarefa + %d tarefas + + + 1 person + %d people + + Hoje + Amanhã + Ontem + Confirma? + Pergunta: + Informação + Guardar + Sim + Não + Fechar + Concluído + Por favor aguarde... + A Sincronizar... + Sincronização + Estado + Opções + Acções + Terminar sessão + + desactivar + every fifteen minutes + every thirty minutes + every hour + every three hours + every six hours + every twelve hours + every day + every three days + every week + diff --git a/api/res/values-ru/strings.xml b/api/res/values-ru/strings.xml index d6b15977e..a76e6d36f 100755 --- a/api/res/values-ru/strings.xml +++ b/api/res/values-ru/strings.xml @@ -4,243 +4,249 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - - - - - - - 1 год - - %d года/лет - - - - 1 месяц - - %d месяца/месяцев - - - - 1 неделя - - %d недели/недель - - - - 1 день - - %d дня/дней - - - - 1 рабочий день - - %d рабочих дня - - - - 1 час - - %d часа/часов - - - - 1 минута - - %d минуты/минут - - - - 1 секунда - - %d секунды/секунд - - - - 1 час - - %d ч - - - - 1 мин - - %d мин - - - - 1 с - - %d с - - - - 1 задача - - %d задач(а/и) - - - - 1 человек - - %d человек - - - - Сегодня - - - Завтра - - - Вчера - - - Завт - - - Сег - - - - - Подтвердить? - - - Вопрос: - - - Информация - - - Ошибка! - - - Готово - - - Да - - - Нет - - - Закрыть - - - Готово - - - Ой, похоже произошла ошибка! Подробности ниже:\n\n%s - - - Ой, похоже произошла ошибка! - - - Пожалуйста, подождите… - - - - - Синхронизация задач… - - - Синхронизация… - - - Синхронизация - - - Синхронизировать - - - Astrid.com, Задачи Google, сохраненные данные, локальная резервная копия - - - Ошибка соединения! Проверьте подключение к интернету. - - - - - Состояние - - - Состояние: %s - - Вход не выполнен - - Процесс синхронизации… - - Последняя синхронизация\n%s - - Ошибка: %s - - Синхронизировано с ошибками: %s - - Последняя успешная синхронизация: %s - - Синхронизаций не выполнялось! - - - Параметры - - - Фоновая синхронизация - - Фоновая синхронизация отключена - - Сейчас установлено: %s - - - Только через Wifi - - Фоновая синхронизация происходит только через Wifi - - Фоновая синхронизация происходит всегда - - - Действия - - - Синхронизировать - - Войти и синхронизировать! - - - Вы вошли в систему как: - - - Отчёт о состоянии - - - Нажмите, чтобы отправить отчет команде Astrid - - Отправить отчет - - - Выйти - - Очищает все данные синхронизации - - - Выйти / очистить данные синхронизации? - - - В процессе последней синхронизации с %s возникли проблемы подключения к сети. Пожалуйста, повторите попытку позже. - - - - отключить - каждые 15 минут - каждые 30 минут - каждый час - каждые 3 часа - каждые 6 часов - каждые 12 часов - каждый день - каждые 3 дня - каждую неделю - - + + + + + + + 1 год + + %d года/лет + + + + 1 месяц + + %d месяца/месяцев + + + + 1 неделя + + %d недели/недель + + + + 1 день + + %d дня/дней + + + + 1 рабочий день + + %d рабочих дня + + + + 1 час + + %d часа/часов + + + + 1 минута + + %d минуты/минут + + + + 1 секунда + + %d секунды/секунд + + + + 1 час + + %d ч + + + + 1 мин + + %d мин + + + + 1 с + + %d с + + + + 1 задача + + %d задач(а/и) + + + + 1 человек + + %d человек + + + + Сегодня + + + Завтра + + + Вчера + + + Завт + + + Сег + + + + + Подтвердить? + + + Вопрос: + + + Информация + + + Ошибка! + + + Готово + + + Да + + + Нет + + + Закрыть + + + Готово + + + Ой, похоже произошла ошибка! Подробности ниже:\n\n%s + + + Ой, похоже произошла ошибка! + + + Пожалуйста, подождите… + + + + + Синхронизация задач… + + + Синхронизация… + + + Синхронизация + + + Синхронизировать + + + Astrid.com, Задачи Google, сохраненные данные, локальная резервная + копия + + + + Ошибка соединения! Проверьте подключение к интернету. + + + + + Состояние + + + Состояние: %s + + Вход не выполнен + + Процесс синхронизации… + + Последняя синхронизация\n%s + + Ошибка: %s + + Синхронизировано с ошибками: %s + + Последняя успешная синхронизация: %s + + Синхронизаций не выполнялось! + + + Параметры + + + Фоновая синхронизация + + Фоновая синхронизация отключена + + Сейчас установлено: %s + + + Только через Wifi + + Фоновая синхронизация происходит только через Wifi + + + Фоновая синхронизация происходит всегда + + + Действия + + + Синхронизировать + + Войти и синхронизировать! + + + Вы вошли в систему как: + + + Отчёт о состоянии + + + Нажмите, чтобы отправить отчет команде Astrid + + + Отправить отчет + + + Выйти + + Очищает все данные синхронизации + + + Выйти / очистить данные синхронизации? + + + В процессе последней синхронизации с %s возникли проблемы + подключения к сети. Пожалуйста, повторите попытку позже. + + + + + отключить + каждые 15 минут + каждые 30 минут + каждый час + каждые 3 часа + каждые 6 часов + каждые 12 часов + каждый день + каждые 3 дня + каждую неделю + + diff --git a/api/res/values-sv/strings.xml b/api/res/values-sv/strings.xml index ab1a98f19..b96effc83 100755 --- a/api/res/values-sv/strings.xml +++ b/api/res/values-sv/strings.xml @@ -4,244 +4,250 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - - - - - - - 1 år - - %d år - - - - 1 månad - - %d månader - - - - 1 vecka - - %d veckor - - - - 1 dag - - %d dagar - - - - 1 Veckodag - - %d Veckodagar - - - - 1 timme - - %d timmar - - - - 1 minut - - %d minuter - - - - 1 sekund - - %d sekunder - - - - 1 tim - - %d tim - - - - 1 min - - %d min - - - - 1 sek - - %d sek - - - - 1 uppgift - - %d uppgifter - - - - 1 person - - %d personer - - - - Today - - - Tomorrow - - - Igår - - - imorn - - - Igår - - - - - Bekräfta? - - - Fråga: - - - Information - - - Fel! - - - Spara - - - Ja - - - Nej - - - Stäng - - - Klar - - - Oj, det uppstod ett fel! Detta hände:\n\n%s - - - Oj, det uppstod ett fel! - - - Var god vänta... - - - - - Synkroniserar dina uppgifter... - - - Synkroniserar... - - - Synkronisering - - - Sync now - - - Astrid.com, Google Aktiviteter, sparad data, lokal backup - - - Tillkopplingsfel! Kontrollera din tillkoppling till internet. - - - - - Status - - - Status: %s - - Ej inloggad - - Synkronisering pågår... - - Synkroniserades senast:\n%s - - Misslyckades: %s - - Synkade med fel: %s - - Synkronisering lyckades senast: %s - - Aldrig synkroniserad! - - - Alternativ - - - Bakgrundssynkronisering - - Bakgrundssynkronisering är inaktiverad - - Aktuell inställning: %s - - - Endast Wi-Fi Inställning - - Bakgrundssynkronisering sker endast när du är ansluten till Wi-Fi - - Bakgrundssynkronisering sker alltid - - - Åtgärder - - - Synkronisera nu - - Logga in & synkronisera! - - - Inloggad som: - - - Status rapport - - - Klicka för att skicka en rapport till Astrid-teamet - - Skicka rapport - - - Logga ut - - Rensar alla synkroniseringsdata - - - Logga ut / rensa synkroniseringsdata? - - - Ett nätverksproblem uppstod -vid senaste synkroniseringen med %s. Vänligen försök igen. - - - - inaktivera - varje kvartstimme - varje halvtimme - varje timme - var tredje timme - var sjätte timme - var tolfte timme - varje dag - var tredje dag - varje vecka - - + + + + + + + 1 år + + %d år + + + + 1 månad + + %d månader + + + + 1 vecka + + %d veckor + + + + 1 dag + + %d dagar + + + + 1 Veckodag + + %d Veckodagar + + + + 1 timme + + %d timmar + + + + 1 minut + + %d minuter + + + + 1 sekund + + %d sekunder + + + + 1 tim + + %d tim + + + + 1 min + + %d min + + + + 1 sek + + %d sek + + + + 1 uppgift + + %d uppgifter + + + + 1 person + + %d personer + + + + Today + + + Tomorrow + + + Igår + + + imorn + + + Igår + + + + + Bekräfta? + + + Fråga: + + + Information + + + Fel! + + + Spara + + + Ja + + + Nej + + + Stäng + + + Klar + + + Oj, det uppstod ett fel! Detta hände:\n\n%s + + + Oj, det uppstod ett fel! + + + Var god vänta... + + + + + Synkroniserar dina uppgifter... + + + Synkroniserar... + + + Synkronisering + + + Sync now + + + Astrid.com, Google Aktiviteter, sparad data, lokal backup + + + Tillkopplingsfel! Kontrollera din tillkoppling till internet. + + + + + + Status + + + Status: %s + + Ej inloggad + + Synkronisering pågår... + + Synkroniserades senast:\n%s + + Misslyckades: %s + + Synkade med fel: %s + + Synkronisering lyckades senast: %s + + Aldrig synkroniserad! + + + Alternativ + + + Bakgrundssynkronisering + + Bakgrundssynkronisering är inaktiverad + + Aktuell inställning: %s + + + Endast Wi-Fi Inställning + + Bakgrundssynkronisering sker endast när du är + ansluten till Wi-Fi + + + Bakgrundssynkronisering sker alltid + + + Åtgärder + + + Synkronisera nu + + Logga in & synkronisera! + + + Inloggad som: + + + Status rapport + + + Klicka för att skicka en rapport till + Astrid-teamet + + + Skicka rapport + + + Logga ut + + Rensar alla synkroniseringsdata + + + Logga ut / rensa synkroniseringsdata? + + + Ett nätverksproblem uppstod + vid senaste synkroniseringen med %s. Vänligen försök igen. + + + + + inaktivera + varje kvartstimme + varje halvtimme + varje timme + var tredje timme + var sjätte timme + var tolfte timme + varje dag + var tredje dag + varje vecka + + diff --git a/api/res/values-th/strings.xml b/api/res/values-th/strings.xml index e11fcfee6..2cb6f36fe 100644 --- a/api/res/values-th/strings.xml +++ b/api/res/values-th/strings.xml @@ -1,77 +1,77 @@ - - 1 Year - %d Years - - - 1 Month - %d Months - - - 1 Week - %d Weeks - - - 1 วัน - %d วัน - - - 1 Weekday - %d Weekdays - - - 1 ชั่วโมง - %d ชั่วโมง - - - 1 นาที - %d นาที - - - 1 วินาที - %d วินาที - - - 1 ช.ม. - %d ช.ม. - - - 1 นาที - %d นาที - - - 1 วิ. - %d วิ. - - - 1 task - %d tasks - - - 1 person - %d people - - วันนี้ - พรุ่งนี้ - เมื่อวาน - ข้อมูล - บันทึก - เสร็จแล้ว - ข้อผิดพลาดในการเชื่อมต่อ! ตรวจดูการเชื่อมต่ออินเตอร์เน็ท - สถานะ - ตัวเลือก - การดำเนินการ - - disable - every fifteen minutes - every thirty minutes - every hour - every three hours - every six hours - every twelve hours - every day - every three days - every week - + + 1 Year + %d Years + + + 1 Month + %d Months + + + 1 Week + %d Weeks + + + 1 วัน + %d วัน + + + 1 Weekday + %d Weekdays + + + 1 ชั่วโมง + %d ชั่วโมง + + + 1 นาที + %d นาที + + + 1 วินาที + %d วินาที + + + 1 ช.ม. + %d ช.ม. + + + 1 นาที + %d นาที + + + 1 วิ. + %d วิ. + + + 1 task + %d tasks + + + 1 person + %d people + + วันนี้ + พรุ่งนี้ + เมื่อวาน + ข้อมูล + บันทึก + เสร็จแล้ว + ข้อผิดพลาดในการเชื่อมต่อ! ตรวจดูการเชื่อมต่ออินเตอร์เน็ท + สถานะ + ตัวเลือก + การดำเนินการ + + disable + every fifteen minutes + every thirty minutes + every hour + every three hours + every six hours + every twelve hours + every day + every three days + every week + diff --git a/api/res/values-tr/strings.xml b/api/res/values-tr/strings.xml index 2eb388395..b32a64e3d 100755 --- a/api/res/values-tr/strings.xml +++ b/api/res/values-tr/strings.xml @@ -4,243 +4,245 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - - - - - - - 1 Yıl - - %d Yıl - - - - 1 Ay - - %d Ay - - - - 1 Hafta - - %d hafta - - - - 1 Gün - - %d gün - - - - 1 haftaiçi gün - - %d haftaiçi günü - - - - 1 Saat - - %d saat - - - - 1 Dakika - - %d dakika - - - - 1 Saniye - - %d saniye - - - - 1 saat - - %d saat - - - - 1 dakika - - %d dakika - - - - 1 saniye - - %d saniye - - - - 1 görev - - %d görev - - - - 1 kişi - - %d kişi - - - - Bugün - - - Yarın - - - Dün - - - Yarın - - - Dün - - - - - Onayla? - - - Soru: - - - Bilgi - - - Hata! - - - Kaydet - - - Evet - - - Hayır - - - Kapat - - - Yapıldı - - - Oops, bir sorun meydana geldi! Olan şu:\n\n%s - - - Oops, bir sorun meydana geldi! - - - Lütfen bekleyin... - - - - - Görevleriniz eşleniyor... - - - Eşleniyor... - - - Sync & backup - - - Sync now - - - Astrid.com, Google Tasks, saved data, local backup - - - Bağlantı Hatası! Internet bağlantınızı denetleyin. - - - - - Durum - - - Durum: %s - - Oturum açılmadı - - Senkronizasyon devam ediyor... - - Son Senk.\n%s - - Başarısız: %s - - Hatalı Senkron: %s - - Son Başarılı Eşleme: %s - - Hiç Eşleme Yapılmamış! - - - Seçenekler - - - Arkaplanda senkronizasyon - - Arkaplanda senkronizasyon devre dışı - - Mevcut ayar: %s - - - Sadece Wifi Ayarı - - Sadece Wifi ile arkaplan senkronu - - Arkaplan senkronu her zaman etkin - - - Eylemler - - - Şimdi Eşle - - Giriş Yapı & Senktronize et! - - - Giriş yapılan hesap: - - - Durum Raporu - - - Astrid takımına bildirmek için tıklayın - - Rapor Gönder - - - Çıkış Yap - - Bütün eşleme verilerini temizle - - - Çıkış Yap / Senkron verisini sil? - - - %s ile son eşleme yapılırken bir ağ bağlantı sorunu oluştu. Lütfen daha sonra yeniden deneyin. - - - - devre dışı bırak - her 15 dakika - her 30 dakika - her saat - her 3 saat - her 6 saat - her 12 saat - hergün - her 3 gün - her hafta - - + + + + + + + 1 Yıl + + %d Yıl + + + + 1 Ay + + %d Ay + + + + 1 Hafta + + %d hafta + + + + 1 Gün + + %d gün + + + + 1 haftaiçi gün + + %d haftaiçi günü + + + + 1 Saat + + %d saat + + + + 1 Dakika + + %d dakika + + + + 1 Saniye + + %d saniye + + + + 1 saat + + %d saat + + + + 1 dakika + + %d dakika + + + + 1 saniye + + %d saniye + + + + 1 görev + + %d görev + + + + 1 kişi + + %d kişi + + + + Bugün + + + Yarın + + + Dün + + + Yarın + + + Dün + + + + + Onayla? + + + Soru: + + + Bilgi + + + Hata! + + + Kaydet + + + Evet + + + Hayır + + + Kapat + + + Yapıldı + + + Oops, bir sorun meydana geldi! Olan şu:\n\n%s + + + Oops, bir sorun meydana geldi! + + + Lütfen bekleyin... + + + + + Görevleriniz eşleniyor... + + + Eşleniyor... + + + Sync & backup + + + Sync now + + + Astrid.com, Google Tasks, saved data, local backup + + + Bağlantı Hatası! Internet bağlantınızı denetleyin. + + + + + Durum + + + Durum: %s + + Oturum açılmadı + + Senkronizasyon devam ediyor... + + Son Senk.\n%s + + Başarısız: %s + + Hatalı Senkron: %s + + Son Başarılı Eşleme: %s + + Hiç Eşleme Yapılmamış! + + + Seçenekler + + + Arkaplanda senkronizasyon + + Arkaplanda senkronizasyon devre dışı + + Mevcut ayar: %s + + + Sadece Wifi Ayarı + + Sadece Wifi ile arkaplan senkronu + + Arkaplan senkronu her zaman etkin + + + Eylemler + + + Şimdi Eşle + + Giriş Yapı & Senktronize et! + + + Giriş yapılan hesap: + + + Durum Raporu + + + Astrid takımına bildirmek için tıklayın + + Rapor Gönder + + + Çıkış Yap + + Bütün eşleme verilerini temizle + + + Çıkış Yap / Senkron verisini sil? + + + %s ile son eşleme yapılırken bir ağ bağlantı sorunu oluştu. + Lütfen daha sonra yeniden deneyin. + + + + + devre dışı bırak + her 15 dakika + her 30 dakika + her saat + her 3 saat + her 6 saat + her 12 saat + hergün + her 3 gün + her hafta + + diff --git a/api/res/values-zh-rCN/strings.xml b/api/res/values-zh-rCN/strings.xml index 4c081cda1..7cd58ce03 100755 --- a/api/res/values-zh-rCN/strings.xml +++ b/api/res/values-zh-rCN/strings.xml @@ -4,243 +4,243 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - - - - - - - 1 年 - - %d 年 - - - - 1 个月 - - %d 个月 - - - - 1 周 - - %d 周 - - - - 1 天 - - %d 天 - - - - 1 个任务天 - - %d 个任务天 - - - - 1 小时 - - %d 小时 - - - - 1 分钟 - - %d 分钟 - - - - 1 秒 - - %d 秒 - - - - 1 小时 - - %d 小时 - - - - 1 分钟 - - %d 分钟 - - - - 1 秒 - - %d 秒 - - - - 1 个任务 - - %d 个任务 - - - - 一个人 - - %d 个人 - - - - 今天 - - - 明天 - - - 昨天 - - - 明天 - - - 昨天 - - - - - 确认? - - - 问题: - - - 信息 - - - 错误! - - - 保存 - - - 确定 - - - 取消 - - - 关闭 - - - 完成 - - - 糟糕,发生错误!状况是:\n\n%s - - - 糟糕,发生错误! - - - 请稍候... - - - - - 任务同步中... - - - 正在同步中... - - - 同步和备份 - - - Sync now - - - Astrid.com,谷歌任务,已存数据,本地备份 - - - 连接错误!请检查您的因特网连接。 - - - - - 状态 - - - 状态:%s - - 未登陆 - - 同步中... - - 上次同步:\n%s - - 失败:%s - - 同步 w/ 错误: %s 上次同步日期 - - 上次成功同步:%s - - 未同步过! - - - 选项 - - - 后台同步 - - 后台同步已关闭 - - 目前同步间隔:%s - - - Wifi 才可使用的设置 - - 使用 Wifi 才启动后台同步 - - 总是使用后台同步 - - - 动作 - - - 现在同步 - - 登陆并同步! - - - 已经登录为: - - - 状态报告 - - - 点击给 Astrid 团队发送报告 - - 发送报告 - - - 登出 - - 清除所有同步资料 - - - 登出/清除同步资料? - - - 在最近与 %s 同步时网络连接发生问题。请重试。 - - - - 停用 - 每15分钟 - 每30分钟 - 每小时 - 每3小时 - 每6小时 - 每12小时 - 每天 - 每3天 - 每周 - - + + + + + + + 1 年 + + %d 年 + + + + 1 个月 + + %d 个月 + + + + 1 周 + + %d 周 + + + + 1 天 + + %d 天 + + + + 1 个任务天 + + %d 个任务天 + + + + 1 小时 + + %d 小时 + + + + 1 分钟 + + %d 分钟 + + + + 1 秒 + + %d 秒 + + + + 1 小时 + + %d 小时 + + + + 1 分钟 + + %d 分钟 + + + + 1 秒 + + %d 秒 + + + + 1 个任务 + + %d 个任务 + + + + 一个人 + + %d 个人 + + + + 今天 + + + 明天 + + + 昨天 + + + 明天 + + + 昨天 + + + + + 确认? + + + 问题: + + + 信息 + + + 错误! + + + 保存 + + + 确定 + + + 取消 + + + 关闭 + + + 完成 + + + 糟糕,发生错误!状况是:\n\n%s + + + 糟糕,发生错误! + + + 请稍候... + + + + + 任务同步中... + + + 正在同步中... + + + 同步和备份 + + + Sync now + + + Astrid.com,谷歌任务,已存数据,本地备份 + + + 连接错误!请检查您的因特网连接。 + + + + + 状态 + + + 状态:%s + + 未登陆 + + 同步中... + + 上次同步:\n%s + + 失败:%s + + 同步 w/ 错误: %s 上次同步日期 + + 上次成功同步:%s + + 未同步过! + + + 选项 + + + 后台同步 + + 后台同步已关闭 + + 目前同步间隔:%s + + + Wifi 才可使用的设置 + + 使用 Wifi 才启动后台同步 + + 总是使用后台同步 + + + 动作 + + + 现在同步 + + 登陆并同步! + + + 已经登录为: + + + 状态报告 + + + 点击给 Astrid 团队发送报告 + + 发送报告 + + + 登出 + + 清除所有同步资料 + + + 登出/清除同步资料? + + + 在最近与 %s 同步时网络连接发生问题。请重试。 + + + + 停用 + 每15分钟 + 每30分钟 + 每小时 + 每3小时 + 每6小时 + 每12小时 + 每天 + 每3天 + 每周 + + diff --git a/api/res/values-zh-rTW/strings.xml b/api/res/values-zh-rTW/strings.xml index 3696287af..bbde844ce 100755 --- a/api/res/values-zh-rTW/strings.xml +++ b/api/res/values-zh-rTW/strings.xml @@ -4,243 +4,243 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - - - - - - - 1 年 - - %d 年 - - - - 1 個月 - - %d 個月 - - - - 1 週 - - %d 週 - - - - 1 天 - - %d 天 - - - - 1 個工作天 - - %d 個工作天 - - - - 1 小時 - - %d 小時 - - - - 1 分鐘 - - %d 分鐘 - - - - 1 秒 - - %d 秒 - - - - 1 小時 - - %d 小時 - - - - 1 分鐘 - - %d 分鐘 - - - - 1 秒 - - %d 秒 - - - - 1 個工作 - - %d 個工作 - - - - 一個人 - - %d個人 - - - - 今天 - - - 明天 - - - 昨天 - - - 明天 - - - 昨天 - - - - - 確認? - - - 問題: - - - 資訊 - - - 錯誤! - - - 儲存 - - - 確定 - - - 取消 - - - 關閉 - - - 完成 - - - 糟糕,發生錯誤!狀況是:\n\n%s - - - 糟糕,發生錯誤! - - - 請稍候... - - - - - 工作同步中... - - - 正在同步中... - - - 同步和備份 - - - Sync now - - - Astrid.com,谷歌任務,已存數據,本地備份 - - - 連結錯誤! 檢查您的網際網路連線. - - - - - 狀態 - - - 狀態:%s - - 未登陸 - - 同步中... - - 上次同步:\n%s - - 失敗:%s - - 同步w/ 錯誤: %s 上次同步日期 - - 上次成功同步:%s - - 未同步過! - - - 選項 - - - 後台同步 - - 後台同步已關閉 - - 目前同步間隔:%s - - - Wifi 才可使用的設置 - - 使用 Wifi 才啟動後台同步 - - 總是使用後台同步 - - - 動作 - - - 現在同步 - - 登陸並同步! - - - 已經登錄為: - - - 狀態報告 - - - 點擊給 Astrid 團隊發送報告 - - 發送報告 - - - 登出 - - 清除所有同步資料 - - - 登出/清除同步資料? - - - 在最近與%s 同步時網絡連接發生問題。請重試。 - - - - 停用 - 每15分鐘 - 每30分鐘 - 每小時 - 每3小時 - 每6小時 - 每12小時 - 每天 - 每3天 - 每週 - - + + + + + + + 1 年 + + %d 年 + + + + 1 個月 + + %d 個月 + + + + 1 週 + + %d 週 + + + + 1 天 + + %d 天 + + + + 1 個工作天 + + %d 個工作天 + + + + 1 小時 + + %d 小時 + + + + 1 分鐘 + + %d 分鐘 + + + + 1 秒 + + %d 秒 + + + + 1 小時 + + %d 小時 + + + + 1 分鐘 + + %d 分鐘 + + + + 1 秒 + + %d 秒 + + + + 1 個工作 + + %d 個工作 + + + + 一個人 + + %d個人 + + + + 今天 + + + 明天 + + + 昨天 + + + 明天 + + + 昨天 + + + + + 確認? + + + 問題: + + + 資訊 + + + 錯誤! + + + 儲存 + + + 確定 + + + 取消 + + + 關閉 + + + 完成 + + + 糟糕,發生錯誤!狀況是:\n\n%s + + + 糟糕,發生錯誤! + + + 請稍候... + + + + + 工作同步中... + + + 正在同步中... + + + 同步和備份 + + + Sync now + + + Astrid.com,谷歌任務,已存數據,本地備份 + + + 連結錯誤! 檢查您的網際網路連線. + + + + + 狀態 + + + 狀態:%s + + 未登陸 + + 同步中... + + 上次同步:\n%s + + 失敗:%s + + 同步w/ 錯誤: %s 上次同步日期 + + 上次成功同步:%s + + 未同步過! + + + 選項 + + + 後台同步 + + 後台同步已關閉 + + 目前同步間隔:%s + + + Wifi 才可使用的設置 + + 使用 Wifi 才啟動後台同步 + + 總是使用後台同步 + + + 動作 + + + 現在同步 + + 登陸並同步! + + + 已經登錄為: + + + 狀態報告 + + + 點擊給 Astrid 團隊發送報告 + + 發送報告 + + + 登出 + + 清除所有同步資料 + + + 登出/清除同步資料? + + + 在最近與%s 同步時網絡連接發生問題。請重試。 + + + + 停用 + 每15分鐘 + 每30分鐘 + 每小時 + 每3小時 + 每6小時 + 每12小時 + 每天 + 每3天 + 每週 + + diff --git a/api/res/values/colors.xml b/api/res/values/colors.xml index 498c753f6..c1f3c8d3a 100644 --- a/api/res/values/colors.xml +++ b/api/res/values/colors.xml @@ -4,14 +4,14 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - - + + #ffff5555 #fffea400 #ff33a5e8 - #ff808080 - #ff505050 + #ff808080 + #ff505050 #ff202020 - + diff --git a/api/res/values/keys.xml b/api/res/values/keys.xml index 0106ccb5e..a4262c09a 100644 --- a/api/res/values/keys.xml +++ b/api/res/values/keys.xml @@ -3,10 +3,10 @@ This file contains preference keys and preference list values. These should not be translated --> - - - - + + + + 0 @@ -20,8 +20,8 @@ 259200 604800 - - + + sync_status sync_bgwifi @@ -33,5 +33,5 @@ sync_options sync_last_error - + diff --git a/api/res/values/strings.xml b/api/res/values/strings.xml index 25eb24f78..6fd875b71 100644 --- a/api/res/values/strings.xml +++ b/api/res/values/strings.xml @@ -4,244 +4,249 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - - - - - - - 1 Year - - %d Years - - - - 1 Month - - %d Months - - - - 1 Week - - %d Weeks - - - - 1 Day - - %d Days - - - - 1 Weekday - - %d Weekdays - - - - 1 Hour - - %d Hours - - - - 1 Minute - - %d Minutes - - - - 1 Second - - %d Seconds - - - - 1 Hr - - %d Hrs - - - - 1 Min - - %d Min - - - - 1 Sec - - %d Sec - - - - 1 task - - %d tasks - - - - 1 person - - %d people - - - - Today - - - Tomorrow - - - Yesterday - - - Tmrw - - - Yest - - - - - Confirm? - - - Question: - - - Information - - - Error! - - - Save - - - Yes - - - No - - - Close - - - Done - - - Oops, looks like an error occurred! Here\'s what happened:\n\n%s - - - Oops, looks like an error occurred! - - - Please wait... - - - - - Synchronizing your tasks... - - - Synchronizing... - - - Sync & backup - - - Sync now - - - Astrid.com, Google Tasks, saved data, local backup - - - Connection Error! Check your Internet connection. - - - - - Status - - - Status: %s - - Not logged in - - Sync ongoing... - - Last sync:\n%s - - Failed on: %s - - Sync w/ errors: %s - - Last successful sync: %s - - Never synchronized! - - - Options - - - Background sync - - Background synchronization is disabled - - Currently set to: %s - - - Wifi only setting - - Background synchronization only happens when on Wifi - - Background synchronization will always occur - - - Actions - - - Synchronize now - - Log in & synchronize! - - - Logged in as: - - - Status report - - - Click to send a report to the Astrid team - - Send report - - - Log out - - Clears all synchronization data - - - Log out/clear synchronization data? - - - There was a problem connecting to the network - during the last sync with %s. Please try again later. - - - - disable - every fifteen minutes - every thirty minutes - every hour - every three hours - every six hours - every twelve hours - every day - every three days - every week - - + + + + + + + 1 Year + + %d Years + + + + 1 Month + + %d Months + + + + 1 Week + + %d Weeks + + + + 1 Day + + %d Days + + + + 1 Weekday + + %d Weekdays + + + + 1 Hour + + %d Hours + + + + 1 Minute + + %d Minutes + + + + 1 Second + + %d Seconds + + + + 1 Hr + + %d Hrs + + + + 1 Min + + %d Min + + + + 1 Sec + + %d Sec + + + + 1 task + + %d tasks + + + + 1 person + + %d people + + + + Today + + + Tomorrow + + + Yesterday + + + Tmrw + + + Yest + + + + + Confirm? + + + Question: + + + Information + + + Error! + + + Save + + + Yes + + + No + + + Close + + + Done + + + Oops, looks like an error occurred! Here\'s what happened:\n\n%s + + + + Oops, looks like an error occurred! + + + Please wait... + + + + + Synchronizing your tasks... + + + Synchronizing... + + + Sync & backup + + + Sync now + + + Astrid.com, Google Tasks, saved data, local backup + + + Connection Error! Check your Internet connection. + + + + + Status + + + Status: %s + + Not logged in + + Sync ongoing... + + Last sync:\n%s + + Failed on: %s + + Sync w/ errors: %s + + Last successful sync: %s + + Never synchronized! + + + Options + + + Background sync + + Background synchronization is disabled + + Currently set to: %s + + + Wifi only setting + + Background synchronization only happens when on + Wifi + + + Background synchronization will always occur + + + + Actions + + + Synchronize now + + Log in & synchronize! + + + Logged in as: + + + Status report + + + Click to send a report to the Astrid team + + Send report + + + Log out + + Clears all synchronization data + + + Log out/clear synchronization data? + + + There was a problem connecting to the network + during the last sync with %s. Please try again later. + + + + + disable + every fifteen minutes + every thirty minutes + every hour + every three hours + every six hours + every twelve hours + every day + every three days + every week + + diff --git a/api/src/com/todoroo/andlib/data/AbstractDatabase.java b/api/src/com/todoroo/andlib/data/AbstractDatabase.java index f24952551..2ff93f9d7 100644 --- a/api/src/com/todoroo/andlib/data/AbstractDatabase.java +++ b/api/src/com/todoroo/andlib/data/AbstractDatabase.java @@ -5,9 +5,6 @@ */ package com.todoroo.andlib.data; -import java.lang.reflect.Field; -import java.util.ArrayList; - import android.content.ContentValues; import android.content.Context; import android.database.Cursor; @@ -24,25 +21,27 @@ import com.todoroo.andlib.service.DependencyInjectionService; import com.todoroo.andlib.service.ExceptionService; import com.todoroo.andlib.utility.AndroidUtilities; +import java.lang.reflect.Field; +import java.util.ArrayList; + /** * AbstractDatabase is a database abstraction which wraps a SQLite database. - *

+ *

* Users of this class are in charge of the database's lifecycle - ensuring that * the database is open when needed and closed when usage is finished. Within an * activity, this is typically accomplished through the onResume and onPause * methods, though if the database is not needed for the activity's entire * lifecycle, it can be closed earlier. - *

+ *

* Direct querying is not recommended for type safety reasons. Instead, use one * of the service classes to issue the request and return a {@link TodorooCursor}. * * @author Tim Su - * */ @SuppressWarnings("nls") abstract public class AbstractDatabase { - // --- abstract methods + // --- abstract methods /** * @return database name @@ -67,6 +66,7 @@ abstract public class AbstractDatabase { /** * Upgrades an open database from one version to the next + * * @param oldVersion * @param newVersion * @return true if upgrade was handled, false otherwise @@ -105,12 +105,12 @@ abstract public class AbstractDatabase { } protected void onDatabaseUpdated() { - for(DatabaseUpdateListener listener : listeners) { + for (DatabaseUpdateListener listener : listeners) { listener.onDatabaseUpdated(); } } - // --- internal implementation + // --- internal implementation @Autowired private ExceptionService exceptionService; @@ -121,12 +121,13 @@ abstract public class AbstractDatabase { /** * Return the name of the table containing these models + * * @param modelType * @return */ public final Table getTable(Class modelType) { - for(Table table : getTables()) { - if(table.modelClass.equals(modelType)) + for (Table table : getTables()) { + if (table.modelClass.equals(modelType)) return table; } throw new UnsupportedOperationException("Unknown model class " + modelType); //$NON-NLS-1$ @@ -149,8 +150,8 @@ abstract public class AbstractDatabase { } protected synchronized final void initializeHelper() { - if(helper == null) { - if(ContextManager.getContext() == null) + if (helper == null) { + if (ContextManager.getContext() == null) throw new NullPointerException("Null context creating database helper"); helper = new DatabaseHelper(ContextManager.getContext(), getName(), null, getVersion()); @@ -164,7 +165,7 @@ abstract public class AbstractDatabase { public synchronized final void openForWriting() { initializeHelper(); - if(database != null && !database.isReadOnly() && database.isOpen()) + if (database != null && !database.isReadOnly() && database.isOpen()) return; try { @@ -192,7 +193,7 @@ abstract public class AbstractDatabase { */ public synchronized final void openForReading() { initializeHelper(); - if(database != null && database.isOpen()) + if (database != null && database.isOpen()) return; database = helper.getReadableDatabase(); } @@ -201,7 +202,7 @@ abstract public class AbstractDatabase { * Close the database if it has been opened previously */ public synchronized final void close() { - if(database != null) { + if (database != null) { database.close(); } database = null; @@ -220,7 +221,7 @@ abstract public class AbstractDatabase { * @return sql database. opens database if not yet open */ public synchronized final SQLiteDatabase getDatabase() { - if(database == null) { + if (database == null) { AndroidUtilities.sleepDeep(300L); openForWriting(); } @@ -273,7 +274,7 @@ abstract public class AbstractDatabase { /* * @see android.database.sqlite.SQLiteDatabase#update(String table, ContentValues values, String whereClause, String[] whereArgs) */ - public synchronized int update(String table, ContentValues values, String whereClause, String[] whereArgs) { + public synchronized int update(String table, ContentValues values, String whereClause, String[] whereArgs) { int result = getDatabase().update(table, values, whereClause, whereArgs); onDatabaseUpdated(); return result; @@ -287,7 +288,7 @@ abstract public class AbstractDatabase { private class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context, String name, - CursorFactory factory, int version) { + CursorFactory factory, int version) { super(context, name, factory, version); } @@ -300,11 +301,11 @@ abstract public class AbstractDatabase { SqlConstructorVisitor sqlVisitor = new SqlConstructorVisitor(); // create tables - for(Table table : getTables()) { + for (Table table : getTables()) { sql.append("CREATE TABLE IF NOT EXISTS ").append(table.name).append('('). - append(AbstractModel.ID_PROPERTY).append(" INTEGER PRIMARY KEY AUTOINCREMENT"); - for(Property property : table.getProperties()) { - if(AbstractModel.ID_PROPERTY.name.equals(property.name)) + append(AbstractModel.ID_PROPERTY).append(" INTEGER PRIMARY KEY AUTOINCREMENT"); + for (Property property : table.getProperties()) { + if (AbstractModel.ID_PROPERTY.name.equals(property.name)) continue; sql.append(',').append(property.accept(sqlVisitor, null)); } @@ -328,7 +329,7 @@ abstract public class AbstractDatabase { database = db; try { - if(!AbstractDatabase.this.onUpgrade(oldVersion, newVersion)) { + if (!AbstractDatabase.this.onUpgrade(oldVersion, newVersion)) { // We don't know how to handle this case because someone forgot to // implement the upgrade. We can't drop tables, we can only // throw a nasty exception at this time @@ -347,7 +348,6 @@ abstract public class AbstractDatabase { * Visitor that returns SQL constructor for this property * * @author Tim Su - * */ public static class SqlConstructorVisitor implements PropertyVisitor { diff --git a/api/src/com/todoroo/andlib/data/AbstractModel.java b/api/src/com/todoroo/andlib/data/AbstractModel.java index 4a572d750..1bfa6bccc 100644 --- a/api/src/com/todoroo/andlib/data/AbstractModel.java +++ b/api/src/com/todoroo/andlib/data/AbstractModel.java @@ -5,15 +5,6 @@ */ package com.todoroo.andlib.data; -import java.lang.reflect.Array; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map.Entry; -import java.util.Set; - import android.content.ContentValues; import android.os.Parcel; import android.os.Parcelable; @@ -24,15 +15,23 @@ import com.todoroo.andlib.data.Property.LongProperty; import com.todoroo.andlib.data.Property.PropertyVisitor; import com.todoroo.andlib.utility.AndroidUtilities; +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map.Entry; +import java.util.Set; + /** * AbstractModel represents a row in a database. - *

+ *

* A single database can be represented by multiple AbstractModels * corresponding to different queries that return a different set of columns. * Each model exposes a set of properties that it contains. * * @author Tim Su - * */ public abstract class AbstractModel implements Parcelable, Cloneable { @@ -42,21 +41,31 @@ public abstract class AbstractModel implements Parcelable, Cloneable { // --- constants - /** id property common to all models */ + /** + * id property common to all models + */ protected static final String ID_PROPERTY_NAME = "_id"; //$NON-NLS-1$ - /** id field common to all models */ + /** + * id field common to all models + */ public static final LongProperty ID_PROPERTY = new LongProperty(null, ID_PROPERTY_NAME); - /** sentinel for objects without an id */ + /** + * sentinel for objects without an id + */ public static final long NO_ID = 0; - /** prefix for transitories retained in content values */ + /** + * prefix for transitories retained in content values + */ public static final String RETAIN_TRANSITORY_PREFIX = "retain-trans-"; //$NON-NLS-1$ // --- abstract methods - /** Get the default values for this object */ + /** + * Get the default values for this object + */ abstract public ContentValues getDefaultValues(); // --- data store variables and management @@ -68,35 +77,47 @@ public abstract class AbstractModel implements Parcelable, Cloneable { * the database (values), then defaults (getDefaultValues) */ - /** User set values */ + /** + * User set values + */ protected ContentValues setValues = null; - /** Values from database */ + /** + * Values from database + */ protected ContentValues values = null; - /** Transitory Metadata (not saved in database) */ + /** + * Transitory Metadata (not saved in database) + */ protected HashMap transitoryData = null; - /** Get database-read values for this object */ + /** + * Get database-read values for this object + */ public ContentValues getDatabaseValues() { return values; } - /** Get the user-set values for this object */ + /** + * Get the user-set values for this object + */ public ContentValues getSetValues() { return setValues; } - /** Get a list of all field/value pairs merged across data sources */ + /** + * Get a list of all field/value pairs merged across data sources + */ public ContentValues getMergedValues() { ContentValues mergedValues = new ContentValues(); ContentValues defaultValues = getDefaultValues(); - if(defaultValues != null) + if (defaultValues != null) mergedValues.putAll(defaultValues); - if(values != null) + if (values != null) mergedValues.putAll(values); - if(setValues != null) + if (setValues != null) mergedValues.putAll(setValues); return mergedValues; @@ -115,9 +136,9 @@ public abstract class AbstractModel implements Parcelable, Cloneable { * saved - future saves will not need to write all the data as before. */ public void markSaved() { - if(values == null) + if (values == null) values = setValues; - else if(setValues != null) + else if (setValues != null) values.putAll(setValues); setValues = null; } @@ -128,10 +149,10 @@ public abstract class AbstractModel implements Parcelable, Cloneable { */ @Override public boolean equals(Object other) { - if(other == null || other.getClass() != getClass()) + if (other == null || other.getClass() != getClass()) return false; - return getMergedValues().equals(((AbstractModel)other).getMergedValues()); + return getMergedValues().equals(((AbstractModel) other).getMergedValues()); } @Override @@ -144,10 +165,10 @@ public abstract class AbstractModel implements Parcelable, Cloneable { public String toString() { StringBuilder builder = new StringBuilder(); builder.append(getClass().getSimpleName()).append("\n") - .append("set values:\n") - .append(setValues).append("\n") - .append("values:\n") - .append(values).append("\n"); + .append("set values:\n") + .append(setValues).append("\n") + .append("values:\n") + .append(values).append("\n"); return builder.toString(); } @@ -159,14 +180,16 @@ public abstract class AbstractModel implements Parcelable, Cloneable { } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } - if(setValues != null) + if (setValues != null) clone.setValues = new ContentValues(setValues); - if(values != null) + if (values != null) clone.values = new ContentValues(values); return clone; } - /** Check if this model has values that have been changed */ + /** + * Check if this model has values that have been changed + */ public boolean isModified() { return setValues.size() > 0; } @@ -198,29 +221,29 @@ public abstract class AbstractModel implements Parcelable, Cloneable { */ public synchronized TYPE getValue(Property property) { Object value; - if(setValues != null && setValues.containsKey(property.getColumnName())) + if (setValues != null && setValues.containsKey(property.getColumnName())) value = setValues.get(property.getColumnName()); - else if(values != null && values.containsKey(property.getColumnName())) + else if (values != null && values.containsKey(property.getColumnName())) value = values.get(property.getColumnName()); - else if(getDefaultValues().containsKey(property.getColumnName())) + else if (getDefaultValues().containsKey(property.getColumnName())) value = getDefaultValues().get(property.getColumnName()); else throw new UnsupportedOperationException( - "Model Error: Did not read property " + property.name); //$NON-NLS-1$ + "Model Error: Did not read property " + property.name); //$NON-NLS-1$ // resolve properties that were retrieved with a different type than accessed try { - if(value instanceof String && property instanceof LongProperty) - return (TYPE) Long.valueOf((String)value); - else if(value instanceof String && property instanceof IntegerProperty) - return (TYPE) Integer.valueOf((String)value); - else if(value instanceof String && property instanceof DoubleProperty) - return (TYPE) Double.valueOf((String)value); - else if(value instanceof Integer && property instanceof LongProperty) - return (TYPE) Long.valueOf(((Number)value).longValue()); + if (value instanceof String && property instanceof LongProperty) + return (TYPE) Long.valueOf((String) value); + else if (value instanceof String && property instanceof IntegerProperty) + return (TYPE) Integer.valueOf((String) value); + else if (value instanceof String && property instanceof DoubleProperty) + return (TYPE) Double.valueOf((String) value); + else if (value instanceof Integer && property instanceof LongProperty) + return (TYPE) Long.valueOf(((Number) value).longValue()); return (TYPE) value; } catch (NumberFormatException e) { return (TYPE) getDefaultValues().get(property.name); @@ -235,9 +258,9 @@ public abstract class AbstractModel implements Parcelable, Cloneable { abstract public long getId(); protected long getIdHelper(LongProperty id) { - if(setValues != null && setValues.containsKey(id.name)) + if (setValues != null && setValues.containsKey(id.name)) return setValues.getAsLong(id.name); - else if(values != null && values.containsKey(id.name)) + else if (values != null && values.containsKey(id.name)) return values.getAsLong(id.name); else return NO_ID; @@ -247,7 +270,7 @@ public abstract class AbstractModel implements Parcelable, Cloneable { if (setValues == null) setValues = new ContentValues(); - if(id == NO_ID) + if (id == NO_ID) clearValue(ID_PROPERTY); else setValues.put(ID_PROPERTY_NAME, id); @@ -265,9 +288,9 @@ public abstract class AbstractModel implements Parcelable, Cloneable { * @return true if setValues or values contains this property */ public boolean containsValue(Property property) { - if(setValues != null && setValues.containsKey(property.getColumnName())) + if (setValues != null && setValues.containsKey(property.getColumnName())) return true; - if(values != null && values.containsKey(property.getColumnName())) + if (values != null && values.containsKey(property.getColumnName())) return true; return false; } @@ -275,12 +298,12 @@ public abstract class AbstractModel implements Parcelable, Cloneable { /** * @param property * @return true if setValues or values contains this property, and the value - * stored is not null + * stored is not null */ public boolean containsNonNullValue(Property property) { - if(setValues != null && setValues.containsKey(property.getColumnName())) + if (setValues != null && setValues.containsKey(property.getColumnName())) return setValues.get(property.getColumnName()) != null; - if(values != null && values.containsKey(property.getColumnName())) + if (values != null && values.containsKey(property.getColumnName())) return values.get(property.getColumnName()) != null; return false; } @@ -294,12 +317,12 @@ public abstract class AbstractModel implements Parcelable, Cloneable { protected synchronized boolean shouldSaveValue( Property property, TYPE newValue) { - // we've already decided to save it, so overwrite old value + // we've already decided to save it, so overwrite old value if (setValues.containsKey(property.getColumnName())) - return true; + return true; // values contains this key, we should check it out - if(values != null && values.containsKey(property.getColumnName())) { + if (values != null && values.containsKey(property.getColumnName())) { TYPE value = getValue(property); if (value == null) { if (newValue == null) @@ -316,7 +339,7 @@ public abstract class AbstractModel implements Parcelable, Cloneable { * Sets the given property. Make sure this model has this property! */ public synchronized void setValue(Property property, - TYPE value) { + TYPE value) { if (setValues == null) setValues = new ContentValues(); if (!shouldSaveValue(property, value)) @@ -350,23 +373,25 @@ public abstract class AbstractModel implements Parcelable, Cloneable { /** * Clear the key for the given property + * * @param property */ public synchronized void clearValue(Property property) { - if(setValues != null && setValues.containsKey(property.getColumnName())) + if (setValues != null && setValues.containsKey(property.getColumnName())) setValues.remove(property.getColumnName()); - if(values != null && values.containsKey(property.getColumnName())) + if (values != null && values.containsKey(property.getColumnName())) values.remove(property.getColumnName()); } /** * Sets the state of the given flag on the given property + * * @param property * @param flag * @param value */ public void setFlag(IntegerProperty property, int flag, boolean value) { - if(value) + if (value) setValue(property, getValue(property) | flag); else setValue(property, getValue(property) & ~flag); @@ -374,8 +399,9 @@ public abstract class AbstractModel implements Parcelable, Cloneable { /** * Returns the set state of the given flag on the given property + * * @param property the property to get the set state of the flag - * @param flag the flag-descriptor (e.g. Task.FLAG_REPEAT_AFTER_COMPLETION) + * @param flag the flag-descriptor (e.g. Task.FLAG_REPEAT_AFTER_COMPLETION) * @return true if the flag is set */ public boolean getFlag(IntegerProperty property, int flag) { @@ -386,13 +412,13 @@ public abstract class AbstractModel implements Parcelable, Cloneable { // --- setting and retrieving flags public synchronized void putTransitory(String key, Object value) { - if(transitoryData == null) + if (transitoryData == null) transitoryData = new HashMap(); transitoryData.put(key, value); } public Object getTransitory(String key) { - if(transitoryData == null) + if (transitoryData == null) return null; return transitoryData.get(key); } @@ -427,18 +453,18 @@ public abstract class AbstractModel implements Parcelable, Cloneable { */ protected static Property[] generateProperties(Class cls) { ArrayList> properties = new ArrayList>(); - if(cls.getSuperclass() != AbstractModel.class) + if (cls.getSuperclass() != AbstractModel.class) properties.addAll(Arrays.asList(generateProperties( - (Class) cls.getSuperclass()))); + (Class) cls.getSuperclass()))); // a property is public, static & extends Property - for(Field field : cls.getFields()) { - if((field.getModifiers() & Modifier.STATIC) == 0) + for (Field field : cls.getFields()) { + if ((field.getModifiers() & Modifier.STATIC) == 0) continue; - if(!Property.class.isAssignableFrom(field.getType())) + if (!Property.class.isAssignableFrom(field.getType())) continue; try { - if(((Property) field.get(null)).table == null) + if (((Property) field.get(null)).table == null) continue; properties.add((Property) field.get(null)); } catch (IllegalArgumentException e) { @@ -455,7 +481,6 @@ public abstract class AbstractModel implements Parcelable, Cloneable { * Visitor that saves a value into a content values store * * @author Tim Su - * */ public static class ContentValuesSavingVisitor implements PropertyVisitor { @@ -467,7 +492,7 @@ public abstract class AbstractModel implements Parcelable, Cloneable { // we don't allow null values, as they indicate unset properties // when the database was written - if(value != null) + if (value != null) property.accept(this, value); } @@ -516,9 +541,9 @@ public abstract class AbstractModel implements Parcelable, Cloneable { */ abstract protected Parcelable.Creator getCreator(); - /** - * Parcelable creator helper - */ + /** + * Parcelable creator helper + */ protected static final class ModelCreator implements Parcelable.Creator { @@ -551,7 +576,11 @@ public abstract class AbstractModel implements Parcelable, Cloneable { */ public TYPE[] newArray(int size) { return (TYPE[]) Array.newInstance(cls, size); - }; - }; + } + + ; + } + + ; } diff --git a/api/src/com/todoroo/andlib/data/ContentResolverDao.java b/api/src/com/todoroo/andlib/data/ContentResolverDao.java index 472c7c6b7..df804bc2a 100644 --- a/api/src/com/todoroo/andlib/data/ContentResolverDao.java +++ b/api/src/com/todoroo/andlib/data/ContentResolverDao.java @@ -5,10 +5,6 @@ */ package com.todoroo.andlib.data; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.Set; - import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; @@ -22,23 +18,32 @@ import com.todoroo.andlib.sql.Criterion; import com.todoroo.andlib.sql.Query; import com.todoroo.andlib.utility.AndroidUtilities; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.Set; + /** * DAO for reading and writing values from an Android ContentResolver * - * @author Tim Su - * * @param model type + * @author Tim Su */ public class ContentResolverDao { - /** class of model */ + /** + * class of model + */ private final Class modelClass; - /** base content uri */ + /** + * base content uri + */ private final Uri baseUri; - /** content resolver */ + /** + * content resolver + */ private final ContentResolver cr; @Autowired @@ -47,7 +52,7 @@ public class ContentResolverDao { public ContentResolverDao(Class modelClass, Context context, Uri baseUri) { DependencyInjectionService.getInstance().inject(this); this.modelClass = modelClass; - if(debug == null) + if (debug == null) debug = false; this.baseUri = baseUri; @@ -56,6 +61,7 @@ public class ContentResolverDao { /** * Returns a URI for a single id + * * @param id * @return */ @@ -65,6 +71,7 @@ public class ContentResolverDao { /** * Delete specific item from the given table + * * @param id * @return number of rows affected */ @@ -74,6 +81,7 @@ public class ContentResolverDao { /** * Delete by criteria + * * @param where * @return number of rows affected */ @@ -83,11 +91,12 @@ public class ContentResolverDao { /** * Query content provider + * * @param query * @return */ public TodorooCursor query(Query query) { - if(debug) + if (debug) Log.i("SQL-" + modelClass.getSimpleName(), query.toString()); //$NON-NLS-1$ Cursor cursor = query.queryContentResolver(cr, baseUri); return new TodorooCursor(cursor, query.getFields()); @@ -95,15 +104,16 @@ public class ContentResolverDao { /** * Create new or save existing model + * * @param model * @return true if data was written to the db, false otherwise */ public boolean save(TYPE model) { writeTransitoriesToModelContentValues(model); - if(model.isSaved()) { - if(model.getSetValues() == null) + if (model.isSaved()) { + if (model.getSetValues() == null) return false; - if(cr.update(uriWithId(model.getId()), model.getSetValues(), null, null) != 0) + if (cr.update(uriWithId(model.getId()), model.getSetValues(), null, null) != 0) return true; } Uri uri = cr.insert(baseUri, model.getMergedValues()); @@ -130,12 +140,9 @@ public class ContentResolverDao { * Returns object corresponding to the given identifier * * @param database - * @param table - * name of table - * @param properties - * properties to read - * @param id - * id of item + * @param table name of table + * @param properties properties to read + * @param id id of item * @return null if no item found */ public TYPE fetch(long id, Property... properties) { diff --git a/api/src/com/todoroo/andlib/data/DatabaseDao.java b/api/src/com/todoroo/andlib/data/DatabaseDao.java index 2535c001f..49a6d93a5 100644 --- a/api/src/com/todoroo/andlib/data/DatabaseDao.java +++ b/api/src/com/todoroo/andlib/data/DatabaseDao.java @@ -5,14 +5,6 @@ */ package com.todoroo.andlib.data; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.Map.Entry; -import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; - import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteTransactionListener; @@ -26,6 +18,13 @@ import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.data.OutstandingEntry; import com.todoroo.astrid.data.SyncFlags; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.Map.Entry; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; /** @@ -34,7 +33,6 @@ import com.todoroo.astrid.data.SyncFlags; * of {@link ContentResolverDao} instead. * * @author Tim Su - * */ public class DatabaseDao { @@ -54,7 +52,7 @@ public class DatabaseDao { public DatabaseDao(Class modelClass) { DependencyInjectionService.getInstance().inject(this); this.modelClass = modelClass; - if(debug == null) + if (debug == null) debug = false; } @@ -63,7 +61,9 @@ public class DatabaseDao { setDatabase(database); } - /** Gets table associated with this DAO */ + /** + * Gets table associated with this DAO + */ public Table getTable() { return table; } @@ -79,7 +79,7 @@ public class DatabaseDao { * @param database */ public void setDatabase(AbstractDatabase database) { - if(database == this.database) + if (database == this.database) return; this.database = database; table = database.getTable(modelClass); @@ -93,7 +93,7 @@ public class DatabaseDao { } private final ArrayList> listeners = - new ArrayList>(); + new ArrayList>(); public void addListener(ModelUpdateListener listener) { listeners.add(listener); @@ -101,7 +101,7 @@ public class DatabaseDao { protected void onModelUpdated(TYPE model, boolean outstandingEntries) { TYPE modelCopy = (TYPE) model.clone(); - for(ModelUpdateListener listener : listeners) { + for (ModelUpdateListener listener : listeners) { listener.onModelUpdated(modelCopy, outstandingEntries); } } @@ -116,7 +116,7 @@ public class DatabaseDao { */ public TodorooCursor query(Query query) { query.from(table); - if(debug) + if (debug) Log.i("SQL-" + modelClass.getSimpleName(), query.toString()); //$NON-NLS-1$ Cursor cursor = database.rawQuery(query.toString(), null); return new TodorooCursor(cursor, query.getFields()); @@ -132,7 +132,7 @@ public class DatabaseDao { */ public TodorooCursor rawQuery(String selection, String[] selectionArgs, Property... properties) { String[] fields = new String[properties.length]; - for(int i = 0; i < properties.length; i++) + for (int i = 0; i < properties.length; i++) fields[i] = properties[i].name; return new TodorooCursor(database.getDatabase().query(table.name, fields, selection, selectionArgs, null, null, null), @@ -143,12 +143,9 @@ public class DatabaseDao { * Returns object corresponding to the given identifier * * @param database - * @param table - * name of table - * @param properties - * properties to read - * @param id - * id of item + * @param table name of table + * @param properties properties to read + * @param id id of item * @return null if no item found */ public TYPE fetch(long id, Property... properties) { @@ -193,6 +190,7 @@ public class DatabaseDao { /** * Delete all matching a clause + * * @param where predicate for deletion * @return # of deleted items */ @@ -203,14 +201,15 @@ public class DatabaseDao { /** * Update all matching a clause to have the values set on template object. - *

+ *

* Example (updates "joe" => "bob" in metadata value1): * {code} * Metadata item = new Metadata(); * item.setValue(Metadata.VALUE1, "bob"); * update(item, Metadata.VALUE1.eq("joe")); * {code} - * @param where sql criteria + * + * @param where sql criteria * @param template set fields on this object in order to set them in the db. * @return # of updated items */ @@ -241,8 +240,10 @@ public class DatabaseDao { Log.e(ERROR_TAG, "Error updating rows", new Throwable()); //$NON-NLS-1$ result.set(0); } + @Override public void onCommit() {/**/} + @Override public void onBegin() {/**/} }); @@ -299,7 +300,7 @@ public class DatabaseDao { boolean recordOutstanding = shouldRecordOutstanding(item); final AtomicBoolean result = new AtomicBoolean(false); - synchronized(database) { + synchronized (database) { if (recordOutstanding) { // begin transaction database.getDatabase().beginTransactionWithListener(new SQLiteTransactionListener() { @Override @@ -307,8 +308,10 @@ public class DatabaseDao { Log.e(ERROR_TAG, "Error inserting or updating rows", new Throwable()); //$NON-NLS-1$ result.set(false); } + @Override public void onCommit() {/**/} + @Override public void onBegin() {/**/} }); @@ -316,7 +319,7 @@ public class DatabaseDao { int numOutstanding = 0; try { result.set(op.makeChange()); - if(result.get()) { + if (result.get()) { if (recordOutstanding && ((numOutstanding = createOutstandingEntries(item.getId(), values)) != -1)) // Create entries for setValues in outstanding table database.getDatabase().setTransactionSuccessful(); } @@ -336,10 +339,8 @@ public class DatabaseDao { * Creates the given item. * * @param database - * @param table - * table name - * @param item - * item model + * @param table table name + * @param item item model * @return returns true on success. */ public boolean createNew(final TYPE item) { @@ -363,15 +364,13 @@ public class DatabaseDao { * Saves the given item. Will not create a new item! * * @param database - * @param table - * table name - * @param item - * item model + * @param table table name + * @param item item model * @return returns true on success. */ public boolean saveExisting(final TYPE item) { final ContentValues values = item.getSetValues(); - if(values == null || values.size() == 0) // nothing changed + if (values == null || values.size() == 0) // nothing changed return true; DatabaseChangeOp update = new DatabaseChangeOp() { @Override @@ -412,6 +411,7 @@ public class DatabaseDao { * Returns true if an entry in the outstanding table should be recorded for this * column. Subclasses can override to return false for insignificant columns * (e.g. Task.DETAILS, last modified, etc.) + * * @param columnName * @return */ @@ -426,12 +426,9 @@ public class DatabaseDao { * Returns cursor to object corresponding to the given identifier * * @param database - * @param table - * name of table - * @param properties - * properties to read - * @param id - * id of item + * @param table name of table + * @param properties properties to read + * @param id id of item * @return */ protected TodorooCursor fetchItem(long id, Property... properties) { diff --git a/api/src/com/todoroo/andlib/data/Property.java b/api/src/com/todoroo/andlib/data/Property.java index e481eb662..b773b5893 100644 --- a/api/src/com/todoroo/andlib/data/Property.java +++ b/api/src/com/todoroo/andlib/data/Property.java @@ -5,10 +5,6 @@ */ package com.todoroo.andlib.data; -import static com.todoroo.andlib.sql.SqlConstants.COMMA; -import static com.todoroo.andlib.sql.SqlConstants.LEFT_PARENTHESIS; -import static com.todoroo.andlib.sql.SqlConstants.RIGHT_PARENTHESIS; -import static com.todoroo.andlib.sql.SqlConstants.SPACE; import android.text.TextUtils; import com.todoroo.andlib.sql.Criterion; @@ -16,40 +12,59 @@ import com.todoroo.andlib.sql.Field; import com.todoroo.andlib.sql.Operator; import com.todoroo.andlib.sql.UnaryCriterion; +import static com.todoroo.andlib.sql.SqlConstants.COMMA; +import static com.todoroo.andlib.sql.SqlConstants.LEFT_PARENTHESIS; +import static com.todoroo.andlib.sql.SqlConstants.RIGHT_PARENTHESIS; +import static com.todoroo.andlib.sql.SqlConstants.SPACE; + /** * Property represents a typed column in a database. - * + *

* Within a given database row, the parameter may not exist, in which case the * value is null, it may be of an incorrect type, in which case an exception is * thrown, or the correct type, in which case the value is returned. * + * @param a database supported type, such as String or Integer * @author Tim Su - * - * @param - * a database supported type, such as String or Integer */ @SuppressWarnings("nls") public abstract class Property extends Field implements Cloneable { // --- implementation - /** The database table name this property */ + /** + * The database table name this property + */ public final Table table; - /** The database column name for this property */ + /** + * The database column name for this property + */ public final String name; - /** Can this field be null? */ + /** + * Can this field be null? + */ public static final int PROP_FLAG_NULLABLE = 1 << 0; - /** Is this field a date? */ + /** + * Is this field a date? + */ public static final int PROP_FLAG_DATE = 1 << 1; - /** Is this field a user id? */ + /** + * Is this field a user id? + */ public static final int PROP_FLAG_USER_ID = 1 << 2; - /** Is this field a boolean? */ + /** + * Is this field a boolean? + */ public static final int PROP_FLAG_BOOLEAN = 1 << 3; - /** Is this field a serialized JSON object? */ + /** + * Is this field a serialized JSON object? + */ public static final int PROP_FLAG_JSON = 1 << 4; - /** Is this field for pictures? (usually as a json object containing "path" key or urls) */ + /** + * Is this field for pictures? (usually as a json object containing "path" key or urls) + */ public static final int PROP_FLAG_PICTURE = 1 << 5; public int flags = 0; @@ -109,7 +124,7 @@ public abstract class Property extends Field implements Cloneable { try { Property newInstance = this.getClass().getConstructor(Table.class, String.class).newInstance(aliasedTable, this.name); - if(!TextUtils.isEmpty(columnAlias)) + if (!TextUtils.isEmpty(columnAlias)) return (Property) newInstance.as(columnAlias); return newInstance; } catch (Exception e) { @@ -123,7 +138,6 @@ public abstract class Property extends Field implements Cloneable { * Visitor interface for property classes * * @author Tim Su - * */ public interface PropertyVisitor { public RETURN visitInteger(Property property, PARAMETER data); @@ -141,7 +155,6 @@ public abstract class Property extends Field implements Cloneable { * Integer property type. See {@link Property} * * @author Tim Su - * */ public static class IntegerProperty extends Property { @@ -178,7 +191,6 @@ public abstract class Property extends Field implements Cloneable { * String property type. See {@link Property} * * @author Tim Su - * */ public static class StringProperty extends Property { @@ -230,7 +242,6 @@ public abstract class Property extends Field implements Cloneable { * Double property type. See {@link Property} * * @author Tim Su - * */ public static class DoubleProperty extends Property { @@ -263,7 +274,6 @@ public abstract class Property extends Field implements Cloneable { * Long property type. See {@link Property} * * @author Tim Su - * */ public static class LongProperty extends Property { @@ -308,7 +318,9 @@ public abstract class Property extends Field implements Cloneable { // --- pseudo-properties - /** Runs a SQL function and returns the result as a string */ + /** + * Runs a SQL function and returns the result as a string + */ public static class StringFunctionProperty extends StringProperty { public StringFunctionProperty(String function, String columnName) { super(null, columnName, function); @@ -316,7 +328,9 @@ public abstract class Property extends Field implements Cloneable { } } - /** Runs a SQL function and returns the result as a string */ + /** + * Runs a SQL function and returns the result as a string + */ public static class IntegerFunctionProperty extends IntegerProperty { public IntegerFunctionProperty(String function, String columnName) { super(null, columnName, function); @@ -324,7 +338,9 @@ public abstract class Property extends Field implements Cloneable { } } - /** Counting in aggregated tables. Returns the result of COUNT(1) */ + /** + * Counting in aggregated tables. Returns the result of COUNT(1) + */ public static final class CountProperty extends IntegerFunctionProperty { public CountProperty() { super("COUNT(1)", "count"); diff --git a/api/src/com/todoroo/andlib/data/Table.java b/api/src/com/todoroo/andlib/data/Table.java index 29da2cf77..26b9462f5 100644 --- a/api/src/com/todoroo/andlib/data/Table.java +++ b/api/src/com/todoroo/andlib/data/Table.java @@ -13,7 +13,6 @@ import com.todoroo.andlib.sql.SqlTable; * clone the table when it returns. * * @author Tim Su - * */ public final class Table extends SqlTable { public final String name; @@ -32,12 +31,13 @@ public final class Table extends SqlTable { /** * Reads a list of properties from model class by reflection + * * @return property array */ @SuppressWarnings("nls") public Property[] getProperties() { try { - return (Property[])modelClass.getField("PROPERTIES").get(null); + return (Property[]) modelClass.getField("PROPERTIES").get(null); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (SecurityException e) { @@ -61,25 +61,26 @@ public final class Table extends SqlTable { /** * Create a field object based on the given property + * * @param property * @return */ @SuppressWarnings("nls") public Field field(Property property) { - if(alias != null) + if (alias != null) return Field.field(alias + "." + property.name); return Field.field(name + "." + property.name); } @Override public String toString() { - if(hasAlias()) + if (hasAlias()) return expression + " AS " + alias; //$NON-NLS-1$ return expression; } public String name() { - if(hasAlias()) + if (hasAlias()) return alias; return name; } diff --git a/api/src/com/todoroo/andlib/data/TodorooCursor.java b/api/src/com/todoroo/andlib/data/TodorooCursor.java index 0f512911b..fc720a82e 100644 --- a/api/src/com/todoroo/andlib/data/TodorooCursor.java +++ b/api/src/com/todoroo/andlib/data/TodorooCursor.java @@ -5,35 +5,42 @@ */ package com.todoroo.andlib.data; -import java.util.WeakHashMap; - import android.database.Cursor; import android.database.CursorWrapper; import com.todoroo.andlib.data.Property.PropertyVisitor; +import java.util.WeakHashMap; + /** * AstridCursor wraps a cursor and allows users to query for individual * {@link Property} types or read an entire {@link AbstractModel} from * a database row. * - * @author Tim Su - * * @param a model type that is returned by this cursor + * @author Tim Su */ public class TodorooCursor extends CursorWrapper { - /** Properties read by this cursor */ + /** + * Properties read by this cursor + */ private final Property[] properties; - /** Weakly cache field name to column id references for this cursor. - * Because it's a weak hash map, entire keys can be discarded by GC */ + /** + * Weakly cache field name to column id references for this cursor. + * Because it's a weak hash map, entire keys can be discarded by GC + */ private final WeakHashMap columnIndexCache; - /** Property reading visitor */ + /** + * Property reading visitor + */ private static final CursorReadingVisitor reader = new CursorReadingVisitor(); - /** Wrapped cursor */ + /** + * Wrapped cursor + */ private final Cursor cursor; /** @@ -55,11 +62,11 @@ public class TodorooCursor extends CursorWrapper { * Get the value for the given property on the underlying {@link Cursor} * * @param type to return - * @param property to retrieve + * @param property to retrieve * @return */ public PROPERTY_TYPE get(Property property) { - return (PROPERTY_TYPE)property.accept(reader, this); + return (PROPERTY_TYPE) property.accept(reader, this); } /** @@ -71,6 +78,7 @@ public class TodorooCursor extends CursorWrapper { /** * Gets entire property list + * * @return */ public Property[] getProperties() { @@ -82,7 +90,7 @@ public class TodorooCursor extends CursorWrapper { */ public synchronized int getColumnIndexFromCache(String field) { Integer index = columnIndexCache.get(field); - if(index == null) { + if (index == null) { index = getColumnIndexOrThrow(field); columnIndexCache.put(field, index); } @@ -94,37 +102,36 @@ public class TodorooCursor extends CursorWrapper { * Visitor that reads the given property from a cursor * * @author Tim Su - * */ public static class CursorReadingVisitor implements PropertyVisitor> { public Object visitDouble(Property property, - TodorooCursor cursor) { + TodorooCursor cursor) { int column = columnIndex(property, cursor); - if(property.checkFlag(Property.PROP_FLAG_NULLABLE) && cursor.isNull(column)) + if (property.checkFlag(Property.PROP_FLAG_NULLABLE) && cursor.isNull(column)) return null; return cursor.getDouble(column); } public Object visitInteger(Property property, - TodorooCursor cursor) { + TodorooCursor cursor) { int column = columnIndex(property, cursor); - if(property.checkFlag(Property.PROP_FLAG_NULLABLE) && cursor.isNull(column)) + if (property.checkFlag(Property.PROP_FLAG_NULLABLE) && cursor.isNull(column)) return null; return cursor.getInt(column); } public Object visitLong(Property property, TodorooCursor cursor) { int column = columnIndex(property, cursor); - if(property.checkFlag(Property.PROP_FLAG_NULLABLE) && cursor.isNull(column)) + if (property.checkFlag(Property.PROP_FLAG_NULLABLE) && cursor.isNull(column)) return null; return cursor.getLong(column); } public Object visitString(Property property, - TodorooCursor cursor) { + TodorooCursor cursor) { int column = columnIndex(property, cursor); - if(property.checkFlag(Property.PROP_FLAG_NULLABLE) && cursor.isNull(column)) + if (property.checkFlag(Property.PROP_FLAG_NULLABLE) && cursor.isNull(column)) return null; return cursor.getString(column); } diff --git a/api/src/com/todoroo/andlib/service/AbstractDependencyInjector.java b/api/src/com/todoroo/andlib/service/AbstractDependencyInjector.java index b05fe770f..85ed10d26 100644 --- a/api/src/com/todoroo/andlib/service/AbstractDependencyInjector.java +++ b/api/src/com/todoroo/andlib/service/AbstractDependencyInjector.java @@ -5,19 +5,18 @@ */ package com.todoroo.andlib.service; +import com.todoroo.andlib.service.ExceptionService.ErrorReporter; + import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.util.HashMap; -import com.todoroo.andlib.service.ExceptionService.ErrorReporter; - /** * A Dependency Injector knows how to inject certain dependencies based * on the field that is passed in. You will need to write your own initialization * code to insert this dependency injector into the DI chain. * * @author Tim Su - * */ abstract public class AbstractDependencyInjector { @@ -48,29 +47,27 @@ abstract public class AbstractDependencyInjector { * Cache of classes that were instantiated by the injector */ protected final HashMap, WeakReference> createdObjects = - new HashMap, WeakReference>(); + new HashMap, WeakReference>(); /** * Gets the injected object for this field. If implementing class does not * know how to handle this dependency, it should return null * - * @param object - * object to perform dependency injection on - * @param field - * field tagged with {link Autowired} annotation + * @param object object to perform dependency injection on + * @param field field tagged with {link Autowired} annotation * @return object to assign to this field, or null */ public Object getInjection(Object object, Field field) { - if(injectables.containsKey(field.getName())) { + if (injectables.containsKey(field.getName())) { Object injection = injectables.get(field.getName()); // if it's a class, instantiate the class - if(injection instanceof Class) { - if(createdObjects.containsKey(injection) && + if (injection instanceof Class) { + if (createdObjects.containsKey(injection) && createdObjects.get(injection).get() != null) { injection = createdObjects.get(injection).get(); } else { - Class cls = (Class)injection; + Class cls = (Class) injection; try { injection = cls.newInstance(); } catch (IllegalAccessException e) { diff --git a/api/src/com/todoroo/andlib/service/Autowired.java b/api/src/com/todoroo/andlib/service/Autowired.java index 17de1ab8b..5bf26293c 100644 --- a/api/src/com/todoroo/andlib/service/Autowired.java +++ b/api/src/com/todoroo/andlib/service/Autowired.java @@ -11,11 +11,10 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * Autowired is an annotation that tells the dependency injector to + * Autowired is an annotation that tells the dependency injector to * set up the class as appropriate. - * - * @author Tim Su * + * @author Tim Su */ @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) diff --git a/api/src/com/todoroo/andlib/service/ContextManager.java b/api/src/com/todoroo/andlib/service/ContextManager.java index eeea1d5be..f3714157b 100644 --- a/api/src/com/todoroo/andlib/service/ContextManager.java +++ b/api/src/com/todoroo/andlib/service/ContextManager.java @@ -12,8 +12,8 @@ import android.content.res.Resources; /** * Singleton class to manage current application context * b - * @author Tim Su * + * @author Tim Su */ public final class ContextManager { @@ -28,9 +28,9 @@ public final class ContextManager { * @param context */ public static void setContext(Context context) { - if(context == null || context.getApplicationContext() == null) + if (context == null || context.getApplicationContext() == null) return; - if(ContextManager.context != null && !(context instanceof Activity)) + if (ContextManager.context != null && !(context instanceof Activity)) return; ContextManager.context = context; } @@ -45,7 +45,7 @@ public final class ContextManager { /** * Convenience method to read a string from the resources * - * @param resId resource + * @param resId resource * @param parameters % arguments * @return resource string */ diff --git a/api/src/com/todoroo/andlib/service/DependencyInjectionService.java b/api/src/com/todoroo/andlib/service/DependencyInjectionService.java index e5ea6ca0f..2d726d1b6 100644 --- a/api/src/com/todoroo/andlib/service/DependencyInjectionService.java +++ b/api/src/com/todoroo/andlib/service/DependencyInjectionService.java @@ -5,25 +5,23 @@ */ package com.todoroo.andlib.service; -import java.lang.reflect.Field; -import java.util.LinkedList; - import com.todoroo.andlib.service.ExceptionService.AndroidLogReporter; import com.todoroo.andlib.service.ExceptionService.ErrorReporter; +import java.lang.reflect.Field; +import java.util.LinkedList; /** * Simple Dependency Injection Service for Android. - *

+ *

* Add dependency injectors to the injector chain, then invoke this method * against classes you wish to perform dependency injection for. - *

+ *

* All errors encountered are handled as warnings, so if dependency injection * seems to be failing, check the logs for more information. * * @author Tim Su - * */ public class DependencyInjectionService { @@ -35,8 +33,7 @@ public class DependencyInjectionService { /** * Perform dependency injection in the caller object * - * @param caller - * object to perform DI on + * @param caller object to perform DI on */ @SuppressWarnings("nls") public void inject(Object caller) { @@ -45,13 +42,13 @@ public class DependencyInjectionService { // dependency injection to set them as appropriate Class cls = caller.getClass(); - while(cls != null) { + while (cls != null) { String packageName = cls.getPackage().getName(); - if(!isQualifiedPackage(packageName)) + if (!isQualifiedPackage(packageName)) break; - for(Field field : cls.getDeclaredFields()) { - if(field.getAnnotation(Autowired.class) != null) { + for (Field field : cls.getDeclaredFields()) { + if (field.getAnnotation(Autowired.class) != null) { field.setAccessible(true); try { handleField(caller, field); @@ -60,7 +57,7 @@ public class DependencyInjectionService { field.getName(), field.getType()), e); } catch (IllegalArgumentException e) { throw new RuntimeException(String.format("Unable to set field '%s' of type '%s'", - field.getName(), field.getType()), e); + field.getName(), field.getType()), e); } catch (IllegalAccessException e) { throw new RuntimeException(String.format("Unable to set field '%s' of type '%s'", field.getName(), field.getType()), e); @@ -74,11 +71,11 @@ public class DependencyInjectionService { @SuppressWarnings("nls") private boolean isQualifiedPackage(String packageName) { - if(packageName.startsWith("com.todoroo")) + if (packageName.startsWith("com.todoroo")) return true; - if(packageName.startsWith("com.timsu")) + if (packageName.startsWith("com.timsu")) return true; - if(packageName.startsWith("org.weloveastrid")) + if (packageName.startsWith("org.weloveastrid")) return true; return false; } @@ -87,17 +84,15 @@ public class DependencyInjectionService { * This method returns the appropriate dependency object based on the type * that this autowired field accepts * - * @param caller - * calling object - * @param field - * field to inject + * @param caller calling object + * @param field field to inject */ @SuppressWarnings("nls") private synchronized void handleField(Object caller, Field field) throws IllegalStateException, IllegalArgumentException, IllegalAccessException { - if(field.getType().isPrimitive()) + if (field.getType().isPrimitive()) throw new IllegalStateException(String.format( "Tried to dependency-inject primative field '%s' of type '%s'", field.getName(), field.getType())); @@ -117,7 +112,7 @@ public class DependencyInjectionService { throw new IllegalStateException( String.format("No dependency injector found for autowired " + - "field '%s' in class '%s'. Injectors: %s", + "field '%s' in class '%s'. Injectors: %s", field.getName(), caller.getClass().getName(), injectors)); } @@ -130,7 +125,7 @@ public class DependencyInjectionService { protected void addInjectables() { injectables.put("debug", false); injectables.put("exceptionService", ExceptionService.class); - injectables.put("errorReporters", new ErrorReporter[] { + injectables.put("errorReporters", new ErrorReporter[]{ new AndroidLogReporter(), }); } @@ -147,16 +142,18 @@ public class DependencyInjectionService { /** * Gets the singleton instance of the dependency injection service. + * * @return */ public synchronized static DependencyInjectionService getInstance() { - if(instance == null) + if (instance == null) instance = new DependencyInjectionService(); return instance; } /** * Removes the supplied injector + * * @return */ public synchronized void removeInjector(AbstractDependencyInjector injector) { @@ -165,6 +162,7 @@ public class DependencyInjectionService { /** * Adds a Dependency Injector to the front of the list + * * @param injectors */ public synchronized void addInjector(AbstractDependencyInjector injector) { diff --git a/api/src/com/todoroo/andlib/service/ExceptionService.java b/api/src/com/todoroo/andlib/service/ExceptionService.java index cd481d29f..b022f2f23 100644 --- a/api/src/com/todoroo/andlib/service/ExceptionService.java +++ b/api/src/com/todoroo/andlib/service/ExceptionService.java @@ -5,8 +5,6 @@ */ package com.todoroo.andlib.service; -import java.lang.Thread.UncaughtExceptionHandler; - import android.app.Activity; import android.app.AlertDialog; import android.content.Context; @@ -16,11 +14,12 @@ import android.util.Log; import com.todoroo.astrid.api.R; +import java.lang.Thread.UncaughtExceptionHandler; + /** * Exception handling utility class - reports and logs errors * * @author Tim Su - * */ public class ExceptionService { @@ -29,8 +28,8 @@ public class ExceptionService { public ExceptionService() { DependencyInjectionService.getInstance().inject(this); - if(errorReporters == null) { - errorReporters = new ErrorReporter[] { + if (errorReporters == null) { + errorReporters = new ErrorReporter[]{ new AndroidLogReporter() }; } @@ -39,14 +38,14 @@ public class ExceptionService { /** * Report the error via registered error handlers * - * @param name Internal error name. Not displayed to user + * @param name Internal error name. Not displayed to user * @param error Exception encountered. Message will be displayed to user */ public void reportError(String name, Throwable error) { - if(errorReporters == null) + if (errorReporters == null) return; - for(ErrorReporter reporter : errorReporters) { + for (ErrorReporter reporter : errorReporters) { try { reporter.handleError(name, error); } catch (Exception e) { @@ -59,28 +58,28 @@ public class ExceptionService { * Display error dialog if context is activity and report error * * @param context Application Context - * @param name Internal error name. Not displayed to user - * @param error Exception encountered. Message will be displayed to user + * @param name Internal error name. Not displayed to user + * @param error Exception encountered. Message will be displayed to user */ public void displayAndReportError(final Context context, String name, Throwable error) { - if(context instanceof Activity) { + if (context instanceof Activity) { final String messageToDisplay; // pretty up the message when displaying to user - if(error == null) + if (error == null) messageToDisplay = context.getString(R.string.DLG_error_generic); else messageToDisplay = context.getString(R.string.DLG_error, error); - ((Activity)context).runOnUiThread(new Runnable() { + ((Activity) context).runOnUiThread(new Runnable() { public void run() { try { new AlertDialog.Builder(context) - .setTitle(R.string.DLG_error_title) - .setMessage(messageToDisplay) - .setIcon(android.R.drawable.ic_dialog_alert) - .setPositiveButton(android.R.string.ok, null) - .show(); + .setTitle(R.string.DLG_error_title) + .setMessage(messageToDisplay) + .setIcon(android.R.drawable.ic_dialog_alert) + .setPositiveButton(android.R.string.ok, null) + .show(); } catch (Exception e) { // suppress errors during dialog creation } @@ -95,7 +94,6 @@ public class ExceptionService { * Error reporter interface * * @author Tim Su - * */ public interface ErrorReporter { public void handleError(String name, Throwable error); @@ -105,7 +103,6 @@ public class ExceptionService { * AndroidLogReporter reports errors to LogCat * * @author Tim Su - * */ public static class AndroidLogReporter implements ErrorReporter { @@ -117,21 +114,21 @@ public class ExceptionService { */ public void handleError(String name, Throwable error) { String tag = null; - if(ContextManager.getContext() != null) { + if (ContextManager.getContext() != null) { PackageManager pm = ContextManager.getContext().getPackageManager(); try { String appName = pm.getApplicationInfo(ContextManager.getContext(). getPackageName(), 0).loadLabel(pm).toString(); - tag = appName + "-" + name; //$NON-NLS-1$ + tag = appName + "-" + name; //$NON-NLS-1$ } catch (NameNotFoundException e) { // give up } } - if(tag == null) + if (tag == null) tag = "unknown-" + name; //$NON-NLS-1$ - if(error == null) + if (error == null) Log.e(tag, "Exception: " + name); //$NON-NLS-1$ else Log.e(tag, error.toString(), error); @@ -143,7 +140,6 @@ public class ExceptionService { * report errors * * @author Tim Su - * */ public static class TodorooUncaughtExceptionHandler implements UncaughtExceptionHandler { private final UncaughtExceptionHandler defaultUEH; @@ -157,7 +153,7 @@ public class ExceptionService { } public void uncaughtException(Thread thread, Throwable ex) { - if(exceptionService != null) + if (exceptionService != null) exceptionService.reportError("uncaught", ex); //$NON-NLS-1$ defaultUEH.uncaughtException(thread, ex); } diff --git a/api/src/com/todoroo/andlib/service/HttpRestClient.java b/api/src/com/todoroo/andlib/service/HttpRestClient.java index e2c514279..bcdf25584 100644 --- a/api/src/com/todoroo/andlib/service/HttpRestClient.java +++ b/api/src/com/todoroo/andlib/service/HttpRestClient.java @@ -5,10 +5,9 @@ */ package com.todoroo.andlib.service; -import java.io.IOException; -import java.io.InputStream; -import java.lang.ref.WeakReference; -import java.util.zip.GZIPInputStream; +import android.util.Log; + +import com.todoroo.andlib.utility.AndroidUtilities; import org.apache.http.Header; import org.apache.http.HeaderElement; @@ -37,15 +36,15 @@ import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.protocol.HttpContext; -import android.util.Log; - -import com.todoroo.andlib.utility.AndroidUtilities; +import java.io.IOException; +import java.io.InputStream; +import java.lang.ref.WeakReference; +import java.util.zip.GZIPInputStream; /** * RestClient allows Android to consume web requests. * * @author Tim Su - * */ public class HttpRestClient implements RestClient { @@ -108,7 +107,7 @@ public class HttpRestClient implements RestClient { final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (!request.containsHeader("Accept-Encoding")) - request.addHeader("Accept-Encoding", "gzip"); + request.addHeader("Accept-Encoding", "gzip"); } }); @@ -141,7 +140,7 @@ public class HttpRestClient implements RestClient { @Override public InputStream getContent() - throws IOException, IllegalStateException { + throws IOException, IllegalStateException { // the wrapped entity's getContent() decides about repeatability InputStream wrappedin = wrappedEntity.getContent(); @@ -159,7 +158,7 @@ public class HttpRestClient implements RestClient { private String processHttpResponse(HttpResponse response) throws IOException { int statusCode = response.getStatusLine().getStatusCode(); - if(statusCode >= HTTP_UNAVAILABLE_START && statusCode <= HTTP_UNAVAILABLE_END) { + if (statusCode >= HTTP_UNAVAILABLE_START && statusCode <= HTTP_UNAVAILABLE_END) { throw new HttpUnavailableException(); } @@ -175,7 +174,7 @@ public class HttpRestClient implements RestClient { } } - if(statusCode != HTTP_OK) { + if (statusCode != HTTP_OK) { System.out.println(body); throw new HttpErrorException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); @@ -192,7 +191,7 @@ public class HttpRestClient implements RestClient { * @throws IOException */ public synchronized String get(String url) throws IOException { - if(debug) + if (debug) Log.d("http-rest-client-get", url); //$NON-NLS-1$ try { @@ -213,18 +212,17 @@ public class HttpRestClient implements RestClient { * Issue an HTTP POST for the given URL, return the response * * @param url - * @param data - * url-encoded data + * @param data url-encoded data * @throws IOException */ public synchronized String post(String url, HttpEntity data, Header... headers) throws IOException { - if(debug) + if (debug) Log.d("http-rest-client-post", url + " | " + data); //$NON-NLS-1$ //$NON-NLS-2$ try { HttpPost httpPost = new HttpPost(url); httpPost.setEntity(data); - for(Header header : headers) + for (Header header : headers) httpPost.addHeader(header); HttpResponse response = getClient().execute(httpPost); diff --git a/api/src/com/todoroo/andlib/service/HttpUnavailableException.java b/api/src/com/todoroo/andlib/service/HttpUnavailableException.java index 6aea1cb4c..857da6964 100644 --- a/api/src/com/todoroo/andlib/service/HttpUnavailableException.java +++ b/api/src/com/todoroo/andlib/service/HttpUnavailableException.java @@ -11,7 +11,6 @@ import java.io.IOException; * Exception displayed when a 500 error is received on an HTTP invocation * * @author Tim Su - * */ public class HttpUnavailableException extends IOException { diff --git a/api/src/com/todoroo/andlib/service/NotificationManager.java b/api/src/com/todoroo/andlib/service/NotificationManager.java index 95e4a1cac..666343bca 100644 --- a/api/src/com/todoroo/andlib/service/NotificationManager.java +++ b/api/src/com/todoroo/andlib/service/NotificationManager.java @@ -12,7 +12,6 @@ import android.content.Context; * Notification Manager stub * * @author Tim Su - * */ public interface NotificationManager { @@ -27,13 +26,13 @@ public interface NotificationManager { * Android's notification manager * * @author Tim Su - * */ public static class AndroidNotificationManager implements NotificationManager { private final android.app.NotificationManager nm; + public AndroidNotificationManager(Context context) { nm = (android.app.NotificationManager) - context.getSystemService(Context.NOTIFICATION_SERVICE); + context.getSystemService(Context.NOTIFICATION_SERVICE); } public void cancel(int id) { diff --git a/api/src/com/todoroo/andlib/service/RestClient.java b/api/src/com/todoroo/andlib/service/RestClient.java index 5c0851835..26d2cabc3 100644 --- a/api/src/com/todoroo/andlib/service/RestClient.java +++ b/api/src/com/todoroo/andlib/service/RestClient.java @@ -5,18 +5,18 @@ */ package com.todoroo.andlib.service; -import java.io.IOException; - import org.apache.http.Header; import org.apache.http.HttpEntity; +import java.io.IOException; + /** * RestClient stub invokes the HTML requests as desired * * @author Tim Su - * */ public interface RestClient { public String get(String url) throws IOException; + public String post(String url, HttpEntity data, Header... headers) throws IOException; } \ No newline at end of file diff --git a/api/src/com/todoroo/andlib/sql/DBObject.java b/api/src/com/todoroo/andlib/sql/DBObject.java index d10da034b..f95851003 100644 --- a/api/src/com/todoroo/andlib/sql/DBObject.java +++ b/api/src/com/todoroo/andlib/sql/DBObject.java @@ -12,7 +12,7 @@ public abstract class DBObject> implements Cloneable { protected String alias; protected final String expression; - protected DBObject(String expression){ + protected DBObject(String expression) { this.expression = expression; } @@ -38,7 +38,8 @@ public abstract class DBObject> implements Cloneable { DBObject dbObject = (DBObject) o; if (alias != null ? !alias.equals(dbObject.alias) : dbObject.alias != null) return false; - if (expression != null ? !expression.equals(dbObject.expression) : dbObject.expression != null) return false; + if (expression != null ? !expression.equals(dbObject.expression) : dbObject.expression != null) + return false; return true; } @@ -64,7 +65,7 @@ public abstract class DBObject> implements Cloneable { sb.append(SPACE).append(AS).append(SPACE).append(alias); } else { int pos = expression.indexOf('.'); - if(pos > 0) + if (pos > 0) sb.append(SPACE).append(AS).append(SPACE).append(expression.substring(pos + 1)); } return sb.toString(); diff --git a/api/src/com/todoroo/andlib/sql/Field.java b/api/src/com/todoroo/andlib/sql/Field.java index 56bd55416..6cfe2048e 100644 --- a/api/src/com/todoroo/andlib/sql/Field.java +++ b/api/src/com/todoroo/andlib/sql/Field.java @@ -23,14 +23,14 @@ public class Field extends DBObject { } public Criterion eq(Object value) { - if(value == null) + if (value == null) return UnaryCriterion.isNull(this); return UnaryCriterion.eq(this, value); } /** * Adds the criterion that the field must be equal to the given string, ignoring case. - * + *

* Thanks to a sqlite bug, this will only work for ASCII values. * * @param value string which field must equal @@ -38,14 +38,14 @@ public class Field extends DBObject { */ @SuppressWarnings("nls") public Criterion eqCaseInsensitive(String value) { - if(value == null) + if (value == null) return UnaryCriterion.isNull(this); String escaped = value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_"); return UnaryCriterion.like(this, escaped, "\\"); } public Criterion neq(Object value) { - if(value == null) + if (value == null) return UnaryCriterion.isNotNull(this); return UnaryCriterion.neq(this, value); } diff --git a/api/src/com/todoroo/andlib/sql/Functions.java b/api/src/com/todoroo/andlib/sql/Functions.java index 1436f1857..a818c71ac 100644 --- a/api/src/com/todoroo/andlib/sql/Functions.java +++ b/api/src/com/todoroo/andlib/sql/Functions.java @@ -10,15 +10,13 @@ import com.todoroo.andlib.data.Property.LongProperty; import com.todoroo.andlib.data.Property.StringProperty; - - @SuppressWarnings("nls") public final class Functions { public static String caseStatement(Criterion when, Object ifTrue, Object ifFalse) { return new StringBuilder("(CASE WHEN "). - append(when.toString()).append(" THEN ").append(value(ifTrue)). - append(" ELSE ").append(value(ifFalse)).append(" END)").toString(); + append(when.toString()).append(" THEN ").append(value(ifTrue)). + append(" ELSE ").append(value(ifFalse)).append(" END)").toString(); } private static String value(Object value) { diff --git a/api/src/com/todoroo/andlib/sql/Operator.java b/api/src/com/todoroo/andlib/sql/Operator.java index 5e28d8e79..b94a0259e 100644 --- a/api/src/com/todoroo/andlib/sql/Operator.java +++ b/api/src/com/todoroo/andlib/sql/Operator.java @@ -5,11 +5,11 @@ */ package com.todoroo.andlib.sql; -import static com.todoroo.andlib.sql.SqlConstants.SPACE; - import java.util.HashMap; import java.util.Map; +import static com.todoroo.andlib.sql.SqlConstants.SPACE; + @SuppressWarnings("nls") public final class Operator { @@ -47,7 +47,7 @@ public final class Operator { } public Operator getContrary() { - if(!contraryRegistry.containsKey(this)){ + if (!contraryRegistry.containsKey(this)) { Operator opposite = new Operator(not.toString() + SPACE + this.toString()); contraryRegistry.put(this, opposite); contraryRegistry.put(opposite, this); diff --git a/api/src/com/todoroo/andlib/sql/Order.java b/api/src/com/todoroo/andlib/sql/Order.java index 70479da90..9630ac8a1 100644 --- a/api/src/com/todoroo/andlib/sql/Order.java +++ b/api/src/com/todoroo/andlib/sql/Order.java @@ -5,11 +5,11 @@ */ package com.todoroo.andlib.sql; -import static com.todoroo.andlib.sql.SqlConstants.SPACE; - import java.util.ArrayList; import java.util.List; +import static com.todoroo.andlib.sql.SqlConstants.SPACE; + public class Order { private final Object expression; private final List secondaryExpressions; @@ -45,8 +45,8 @@ public class Order { public String toString() { StringBuilder sb = new StringBuilder(); sb.append(expression.toString()) - .append(SPACE) - .append(orderType.toString()); + .append(SPACE) + .append(orderType.toString()); for (Order secondary : secondaryExpressions) { sb.append(", ").append(secondary.toString()); //$NON-NLS-1$ @@ -56,7 +56,7 @@ public class Order { } public Order reverse() { - if(orderType == OrderType.ASC) + if (orderType == OrderType.ASC) return new Order(expression, OrderType.DESC); else return new Order(expression, OrderType.ASC); diff --git a/api/src/com/todoroo/andlib/sql/Query.java b/api/src/com/todoroo/andlib/sql/Query.java index cefbcd5ce..77694d297 100644 --- a/api/src/com/todoroo/andlib/sql/Query.java +++ b/api/src/com/todoroo/andlib/sql/Query.java @@ -5,6 +5,17 @@ */ package com.todoroo.andlib.sql; +import android.content.ContentResolver; +import android.database.Cursor; +import android.net.Uri; + +import com.todoroo.andlib.data.Property; +import com.todoroo.astrid.api.AstridApiConstants; + +import java.util.ArrayList; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + import static com.todoroo.andlib.sql.SqlConstants.ALL; import static com.todoroo.andlib.sql.SqlConstants.COMMA; import static com.todoroo.andlib.sql.SqlConstants.DISTINCT; @@ -21,17 +32,6 @@ import static com.todoroo.andlib.sql.SqlConstants.WHERE; import static com.todoroo.andlib.sql.SqlTable.table; import static java.util.Arrays.asList; -import java.util.ArrayList; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import android.content.ContentResolver; -import android.database.Cursor; -import android.net.Uri; - -import com.todoroo.andlib.data.Property; -import com.todoroo.astrid.api.AstridApiConstants; - public final class Query { private SqlTable table; @@ -117,14 +117,14 @@ public final class Query { visitFromClause(sql); visitJoinClause(sql); - if(queryTemplate == null) { + if (queryTemplate == null) { visitWhereClause(sql); visitGroupByClause(sql); visitUnionClause(sql); visitOrderByClause(sql); visitLimitClause(sql); } else { - if(groupBies.size() > 0 || orders.size() > 0 || + if (groupBies.size() > 0 || orders.size() > 0 || havings.size() > 0) throw new IllegalStateException("Can't have extras AND query template"); //$NON-NLS-1$ sql.append(queryTemplate); @@ -198,7 +198,7 @@ public final class Query { private void visitSelectClause(StringBuilder sql) { sql.append(SELECT).append(SPACE); - if(distinct) + if (distinct) sql.append(DISTINCT).append(SPACE); if (fields.isEmpty()) { sql.append(ALL).append(SPACE); @@ -211,7 +211,7 @@ public final class Query { } private void visitLimitClause(StringBuilder sql) { - if(limits > -1) + if (limits > -1) sql.append(LIMIT).append(SPACE).append(limits).append(SPACE); } @@ -226,6 +226,7 @@ public final class Query { /** * Gets a list of fields returned by this query + * * @return */ public Property[] getFields() { @@ -234,6 +235,7 @@ public final class Query { /** * Add the SQL query template (comes after the "from") + * * @param template * @return query */ @@ -244,6 +246,7 @@ public final class Query { /** * Parse out properties and run query + * * @param cr * @param baseUri * @return @@ -251,24 +254,24 @@ public final class Query { public Cursor queryContentResolver(ContentResolver cr, Uri baseUri) { Uri uri = baseUri; - if(joins.size() != 0) + if (joins.size() != 0) throw new UnsupportedOperationException("can't perform join in content resolver query"); //$NON-NLS-1$ String[] projection = new String[fields.size()]; - for(int i = 0; i < projection.length; i++) + for (int i = 0; i < projection.length; i++) projection[i] = fields.get(i).toString(); StringBuilder groupByClause = new StringBuilder(); StringBuilder selectionClause = new StringBuilder(); StringBuilder orderClause = new StringBuilder(); - if(queryTemplate != null) { + if (queryTemplate != null) { QueryTemplateHelper.queryForContentResolver(queryTemplate, selectionClause, orderClause, groupByClause); } else { - if(groupBies.size() > 0) { + if (groupBies.size() > 0) { for (Field groupBy : groupBies) groupByClause.append(SPACE).append(groupBy).append(COMMA); - if(groupByClause.length() > 0) + if (groupByClause.length() > 0) groupByClause.deleteCharAt(groupByClause.length() - 1); } @@ -277,39 +280,43 @@ public final class Query { for (Order order : orders) orderClause.append(SPACE).append(order).append(COMMA); - if(orderClause.length() > 0) + if (orderClause.length() > 0) orderClause.deleteCharAt(orderClause.length() - 1); } - if(groupByClause.length() > 0) + if (groupByClause.length() > 0) uri = Uri.withAppendedPath(baseUri, AstridApiConstants.GROUP_BY_URI + groupByClause.toString().trim()); return cr.query(uri, projection, selectionClause.toString(), null, orderClause.toString()); } - /** query template helper */ + /** + * query template helper + */ public static class QueryTemplateHelper { - /** build a content resolver query */ + /** + * build a content resolver query + */ @SuppressWarnings("nls") public static void queryForContentResolver(String queryTemplate, - StringBuilder selectionClause, StringBuilder orderClause, - StringBuilder groupByClause) { + StringBuilder selectionClause, StringBuilder orderClause, + StringBuilder groupByClause) { Pattern where = Pattern.compile("WHERE (.*?)(LIMIT|HAVING|GROUP|ORDER|\\Z)"); Matcher whereMatcher = where.matcher(queryTemplate); - if(whereMatcher.find()) + if (whereMatcher.find()) selectionClause.append(whereMatcher.group(1).trim()); Pattern group = Pattern.compile("GROUP BY (.*?)(LIMIT|HAVING|ORDER|\\Z)"); Matcher groupMatcher = group.matcher(queryTemplate); - if(groupMatcher.find()) + if (groupMatcher.find()) groupByClause.append(groupMatcher.group(1).trim()); Pattern order = Pattern.compile("ORDER BY (.*?)(LIMIT|HAVING|\\Z)"); Matcher orderMatcher = order.matcher(queryTemplate); - if(orderMatcher.find()) + if (orderMatcher.find()) orderClause.append(orderMatcher.group(1).trim()); } diff --git a/api/src/com/todoroo/andlib/sql/QueryTemplate.java b/api/src/com/todoroo/andlib/sql/QueryTemplate.java index ce46495bc..7abd50e42 100644 --- a/api/src/com/todoroo/andlib/sql/QueryTemplate.java +++ b/api/src/com/todoroo/andlib/sql/QueryTemplate.java @@ -5,6 +5,8 @@ */ package com.todoroo.andlib.sql; +import java.util.ArrayList; + import static com.todoroo.andlib.sql.SqlConstants.COMMA; import static com.todoroo.andlib.sql.SqlConstants.GROUP_BY; import static com.todoroo.andlib.sql.SqlConstants.LIMIT; @@ -13,14 +15,11 @@ import static com.todoroo.andlib.sql.SqlConstants.SPACE; import static com.todoroo.andlib.sql.SqlConstants.WHERE; import static java.util.Arrays.asList; -import java.util.ArrayList; - /** * Query Template returns a bunch of criteria that allows a query to be * constructed * * @author Tim Su - * */ public final class QueryTemplate { @@ -58,7 +57,7 @@ public final class QueryTemplate { visitWhereClause(sql); visitGroupByClause(sql); visitOrderByClause(sql); - if(limit != null) + if (limit != null) sql.append(LIMIT).append(SPACE).append(limit); return sql.toString(); } diff --git a/api/src/com/todoroo/andlib/sql/SqlTable.java b/api/src/com/todoroo/andlib/sql/SqlTable.java index a486df954..3baa5d4d0 100644 --- a/api/src/com/todoroo/andlib/sql/SqlTable.java +++ b/api/src/com/todoroo/andlib/sql/SqlTable.java @@ -20,6 +20,6 @@ public class SqlTable extends DBObject { if (hasAlias()) { return alias + "." + fieldName; } - return expression+"."+fieldName; + return expression + "." + fieldName; } } diff --git a/api/src/com/todoroo/andlib/sql/UnaryCriterion.java b/api/src/com/todoroo/andlib/sql/UnaryCriterion.java index a23db5e2c..ff48d58c2 100644 --- a/api/src/com/todoroo/andlib/sql/UnaryCriterion.java +++ b/api/src/com/todoroo/andlib/sql/UnaryCriterion.java @@ -38,9 +38,9 @@ public class UnaryCriterion extends Criterion { @SuppressWarnings("nls") protected void afterPopulateOperator(StringBuilder sb) { - if(value == null) + if (value == null) return; - else if(value instanceof String) + else if (value instanceof String) sb.append("'").append(sanitize((String) value)).append("'"); else sb.append(value); @@ -48,6 +48,7 @@ public class UnaryCriterion extends Criterion { /** * Sanitize the given input for SQL + * * @param input * @return */ @@ -109,6 +110,7 @@ public class UnaryCriterion extends Criterion { protected void populateOperator(StringBuilder sb) { sb.append(SPACE).append(operator).append(SPACE); } + @SuppressWarnings("nls") @Override protected void afterPopulateOperator(StringBuilder sb) { diff --git a/api/src/com/todoroo/andlib/utility/AndroidUtilities.java b/api/src/com/todoroo/andlib/utility/AndroidUtilities.java index 4b0fc9c70..9274c0626 100644 --- a/api/src/com/todoroo/andlib/utility/AndroidUtilities.java +++ b/api/src/com/todoroo/andlib/utility/AndroidUtilities.java @@ -5,34 +5,6 @@ */ package com.todoroo.andlib.utility; -import java.io.BufferedInputStream; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.lang.reflect.Array; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.math.BigInteger; -import java.net.URL; -import java.net.URLConnection; -import java.security.MessageDigest; -import java.util.Arrays; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - import android.app.Activity; import android.content.BroadcastReceiver; import android.content.ContentValues; @@ -60,11 +32,38 @@ import android.widget.TextView; import com.todoroo.andlib.service.ExceptionService; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.BufferedInputStream; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.lang.reflect.Array; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.math.BigInteger; +import java.net.URL; +import java.net.URLConnection; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + /** * Android Utility Classes * * @author Tim Su - * */ public class AndroidUtilities { @@ -73,7 +72,9 @@ public class AndroidUtilities { // --- utility methods - /** Suppress virtual keyboard until user's first tap */ + /** + * Suppress virtual keyboard until user's first tap + */ public static void suppressVirtualKeyboard(final TextView editor) { final int inputType = editor.getInputType(); editor.setInputType(InputType.TYPE_NULL); @@ -91,7 +92,7 @@ public class AndroidUtilities { */ public static boolean isConnected(Context context) { ConnectivityManager manager = (ConnectivityManager) - context.getSystemService(Context.CONNECTIVITY_SERVICE); + context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo(); if (info == null) return false; @@ -100,7 +101,9 @@ public class AndroidUtilities { return true; } - /** Fetch the image specified by the given url */ + /** + * Fetch the image specified by the given url + */ public static Bitmap fetchImage(URL url) throws IOException { InputStream is = null; try { @@ -115,20 +118,23 @@ public class AndroidUtilities { bis.close(); } } finally { - if(is != null) + if (is != null) is.close(); } } - /** Read a bitmap from the specified file, scaling if necessary - * Returns null if scaling failed after several tries */ - private static final int[] SAMPLE_SIZES = { 1, 2, 4, 6, 8, 10 }; + /** + * Read a bitmap from the specified file, scaling if necessary + * Returns null if scaling failed after several tries + */ + private static final int[] SAMPLE_SIZES = {1, 2, 4, 6, 8, 10}; private static final int MAX_DIM = 1024; + public static Bitmap readScaledBitmap(String file) { Bitmap bitmap = null; int tries = 0; BitmapFactory.Options opts = new BitmapFactory.Options(); - while((bitmap == null || (bitmap.getWidth() > MAX_DIM || bitmap.getHeight() > MAX_DIM)) && tries < SAMPLE_SIZES.length) { + while ((bitmap == null || (bitmap.getWidth() > MAX_DIM || bitmap.getHeight() > MAX_DIM)) && tries < SAMPLE_SIZES.length) { opts.inSampleSize = SAMPLE_SIZES[tries]; try { bitmap = BitmapFactory.decodeFile(file, opts); @@ -151,8 +157,8 @@ public class AndroidUtilities { */ public static void startExternalIntent(Context context, Intent intent, int request) { try { - if(request > -1 && context instanceof Activity) - ((Activity)context).startActivityForResult(intent, request); + if (request > -1 && context instanceof Activity) + ((Activity) context).startActivityForResult(intent, request); else context.startActivity(intent); } catch (Exception e) { @@ -182,6 +188,7 @@ public class AndroidUtilities { /** * Put an arbitrary object into a {@link ContentValues} + * * @param target * @param key * @param value @@ -210,6 +217,7 @@ public class AndroidUtilities { /** * Put an arbitrary object into a {@link ContentValues} + * * @param target * @param key * @param value @@ -244,7 +252,7 @@ public class AndroidUtilities { public static String[][] contentValuesToStringArrays(ContentValues source) { String[][] result = new String[2][source.size()]; int i = 0; - for(Entry entry : source.valueSet()) { + for (Entry entry : source.valueSet()) { result[0][i] = entry.getKey(); result[1][i++] = entry.getValue().toString(); } @@ -253,19 +261,21 @@ public class AndroidUtilities { /** * Return index of value in array + * * @param array array to search * @param value value to look for * @return */ public static int indexOf(TYPE[] array, TYPE value) { - for(int i = 0; i < array.length; i++) - if(array[i].equals(value)) + for (int i = 0; i < array.length; i++) + if (array[i].equals(value)) return i; return -1; } /** * Return index of value in integer array + * * @param array array to search * @param value value to look for * @return @@ -282,24 +292,26 @@ public class AndroidUtilities { */ public static String contentValuesToSerializedString(ContentValues source) { StringBuilder result = new StringBuilder(); - for(Entry entry : source.valueSet()) { + for (Entry entry : source.valueSet()) { addSerialized(result, entry.getKey(), entry.getValue()); } return result.toString(); } - /** add serialized helper */ + /** + * add serialized helper + */ private static void addSerialized(StringBuilder result, - String key, Object value) { + String key, Object value) { result.append(key.replace(SERIALIZATION_SEPARATOR, SEPARATOR_ESCAPE)).append( SERIALIZATION_SEPARATOR); - if(value instanceof Integer) + if (value instanceof Integer) result.append('i').append(value); - else if(value instanceof Double) + else if (value instanceof Double) result.append('d').append(value); - else if(value instanceof Long) + else if (value instanceof Long) result.append('l').append(value); - else if(value instanceof String) + else if (value instanceof String) result.append('s').append(value.toString().replace(SERIALIZATION_SEPARATOR, SEPARATOR_ESCAPE)); else if (value instanceof Boolean) result.append('b').append(value); @@ -316,7 +328,7 @@ public class AndroidUtilities { if (source == null) return null; - for(String key : source.keySet()) { + for (String key : source.keySet()) { addSerialized(result, key, source.get(key)); } return result.toString(); @@ -324,32 +336,33 @@ public class AndroidUtilities { /** * Turn ContentValues into a string + * * @param string * @return */ public static ContentValues contentValuesFromSerializedString(String string) { - if(string == null) + if (string == null) return new ContentValues(); ContentValues result = new ContentValues(); fromSerialized(string, result, new SerializedPut() { public void put(ContentValues object, String key, char type, String value) throws NumberFormatException { - switch(type) { - case 'i': - object.put(key, Integer.parseInt(value)); - break; - case 'd': - object.put(key, Double.parseDouble(value)); - break; - case 'l': - object.put(key, Long.parseLong(value)); - break; - case 's': - object.put(key, value.replace(SEPARATOR_ESCAPE, SERIALIZATION_SEPARATOR)); - break; - case 'b': - object.put(key, Boolean.parseBoolean(value)); - break; + switch (type) { + case 'i': + object.put(key, Integer.parseInt(value)); + break; + case 'd': + object.put(key, Double.parseDouble(value)); + break; + case 'l': + object.put(key, Long.parseLong(value)); + break; + case 's': + object.put(key, value.replace(SEPARATOR_ESCAPE, SERIALIZATION_SEPARATOR)); + break; + case 'b': + object.put(key, Boolean.parseBoolean(value)); + break; } } }); @@ -358,32 +371,33 @@ public class AndroidUtilities { /** * Turn {@link android.os.Bundle} into a string + * * @param string * @return */ public static Bundle bundleFromSerializedString(String string) { - if(string == null) + if (string == null) return new Bundle(); Bundle result = new Bundle(); fromSerialized(string, result, new SerializedPut() { public void put(Bundle object, String key, char type, String value) throws NumberFormatException { - switch(type) { - case 'i': - object.putInt(key, Integer.parseInt(value)); - break; - case 'd': - object.putDouble(key, Double.parseDouble(value)); - break; - case 'l': - object.putLong(key, Long.parseLong(value)); - break; - case 's': - object.putString(key, value.replace(SEPARATOR_ESCAPE, SERIALIZATION_SEPARATOR)); - break; - case 'b': - object.putBoolean(key, Boolean.parseBoolean(value)); - break; + switch (type) { + case 'i': + object.putInt(key, Integer.parseInt(value)); + break; + case 'd': + object.putDouble(key, Double.parseDouble(value)); + break; + case 'l': + object.putLong(key, Long.parseLong(value)); + break; + case 's': + object.putString(key, value.replace(SEPARATOR_ESCAPE, SERIALIZATION_SEPARATOR)); + break; + case 'b': + object.putBoolean(key, Boolean.parseBoolean(value)); + break; } } }); @@ -397,12 +411,12 @@ public class AndroidUtilities { @SuppressWarnings("nls") private static void fromSerialized(String string, T object, SerializedPut putter) { String[] pairs = string.split("\\" + SERIALIZATION_SEPARATOR); //$NON-NLS-1$ - for(int i = 0; i < pairs.length; i += 2) { + for (int i = 0; i < pairs.length; i += 2) { try { String key = pairs[i].replaceAll(SEPARATOR_ESCAPE, SERIALIZATION_SEPARATOR); - String value = pairs[i+1].substring(1); + String value = pairs[i + 1].substring(1); try { - putter.put(object, key, pairs[i+1].charAt(0), value); + putter.put(object, key, pairs[i + 1].charAt(0), value); } catch (NumberFormatException e) { // failed parse to number putter.put(object, key, 's', value); @@ -414,31 +428,30 @@ public class AndroidUtilities { } - - /** * Turn ContentValues into a string + * * @param string * @return */ @SuppressWarnings("nls") public static ContentValues contentValuesFromString(String string) { - if(string == null) + if (string == null) return null; String[] pairs = string.split("="); ContentValues result = new ContentValues(); String key = null; - for(int i = 0; i < pairs.length; i++) { + for (int i = 0; i < pairs.length; i++) { String newKey = null; int lastSpace = pairs[i].lastIndexOf(' '); - if(lastSpace != -1) { + if (lastSpace != -1) { newKey = pairs[i].substring(lastSpace + 1); pairs[i] = pairs[i].substring(0, lastSpace); } else { - newKey = pairs[i]; + newKey = pairs[i]; } - if(key != null) + if (key != null) result.put(key.trim(), pairs[i].trim()); key = newKey; } @@ -447,14 +460,15 @@ public class AndroidUtilities { /** * Returns true if a and b or null or a.equals(b) + * * @param a * @param b * @return */ public static boolean equals(Object a, Object b) { - if(a == null && b == null) + if (a == null && b == null) return true; - if(a == null) + if (a == null) return false; return a.equals(b); } @@ -481,6 +495,7 @@ public class AndroidUtilities { /** * Copy stream from source to destination + * * @param source * @param dest * @throws IOException @@ -507,20 +522,21 @@ public class AndroidUtilities { /** * Find a child view of a certain type + * * @param view * @param type * @return first view (by DFS) if found, or null if none */ public static TYPE findViewByType(View view, Class type) { - if(view == null) + if (view == null) return null; - if(type.isInstance(view)) + if (type.isInstance(view)) return (TYPE) view; - if(view instanceof ViewGroup) { + if (view instanceof ViewGroup) { ViewGroup group = (ViewGroup) view; - for(int i = 0; i < group.getChildCount(); i++) { + for (int i = 0; i < group.getChildCount(); i++) { TYPE v = findViewByType(group.getChildAt(i), type); - if(v != null) + if (v != null) return v; } } @@ -536,13 +552,14 @@ public class AndroidUtilities { /** * Copy databases to a given folder. Useful for debugging + * * @param folder */ public static void copyDatabases(Context context, String folder) { File folderFile = new File(folder); - if(!folderFile.exists()) + if (!folderFile.exists()) folderFile.mkdir(); - for(String db : context.databaseList()) { + for (String db : context.databaseList()) { File dbFile = context.getDatabasePath(db); try { copyFile(dbFile, new File(folderFile.getAbsolutePath() + @@ -555,6 +572,7 @@ public class AndroidUtilities { /** * Sort files by date so the newest file is on top + * * @param files */ public static void sortFilesByDateDesc(File[] files) { @@ -567,13 +585,14 @@ public class AndroidUtilities { /** * Search for the given value in the map, returning key if found + * * @param map * @param value * @return null if not found, otherwise key */ - public static KEY findKeyInMap(Map map, VALUE value){ - for (Entry entry: map.entrySet()) { - if(entry.getValue().equals(value)) + public static KEY findKeyInMap(Map map, VALUE value) { + for (Entry entry : map.entrySet()) { + if (entry.getValue().equals(value)) return entry.getKey(); } return null; @@ -597,30 +616,31 @@ public class AndroidUtilities { * If you want to set a transition, please use this method rather than callApiMethod to ensure * you really pass an Activity-instance. * - * @param activity the activity-instance for which to set the finish-transition + * @param activity the activity-instance for which to set the finish-transition * @param enterAnim the incoming-transition of the next activity - * @param exitAnim the outgoing-transition of this activity + * @param exitAnim the outgoing-transition of this activity */ public static void callOverridePendingTransition(Activity activity, int enterAnim, int exitAnim) { callApiMethod(5, activity, "overridePendingTransition", //$NON-NLS-1$ - new Class[] { Integer.TYPE, Integer.TYPE }, + new Class[]{Integer.TYPE, Integer.TYPE}, enterAnim, exitAnim); } /** * Call a method via reflection if API level is at least minSdk - * @param minSdk minimum sdk number (i.e. 8) - * @param receiver object to call method on + * + * @param minSdk minimum sdk number (i.e. 8) + * @param receiver object to call method on * @param methodName method name to call - * @param params method parameter types - * @param args arguments + * @param params method parameter types + * @param args arguments * @return method return value, or null if nothing was called or exception */ public static Object callApiMethod(int minSdk, Object receiver, - String methodName, Class[] params, Object... args) { - if(getSdkVersion() < minSdk) + String methodName, Class[] params, Object... args) { + if (getSdkVersion() < minSdk) return null; return AndroidUtilities.callMethod(receiver.getClass(), @@ -629,17 +649,18 @@ public class AndroidUtilities { /** * Call a static method via reflection if API level is at least minSdk - * @param minSdk minimum sdk number (i.e. 8) - * @param className fully qualified class to call method on + * + * @param minSdk minimum sdk number (i.e. 8) + * @param className fully qualified class to call method on * @param methodName method name to call - * @param params method parameter types - * @param args arguments + * @param params method parameter types + * @param args arguments * @return method return value, or null if nothing was called or exception */ @SuppressWarnings("nls") public static Object callApiStaticMethod(int minSdk, String className, - String methodName, Class[] params, Object... args) { - if(getSdkVersion() < minSdk) + String methodName, Class[] params, Object... args) { + if (getSdkVersion() < minSdk) return null; try { @@ -653,16 +674,17 @@ public class AndroidUtilities { /** * Call a method via reflection - * @param class class to call method on - * @param receiver object to call method on (can be null) + * + * @param class class to call method on + * @param receiver object to call method on (can be null) * @param methodName method name to call - * @param params method parameter types - * @param args arguments + * @param params method parameter types + * @param args arguments * @return method return value, or null if nothing was called or exception */ @SuppressWarnings("nls") public static Object callMethod(Class cls, Object receiver, - String methodName, Class[] params, Object... args) { + String methodName, Class[] params, Object... args) { try { Method method = cls.getMethod(methodName, params); Object result = method.invoke(receiver, args); @@ -685,6 +707,7 @@ public class AndroidUtilities { /** * From Android MyTracks project (http://mytracks.googlecode.com/). * Licensed under the Apache Public License v2 + * * @param activity * @param id * @return @@ -738,6 +761,7 @@ public class AndroidUtilities { /** * Performs an md5 hash on the input string + * * @param input * @return */ @@ -747,9 +771,9 @@ public class AndroidUtilities { byte[] bytesOfMessage = input.getBytes("UTF-8"); MessageDigest md = MessageDigest.getInstance("MD5"); byte[] digest = md.digest(bytesOfMessage); - BigInteger bigInt = new BigInteger(1,digest); + BigInteger bigInt = new BigInteger(1, digest); String hashtext = bigInt.toString(16); - while(hashtext.length() < 32 ){ + while (hashtext.length() < 32) { hashtext = "0" + hashtext; } return hashtext; @@ -760,6 +784,7 @@ public class AndroidUtilities { /** * Create an intent to a remote activity + * * @param appPackage * @param activityClass * @return @@ -772,6 +797,7 @@ public class AndroidUtilities { /** * Gets application signature + * * @return application signature, or null if an error was encountered */ public static String getSignature(Context context, String packageName) { @@ -786,6 +812,7 @@ public class AndroidUtilities { /** * Join items to a list + * * @param * @param list * @param newList @@ -804,11 +831,11 @@ public class AndroidUtilities { T[] newList = (T[]) Array.newInstance(type, length); if (list != null) { - for(int i = 0; i < list.length; i++) + for (int i = 0; i < list.length; i++) newList[i] = list[i]; } if (newItems != null) { - for(int i = 0; i < newItems.length; i++) + for (int i = 0; i < newItems.length; i++) newList[originalListLength + i] = newItems[i]; } return newList; @@ -819,9 +846,9 @@ public class AndroidUtilities { private static ExceptionService exceptionService = null; private static ExceptionService getExceptionService() { - if(exceptionService == null) - synchronized(AndroidUtilities.class) { - if(exceptionService == null) + if (exceptionService == null) + synchronized (AndroidUtilities.class) { + if (exceptionService == null) exceptionService = new ExceptionService(); } return exceptionService; @@ -829,16 +856,17 @@ public class AndroidUtilities { /** * Concatenate additional stuff to the end of the array + * * @param params * @param additional * @return */ public static TYPE[] concat(TYPE[] dest, TYPE[] source, TYPE... additional) { int i = 0; - for(; i < Math.min(dest.length, source.length); i++) + for (; i < Math.min(dest.length, source.length); i++) dest[i] = source[i]; int base = i; - for(; i < dest.length; i++) + for (; i < dest.length; i++) dest[i] = additional[i - base]; return dest; } @@ -847,6 +875,7 @@ public class AndroidUtilities { * Returns a map where the keys are the values of the map argument * and the values are the corresponding keys. Use at your own * risk if your map is not 1-to-1! + * * @param map * @return */ @@ -862,6 +891,7 @@ public class AndroidUtilities { /** * Capitalize the first character + * * @param string * @return */ @@ -871,11 +901,12 @@ public class AndroidUtilities { /** * Dismiss the keyboard if it is displayed by any of the listed views + * * @param context - * @param views - a list of views that might potentially be displaying the keyboard + * @param views - a list of views that might potentially be displaying the keyboard */ - public static void hideSoftInputForViews(Context context, View...views) { - InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE); + public static void hideSoftInputForViews(Context context, View... views) { + InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); for (View v : views) { imm.hideSoftInputFromWindow(v.getWindowToken(), 0); } @@ -883,6 +914,7 @@ public class AndroidUtilities { /** * Returns true if the screen is large or xtra large + * * @param context * @return */ @@ -914,6 +946,7 @@ public class AndroidUtilities { /** * Wraps a call to Activity.unregisterReceiver in a try/catch block to prevent * exceptions being thrown if receiver was never registered with that activity + * * @param activity * @param receiver */ @@ -965,6 +998,7 @@ public class AndroidUtilities { /** * Returns the final word characters after the last '.' + * * @param file * @return */ diff --git a/api/src/com/todoroo/andlib/utility/DateUtilities.java b/api/src/com/todoroo/andlib/utility/DateUtilities.java index 32ea38579..285bf5b2f 100644 --- a/api/src/com/todoroo/andlib/utility/DateUtilities.java +++ b/api/src/com/todoroo/andlib/utility/DateUtilities.java @@ -5,6 +5,12 @@ */ package com.todoroo.andlib.utility; +import android.content.Context; +import android.text.format.DateFormat; +import android.text.format.DateUtils; + +import com.todoroo.astrid.api.R; + import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; @@ -12,12 +18,6 @@ import java.util.Calendar; import java.util.Date; import java.util.Locale; -import android.content.Context; -import android.text.format.DateFormat; -import android.text.format.DateUtils; - -import com.todoroo.astrid.api.R; - public class DateUtilities { @@ -25,16 +25,20 @@ public class DateUtilities { * ============================================================ long time * ====================================================================== */ - /** Convert unixtime into date */ + /** + * Convert unixtime into date + */ public static final Date unixtimeToDate(long millis) { - if(millis == 0) + if (millis == 0) return null; return new Date(millis); } - /** Convert date into unixtime */ + /** + * Convert date into unixtime + */ public static final long dateToUnixtime(Date date) { - if(date == null) + if (date == null) return 0; return date.getTime(); } @@ -43,7 +47,7 @@ public class DateUtilities { * Add the specified amount of months to the given time.
* The day of month will stay the same.
* - * @param time the base-time (in milliseconds) to which the amount of months is added + * @param time the base-time (in milliseconds) to which the amount of months is added * @param interval the amount of months to be added * @return the calculated time in milliseconds */ @@ -54,28 +58,40 @@ public class DateUtilities { return c.getTimeInMillis(); } - /** Returns unixtime for current time */ + /** + * Returns unixtime for current time + */ public static final long now() { return System.currentTimeMillis(); } - /** Returns unixtime one month from now */ + /** + * Returns unixtime one month from now + */ public static final long oneMonthFromNow() { Date date = new Date(); date.setMonth(date.getMonth() + 1); return date.getTime(); } - /** Represents a single hour */ + /** + * Represents a single hour + */ public static final long ONE_HOUR = 3600000L; - /** Represents a single day */ + /** + * Represents a single day + */ public static final long ONE_DAY = 24 * ONE_HOUR; - /** Represents a single week */ + /** + * Represents a single week + */ public static final long ONE_WEEK = 7 * ONE_DAY; - /** Represents a single minute */ + /** + * Represents a single minute + */ public static final long ONE_MINUTE = 60000L; /* ====================================================================== @@ -85,7 +101,7 @@ public class DateUtilities { static Boolean is24HourOverride = null; public static boolean is24HourFormat(Context context) { - if(is24HourOverride != null) + if (is24HourOverride != null) return is24HourOverride; return DateFormat.is24HourFormat(context); @@ -93,7 +109,7 @@ public class DateUtilities { /** * @param context android context - * @param date time to format + * @param date time to format * @return time, with hours and minutes */ @SuppressWarnings("nls") @@ -101,10 +117,9 @@ public class DateUtilities { String value; if (is24HourFormat(context)) { value = "H:mm"; - } else if (date.getMinutes() == 0 && excludeZeroMinutes){ + } else if (date.getMinutes() == 0 && excludeZeroMinutes) { value = "h a"; - } - else { + } else { value = "h:mm a"; } return new SimpleDateFormat(value).format(date); @@ -122,7 +137,7 @@ public class DateUtilities { /** * @param context android context - * @param date date to format + * @param date date to format * @return date, with month, day, and year */ @SuppressWarnings("nls") @@ -134,20 +149,21 @@ public class DateUtilities { // united states, you are special Locale locale = Locale.getDefault(); if (arrayBinaryContains(locale.getLanguage(), "ja", "ko", "zh") - || arrayBinaryContains(locale.getCountry(), "BZ", "CA", "KE", "MN" ,"US")) + || arrayBinaryContains(locale.getCountry(), "BZ", "CA", "KE", "MN", "US")) value = "'#' d'$'"; else value = "d'$' '#'"; if (includeYear) value += ", yyyy"; - if (arrayBinaryContains(locale.getLanguage(), "ja", "zh")){ + if (arrayBinaryContains(locale.getLanguage(), "ja", "zh")) { standardDate = new SimpleDateFormat(value).format(date).replace("#", month).replace("$", "\u65E5"); //$NON-NLS-1$ - }else if ("ko".equals(Locale.getDefault().getLanguage())){ + } else if ("ko".equals(Locale.getDefault().getLanguage())) { standardDate = new SimpleDateFormat(value).format(date).replace("#", month).replace("$", "\uC77C"); //$NON-NLS-1$ - }else{ + } else { standardDate = new SimpleDateFormat(value).format(date).replace("#", month).replace("$", ""); } - return standardDate;} + return standardDate; + } public static String getDateString(Context context, Date date) { return getDateString(context, date, true); @@ -155,7 +171,7 @@ public class DateUtilities { /** * @param context android context - * @param date date to format + * @param date date to format * @return date, with month, day, and year */ @SuppressWarnings("nls") @@ -166,12 +182,12 @@ public class DateUtilities { Locale locale = Locale.getDefault(); // united states, you are special if (arrayBinaryContains(locale.getLanguage(), "ja", "ko", "zh") - || arrayBinaryContains(locale.getCountry(), "BZ", "CA", "KE", "MN" ,"US")) + || arrayBinaryContains(locale.getCountry(), "BZ", "CA", "KE", "MN", "US")) value = "'#' d"; else value = "d '#'"; - if (date.getYear() != (new Date()).getYear()) { + if (date.getYear() != (new Date()).getYear()) { value = value + "\nyyyy"; } if (arrayBinaryContains(locale.getLanguage(), "ja", "zh")) //$NON-NLS-1$ @@ -231,16 +247,16 @@ public class DateUtilities { long today = clearTime(new Date()); long input = clearTime(new Date(date)); - if(today == input) + if (today == input) return context.getString(R.string.today).toLowerCase(); - if(today + ONE_DAY == input) + if (today + ONE_DAY == input) return context.getString(abbreviated ? R.string.tmrw : R.string.tomorrow).toLowerCase(); - if(today == input + ONE_DAY) + if (today == input + ONE_DAY) return context.getString(abbreviated ? R.string.yest : R.string.yesterday).toLowerCase(); - if(today + DateUtilities.ONE_WEEK >= input && + if (today + DateUtilities.ONE_WEEK >= input && today - DateUtilities.ONE_WEEK <= input) return abbreviated ? DateUtilities.getWeekdayShort(new Date(date)) : DateUtilities.getWeekday(new Date(date)); @@ -270,6 +286,7 @@ public class DateUtilities { } private static final Calendar calendar = Calendar.getInstance(); + public static long getStartOfDay(long time) { calendar.setTimeInMillis(time); calendar.set(Calendar.HOUR, 0); diff --git a/api/src/com/todoroo/andlib/utility/DialogUtilities.java b/api/src/com/todoroo/andlib/utility/DialogUtilities.java index 1d9d30da4..328124eea 100644 --- a/api/src/com/todoroo/andlib/utility/DialogUtilities.java +++ b/api/src/com/todoroo/andlib/utility/DialogUtilities.java @@ -27,21 +27,21 @@ public class DialogUtilities { * @param okListener */ public static void viewDialog(final Activity activity, final String text, - final View view, final DialogInterface.OnClickListener okListener, - final DialogInterface.OnClickListener cancelListener) { - if(activity.isFinishing()) + final View view, final DialogInterface.OnClickListener okListener, + final DialogInterface.OnClickListener cancelListener) { + if (activity.isFinishing()) return; tryOnUiThread(activity, new Runnable() { public void run() { new AlertDialog.Builder(activity) - .setTitle(R.string.DLG_question_title) - .setMessage(text) - .setView(view) - .setIcon(android.R.drawable.ic_dialog_alert) - .setPositiveButton(android.R.string.ok, okListener) - .setNegativeButton(android.R.string.cancel, cancelListener) - .show().setOwnerActivity(activity); + .setTitle(R.string.DLG_question_title) + .setMessage(text) + .setView(view) + .setIcon(android.R.drawable.ic_dialog_alert) + .setPositiveButton(android.R.string.ok, okListener) + .setNegativeButton(android.R.string.cancel, cancelListener) + .show().setOwnerActivity(activity); } }); } @@ -60,11 +60,11 @@ public class DialogUtilities { webView.setBackgroundColor(0); new AlertDialog.Builder(context) - .setTitle(title) - .setView(webView) - .setIcon(android.R.drawable.ic_dialog_info) - .setPositiveButton(android.R.string.ok, null) - .show(); + .setTitle(title) + .setView(webView) + .setIcon(android.R.drawable.ic_dialog_info) + .setPositiveButton(android.R.string.ok, null) + .show(); } /** @@ -75,18 +75,18 @@ public class DialogUtilities { * @param okListener */ public static void okDialog(final Activity activity, final String text, - final DialogInterface.OnClickListener okListener) { - if(activity.isFinishing()) + final DialogInterface.OnClickListener okListener) { + if (activity.isFinishing()) return; tryOnUiThread(activity, new Runnable() { public void run() { new AlertDialog.Builder(activity) - .setTitle(R.string.DLG_information_title) - .setMessage(text) - .setIcon(android.R.drawable.ic_dialog_alert) - .setPositiveButton(android.R.string.ok, okListener) - .show().setOwnerActivity(activity); + .setTitle(R.string.DLG_information_title) + .setMessage(text) + .setIcon(android.R.drawable.ic_dialog_alert) + .setPositiveButton(android.R.string.ok, okListener) + .show().setOwnerActivity(activity); } }); } @@ -99,19 +99,19 @@ public class DialogUtilities { * @param okListener */ public static void okDialog(final Activity activity, final String title, - final int icon, final CharSequence text, - final DialogInterface.OnClickListener okListener) { - if(activity.isFinishing()) + final int icon, final CharSequence text, + final DialogInterface.OnClickListener okListener) { + if (activity.isFinishing()) return; tryOnUiThread(activity, new Runnable() { public void run() { new AlertDialog.Builder(activity) - .setTitle(title) - .setMessage(text) - .setIcon(icon) - .setPositiveButton(android.R.string.ok, okListener) - .show().setOwnerActivity(activity); + .setTitle(title) + .setMessage(text) + .setIcon(icon) + .setPositiveButton(android.R.string.ok, okListener) + .show().setOwnerActivity(activity); } }); } @@ -126,8 +126,8 @@ public class DialogUtilities { * @param cancelListener */ public static void okCancelDialog(final Activity activity, final String title, - final String text, final DialogInterface.OnClickListener okListener, - final DialogInterface.OnClickListener cancelListener) { + final String text, final DialogInterface.OnClickListener okListener, + final DialogInterface.OnClickListener cancelListener) { okCancelCustomDialog(activity, title, text, android.R.string.ok, android.R.string.cancel, android.R.drawable.ic_dialog_alert, okListener, cancelListener); } @@ -141,40 +141,42 @@ public class DialogUtilities { * @param cancelListener */ public static void okCancelDialog(final Activity activity, final String text, - final DialogInterface.OnClickListener okListener, - final DialogInterface.OnClickListener cancelListener) { + final DialogInterface.OnClickListener okListener, + final DialogInterface.OnClickListener cancelListener) { okCancelCustomDialog(activity, activity.getString(R.string.DLG_confirm_title), text, android.R.string.ok, android.R.string.cancel, android.R.drawable.ic_dialog_alert, okListener, cancelListener); } /** - * Displays a dialog box with custom titled OK and cancel button titles - */ + * Displays a dialog box with custom titled OK and cancel button titles + */ public static void okCancelCustomDialog(final Activity activity, final String title, final String text, - final int okTitleId, final int cancelTitleId, - final int icon, - final DialogInterface.OnClickListener okListener, - final DialogInterface.OnClickListener cancelListener) { - if(activity.isFinishing()) + final int okTitleId, final int cancelTitleId, + final int icon, + final DialogInterface.OnClickListener okListener, + final DialogInterface.OnClickListener cancelListener) { + if (activity.isFinishing()) return; tryOnUiThread(activity, new Runnable() { public void run() { new AlertDialog.Builder(activity) - .setTitle(R.string.DLG_confirm_title) - .setMessage(text) - .setTitle(title) - .setIcon(icon) - .setPositiveButton(okTitleId, okListener) - .setNegativeButton(cancelTitleId, cancelListener) - .show().setOwnerActivity(activity); + .setTitle(R.string.DLG_confirm_title) + .setMessage(text) + .setTitle(title) + .setIcon(icon) + .setPositiveButton(okTitleId, okListener) + .setNegativeButton(cancelTitleId, cancelListener) + .show().setOwnerActivity(activity); } }); } - /** Run runnable with progress dialog */ + /** + * Run runnable with progress dialog + */ public static ProgressDialog runWithProgressDialog(final Activity activity, final Runnable runnable) { final ProgressDialog progressdiag = progressDialog(activity, activity.getString(R.string.DLG_wait)); new Thread(new Runnable() { @@ -196,6 +198,7 @@ public class DialogUtilities { /** * Displays a progress dialog. Must be run on the UI thread + * * @param context * @param text * @return @@ -217,7 +220,7 @@ public class DialogUtilities { * @param dialog */ public static void dismissDialog(Activity activity, final Dialog dialog) { - if(dialog == null) + if (dialog == null) return; tryOnUiThread(activity, new Runnable() { public void run() { diff --git a/api/src/com/todoroo/andlib/utility/Pair.java b/api/src/com/todoroo/andlib/utility/Pair.java index 822ce4ee2..a44618ec1 100644 --- a/api/src/com/todoroo/andlib/utility/Pair.java +++ b/api/src/com/todoroo/andlib/utility/Pair.java @@ -8,10 +8,9 @@ package com.todoroo.andlib.utility; /** * Pair utility class * - * @author Tim Su - * * @param * @param + * @author Tim Su */ public class Pair { diff --git a/api/src/com/todoroo/andlib/utility/Preferences.java b/api/src/com/todoroo/andlib/utility/Preferences.java index 95ab91812..e5fa865da 100644 --- a/api/src/com/todoroo/andlib/utility/Preferences.java +++ b/api/src/com/todoroo/andlib/utility/Preferences.java @@ -17,7 +17,6 @@ import com.todoroo.andlib.service.ContextManager; * Helper class for reading and writing SharedPreferences * * @author Tim Su - * */ public class Preferences { @@ -33,12 +32,13 @@ public class Preferences { */ public static void setIfUnset(SharedPreferences prefs, Editor editor, Resources r, int keyResource, int value) { String key = r.getString(keyResource); - if(!prefs.contains(key)) + if (!prefs.contains(key)) editor.putString(key, Integer.toString(value)); } /** * Helper to write to editor if key specified is null + * * @param prefs * @param editor * @param r @@ -47,12 +47,13 @@ public class Preferences { */ public static void setIfUnset(SharedPreferences prefs, Editor editor, Resources r, int keyResource, boolean value) { String key = r.getString(keyResource); - if(!prefs.contains(key) || !(prefs.getAll().get(key) instanceof Boolean)) + if (!prefs.contains(key) || !(prefs.getAll().get(key) instanceof Boolean)) editor.putBoolean(key, value); } /** * Helper to write to editor if key specified is null + * * @param prefs * @param editor * @param r @@ -61,7 +62,7 @@ public class Preferences { */ public static void setIfUnset(SharedPreferences prefs, Editor editor, Resources r, int keyResource, String value) { String key = r.getString(keyResource); - if(!prefs.contains(key) || !(prefs.getAll().get(key) instanceof String)) + if (!prefs.contains(key) || !(prefs.getAll().get(key) instanceof String)) editor.putString(key, value); } @@ -71,9 +72,11 @@ public class Preferences { private static SharedPreferences preferences = null; - /** Get preferences object from the context */ + /** + * Get preferences object from the context + */ public static SharedPreferences getPrefs(Context context) { - if(preferences != null) + if (preferences != null) return preferences; context = context.getApplicationContext(); @@ -91,7 +94,9 @@ public class Preferences { return preferences; } - /** @return true if given preference is set */ + /** + * @return true if given preference is set + */ public static boolean isSet(String key) { Context context = ContextManager.getContext(); return getPrefs(context).contains(key); @@ -99,7 +104,8 @@ public class Preferences { // --- preference fetching (string) - /** Gets an string value from a string preference. Returns null + /** + * Gets an string value from a string preference. Returns null * if the value is not set * * @param context @@ -111,7 +117,8 @@ public class Preferences { return getPrefs(context).getString(key, null); } - /** Gets an string value from a string preference. Returns null + /** + * Gets an string value from a string preference. Returns null * if the value is not set * * @param context @@ -123,7 +130,8 @@ public class Preferences { return getPrefs(context).getString(context.getResources().getString(keyResource), null); } - /** Gets an integer value from a string preference. Returns null + /** + * Gets an integer value from a string preference. Returns null * if the value is not set or not an integer. * * @param keyResource resource from string.xml @@ -133,7 +141,7 @@ public class Preferences { Context context = ContextManager.getContext(); Resources r = context.getResources(); String value = getPrefs(context).getString(r.getString(keyResource), null); - if(value == null) + if (value == null) return defaultValue; try { @@ -143,7 +151,8 @@ public class Preferences { } } - /** Gets an float value from a string preference. Returns null + /** + * Gets an float value from a string preference. Returns null * if the value is not set or not an flat. * * @param keyResource resource from string.xml @@ -191,7 +200,8 @@ public class Preferences { // --- preference fetching (boolean) - /** Gets a boolean preference (e.g. a CheckBoxPreference setting) + /** + * Gets a boolean preference (e.g. a CheckBoxPreference setting) * * @param key * @param defValue @@ -206,7 +216,8 @@ public class Preferences { } } - /** Gets a boolean preference (e.g. a CheckBoxPreference setting) + /** + * Gets a boolean preference (e.g. a CheckBoxPreference setting) * * @param keyResource * @param defValue @@ -218,6 +229,7 @@ public class Preferences { /** * Sets boolean preference + * * @param key * @param value */ @@ -227,6 +239,7 @@ public class Preferences { /** * Sets boolean preference + * * @param key * @param value */ @@ -239,7 +252,8 @@ public class Preferences { // --- preference fetching (int) - /** Gets a int preference + /** + * Gets a int preference * * @param key * @param defValue @@ -252,6 +266,7 @@ public class Preferences { /** * Sets int preference + * * @param key * @param value */ @@ -264,7 +279,8 @@ public class Preferences { // --- preference fetching (long) - /** Gets a long preference + /** + * Gets a long preference * * @param key * @param defValue @@ -277,6 +293,7 @@ public class Preferences { /** * Sets long preference + * * @param key * @param value */ @@ -289,6 +306,7 @@ public class Preferences { /** * Clears a preference + * * @param key */ public static void clear(String key) { diff --git a/api/src/com/todoroo/andlib/utility/TodorooPreferenceActivity.java b/api/src/com/todoroo/andlib/utility/TodorooPreferenceActivity.java index 5f9dd8921..2f95518f9 100644 --- a/api/src/com/todoroo/andlib/utility/TodorooPreferenceActivity.java +++ b/api/src/com/todoroo/andlib/utility/TodorooPreferenceActivity.java @@ -29,7 +29,6 @@ import com.todoroo.andlib.service.ContextManager; * updatePreferences to update the summary with preference values. * * @author Tim Su - * */ abstract public class TodorooPreferenceActivity extends PreferenceActivity { @@ -39,8 +38,9 @@ abstract public class TodorooPreferenceActivity extends PreferenceActivity { /** * Update preferences for the given preference + * * @param preference - * @param value setting. may be null. + * @param value setting. may be null. */ public abstract void updatePreferences(Preference preference, Object value); @@ -60,21 +60,21 @@ abstract public class TodorooPreferenceActivity extends PreferenceActivity { } protected void initializePreference(Preference preference) { - if(preference instanceof PreferenceGroup) { - PreferenceGroup group = (PreferenceGroup)preference; - for(int i = 0; i < group.getPreferenceCount(); i++) { + if (preference instanceof PreferenceGroup) { + PreferenceGroup group = (PreferenceGroup) preference; + for (int i = 0; i < group.getPreferenceCount(); i++) { initializePreference(group.getPreference(i)); } updatePreferences(group, null); } else { Object value = null; - if(preference instanceof ListPreference) - value = ((ListPreference)preference).getValue(); - else if(preference instanceof CheckBoxPreference) - value = ((CheckBoxPreference)preference).isChecked(); - else if(preference instanceof EditTextPreference) - value = ((EditTextPreference)preference).getText(); - else if(preference instanceof RingtonePreference) + if (preference instanceof ListPreference) + value = ((ListPreference) preference).getValue(); + else if (preference instanceof CheckBoxPreference) + value = ((CheckBoxPreference) preference).isChecked(); + else if (preference instanceof EditTextPreference) + value = ((EditTextPreference) preference).getText(); + else if (preference instanceof RingtonePreference) value = getPreferenceManager().getSharedPreferences().getString(preference.getKey(), null); updatePreferences(preference, value); @@ -93,7 +93,7 @@ abstract public class TodorooPreferenceActivity extends PreferenceActivity { @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); - if(hasFocus) { + if (hasFocus) { initializePreference(getPreferenceScreen()); } } diff --git a/api/src/com/todoroo/astrid/api/Addon.java b/api/src/com/todoroo/astrid/api/Addon.java index bf3e1ecaf..d97d92973 100644 --- a/api/src/com/todoroo/astrid/api/Addon.java +++ b/api/src/com/todoroo/astrid/api/Addon.java @@ -13,7 +13,6 @@ import android.os.Parcelable; * which affect all other extension points that share the same identifier. * * @author Tim Su - * */ public class Addon implements Parcelable { @@ -89,7 +88,9 @@ public class Addon implements Parcelable { */ public Addon[] newArray(int size) { return new Addon[size]; - }; + } + + ; }; } diff --git a/api/src/com/todoroo/astrid/api/AstridApiConstants.java b/api/src/com/todoroo/astrid/api/AstridApiConstants.java index 5f7a499a9..f36206a15 100644 --- a/api/src/com/todoroo/astrid/api/AstridApiConstants.java +++ b/api/src/com/todoroo/astrid/api/AstridApiConstants.java @@ -70,7 +70,7 @@ public class AstridApiConstants { /** * Extras name for old task due date */ - public static final String EXTRAS_OLD_DUE_DATE= "oldDueDate"; + public static final String EXTRAS_OLD_DUE_DATE = "oldDueDate"; /** * Extras name for new task due date @@ -144,7 +144,7 @@ public class AstridApiConstants { /** * Action name for broadcast intent requesting details for a task. * Extended details are displayed when a user presses on a task. - * + *

*

  • EXTRAS_TASK_ID id of the task *
  • EXTRAS_EXTENDED whether request is for standard or extended details */ diff --git a/api/src/com/todoroo/astrid/api/CustomFilterCriterion.java b/api/src/com/todoroo/astrid/api/CustomFilterCriterion.java index 0e2b2bcef..bbf671057 100644 --- a/api/src/com/todoroo/astrid/api/CustomFilterCriterion.java +++ b/api/src/com/todoroo/astrid/api/CustomFilterCriterion.java @@ -15,13 +15,12 @@ import android.os.Parcelable; * together criteria * * @author Tim Su - * */ abstract public class CustomFilterCriterion implements Parcelable { /** * Criteria Identifier. This identifier allows saved filters to be reloaded. - *

    + *

    * e.g "duedate" */ public String identifier; @@ -29,7 +28,7 @@ abstract public class CustomFilterCriterion implements Parcelable { /** * Criteria Title. If the title contains ?, this is replaced by the entry * label string selected. - *

    + *

    * e.g "Due: ?" */ public String text; @@ -37,7 +36,7 @@ abstract public class CustomFilterCriterion implements Parcelable { /** * Criterion SQL. This query should return task id's. If this contains * ?, it will be replaced by the entry value - *

    + *

    * Examples: *

      *
    • SELECT _id FROM tasks WHERE dueDate <= ? @@ -86,8 +85,8 @@ abstract public class CustomFilterCriterion implements Parcelable { identifier = source.readString(); text = source.readString(); sql = source.readString(); - valuesForNewTasks = (ContentValues)source.readParcelable(ContentValues.class.getClassLoader()); - icon = (Bitmap)source.readParcelable(Bitmap.class.getClassLoader()); + valuesForNewTasks = (ContentValues) source.readParcelable(ContentValues.class.getClassLoader()); + icon = (Bitmap) source.readParcelable(Bitmap.class.getClassLoader()); name = source.readString(); } } diff --git a/api/src/com/todoroo/astrid/api/Filter.java b/api/src/com/todoroo/astrid/api/Filter.java index 4c1f99a28..5a7637b3e 100644 --- a/api/src/com/todoroo/astrid/api/Filter.java +++ b/api/src/com/todoroo/astrid/api/Filter.java @@ -15,20 +15,21 @@ import com.todoroo.andlib.sql.QueryTemplate; /** * A FilterListFilter allows users to display tasks that have * something in common. - *

      + *

      * A plug-in can expose new FilterListFilters to the system by * responding to the com.todoroo.astrid.GET_FILTERS broadcast * intent. * * @author Tim Su - * */ public class Filter extends FilterListItem { // --- constants - /** Constant for valuesForNewTasks to indicate the value should be replaced - * with the current time as long */ + /** + * Constant for valuesForNewTasks to indicate the value should be replaced + * with the current time as long + */ public static final long VALUE_NOW = Long.MIN_VALUE + 1; // --- instance variables @@ -36,7 +37,7 @@ public class Filter extends FilterListItem { /** * Expanded title of this filter. This is displayed at the top * of the screen when user is viewing this filter. - *

      + *

      * e.g "Tasks With Notes" */ public String title; @@ -46,14 +47,14 @@ public class Filter extends FilterListItem { * statement after "SELECT fields FROM table %s". It is * recommended that you use a {@link QueryTemplate} to construct your * query. - *

      + *

      * Examples: *

        *
      • "WHERE completionDate = 0" *
      • "INNER JOIN " + - * Constants.TABLE_METADATA + " ON metadata.task = tasks.id WHERE - * metadata.namespace = " + NAMESPACE + " AND metadata.key = 'a' AND - * metadata.value = 'b' GROUP BY tasks.id ORDER BY tasks.title" + * Constants.TABLE_METADATA + " ON metadata.task = tasks.id WHERE + * metadata.namespace = " + NAMESPACE + " AND metadata.key = 'a' AND + * metadata.value = 'b' GROUP BY tasks.id ORDER BY tasks.title" *
      */ protected String sqlQuery; @@ -74,36 +75,30 @@ public class Filter extends FilterListItem { /** * Utility constructor for creating a Filter object - * @param listingTitle - * Title of this item as displayed on the lists page, e.g. Inbox - * @param title - * Expanded title of this filter when user is viewing this - * filter, e.g. Inbox (20 tasks) - * @param sqlQuery - * SQL query for this list (see {@link #sqlQuery} for examples). - * @param valuesForNewTasks - * see {@link #sqlForNewTasks} + * + * @param listingTitle Title of this item as displayed on the lists page, e.g. Inbox + * @param title Expanded title of this filter when user is viewing this + * filter, e.g. Inbox (20 tasks) + * @param sqlQuery SQL query for this list (see {@link #sqlQuery} for examples). + * @param valuesForNewTasks see {@link #sqlForNewTasks} */ public Filter(String listingTitle, String title, - QueryTemplate sqlQuery, ContentValues valuesForNewTasks) { + QueryTemplate sqlQuery, ContentValues valuesForNewTasks) { this(listingTitle, title, sqlQuery == null ? null : sqlQuery.toString(), valuesForNewTasks); } /** * Utility constructor for creating a Filter object - * @param listingTitle - * Title of this item as displayed on the lists page, e.g. Inbox - * @param title - * Expanded title of this filter when user is viewing this - * filter, e.g. Inbox (20 tasks) - * @param sqlQuery - * SQL query for this list (see {@link #sqlQuery} for examples). - * @param valuesForNewTasks - * see {@link #sqlForNewTasks} + * + * @param listingTitle Title of this item as displayed on the lists page, e.g. Inbox + * @param title Expanded title of this filter when user is viewing this + * filter, e.g. Inbox (20 tasks) + * @param sqlQuery SQL query for this list (see {@link #sqlQuery} for examples). + * @param valuesForNewTasks see {@link #sqlForNewTasks} */ public Filter(String listingTitle, String title, - String sqlQuery, ContentValues valuesForNewTasks) { + String sqlQuery, ContentValues valuesForNewTasks) { this.listingTitle = listingTitle; this.title = title; this.sqlQuery = sqlQuery; @@ -128,8 +123,7 @@ public class Filter extends FilterListItem { /** * Utility constructor * - * @param plugin - * {@link Addon} identifier that encompasses object + * @param plugin {@link Addon} identifier that encompasses object */ protected Filter() { // do nothing diff --git a/api/src/com/todoroo/astrid/api/FilterCategory.java b/api/src/com/todoroo/astrid/api/FilterCategory.java index cdca14ff3..3de203890 100644 --- a/api/src/com/todoroo/astrid/api/FilterCategory.java +++ b/api/src/com/todoroo/astrid/api/FilterCategory.java @@ -13,7 +13,6 @@ import android.os.Parcelable; * a user to show/hide all of its children. * * @author Tim Su - * */ public class FilterCategory extends FilterListItem { @@ -24,10 +23,9 @@ public class FilterCategory extends FilterListItem { /** * Constructor for creating a new FilterCategory - * @param listingTitle - * Title of this item as displayed on the lists page, e.g. Inbox - * @param children - * filters belonging to this category + * + * @param listingTitle Title of this item as displayed on the lists page, e.g. Inbox + * @param children filters belonging to this category */ public FilterCategory(String listingTitle, Filter[] children) { this.listingTitle = listingTitle; @@ -37,8 +35,7 @@ public class FilterCategory extends FilterListItem { /** * Constructor for creating a new FilterCategory * - * @param plugin - * {@link Addon} identifier that encompasses object + * @param plugin {@link Addon} identifier that encompasses object */ protected FilterCategory() { // @@ -77,8 +74,8 @@ public class FilterCategory extends FilterListItem { Parcelable[] parcelableChildren = source.readParcelableArray( FilterCategory.class.getClassLoader()); item.children = new Filter[parcelableChildren.length]; - for(int i = 0; i < item.children.length; i++) { - if(parcelableChildren[i] instanceof FilterListItem) + for (int i = 0; i < item.children.length; i++) { + if (parcelableChildren[i] instanceof FilterListItem) item.children[i] = (Filter) parcelableChildren[i]; else item.children[i] = null; diff --git a/api/src/com/todoroo/astrid/api/FilterCategoryWithNewButton.java b/api/src/com/todoroo/astrid/api/FilterCategoryWithNewButton.java index 9a7863aa5..31a4acf2b 100644 --- a/api/src/com/todoroo/astrid/api/FilterCategoryWithNewButton.java +++ b/api/src/com/todoroo/astrid/api/FilterCategoryWithNewButton.java @@ -13,7 +13,6 @@ import android.os.Parcelable; * A FilterCategoryWithNewButton has a button for new filter creation * * @author Tim Su - * */ public class FilterCategoryWithNewButton extends FilterCategory { @@ -29,10 +28,9 @@ public class FilterCategoryWithNewButton extends FilterCategory { /** * Constructor for creating a new FilterCategory - * @param listingTitle - * Title of this item as displayed on the lists page, e.g. Inbox - * @param children - * filters belonging to this category + * + * @param listingTitle Title of this item as displayed on the lists page, e.g. Inbox + * @param children filters belonging to this category */ public FilterCategoryWithNewButton(String listingTitle, Filter[] children) { this.listingTitle = listingTitle; @@ -42,8 +40,7 @@ public class FilterCategoryWithNewButton extends FilterCategory { /** * Constructor for creating a new FilterCategory * - * @param plugin - * {@link Addon} identifier that encompasses object + * @param plugin {@link Addon} identifier that encompasses object */ protected FilterCategoryWithNewButton() { // @@ -85,8 +82,8 @@ public class FilterCategoryWithNewButton extends FilterCategory { Parcelable[] parcelableChildren = source.readParcelableArray( FilterCategoryWithNewButton.class.getClassLoader()); item.children = new Filter[parcelableChildren.length]; - for(int i = 0; i < item.children.length; i++) { - if(parcelableChildren[i] instanceof FilterListItem) + for (int i = 0; i < item.children.length; i++) { + if (parcelableChildren[i] instanceof FilterListItem) item.children[i] = (Filter) parcelableChildren[i]; else item.children[i] = null; diff --git a/api/src/com/todoroo/astrid/api/FilterListHeader.java b/api/src/com/todoroo/astrid/api/FilterListHeader.java index 06e0b064c..f6865216a 100644 --- a/api/src/com/todoroo/astrid/api/FilterListHeader.java +++ b/api/src/com/todoroo/astrid/api/FilterListHeader.java @@ -12,12 +12,12 @@ import android.os.Parcelable; * Section Header for Filter List * * @author Tim Su - * */ public class FilterListHeader extends FilterListItem { /** * Constructor for creating a new FilterListHeader + * * @param listingTitle * @param listingIconResource * @param priority @@ -29,8 +29,7 @@ public class FilterListHeader extends FilterListItem { /** * Constructor for creating a new FilterListHeader * - * @param plugin - * {@link Addon} identifier that encompasses object + * @param plugin {@link Addon} identifier that encompasses object */ protected FilterListHeader() { // diff --git a/api/src/com/todoroo/astrid/api/FilterListItem.java b/api/src/com/todoroo/astrid/api/FilterListItem.java index eb56e0b93..5ca9d04c2 100644 --- a/api/src/com/todoroo/astrid/api/FilterListItem.java +++ b/api/src/com/todoroo/astrid/api/FilterListItem.java @@ -14,7 +14,6 @@ import android.os.Parcelable; * Represents an item displayed by Astrid's FilterListActivity * * @author Tim Su - * */ abstract public class FilterListItem implements Parcelable { diff --git a/api/src/com/todoroo/astrid/api/FilterWithCustomIntent.java b/api/src/com/todoroo/astrid/api/FilterWithCustomIntent.java index 368d08634..b3dbd6b48 100644 --- a/api/src/com/todoroo/astrid/api/FilterWithCustomIntent.java +++ b/api/src/com/todoroo/astrid/api/FilterWithCustomIntent.java @@ -33,12 +33,12 @@ public class FilterWithCustomIntent extends Filter { } public FilterWithCustomIntent(String listingTitle, String title, - QueryTemplate sqlQuery, ContentValues valuesForNewTasks) { + QueryTemplate sqlQuery, ContentValues valuesForNewTasks) { super(listingTitle, title, sqlQuery, valuesForNewTasks); } public FilterWithCustomIntent(String listingTitle, String title, - String sqlQuery, ContentValues valuesForNewTasks) { + String sqlQuery, ContentValues valuesForNewTasks) { super(listingTitle, title, sqlQuery, valuesForNewTasks); } @@ -46,7 +46,7 @@ public class FilterWithCustomIntent extends Filter { Intent intent = new Intent(); intent.putExtra("filter", this); //$NON-NLS-1$ intent.setComponent(new ComponentName(AstridApiConstants.ASTRID_PACKAGE, "com.todoroo.astrid.activity.TaskListActivity")); //$NON-NLS-1$ - if(customExtras != null) + if (customExtras != null) intent.putExtras(customExtras); return intent; diff --git a/api/src/com/todoroo/astrid/api/FilterWithUpdate.java b/api/src/com/todoroo/astrid/api/FilterWithUpdate.java index f44461c64..399ef3902 100644 --- a/api/src/com/todoroo/astrid/api/FilterWithUpdate.java +++ b/api/src/com/todoroo/astrid/api/FilterWithUpdate.java @@ -29,12 +29,12 @@ public class FilterWithUpdate extends FilterWithCustomIntent { } public FilterWithUpdate(String listingTitle, String title, - QueryTemplate sqlQuery, ContentValues valuesForNewTasks) { + QueryTemplate sqlQuery, ContentValues valuesForNewTasks) { super(listingTitle, title, sqlQuery, valuesForNewTasks); } public FilterWithUpdate(String listingTitle, String title, - String sqlQuery, ContentValues valuesForNewTasks) { + String sqlQuery, ContentValues valuesForNewTasks) { super(listingTitle, title, sqlQuery, valuesForNewTasks); } diff --git a/api/src/com/todoroo/astrid/api/IntentFilter.java b/api/src/com/todoroo/astrid/api/IntentFilter.java index cc7d059a9..8f80a3bb2 100644 --- a/api/src/com/todoroo/astrid/api/IntentFilter.java +++ b/api/src/com/todoroo/astrid/api/IntentFilter.java @@ -14,7 +14,6 @@ import android.os.Parcelable; * Special filter that launches a PendingIntent when accessed. * * @author Tim Su - * */ public final class IntentFilter extends FilterListItem implements Parcelable { @@ -26,10 +25,8 @@ public final class IntentFilter extends FilterListItem implements Parcelable { /** * Constructor for creating a new IntentFilter * - * @param listingTitle - * Title of this item as displayed on the lists page, e.g. Inbox - * @param intent - * intent to load + * @param listingTitle Title of this item as displayed on the lists page, e.g. Inbox + * @param intent intent to load */ public IntentFilter(String listingTitle, PendingIntent intent) { this.listingTitle = listingTitle; diff --git a/api/src/com/todoroo/astrid/api/MultipleSelectCriterion.java b/api/src/com/todoroo/astrid/api/MultipleSelectCriterion.java index 2748a9e7f..d9c2e8306 100644 --- a/api/src/com/todoroo/astrid/api/MultipleSelectCriterion.java +++ b/api/src/com/todoroo/astrid/api/MultipleSelectCriterion.java @@ -15,7 +15,6 @@ import android.os.Parcelable; * together criteria * * @author Tim Su - * */ public class MultipleSelectCriterion extends CustomFilterCriterion implements Parcelable { @@ -42,8 +41,8 @@ public class MultipleSelectCriterion extends CustomFilterCriterion implements Pa * @param name */ public MultipleSelectCriterion(String identifier, String title, String sql, - ContentValues valuesForNewTasks, String[] entryTitles, - String[] entryValues, Bitmap icon, String name) { + ContentValues valuesForNewTasks, String[] entryTitles, + String[] entryValues, Bitmap icon, String name) { this.identifier = identifier; this.text = title; this.sql = sql; diff --git a/api/src/com/todoroo/astrid/api/PermaSql.java b/api/src/com/todoroo/astrid/api/PermaSql.java index 7763c1b9c..8bf52c6aa 100644 --- a/api/src/com/todoroo/astrid/api/PermaSql.java +++ b/api/src/com/todoroo/astrid/api/PermaSql.java @@ -5,71 +5,98 @@ */ package com.todoroo.astrid.api; -import java.util.Date; - import com.todoroo.andlib.utility.DateUtilities; +import java.util.Date; + /** * PermaSql allows for creating SQL statements that can be saved and used * later without dates getting stale. It also allows these values to be * used in * * @author Tim Su - * */ public final class PermaSql { // --- placeholder strings - /** value to be replaced with the current time as long */ + /** + * value to be replaced with the current time as long + */ public static final String VALUE_NOW = "NOW()"; //$NON-NLS-1$ - /** value to be replaced by end of day as long */ + /** + * value to be replaced by end of day as long + */ public static final String VALUE_EOD = "EOD()"; //$NON-NLS-1$ - /** value to be replaced by noon today as long */ + /** + * value to be replaced by noon today as long + */ public static final String VALUE_NOON = "NOON()"; //$NON-NLS-1$ - /** value to be replaced by end of day yesterday as long */ + /** + * value to be replaced by end of day yesterday as long + */ public static final String VALUE_EOD_YESTERDAY = "EODY()"; //$NON-NLS-1$ - /** value to be replaced by noon yesterday as long */ + /** + * value to be replaced by noon yesterday as long + */ public static final String VALUE_NOON_YESTERDAY = "NOONY()"; //$NON-NLS-1$ - /** value to be replaced by end of day tomorrow as long */ + /** + * value to be replaced by end of day tomorrow as long + */ public static final String VALUE_EOD_TOMORROW = "EODT()"; //$NON-NLS-1$ - /** value to be replaced by noon tomorrow as long */ + /** + * value to be replaced by noon tomorrow as long + */ public static final String VALUE_NOON_TOMORROW = "NOONT()"; //$NON-NLS-1$ - /** value to be replaced by end of day day after tomorrow as long */ + /** + * value to be replaced by end of day day after tomorrow as long + */ public static final String VALUE_EOD_DAY_AFTER = "EODTT()"; //$NON-NLS-1$ - /** value to be replaced by noon day after tomorrow as long */ + /** + * value to be replaced by noon day after tomorrow as long + */ public static final String VALUE_NOON_DAY_AFTER = "NOONTT()"; //$NON-NLS-1$ - /** value to be replaced by end of day next week as long */ + /** + * value to be replaced by end of day next week as long + */ public static final String VALUE_EOD_NEXT_WEEK = "EODW()"; //$NON-NLS-1$ - /** value to be replaced by noon next week as long */ + /** + * value to be replaced by noon next week as long + */ public static final String VALUE_NOON_NEXT_WEEK = "NOONW()"; //$NON-NLS-1$ - /** value to be replaced by approximate end of day next month as long */ + /** + * value to be replaced by approximate end of day next month as long + */ public static final String VALUE_EOD_NEXT_MONTH = "EODM()"; //$NON-NLS-1$ - /** value to be replaced by approximate noon next month as long */ + /** + * value to be replaced by approximate noon next month as long + */ public static final String VALUE_NOON_NEXT_MONTH = "NOONM()"; //$NON-NLS-1$ - /** Replace placeholder strings with actual */ + /** + * Replace placeholder strings with actual + */ public static String replacePlaceholders(String value) { - if(value.contains(VALUE_NOW)) + if (value.contains(VALUE_NOW)) value = value.replace(VALUE_NOW, Long.toString(DateUtilities.now())); - if(value.contains(VALUE_EOD) || value.contains(VALUE_EOD_DAY_AFTER) || + if (value.contains(VALUE_EOD) || value.contains(VALUE_EOD_DAY_AFTER) || value.contains(VALUE_EOD_NEXT_WEEK) || value.contains(VALUE_EOD_TOMORROW) || value.contains(VALUE_EOD_YESTERDAY) || value.contains(VALUE_EOD_NEXT_MONTH)) { value = replaceEodValues(value); } - if(value.contains(VALUE_NOON) || value.contains(VALUE_NOON_DAY_AFTER) || + if (value.contains(VALUE_NOON) || value.contains(VALUE_NOON_DAY_AFTER) || value.contains(VALUE_NOON_NEXT_WEEK) || value.contains(VALUE_NOON_TOMORROW) || value.contains(VALUE_NOON_YESTERDAY) || value.contains(VALUE_NOON_NEXT_MONTH)) { value = replaceNoonValues(value); diff --git a/api/src/com/todoroo/astrid/api/SyncAction.java b/api/src/com/todoroo/astrid/api/SyncAction.java index aac6855ab..13ac0d382 100644 --- a/api/src/com/todoroo/astrid/api/SyncAction.java +++ b/api/src/com/todoroo/astrid/api/SyncAction.java @@ -13,7 +13,6 @@ import android.os.Parcelable; * Represents an intent that can be called to perform synchronization * * @author Tim Su - * */ public class SyncAction implements Parcelable { @@ -30,10 +29,8 @@ public class SyncAction implements Parcelable { /** * Create an EditOperation object * - * @param label - * label to display - * @param intent - * intent to invoke + * @param label label to display + * @param intent intent to invoke */ public SyncAction(String label, PendingIntent intent) { super(); @@ -61,7 +58,7 @@ public class SyncAction implements Parcelable { */ @Override public boolean equals(Object o) { - if(!(o instanceof SyncAction)) + if (!(o instanceof SyncAction)) return false; SyncAction other = (SyncAction) o; return label.equals(other.label) && intent.getTargetPackage().equals(other.intent.getTargetPackage()); @@ -92,7 +89,7 @@ public class SyncAction implements Parcelable { * {@inheritDoc} */ public SyncAction createFromParcel(Parcel source) { - return new SyncAction(source.readString(), (PendingIntent)source.readParcelable( + return new SyncAction(source.readString(), (PendingIntent) source.readParcelable( PendingIntent.class.getClassLoader())); } @@ -101,7 +98,9 @@ public class SyncAction implements Parcelable { */ public SyncAction[] newArray(int size) { return new SyncAction[size]; - }; + } + + ; }; } diff --git a/api/src/com/todoroo/astrid/api/TaskAction.java b/api/src/com/todoroo/astrid/api/TaskAction.java index a28774b16..db3c0d27c 100644 --- a/api/src/com/todoroo/astrid/api/TaskAction.java +++ b/api/src/com/todoroo/astrid/api/TaskAction.java @@ -12,7 +12,6 @@ import android.graphics.drawable.BitmapDrawable; * Represents an intent that can be called on a task * * @author Tim Su - * */ public class TaskAction { @@ -39,10 +38,8 @@ public class TaskAction { /** * Create an EditOperation object * - * @param text - * label to display - * @param intent - * intent to invoke. {@link #EXTRAS_TASK_ID} will be passed + * @param text label to display + * @param intent intent to invoke. {@link #EXTRAS_TASK_ID} will be passed */ public TaskAction(String text, PendingIntent intent, BitmapDrawable icon) { super(); diff --git a/api/src/com/todoroo/astrid/api/TaskDecoration.java b/api/src/com/todoroo/astrid/api/TaskDecoration.java index 2d9d8a373..ddcc81b92 100644 --- a/api/src/com/todoroo/astrid/api/TaskDecoration.java +++ b/api/src/com/todoroo/astrid/api/TaskDecoration.java @@ -14,7 +14,6 @@ import android.widget.RemoteViews.RemoteView; * Represents a line of text displayed in the Task List * * @author Tim Su - * */ public final class TaskDecoration implements Parcelable { @@ -45,10 +44,9 @@ public final class TaskDecoration implements Parcelable { /** * Creates a TaskDetail object - * @param text - * text to display - * @param color - * color to use for text. Use 0 for default color + * + * @param text text to display + * @param color color to use for text. Use 0 for default color */ public TaskDecoration(RemoteViews decoration, int position, int color) { this.decoration = decoration; @@ -82,7 +80,7 @@ public final class TaskDecoration implements Parcelable { * {@inheritDoc} */ public TaskDecoration createFromParcel(Parcel source) { - return new TaskDecoration((RemoteViews)source.readParcelable( + return new TaskDecoration((RemoteViews) source.readParcelable( RemoteViews.class.getClassLoader()), source.readInt(), source.readInt()); } @@ -92,7 +90,9 @@ public final class TaskDecoration implements Parcelable { */ public TaskDecoration[] newArray(int size) { return new TaskDecoration[size]; - }; + } + + ; }; } diff --git a/api/src/com/todoroo/astrid/api/TextInputCriterion.java b/api/src/com/todoroo/astrid/api/TextInputCriterion.java index 0a7ca5e45..6bb433f65 100644 --- a/api/src/com/todoroo/astrid/api/TextInputCriterion.java +++ b/api/src/com/todoroo/astrid/api/TextInputCriterion.java @@ -15,7 +15,6 @@ import android.os.Parcelable; * together criteria * * @author Tim Su - * */ public class TextInputCriterion extends CustomFilterCriterion implements Parcelable { @@ -43,8 +42,8 @@ public class TextInputCriterion extends CustomFilterCriterion implements Parcela * @param name */ public TextInputCriterion(String identifier, String title, String sql, - ContentValues valuesForNewTasks, String prompt, String hint, - Bitmap icon, String name) { + ContentValues valuesForNewTasks, String prompt, String hint, + Bitmap icon, String name) { this.identifier = identifier; this.text = title; this.sql = sql; diff --git a/api/src/com/todoroo/astrid/core/SearchFilter.java b/api/src/com/todoroo/astrid/core/SearchFilter.java index 94b0aa044..d04c28473 100644 --- a/api/src/com/todoroo/astrid/core/SearchFilter.java +++ b/api/src/com/todoroo/astrid/core/SearchFilter.java @@ -14,15 +14,13 @@ import com.todoroo.astrid.api.FilterListItem; * Special filter that triggers the search functionality when accessed. * * @author Tim Su - * */ public class SearchFilter extends FilterListItem { /** * Constructor for creating a new SearchFilter * - * @param listingTitle - * Title of this item as displayed on the lists page, e.g. Inbox + * @param listingTitle Title of this item as displayed on the lists page, e.g. Inbox */ public SearchFilter(String listingTitle) { this.listingTitle = listingTitle; diff --git a/api/src/com/todoroo/astrid/core/SortHelper.java b/api/src/com/todoroo/astrid/core/SortHelper.java index bba27bdf0..6bdf5b9f8 100644 --- a/api/src/com/todoroo/astrid/core/SortHelper.java +++ b/api/src/com/todoroo/astrid/core/SortHelper.java @@ -16,7 +16,6 @@ import com.todoroo.astrid.data.TaskApiDao.TaskCriteria; * Helpers for sorting a list of tasks * * @author Tim Su - * */ public class SortHelper { @@ -32,14 +31,19 @@ public class SortHelper { public static final int SORT_IMPORTANCE = 3; public static final int SORT_MODIFIED = 4; - /** preference key for sort flags. stored in public prefs */ + /** + * preference key for sort flags. stored in public prefs + */ public static final String PREF_SORT_FLAGS = "sort_flags"; //$NON-NLS-1$ - /** preference key for sort sort. stored in public prefs */ + /** + * preference key for sort sort. stored in public prefs + */ public static final String PREF_SORT_SORT = "sort_sort"; //$NON-NLS-1$ /** * Takes a SQL query, and if there isn't already an order, creates an order. + * * @param originalSql * @param flags * @param sort @@ -48,24 +52,24 @@ public class SortHelper { @SuppressWarnings("nls") public static String adjustQueryForFlagsAndSort(String originalSql, int flags, int sort) { // sort - if(originalSql == null) + if (originalSql == null) originalSql = ""; - if(!originalSql.toUpperCase().contains("ORDER BY")) { + if (!originalSql.toUpperCase().contains("ORDER BY")) { Order order = orderForSortType(sort); - if((flags & FLAG_REVERSE_SORT) > 0) + if ((flags & FLAG_REVERSE_SORT) > 0) order = order.reverse(); originalSql += " ORDER BY " + order; } // flags - if((flags & FLAG_SHOW_COMPLETED) > 0) + if ((flags & FLAG_SHOW_COMPLETED) > 0) originalSql = originalSql.replace(Task.COMPLETION_DATE.eq(0).toString(), Criterion.all.toString()); - if((flags & FLAG_SHOW_HIDDEN) > 0) + if ((flags & FLAG_SHOW_HIDDEN) > 0) originalSql = originalSql.replace(TaskCriteria.isVisible().toString(), Criterion.all.toString()); - if((flags & FLAG_SHOW_DELETED) > 0) + if ((flags & FLAG_SHOW_DELETED) > 0) originalSql = originalSql.replace(Task.DELETION_DATE.eq(0).toString(), Criterion.all.toString()); @@ -78,7 +82,7 @@ public class SortHelper { public static int setManualSort(int flags, boolean status) { flags = (flags & ~FLAG_DRAG_DROP); - if(status) + if (status) flags |= FLAG_DRAG_DROP; return flags; } @@ -86,26 +90,26 @@ public class SortHelper { @SuppressWarnings("nls") public static Order orderForSortType(int sortType) { Order order; - switch(sortType) { - case SORT_ALPHA: - order = Order.asc(Functions.upper(Task.TITLE)); - break; - case SORT_DUE: - order = Order.asc(Functions.caseStatement(Task.DUE_DATE.eq(0), - Functions.now() + "*2", adjustedDueDateFunction()) + "+" + Task.IMPORTANCE + - "+3*" + Task.COMPLETION_DATE); - break; - case SORT_IMPORTANCE: - order = Order.asc(Task.IMPORTANCE + "*" + (2*DateUtilities.now()) + //$NON-NLS-1$ - "+" + Functions.caseStatement(Task.DUE_DATE.eq(0), //$NON-NLS-1$ - 2 * DateUtilities.now(), - Task.DUE_DATE) + "+8*" + Task.COMPLETION_DATE); - break; - case SORT_MODIFIED: - order = Order.desc(Task.MODIFICATION_DATE); - break; - default: - order = defaultTaskOrder(); + switch (sortType) { + case SORT_ALPHA: + order = Order.asc(Functions.upper(Task.TITLE)); + break; + case SORT_DUE: + order = Order.asc(Functions.caseStatement(Task.DUE_DATE.eq(0), + Functions.now() + "*2", adjustedDueDateFunction()) + "+" + Task.IMPORTANCE + + "+3*" + Task.COMPLETION_DATE); + break; + case SORT_IMPORTANCE: + order = Order.asc(Task.IMPORTANCE + "*" + (2 * DateUtilities.now()) + //$NON-NLS-1$ + "+" + Functions.caseStatement(Task.DUE_DATE.eq(0), //$NON-NLS-1$ + 2 * DateUtilities.now(), + Task.DUE_DATE) + "+8*" + Task.COMPLETION_DATE); + break; + case SORT_MODIFIED: + order = Order.desc(Task.MODIFICATION_DATE); + break; + default: + order = defaultTaskOrder(); } if (sortType != SORT_ALPHA) order.addSecondaryExpression(Order.asc(Task.TITLE)); @@ -115,6 +119,7 @@ public class SortHelper { /** * Returns SQL task ordering that is astrid's default algorithm + * * @return */ @SuppressWarnings("nls") diff --git a/api/src/com/todoroo/astrid/data/History.java b/api/src/com/todoroo/astrid/data/History.java index fb34d63c2..682113b47 100644 --- a/api/src/com/todoroo/astrid/data/History.java +++ b/api/src/com/todoroo/astrid/data/History.java @@ -14,61 +14,89 @@ import com.todoroo.astrid.api.AstridApiConstants; @SuppressWarnings("nls") public class History extends AbstractModel { - /** table for this model */ + /** + * table for this model + */ public static final Table TABLE = new Table("history", History.class); - /** content uri for this model */ + /** + * content uri for this model + */ public static final Uri CONTENT_URI = Uri.parse("content://" + AstridApiConstants.API_PACKAGE + "/" + TABLE.name); // --- properties - /** ID */ + /** + * ID + */ public static final LongProperty ID = new LongProperty( TABLE, ID_PROPERTY_NAME); - /** Remote ID */ + /** + * Remote ID + */ public static final StringProperty UUID = new StringProperty( TABLE, RemoteModel.UUID_PROPERTY_NAME); - /** Created at */ + /** + * Created at + */ public static final LongProperty CREATED_AT = new LongProperty( TABLE, "created_at", Property.PROP_FLAG_DATE); - /** User id */ + /** + * User id + */ public static final StringProperty USER_UUID = new StringProperty( TABLE, "user_id", Property.PROP_FLAG_USER_ID); - /** Column name */ + /** + * Column name + */ public static final StringProperty COLUMN = new StringProperty( TABLE, "columnString"); - /** Old value */ + /** + * Old value + */ public static final StringProperty OLD_VALUE = new StringProperty( TABLE, "old_value", Property.PROP_FLAG_NULLABLE); - /** New value */ + /** + * New value + */ public static final StringProperty NEW_VALUE = new StringProperty( TABLE, "new_value", Property.PROP_FLAG_NULLABLE); - /** Table identifier */ + /** + * Table identifier + */ public static final StringProperty TABLE_ID = new StringProperty( TABLE, "table_id"); - /** Target identifier */ + /** + * Target identifier + */ public static final StringProperty TARGET_ID = new StringProperty( TABLE, "target_id"); - /** Task name and id (JSONArray) */ + /** + * Task name and id (JSONArray) + */ public static final StringProperty TASK = new StringProperty( TABLE, "task"); - /** Associated tag id */ + /** + * Associated tag id + */ public static final StringProperty TAG_ID = new StringProperty( TABLE, "tag_id"); - /** Default values container */ + /** + * Default values container + */ private static final ContentValues defaultValues = new ContentValues(); @Override @@ -104,7 +132,9 @@ public class History extends AbstractModel { super.readPropertiesFromCursor(cursor); } - /** List of all properties for this model */ + /** + * List of all properties for this model + */ public static final Property[] PROPERTIES = generateProperties(History.class); private static final Creator CREATOR = new ModelCreator(History.class); diff --git a/api/src/com/todoroo/astrid/data/Metadata.java b/api/src/com/todoroo/astrid/data/Metadata.java index 0ef33eec8..b88371b97 100644 --- a/api/src/com/todoroo/astrid/data/Metadata.java +++ b/api/src/com/todoroo/astrid/data/Metadata.java @@ -21,54 +21,75 @@ import com.todoroo.astrid.api.AstridApiConstants; * Data Model which represents a piece of metadata associated with a task * * @author Tim Su - * */ @SuppressWarnings("nls") public class Metadata extends AbstractModel { // --- table - /** table for this model */ + /** + * table for this model + */ public static final Table TABLE = new Table("metadata", Metadata.class); - /** changes to metadata (specifically tags) are recorded in the task outstanding table */ + /** + * changes to metadata (specifically tags) are recorded in the task outstanding table + */ public static final Class> OUTSTANDING_MODEL = TaskOutstanding.class; - /** content uri for this model */ + /** + * content uri for this model + */ public static final Uri CONTENT_URI = Uri.parse("content://" + AstridApiConstants.API_PACKAGE + "/" + TABLE.name); // --- properties - /** ID */ + /** + * ID + */ public static final LongProperty ID = new LongProperty( TABLE, ID_PROPERTY_NAME); - /** Associated Task */ + /** + * Associated Task + */ public static final LongProperty TASK = new LongProperty( TABLE, "task"); - /** Metadata Key */ + /** + * Metadata Key + */ public static final StringProperty KEY = new StringProperty( TABLE, "key"); - /** Metadata Text Value Column 1 */ + /** + * Metadata Text Value Column 1 + */ public static final StringProperty VALUE1 = new StringProperty( TABLE, "value"); - /** Metadata Text Value Column 2 */ + /** + * Metadata Text Value Column 2 + */ public static final StringProperty VALUE2 = new StringProperty( TABLE, "value2"); - /** Metadata Text Value Column 3 */ + /** + * Metadata Text Value Column 3 + */ public static final StringProperty VALUE3 = new StringProperty( TABLE, "value3"); - /** Metadata Text Value Column 4 */ + /** + * Metadata Text Value Column 4 + */ public static final StringProperty VALUE4 = new StringProperty( TABLE, "value4"); - /** Metadata Text Value Column 5 */ + /** + * Metadata Text Value Column 5 + */ public static final StringProperty VALUE5 = new StringProperty( TABLE, "value5"); @@ -78,20 +99,28 @@ public class Metadata extends AbstractModel { public static final StringProperty VALUE7 = new StringProperty( TABLE, "value7"); - /** Unixtime Metadata was created */ + /** + * Unixtime Metadata was created + */ public static final LongProperty CREATION_DATE = new LongProperty( TABLE, "created"); - /** Unixtime metadata was deleted/tombstoned */ + /** + * Unixtime metadata was deleted/tombstoned + */ public static final LongProperty DELETION_DATE = new LongProperty( TABLE, "deleted"); - /** List of all properties for this model */ + /** + * List of all properties for this model + */ public static final Property[] PROPERTIES = generateProperties(Metadata.class); // --- defaults - /** Default values container */ + /** + * Default values container + */ private static final ContentValues defaultValues = new ContentValues(); static { @@ -121,7 +150,9 @@ public class Metadata extends AbstractModel { @Override public long getId() { return getIdHelper(ID); - }; + } + + ; // --- parcelable helpers diff --git a/api/src/com/todoroo/astrid/data/MetadataApiDao.java b/api/src/com/todoroo/astrid/data/MetadataApiDao.java index 1a92f0b6d..4fcbd1eea 100644 --- a/api/src/com/todoroo/astrid/data/MetadataApiDao.java +++ b/api/src/com/todoroo/astrid/data/MetadataApiDao.java @@ -16,7 +16,6 @@ import com.todoroo.andlib.sql.Criterion; * note. It operates in a one-to-many relation with tasks. * * @author Tim Su - * */ public class MetadataApiDao extends ContentResolverDao { @@ -29,17 +28,23 @@ public class MetadataApiDao extends ContentResolverDao { */ public static class MetadataCriteria { - /** Returns all metadata associated with a given task */ + /** + * Returns all metadata associated with a given task + */ public static Criterion byTask(long taskId) { return Metadata.TASK.eq(taskId); } - /** Returns all metadata associated with a given key */ + /** + * Returns all metadata associated with a given key + */ public static Criterion withKey(String key) { return Metadata.KEY.eq(key); } - /** Returns all metadata associated with a given key */ + /** + * Returns all metadata associated with a given key + */ public static Criterion byTaskAndwithKey(long taskId, String key) { return Criterion.and(withKey(key), byTask(taskId)); } diff --git a/api/src/com/todoroo/astrid/data/RemoteModel.java b/api/src/com/todoroo/astrid/data/RemoteModel.java index 4fbc309eb..c22de89cd 100644 --- a/api/src/com/todoroo/astrid/data/RemoteModel.java +++ b/api/src/com/todoroo/astrid/data/RemoteModel.java @@ -5,15 +5,6 @@ */ package com.todoroo.astrid.data; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Date; - -import org.json.JSONException; -import org.json.JSONObject; - import android.content.ContentValues; import android.content.Context; import android.graphics.Bitmap; @@ -26,39 +17,66 @@ import com.todoroo.andlib.data.Property.StringProperty; import com.todoroo.andlib.data.TodorooCursor; import com.todoroo.andlib.utility.DateUtilities; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Date; + /** * A model that is synchronized to a remote server and has a remote id * * @author Tim Su - * */ abstract public class RemoteModel extends AbstractModel { - /** remote id property common to all remote models */ + /** + * remote id property common to all remote models + */ public static final String UUID_PROPERTY_NAME = "remoteId"; //$NON-NLS-1$ - /** remote id property */ + /** + * remote id property + */ public static final StringProperty UUID_PROPERTY = new StringProperty(null, UUID_PROPERTY_NAME); - /** user id property common to all remote models */ + /** + * user id property common to all remote models + */ protected static final String USER_ID_PROPERTY_NAME = "userId"; //$NON-NLS-1$ - /** user id property */ + /** + * user id property + */ public static final StringProperty USER_ID_PROPERTY = new StringProperty(null, USER_ID_PROPERTY_NAME); - /** user json property common to all remote models */ + /** + * user json property common to all remote models + */ protected static final String USER_JSON_PROPERTY_NAME = "user"; //$NON-NLS-1$ - /** user json property */ - @Deprecated public static final StringProperty USER_JSON_PROPERTY = new StringProperty(null, USER_JSON_PROPERTY_NAME); + /** + * user json property + */ + @Deprecated + public static final StringProperty USER_JSON_PROPERTY = new StringProperty(null, USER_JSON_PROPERTY_NAME); - /** pushed at date property name */ + /** + * pushed at date property name + */ public static final String PUSHED_AT_PROPERTY_NAME = "pushedAt"; //$NON-NLS-1$ - /** pushed at date property name */ + /** + * pushed at date property name + */ public static final LongProperty PUSHED_AT_PROPERTY = new LongProperty(null, PUSHED_AT_PROPERTY_NAME); - /** constant value for no uuid */ + /** + * constant value for no uuid + */ public static final String NO_UUID = "0"; //$NON-NLS-1$ public static final boolean isValidUuid(String uuid) { @@ -78,9 +96,9 @@ abstract public class RemoteModel extends AbstractModel { abstract public String getUuid(); protected String getUuidHelper(StringProperty uuid) { - if(setValues != null && setValues.containsKey(uuid.name)) + if (setValues != null && setValues.containsKey(uuid.name)) return setValues.getAsString(uuid.name); - else if(values != null && values.containsKey(uuid.name)) + else if (values != null && values.containsKey(uuid.name)) return values.getAsString(uuid.name); else return NO_UUID; @@ -90,7 +108,7 @@ abstract public class RemoteModel extends AbstractModel { if (setValues == null) setValues = new ContentValues(); - if(NO_UUID.equals(uuid)) + if (NO_UUID.equals(uuid)) clearValue(UUID_PROPERTY); else setValues.put(UUID_PROPERTY_NAME, uuid); diff --git a/api/src/com/todoroo/astrid/data/StoreObject.java b/api/src/com/todoroo/astrid/data/StoreObject.java index 4131e713e..2e3cd6c54 100644 --- a/api/src/com/todoroo/astrid/data/StoreObject.java +++ b/api/src/com/todoroo/astrid/data/StoreObject.java @@ -21,60 +21,83 @@ import com.todoroo.astrid.api.AstridApiConstants; * Data Model which represents a piece of data unrelated to a task * * @author Tim Su - * */ @SuppressWarnings("nls") public class StoreObject extends AbstractModel { // --- table - /** table for this model */ + /** + * table for this model + */ public static final Table TABLE = new Table("store", StoreObject.class); - /** content uri for this model */ + /** + * content uri for this model + */ public static final Uri CONTENT_URI = Uri.parse("content://" + AstridApiConstants.API_PACKAGE + "/" + TABLE.name); // --- properties - /** ID */ + /** + * ID + */ public static final LongProperty ID = new LongProperty( TABLE, ID_PROPERTY_NAME); - /** Store Type Key */ + /** + * Store Type Key + */ public static final StringProperty TYPE = new StringProperty( TABLE, "type"); - /** Store Item Key */ - public static final StringProperty ITEM= new StringProperty( + /** + * Store Item Key + */ + public static final StringProperty ITEM = new StringProperty( TABLE, "item"); - /** Store Value Column 1 */ + /** + * Store Value Column 1 + */ public static final StringProperty VALUE1 = new StringProperty( TABLE, "value"); - /** Store Value Column 2 */ + /** + * Store Value Column 2 + */ public static final StringProperty VALUE2 = new StringProperty( TABLE, "value2"); - /** Store Value Column 3 */ + /** + * Store Value Column 3 + */ public static final StringProperty VALUE3 = new StringProperty( TABLE, "value3"); - /** Store Value Column 4 */ + /** + * Store Value Column 4 + */ public static final StringProperty VALUE4 = new StringProperty( TABLE, "value4"); - /** Store Value Column 5 */ + /** + * Store Value Column 5 + */ public static final StringProperty VALUE5 = new StringProperty( TABLE, "value5"); - /** List of all properties for this model */ + /** + * List of all properties for this model + */ public static final Property[] PROPERTIES = generateProperties(StoreObject.class); // --- defaults - /** Default values container */ + /** + * Default values container + */ private static final ContentValues defaultValues = new ContentValues(); @Override @@ -100,7 +123,9 @@ public class StoreObject extends AbstractModel { @Override public long getId() { return getIdHelper(ID); - }; + } + + ; // --- parcelable helpers diff --git a/api/src/com/todoroo/astrid/data/StoreObjectApiDao.java b/api/src/com/todoroo/astrid/data/StoreObjectApiDao.java index cc86f11c1..479549387 100644 --- a/api/src/com/todoroo/astrid/data/StoreObjectApiDao.java +++ b/api/src/com/todoroo/astrid/data/StoreObjectApiDao.java @@ -15,7 +15,6 @@ import com.todoroo.andlib.sql.Criterion; * StoreObject is an arbitrary piece of data stored inside of Astrid. * * @author Tim Su - * */ public class StoreObjectApiDao extends ContentResolverDao { @@ -30,12 +29,16 @@ public class StoreObjectApiDao extends ContentResolverDao { */ public static class StoreObjectCriteria { - /** Returns all store objects with given type */ + /** + * Returns all store objects with given type + */ public static Criterion byType(String type) { return StoreObject.TYPE.eq(type); } - /** Returns store object with type and key */ + /** + * Returns store object with type and key + */ public static Criterion byTypeAndItem(String type, String item) { return Criterion.and(byType(type), StoreObject.ITEM.eq(item)); } diff --git a/api/src/com/todoroo/astrid/data/TagData.java b/api/src/com/todoroo/astrid/data/TagData.java index 838a8d89e..3eea53ac6 100644 --- a/api/src/com/todoroo/astrid/data/TagData.java +++ b/api/src/com/todoroo/astrid/data/TagData.java @@ -22,156 +22,229 @@ import com.todoroo.astrid.api.AstridApiConstants; * Data Model which represents a collaboration space for users / tasks. * * @author Tim Su - * */ @SuppressWarnings("nls") public final class TagData extends RemoteModel { // --- table and uri - /** table for this model */ + /** + * table for this model + */ public static final Table TABLE = new Table("tagdata", TagData.class); - /** model class for entries in the outstanding table */ + /** + * model class for entries in the outstanding table + */ public static final Class> OUTSTANDING_MODEL = TagOutstanding.class; - /** content uri for this model */ + /** + * content uri for this model + */ public static final Uri CONTENT_URI = Uri.parse("content://" + AstridApiConstants.API_PACKAGE + "/" + TABLE.name); // --- properties - /** ID */ + /** + * ID + */ public static final LongProperty ID = new LongProperty( TABLE, ID_PROPERTY_NAME); - /** User id */ + /** + * User id + */ public static final StringProperty USER_ID = new StringProperty( TABLE, USER_ID_PROPERTY_NAME, Property.PROP_FLAG_USER_ID); - /** User Object (JSON) */ - @Deprecated public static final StringProperty USER = new StringProperty( + /** + * User Object (JSON) + */ + @Deprecated + public static final StringProperty USER = new StringProperty( TABLE, USER_JSON_PROPERTY_NAME); - /** Remote goal id */ + /** + * Remote goal id + */ public static final StringProperty UUID = new StringProperty( TABLE, UUID_PROPERTY_NAME); - /** Name of Tag */ + /** + * Name of Tag + */ public static final StringProperty NAME = new StringProperty( TABLE, "name"); - /** Project picture */ + /** + * Project picture + */ public static final StringProperty PICTURE = new StringProperty( TABLE, "picture", Property.PROP_FLAG_JSON | Property.PROP_FLAG_PICTURE); - /** Tag team array (JSON) */ - @Deprecated public static final StringProperty MEMBERS = new StringProperty( + /** + * Tag team array (JSON) + */ + @Deprecated + public static final StringProperty MEMBERS = new StringProperty( TABLE, "members"); - /** Tag member count */ + /** + * Tag member count + */ public static final IntegerProperty MEMBER_COUNT = new IntegerProperty( TABLE, "memberCount"); - /** Flags */ + /** + * Flags + */ public static final IntegerProperty FLAGS = new IntegerProperty( TABLE, "flags"); - /** Unixtime Project was created */ + /** + * Unixtime Project was created + */ public static final LongProperty CREATION_DATE = new LongProperty( TABLE, "created", Property.PROP_FLAG_DATE); - /** Unixtime Project was last touched */ + /** + * Unixtime Project was last touched + */ public static final LongProperty MODIFICATION_DATE = new LongProperty( TABLE, "modified", Property.PROP_FLAG_DATE); - /** Unixtime Project was completed. 0 means active */ + /** + * Unixtime Project was completed. 0 means active + */ public static final LongProperty COMPLETION_DATE = new LongProperty( TABLE, "completed", Property.PROP_FLAG_DATE); - /** Unixtime Project was deleted. 0 means not deleted */ + /** + * Unixtime Project was deleted. 0 means not deleted + */ public static final LongProperty DELETION_DATE = new LongProperty( TABLE, "deleted", Property.PROP_FLAG_DATE); - /** Project picture thumbnail */ + /** + * Project picture thumbnail + */ public static final StringProperty THUMB = new StringProperty( TABLE, "thumb"); - /** Project last activity date */ + /** + * Project last activity date + */ public static final LongProperty LAST_ACTIVITY_DATE = new LongProperty( TABLE, "lastActivityDate", Property.PROP_FLAG_DATE); - /** Whether user is part of Tag team */ + /** + * Whether user is part of Tag team + */ public static final IntegerProperty IS_TEAM = new IntegerProperty( TABLE, "isTeam"); - /** Whether Tag has unread activity */ + /** + * Whether Tag has unread activity + */ public static final IntegerProperty IS_UNREAD = new IntegerProperty( TABLE, "isUnread"); - /** Whether tag is a folder */ + /** + * Whether tag is a folder + */ public static final IntegerProperty IS_FOLDER = new IntegerProperty( TABLE, "isFolder", Property.PROP_FLAG_BOOLEAN); - /** Task count */ + /** + * Task count + */ public static final IntegerProperty TASK_COUNT = new IntegerProperty( TABLE, "taskCount"); - /** Tag Desription */ + /** + * Tag Desription + */ public static final StringProperty TAG_DESCRIPTION = new StringProperty( TABLE, "tagDescription"); - /** Pushed at date */ + /** + * Pushed at date + */ public static final LongProperty PUSHED_AT = new LongProperty( TABLE, PUSHED_AT_PROPERTY_NAME, Property.PROP_FLAG_DATE); - /** Tasks pushed at date */ + /** + * Tasks pushed at date + */ public static final LongProperty TASKS_PUSHED_AT = new LongProperty( TABLE, "tasks_pushed_at", Property.PROP_FLAG_DATE); - /** Metadata pushed at date */ + /** + * Metadata pushed at date + */ public static final LongProperty METADATA_PUSHED_AT = new LongProperty( TABLE, "metadata_pushed_at", Property.PROP_FLAG_DATE); - /** User activities pushed at date */ + /** + * User activities pushed at date + */ public static final LongProperty USER_ACTIVITIES_PUSHED_AT = new LongProperty( TABLE, "activities_pushed_at", Property.PROP_FLAG_DATE); - /** Tag ordering */ + /** + * Tag ordering + */ @Deprecated public static final StringProperty TAG_ORDERING = new StringProperty( TABLE, "tagOrdering"); - /** History fetch date */ + /** + * History fetch date + */ public static final LongProperty HISTORY_FETCH_DATE = new LongProperty( TABLE, "historyFetch"); - /** History has more*/ + /** + * History has more + */ public static final IntegerProperty HISTORY_HAS_MORE = new IntegerProperty( TABLE, "historyHasMore"); - /** Last autosync */ + /** + * Last autosync + */ public static final LongProperty LAST_AUTOSYNC = new LongProperty( TABLE, "lastAutosync"); - /** List of all properties for this model */ + /** + * List of all properties for this model + */ public static final Property[] PROPERTIES = generateProperties(TagData.class); // --- flags - /** whether user should not be notified of tag activity */ + /** + * whether user should not be notified of tag activity + */ public static final int FLAG_SILENT = 1 << 1; - /** whether tag is emergent */ + /** + * whether tag is emergent + */ @Deprecated public static final int FLAG_EMERGENT = 1 << 2; - /** whether tag represents a featured list */ + /** + * whether tag represents a featured list + */ public static final int FLAG_FEATURED = 1 << 3; // --- defaults - /** Default values container */ + /** + * Default values container + */ private static final ContentValues defaultValues = new ContentValues(); static { @@ -244,15 +317,19 @@ public final class TagData extends RemoteModel { // --- data access methods - /** Checks whether task is done. Requires COMPLETION_DATE */ + /** + * Checks whether task is done. Requires COMPLETION_DATE + */ public boolean isCompleted() { return getValue(COMPLETION_DATE) > 0; } - /** Checks whether task is deleted. Will return false if DELETION_DATE not read */ + /** + * Checks whether task is deleted. Will return false if DELETION_DATE not read + */ public boolean isDeleted() { // assume false if we didn't load deletion date - if(!containsValue(DELETION_DATE)) + if (!containsValue(DELETION_DATE)) return false; else return getValue(DELETION_DATE) > 0; diff --git a/api/src/com/todoroo/astrid/data/TagMetadata.java b/api/src/com/todoroo/astrid/data/TagMetadata.java index 56dcef837..b88cdd9a2 100644 --- a/api/src/com/todoroo/astrid/data/TagMetadata.java +++ b/api/src/com/todoroo/astrid/data/TagMetadata.java @@ -16,56 +16,82 @@ public class TagMetadata extends AbstractModel { public static final Table TABLE = new Table("tag_metadata", TagMetadata.class); - /** changes to metadata (specifically members) are recorded in the tag outstanding table */ + /** + * changes to metadata (specifically members) are recorded in the tag outstanding table + */ public static final Class> OUTSTANDING_MODEL = TagOutstanding.class; - /** content uri for this model */ + /** + * content uri for this model + */ public static final Uri CONTENT_URI = Uri.parse("content://" + AstridApiConstants.API_PACKAGE + "/" + TABLE.name); // --- properties - /** ID */ + /** + * ID + */ public static final LongProperty ID = new LongProperty( TABLE, ID_PROPERTY_NAME); - /** Tag local id */ + /** + * Tag local id + */ public static final LongProperty TAG_ID = new LongProperty( TABLE, "tag_id"); - /** Tag uuid */ + /** + * Tag uuid + */ public static final StringProperty TAG_UUID = new StringProperty( TABLE, "tag_uuid"); - /** Metadata Key */ + /** + * Metadata Key + */ public static final StringProperty KEY = new StringProperty( TABLE, "key"); - /** Metadata Text Value Column 1 */ + /** + * Metadata Text Value Column 1 + */ public static final StringProperty VALUE1 = new StringProperty( TABLE, "value"); - /** Metadata Text Value Column 2 */ + /** + * Metadata Text Value Column 2 + */ public static final StringProperty VALUE2 = new StringProperty( TABLE, "value2"); - /** Metadata Text Value Column 3 */ + /** + * Metadata Text Value Column 3 + */ public static final StringProperty VALUE3 = new StringProperty( TABLE, "value3"); - /** Unixtime Metadata was created */ + /** + * Unixtime Metadata was created + */ public static final LongProperty CREATION_DATE = new LongProperty( TABLE, "created"); - /** Unixtime metadata was deleted/tombstoned */ + /** + * Unixtime metadata was deleted/tombstoned + */ public static final LongProperty DELETION_DATE = new LongProperty( TABLE, "deleted"); - /** List of all properties for this model */ + /** + * List of all properties for this model + */ public static final Property[] PROPERTIES = generateProperties(TagMetadata.class); - /** Default values container */ + /** + * Default values container + */ private static final ContentValues defaultValues = new ContentValues(); static { diff --git a/api/src/com/todoroo/astrid/data/TagOutstanding.java b/api/src/com/todoroo/astrid/data/TagOutstanding.java index a1198362a..b970c6d91 100644 --- a/api/src/com/todoroo/astrid/data/TagOutstanding.java +++ b/api/src/com/todoroo/astrid/data/TagOutstanding.java @@ -11,12 +11,16 @@ import com.todoroo.andlib.data.Table; @SuppressWarnings("nls") public class TagOutstanding extends OutstandingEntry { - /** table for this model */ + /** + * table for this model + */ public static final Table TABLE = new Table("tags_outstanding", TagOutstanding.class); // --- properties - /** ID */ + /** + * ID + */ public static final LongProperty ID = new LongProperty( TABLE, ID_PROPERTY_NAME); @@ -40,7 +44,9 @@ public class TagOutstanding extends OutstandingEntry { defaultValues.put(VALUE_STRING.name, ""); } - /** List of all properties for this model */ + /** + * List of all properties for this model + */ public static final Property[] PROPERTIES = generateProperties(TagOutstanding.class); @Override diff --git a/api/src/com/todoroo/astrid/data/Task.java b/api/src/com/todoroo/astrid/data/Task.java index bdab30a7f..5ef683e85 100644 --- a/api/src/com/todoroo/astrid/data/Task.java +++ b/api/src/com/todoroo/astrid/data/Task.java @@ -6,8 +6,6 @@ package com.todoroo.astrid.data; -import java.util.Date; - import android.content.ContentValues; import android.content.res.Resources; import android.net.Uri; @@ -23,72 +21,101 @@ import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.api.AstridApiConstants; import com.todoroo.astrid.api.R; +import java.util.Date; + /** * Data Model which represents a task users need to accomplish. * * @author Tim Su - * */ @SuppressWarnings("nls") public final class Task extends RemoteModel { // --- table and uri - /** table for this model */ + /** + * table for this model + */ public static final Table TABLE = new Table("tasks", Task.class); - /** model class for entries in the outstanding table */ + /** + * model class for entries in the outstanding table + */ public static final Class> OUTSTANDING_MODEL = TaskOutstanding.class; - /** content uri for this model */ + /** + * content uri for this model + */ public static final Uri CONTENT_URI = Uri.parse("content://" + AstridApiConstants.API_PACKAGE + "/" + TABLE.name); // --- properties - /** ID */ + /** + * ID + */ public static final LongProperty ID = new LongProperty( TABLE, ID_PROPERTY_NAME); - /** Name of Task */ + /** + * Name of Task + */ public static final StringProperty TITLE = new StringProperty( TABLE, "title"); - /** Importance of Task (see importance flags) */ + /** + * Importance of Task (see importance flags) + */ public static final IntegerProperty IMPORTANCE = new IntegerProperty( TABLE, "importance"); - /** Unixtime Task is due, 0 if not set */ + /** + * Unixtime Task is due, 0 if not set + */ public static final LongProperty DUE_DATE = new LongProperty( TABLE, "dueDate", Property.PROP_FLAG_DATE); - /** Unixtime Task should be hidden until, 0 if not set */ + /** + * Unixtime Task should be hidden until, 0 if not set + */ public static final LongProperty HIDE_UNTIL = new LongProperty( TABLE, "hideUntil", Property.PROP_FLAG_DATE); - /** Unixtime Task was created */ + /** + * Unixtime Task was created + */ public static final LongProperty CREATION_DATE = new LongProperty( TABLE, "created", Property.PROP_FLAG_DATE); - /** Unixtime Task was last touched */ + /** + * Unixtime Task was last touched + */ public static final LongProperty MODIFICATION_DATE = new LongProperty( TABLE, "modified", Property.PROP_FLAG_DATE); - /** Unixtime Task was completed. 0 means active */ + /** + * Unixtime Task was completed. 0 means active + */ public static final LongProperty COMPLETION_DATE = new LongProperty( TABLE, "completed", Property.PROP_FLAG_DATE); - /** Unixtime Task was deleted. 0 means not deleted */ + /** + * Unixtime Task was deleted. 0 means not deleted + */ public static final LongProperty DELETION_DATE = new LongProperty( TABLE, "deleted", Property.PROP_FLAG_DATE); - /** Cached Details Column - built from add-on detail exposers. A null + /** + * Cached Details Column - built from add-on detail exposers. A null * value means there is no value in the cache and it needs to be - * refreshed */ + * refreshed + */ public static final StringProperty DETAILS = new StringProperty( TABLE, "details"); - /** Date details were last updated */ + /** + * Date details were last updated + */ public static final LongProperty DETAILS_DATE = new LongProperty( TABLE, "detailsDate", Property.PROP_FLAG_DATE); @@ -119,24 +146,34 @@ public final class Task extends RemoteModel { public static final IntegerProperty POSTPONE_COUNT = new IntegerProperty( TABLE, "postponeCount"); - /** Flags for when to send reminders */ + /** + * Flags for when to send reminders + */ public static final IntegerProperty REMINDER_FLAGS = new IntegerProperty( TABLE, "notificationFlags"); - /** Reminder period, in milliseconds. 0 means disabled */ + /** + * Reminder period, in milliseconds. 0 means disabled + */ public static final LongProperty REMINDER_PERIOD = new LongProperty( TABLE, "notifications", Property.PROP_FLAG_DATE); - /** Unixtime the last reminder was triggered */ + /** + * Unixtime the last reminder was triggered + */ public static final LongProperty REMINDER_LAST = new LongProperty( TABLE, "lastNotified", Property.PROP_FLAG_DATE); - /** What kind of reminder the last reminder was: private task, - * social with no faces, social with faces */ + /** + * What kind of reminder the last reminder was: private task, + * social with no faces, social with faces + */ public static final StringProperty SOCIAL_REMINDER = new StringProperty( TABLE, "socialReminder"); - /** Unixtime snooze is set (0 -> no snooze) */ + /** + * Unixtime snooze is set (0 -> no snooze) + */ public static final LongProperty REMINDER_SNOOZE = new LongProperty( TABLE, "snoozeTime", Property.PROP_FLAG_DATE); @@ -154,73 +191,113 @@ public final class Task extends RemoteModel { // --- for astrid.com - /** Remote id */ + /** + * Remote id + */ public static final StringProperty UUID = new StringProperty( TABLE, UUID_PROPERTY_NAME, Property.PROP_FLAG_NULLABLE); - /** Assigned user id */ + /** + * Assigned user id + */ public static final StringProperty USER_ID = new StringProperty( TABLE, USER_ID_PROPERTY_NAME, Property.PROP_FLAG_USER_ID); - /** User Object (JSON) */ - @Deprecated public static final StringProperty USER = new StringProperty( + /** + * User Object (JSON) + */ + @Deprecated + public static final StringProperty USER = new StringProperty( TABLE, USER_JSON_PROPERTY_NAME); - /** Creator user id */ + /** + * Creator user id + */ public static final StringProperty CREATOR_ID = new StringProperty( TABLE, "creatorId", Property.PROP_FLAG_USER_ID); - /** Last Sync date */ + /** + * Last Sync date + */ @Deprecated public static final LongProperty LAST_SYNC = new LongProperty( TABLE, "lastSync", Property.PROP_FLAG_DATE); - /** Pushed at date */ + /** + * Pushed at date + */ public static final LongProperty PUSHED_AT = new LongProperty( TABLE, PUSHED_AT_PROPERTY_NAME, Property.PROP_FLAG_DATE); - /** Attachments pushed at date */ + /** + * Attachments pushed at date + */ public static final LongProperty ATTACHMENTS_PUSHED_AT = new LongProperty( TABLE, "attachments_pushed_at", Property.PROP_FLAG_DATE); - /** User activities pushed at date */ + /** + * User activities pushed at date + */ public static final LongProperty USER_ACTIVITIES_PUSHED_AT = new LongProperty( TABLE, "activities_pushed_at", Property.PROP_FLAG_DATE); - /** History fetch time */ + /** + * History fetch time + */ public static final LongProperty HISTORY_FETCH_DATE = new LongProperty( TABLE, "historyFetch"); - /** History has more*/ + /** + * History has more + */ public static final IntegerProperty HISTORY_HAS_MORE = new IntegerProperty( TABLE, "historyHasMore"); - /** List of all properties for this model */ + /** + * List of all properties for this model + */ public static final Property[] PROPERTIES = generateProperties(Task.class); // --- flags - /** whether repeat occurs relative to completion date instead of due date */ - @Deprecated public static final int FLAG_REPEAT_AFTER_COMPLETION = 1 << 1; + /** + * whether repeat occurs relative to completion date instead of due date + */ + @Deprecated + public static final int FLAG_REPEAT_AFTER_COMPLETION = 1 << 1; - /** whether task is read-only */ - @Deprecated public static final int FLAG_IS_READONLY = 1 << 2; + /** + * whether task is read-only + */ + @Deprecated + public static final int FLAG_IS_READONLY = 1 << 2; - /** whether a task is public */ - @Deprecated public static final int FLAG_PUBLIC = 1 << 3; + /** + * whether a task is public + */ + @Deprecated + public static final int FLAG_PUBLIC = 1 << 3; // --- user id special values - /** user id = doesn't exist/ignore it. For filtering in tags */ + /** + * user id = doesn't exist/ignore it. For filtering in tags + */ public static final String USER_ID_IGNORE = "-3"; - /** user id = read user email value */ + /** + * user id = read user email value + */ public static final String USER_ID_EMAIL = "-2"; - /** user id = unassigned */ + /** + * user id = unassigned + */ public static final String USER_ID_UNASSIGNED = "-1"; - /** user id = myself */ + /** + * user id = myself + */ public static final String USER_ID_SELF = "0"; public static boolean isRealUserId(String userId) { @@ -240,16 +317,24 @@ public final class Task extends RemoteModel { // --- notification flags - /** whether to send a reminder at deadline */ + /** + * whether to send a reminder at deadline + */ public static final int NOTIFY_AT_DEADLINE = 1 << 1; - /** whether to send reminders while task is overdue */ + /** + * whether to send reminders while task is overdue + */ public static final int NOTIFY_AFTER_DEADLINE = 1 << 2; - /** reminder mode non-stop */ + /** + * reminder mode non-stop + */ public static final int NOTIFY_MODE_NONSTOP = 1 << 3; - /** reminder mode five times (exclusive with non-stop) */ + /** + * reminder mode five times (exclusive with non-stop) + */ public static final int NOTIFY_MODE_FIVE = 1 << 4; // --- importance settings (note: importance > 3 are supported via plugin) @@ -270,7 +355,7 @@ public final class Task extends RemoteModel { * @return colors that correspond to importance values */ public static int[] getImportanceColors(Resources r) { - return new int[] { + return new int[]{ r.getColor(R.color.importance_1), r.getColor(R.color.importance_2), r.getColor(R.color.importance_3), @@ -285,7 +370,9 @@ public final class Task extends RemoteModel { // --- defaults - /** Default values container */ + /** + * Default values container + */ private static final ContentValues defaultValues = new ContentValues(); static { @@ -310,7 +397,7 @@ public final class Task extends RemoteModel { defaultValues.put(NOTES.name, ""); defaultValues.put(FLAGS.name, 0); defaultValues.put(TIMER_START.name, 0); - defaultValues.put(DETAILS.name, (String)null); + defaultValues.put(DETAILS.name, (String) null); defaultValues.put(DETAILS_DATE.name, 0); defaultValues.put(IS_PUBLIC.name, 0); defaultValues.put(IS_READONLY.name, 0); @@ -370,33 +457,43 @@ public final class Task extends RemoteModel { // --- data access methods - /** Checks whether task is done. Requires COMPLETION_DATE */ + /** + * Checks whether task is done. Requires COMPLETION_DATE + */ public boolean isCompleted() { return getValue(COMPLETION_DATE) > 0; } - /** Checks whether task is deleted. Will return false if DELETION_DATE not read */ + /** + * Checks whether task is deleted. Will return false if DELETION_DATE not read + */ public boolean isDeleted() { // assume false if we didn't load deletion date - if(!containsValue(DELETION_DATE)) + if (!containsValue(DELETION_DATE)) return false; else return getValue(DELETION_DATE) > 0; } - /** Checks whether task is hidden. Requires HIDDEN_UNTIL */ + /** + * Checks whether task is hidden. Requires HIDDEN_UNTIL + */ public boolean isHidden() { return getValue(HIDE_UNTIL) > DateUtilities.now(); } - /** Checks whether task is done. Requires DUE_DATE */ + /** + * Checks whether task is done. Requires DUE_DATE + */ public boolean hasDueDate() { return getValue(DUE_DATE) > 0; } // --- due and hide until date management - /** urgency array index -> significance */ + /** + * urgency array index -> significance + */ public static final int URGENCY_NONE = 0; public static final int URGENCY_TODAY = 1; public static final int URGENCY_TOMORROW = 2; @@ -407,7 +504,9 @@ public final class Task extends RemoteModel { public static final int URGENCY_SPECIFIC_DAY = 7; public static final int URGENCY_SPECIFIC_DAY_TIME = 8; - /** hide until array index -> significance */ + /** + * hide until array index -> significance + */ public static final int HIDE_UNTIL_NONE = 0; public static final int HIDE_UNTIL_DUE = 1; public static final int HIDE_UNTIL_DAY_BEFORE = 2; @@ -420,49 +519,47 @@ public final class Task extends RemoteModel { * Creates due date for this task. If this due date has no time associated, * we move it to the last millisecond of the day. * - * @param setting - * one of the URGENCY_* constants - * @param customDate - * if specific day or day & time is set, this value + * @param setting one of the URGENCY_* constants + * @param customDate if specific day or day & time is set, this value */ public static long createDueDate(int setting, long customDate) { long date; - switch(setting) { - case URGENCY_NONE: - date = 0; - break; - case URGENCY_TODAY: - date = DateUtilities.now(); - break; - case URGENCY_TOMORROW: - date = DateUtilities.now() + DateUtilities.ONE_DAY; - break; - case URGENCY_DAY_AFTER: - date = DateUtilities.now() + 2 * DateUtilities.ONE_DAY; - break; - case URGENCY_NEXT_WEEK: - date = DateUtilities.now() + DateUtilities.ONE_WEEK; - break; - case URGENCY_IN_TWO_WEEKS: - date = DateUtilities.now() + 2 * DateUtilities.ONE_WEEK; - break; - case URGENCY_NEXT_MONTH: - date = DateUtilities.oneMonthFromNow(); - break; - case URGENCY_SPECIFIC_DAY: - case URGENCY_SPECIFIC_DAY_TIME: - date = customDate; - break; - default: - throw new IllegalArgumentException("Unknown setting " + setting); + switch (setting) { + case URGENCY_NONE: + date = 0; + break; + case URGENCY_TODAY: + date = DateUtilities.now(); + break; + case URGENCY_TOMORROW: + date = DateUtilities.now() + DateUtilities.ONE_DAY; + break; + case URGENCY_DAY_AFTER: + date = DateUtilities.now() + 2 * DateUtilities.ONE_DAY; + break; + case URGENCY_NEXT_WEEK: + date = DateUtilities.now() + DateUtilities.ONE_WEEK; + break; + case URGENCY_IN_TWO_WEEKS: + date = DateUtilities.now() + 2 * DateUtilities.ONE_WEEK; + break; + case URGENCY_NEXT_MONTH: + date = DateUtilities.oneMonthFromNow(); + break; + case URGENCY_SPECIFIC_DAY: + case URGENCY_SPECIFIC_DAY_TIME: + date = customDate; + break; + default: + throw new IllegalArgumentException("Unknown setting " + setting); } - if(date <= 0) + if (date <= 0) return date; Date dueDate = new Date(date / 1000L * 1000L); // get rid of millis - if(setting != URGENCY_SPECIFIC_DAY_TIME) { + if (setting != URGENCY_SPECIFIC_DAY_TIME) { dueDate.setHours(12); dueDate.setMinutes(0); dueDate.setSeconds(0); // Seconds == 0 means no due time @@ -475,41 +572,39 @@ public final class Task extends RemoteModel { /** * Create hide until for this task. * - * @param setting - * one of the HIDE_UNTIL_* constants - * @param customDate - * if specific day is set, this value + * @param setting one of the HIDE_UNTIL_* constants + * @param customDate if specific day is set, this value * @return */ public long createHideUntil(int setting, long customDate) { long date; - switch(setting) { - case HIDE_UNTIL_NONE: - return 0; - case HIDE_UNTIL_DUE: - case HIDE_UNTIL_DUE_TIME: - date = getValue(DUE_DATE); - break; - case HIDE_UNTIL_DAY_BEFORE: - date = getValue(DUE_DATE) - DateUtilities.ONE_DAY; - break; - case HIDE_UNTIL_WEEK_BEFORE: - date = getValue(DUE_DATE) - DateUtilities.ONE_WEEK; - break; - case HIDE_UNTIL_SPECIFIC_DAY: - case HIDE_UNTIL_SPECIFIC_DAY_TIME: - date = customDate; - break; - default: - throw new IllegalArgumentException("Unknown setting " + setting); + switch (setting) { + case HIDE_UNTIL_NONE: + return 0; + case HIDE_UNTIL_DUE: + case HIDE_UNTIL_DUE_TIME: + date = getValue(DUE_DATE); + break; + case HIDE_UNTIL_DAY_BEFORE: + date = getValue(DUE_DATE) - DateUtilities.ONE_DAY; + break; + case HIDE_UNTIL_WEEK_BEFORE: + date = getValue(DUE_DATE) - DateUtilities.ONE_WEEK; + break; + case HIDE_UNTIL_SPECIFIC_DAY: + case HIDE_UNTIL_SPECIFIC_DAY_TIME: + date = customDate; + break; + default: + throw new IllegalArgumentException("Unknown setting " + setting); } - if(date <= 0) + if (date <= 0) return date; Date hideUntil = new Date(date / 1000L * 1000L); // get rid of millis - if(setting != HIDE_UNTIL_SPECIFIC_DAY_TIME && setting != HIDE_UNTIL_DUE_TIME) { + if (setting != HIDE_UNTIL_SPECIFIC_DAY_TIME && setting != HIDE_UNTIL_DUE_TIME) { hideUntil.setHours(0); hideUntil.setMinutes(0); hideUntil.setSeconds(0); @@ -523,7 +618,7 @@ public final class Task extends RemoteModel { * Checks whether this due date has a due time or only a date */ public boolean hasDueTime() { - if(!hasDueDate()) + if (!hasDueDate()) return false; return hasDueTime(getValue(Task.DUE_DATE)); } @@ -545,7 +640,7 @@ public final class Task extends RemoteModel { } public String sanitizedRecurrence() { - return getValue(Task.RECURRENCE).replaceAll("BYDAY=;","").replaceAll(";?FROM=[^;]*", ""); //$NON-NLS-1$//$NON-NLS-2$ + return getValue(Task.RECURRENCE).replaceAll("BYDAY=;", "").replaceAll(";?FROM=[^;]*", ""); //$NON-NLS-1$//$NON-NLS-2$ } /** diff --git a/api/src/com/todoroo/astrid/data/TaskApiDao.java b/api/src/com/todoroo/astrid/data/TaskApiDao.java index c781c5bf3..74f082ad8 100644 --- a/api/src/com/todoroo/astrid/data/TaskApiDao.java +++ b/api/src/com/todoroo/astrid/data/TaskApiDao.java @@ -22,7 +22,6 @@ import com.todoroo.astrid.api.PermaSql; * want to use the {@link MetadataApiDao} object. * * @author Tim Su - * */ public class TaskApiDao extends ContentResolverDao { @@ -35,66 +34,90 @@ public class TaskApiDao extends ContentResolverDao { */ public static class TaskCriteria { - /** @return tasks by id */ + /** + * @return tasks by id + */ public static Criterion byId(long id) { return Task.ID.eq(id); } - /** @return tasks that were deleted */ + /** + * @return tasks that were deleted + */ public static Criterion isDeleted() { return Task.DELETION_DATE.neq(0); } - /** @return tasks that were not deleted */ + /** + * @return tasks that were not deleted + */ public static Criterion notDeleted() { return Task.DELETION_DATE.eq(0); } - /** @return tasks that have not yet been completed or deleted */ + /** + * @return tasks that have not yet been completed or deleted + */ public static Criterion activeAndVisible() { return Criterion.and(Task.COMPLETION_DATE.eq(0), Task.DELETION_DATE.eq(0), Task.HIDE_UNTIL.lt(Functions.now())); } - /** @return tasks that have not yet been completed or deleted */ + /** + * @return tasks that have not yet been completed or deleted + */ public static Criterion isActive() { return Criterion.and(Task.COMPLETION_DATE.eq(0), Task.DELETION_DATE.eq(0)); } - /** @return tasks that are not hidden at current time */ + /** + * @return tasks that are not hidden at current time + */ public static Criterion isVisible() { return Task.HIDE_UNTIL.lt(Functions.now()); } - /** @return tasks that have a due date */ + /** + * @return tasks that have a due date + */ public static Criterion hasDeadlines() { return Task.DUE_DATE.neq(0); } - /** @return tasks that are due before a certain unixtime */ + /** + * @return tasks that are due before a certain unixtime + */ public static Criterion dueBeforeNow() { return Criterion.and(Task.DUE_DATE.gt(0), Task.DUE_DATE.lt(Functions.now())); } - /** @return tasks that are due after a certain unixtime */ + /** + * @return tasks that are due after a certain unixtime + */ public static Criterion dueAfterNow() { return Task.DUE_DATE.gt(Functions.now()); } - /** @return tasks completed before a given unixtime */ + /** + * @return tasks completed before a given unixtime + */ public static Criterion completed() { return Criterion.and(Task.COMPLETION_DATE.gt(0), Task.COMPLETION_DATE.lt(Functions.now())); } - /** @return tasks that have a blank or null title */ + /** + * @return tasks that have a blank or null title + */ @SuppressWarnings("nls") public static Criterion hasNoTitle() { return Criterion.or(Task.TITLE.isNull(), Task.TITLE.eq("")); } - /** @return tasks that have not yet been completed or deleted */ + /** + * @return tasks that have not yet been completed or deleted + */ public static Criterion activeVisibleMine() { return Criterion.and(Task.COMPLETION_DATE.eq(0), Task.DELETION_DATE.eq(0), @@ -103,16 +126,19 @@ public class TaskApiDao extends ContentResolverDao { Task.USER_ID.eq(0)); } - /** Check if a given task belongs to someone else & is read-only */ + /** + * Check if a given task belongs to someone else & is read-only + */ public static Criterion ownedByMe() { - return Criterion.and(Task.IS_READONLY.eq(0), - Task.USER_ID.eq(0)); + return Criterion.and(Task.IS_READONLY.eq(0), + Task.USER_ID.eq(0)); } } /** * Count tasks matching criterion + * * @param criterion * @return # of tasks matching */ @@ -127,6 +153,7 @@ public class TaskApiDao extends ContentResolverDao { /** * Count tasks matching query tepmlate + * * @param queryTemplate * @return # of tasks matching */ @@ -157,24 +184,26 @@ public class TaskApiDao extends ContentResolverDao { return false; } - /** @return true if task change shouldn't be broadcast */ + /** + * @return true if task change shouldn't be broadcast + */ public static boolean insignificantChange(ContentValues values) { - if(values == null || values.size() == 0) + if (values == null || values.size() == 0) return true; - if(values.containsKey(Task.DETAILS_DATE.name) && + if (values.containsKey(Task.DETAILS_DATE.name) && values.size() <= 3) return true; - if(values.containsKey(Task.REMINDER_LAST.name) && + if (values.containsKey(Task.REMINDER_LAST.name) && values.size() <= 2) return true; - if(values.containsKey(Task.REMINDER_SNOOZE.name) && + if (values.containsKey(Task.REMINDER_SNOOZE.name) && values.size() <= 2) return true; - if(values.containsKey(Task.TIMER_START.name) && + if (values.containsKey(Task.TIMER_START.name) && values.size() <= 2) return true; diff --git a/api/src/com/todoroo/astrid/data/TaskAttachment.java b/api/src/com/todoroo/astrid/data/TaskAttachment.java index 26f7b0bdb..faf120131 100644 --- a/api/src/com/todoroo/astrid/data/TaskAttachment.java +++ b/api/src/com/todoroo/astrid/data/TaskAttachment.java @@ -23,79 +23,112 @@ import com.todoroo.astrid.api.AstridApiConstants; * Data Model which represents a user. * * @author Tim Su - * */ @SuppressWarnings("nls") public final class TaskAttachment extends RemoteModel { // --- table and uri - /** table for this model */ + /** + * table for this model + */ public static final Table TABLE = new Table("task_attachments", TaskAttachment.class); - /** model class for entries in the outstanding table */ + /** + * model class for entries in the outstanding table + */ public static final Class> OUTSTANDING_MODEL = TaskAttachmentOutstanding.class; - /** content uri for this model */ + /** + * content uri for this model + */ public static final Uri CONTENT_URI = Uri.parse("content://" + AstridApiConstants.API_PACKAGE + "/" + TABLE.name); // --- properties - /** ID */ + /** + * ID + */ public static final LongProperty ID = new LongProperty( TABLE, ID_PROPERTY_NAME); - /** Remote id */ + /** + * Remote id + */ public static final StringProperty UUID = new StringProperty( TABLE, UUID_PROPERTY_NAME); - /** Pushed at date */ + /** + * Pushed at date + */ public static final LongProperty PUSHED_AT = new LongProperty( TABLE, PUSHED_AT_PROPERTY_NAME); - /** Creator user id */ + /** + * Creator user id + */ public static final StringProperty USER_UUID = new StringProperty( TABLE, "user_id"); - /** Task uuid */ + /** + * Task uuid + */ public static final StringProperty TASK_UUID = new StringProperty( TABLE, "task_id"); - /** File name */ + /** + * File name + */ public static final StringProperty NAME = new StringProperty( TABLE, "name"); - /** File url (for downloading) */ + /** + * File url (for downloading) + */ public static final StringProperty URL = new StringProperty( TABLE, "url"); - /** File path (on local storage) */ + /** + * File path (on local storage) + */ public static final StringProperty FILE_PATH = new StringProperty( TABLE, "path"); - /** File size (in bytes) */ + /** + * File size (in bytes) + */ public static final IntegerProperty SIZE = new IntegerProperty( TABLE, "size"); - /** File mimetype */ + /** + * File mimetype + */ public static final StringProperty CONTENT_TYPE = new StringProperty( TABLE, "content_type"); - /** Attachment creation date */ + /** + * Attachment creation date + */ public static final LongProperty CREATED_AT = new LongProperty( TABLE, "created_at", Property.PROP_FLAG_DATE); - /** Attachment deletion date */ + /** + * Attachment deletion date + */ public static final LongProperty DELETED_AT = new LongProperty( TABLE, "deleted_at", Property.PROP_FLAG_DATE); - /** List of all properties for this model */ + /** + * List of all properties for this model + */ public static final Property[] PROPERTIES = generateProperties(TaskAttachment.class); // --- defaults - /** Default values container */ + /** + * Default values container + */ private static final ContentValues defaultValues = new ContentValues(); static { @@ -118,13 +151,19 @@ public final class TaskAttachment extends RemoteModel { } // -- Constants - /** default directory for files on external storage */ + /** + * default directory for files on external storage + */ public static final String FILES_DIRECTORY_DEFAULT = "attachments"; //$NON-NLS-1$ - /** preference key for some other download directory */ + /** + * preference key for some other download directory + */ public static final String FILES_DIRECTORY_PREF = "custom_files_dir"; //$NON-NLS-1$ - /** Constants for file types */ + /** + * Constants for file types + */ public static final String FILE_TYPE_AUDIO = "audio/"; //$NON-NLS-1$ public static final String FILE_TYPE_IMAGE = "image/"; //$NON-NLS-1$ public static final String FILE_TYPE_PDF = "application/pdf"; //$NON-NLS-1$ @@ -137,9 +176,9 @@ public final class TaskAttachment extends RemoteModel { public static final String FILE_TYPE_XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; //$NON-NLS-1$ public static final String[] MS_FILETYPES = { - FILE_TYPE_DOC, FILE_TYPE_DOCX, - FILE_TYPE_XLS, FILE_TYPE_XLSX, - FILE_TYPE_PPT, FILE_TYPE_PPTX, + FILE_TYPE_DOC, FILE_TYPE_DOCX, + FILE_TYPE_XLS, FILE_TYPE_XLSX, + FILE_TYPE_PPT, FILE_TYPE_PPTX, }; public static final String FILE_TYPE_OTHER = "application/octet-stream"; //$NON-NLS-1$ diff --git a/api/src/com/todoroo/astrid/data/TaskAttachmentOutstanding.java b/api/src/com/todoroo/astrid/data/TaskAttachmentOutstanding.java index a51960dc6..e3f377748 100644 --- a/api/src/com/todoroo/astrid/data/TaskAttachmentOutstanding.java +++ b/api/src/com/todoroo/astrid/data/TaskAttachmentOutstanding.java @@ -11,12 +11,16 @@ import com.todoroo.andlib.data.Table; @SuppressWarnings("nls") public class TaskAttachmentOutstanding extends OutstandingEntry { - /** table for this model */ + /** + * table for this model + */ public static final Table TABLE = new Table("task_attachment_outstanding", TaskAttachmentOutstanding.class); // --- properties - /** ID */ + /** + * ID + */ public static final LongProperty ID = new LongProperty( TABLE, ID_PROPERTY_NAME); @@ -40,7 +44,9 @@ public class TaskAttachmentOutstanding extends OutstandingEntry defaultValues.put(VALUE_STRING.name, ""); } - /** List of all properties for this model */ + /** + * List of all properties for this model + */ public static final Property[] PROPERTIES = generateProperties(TaskAttachmentOutstanding.class); @Override diff --git a/api/src/com/todoroo/astrid/data/TaskListMetadata.java b/api/src/com/todoroo/astrid/data/TaskListMetadata.java index d772b53f5..4ecc6a3d3 100644 --- a/api/src/com/todoroo/astrid/data/TaskListMetadata.java +++ b/api/src/com/todoroo/astrid/data/TaskListMetadata.java @@ -23,68 +23,94 @@ import com.todoroo.astrid.api.AstridApiConstants; * Data Model which represents a user. * * @author Tim Su - * */ @SuppressWarnings("nls") public final class TaskListMetadata extends RemoteModel { // --- table and uri - /** table for this model */ + /** + * table for this model + */ public static final Table TABLE = new Table("task_list_metadata", TaskListMetadata.class); - /** model class for entries in the outstanding table */ + /** + * model class for entries in the outstanding table + */ public static final Class> OUTSTANDING_MODEL = TaskListMetadataOutstanding.class; - /** content uri for this model */ + /** + * content uri for this model + */ public static final Uri CONTENT_URI = Uri.parse("content://" + AstridApiConstants.API_PACKAGE + "/" + TABLE.name); // --- properties - /** ID */ + /** + * ID + */ public static final LongProperty ID = new LongProperty( TABLE, ID_PROPERTY_NAME); - /** Remote id */ + /** + * Remote id + */ public static final StringProperty UUID = new StringProperty( TABLE, UUID_PROPERTY_NAME); - /** Pushed at date */ + /** + * Pushed at date + */ public static final LongProperty PUSHED_AT = new LongProperty( TABLE, PUSHED_AT_PROPERTY_NAME); - /** Tag UUID */ + /** + * Tag UUID + */ public static final StringProperty TAG_UUID = new StringProperty( TABLE, "tag_uuid"); - /** Filter id (one of below) */ + /** + * Filter id (one of below) + */ public static final StringProperty FILTER = new StringProperty( TABLE, "filter"); - /** Tree of task ids (serialized to json array) */ + /** + * Tree of task ids (serialized to json array) + */ public static final StringProperty TASK_IDS = new StringProperty( TABLE, "task_ids", Property.PROP_FLAG_JSON); - /** Sort setting (one of below) */ + /** + * Sort setting (one of below) + */ public static final StringProperty SORT = new StringProperty( TABLE, "sort"); - /** Settings hash */ + /** + * Settings hash + */ public static final StringProperty SETTINGS = new StringProperty( TABLE, "settings", Property.PROP_FLAG_JSON); - /** Array of child tags (for folders) */ + /** + * Array of child tags (for folders) + */ public static final StringProperty CHILD_TAG_IDS = new StringProperty( TABLE, "child_tags", Property.PROP_FLAG_JSON); - /** If the folder is collapsed */ + /** + * If the folder is collapsed + */ public static final IntegerProperty IS_COLLAPSED = new IntegerProperty( TABLE, "is_collapsed"); - - /** List of all properties for this model */ + /** + * List of all properties for this model + */ public static final Property[] PROPERTIES = generateProperties(TaskListMetadata.class); public static final String FILTER_ID_ALL = "all"; @@ -102,7 +128,9 @@ public final class TaskListMetadata extends RemoteModel { // --- defaults - /** Default values container */ + /** + * Default values container + */ private static final ContentValues defaultValues = new ContentValues(); static { diff --git a/api/src/com/todoroo/astrid/data/TaskListMetadataOutstanding.java b/api/src/com/todoroo/astrid/data/TaskListMetadataOutstanding.java index 52e60e61c..eab6d0e66 100644 --- a/api/src/com/todoroo/astrid/data/TaskListMetadataOutstanding.java +++ b/api/src/com/todoroo/astrid/data/TaskListMetadataOutstanding.java @@ -11,12 +11,16 @@ import com.todoroo.andlib.data.Table; @SuppressWarnings("nls") public class TaskListMetadataOutstanding extends OutstandingEntry { - /** table for this model */ + /** + * table for this model + */ public static final Table TABLE = new Table("task_list_metadata_outstanding", TaskListMetadataOutstanding.class); // --- properties - /** ID */ + /** + * ID + */ public static final LongProperty ID = new LongProperty( TABLE, ID_PROPERTY_NAME); @@ -40,7 +44,9 @@ public class TaskListMetadataOutstanding extends OutstandingEntry[] PROPERTIES = generateProperties(TaskListMetadataOutstanding.class); @Override diff --git a/api/src/com/todoroo/astrid/data/TaskOutstanding.java b/api/src/com/todoroo/astrid/data/TaskOutstanding.java index 6a90ae5c1..7b5ecc8c4 100644 --- a/api/src/com/todoroo/astrid/data/TaskOutstanding.java +++ b/api/src/com/todoroo/astrid/data/TaskOutstanding.java @@ -11,12 +11,16 @@ import com.todoroo.andlib.data.Table; @SuppressWarnings("nls") public class TaskOutstanding extends OutstandingEntry { - /** table for this model */ + /** + * table for this model + */ public static final Table TABLE = new Table("tasks_outstanding", TaskOutstanding.class); // --- properties - /** ID */ + /** + * ID + */ public static final LongProperty ID = new LongProperty( TABLE, ID_PROPERTY_NAME); @@ -40,7 +44,9 @@ public class TaskOutstanding extends OutstandingEntry { defaultValues.put(VALUE_STRING.name, ""); } - /** List of all properties for this model */ + /** + * List of all properties for this model + */ public static final Property[] PROPERTIES = generateProperties(TaskOutstanding.class); @Override diff --git a/api/src/com/todoroo/astrid/data/Update.java b/api/src/com/todoroo/astrid/data/Update.java index aa04bc25f..a4f84da60 100644 --- a/api/src/com/todoroo/astrid/data/Update.java +++ b/api/src/com/todoroo/astrid/data/Update.java @@ -17,12 +17,10 @@ import com.todoroo.andlib.data.TodorooCursor; import com.todoroo.astrid.api.AstridApiConstants; - /** * Data Model which represents an update (e.g. a comment or data update event) * * @author Tim Su - * */ @SuppressWarnings("nls") @Deprecated @@ -30,80 +28,118 @@ public class Update extends RemoteModel { // --- table - /** table for this model */ + /** + * table for this model + */ public static final Table TABLE = new Table("updates", Update.class); - /** content uri for this model */ + /** + * content uri for this model + */ public static final Uri CONTENT_URI = Uri.parse("content://" + AstridApiConstants.API_PACKAGE + "/" + TABLE.name); // --- properties - /** ID */ + /** + * ID + */ public static final LongProperty ID = new LongProperty( TABLE, ID_PROPERTY_NAME); - /** Remote ID */ + /** + * Remote ID + */ public static final LongProperty REMOTE_ID = new LongProperty( TABLE, UUID_PROPERTY_NAME); - /** Associated Task remote-id (if any) */ + /** + * Associated Task remote-id (if any) + */ public static final LongProperty TASK = new LongProperty( TABLE, "task"); - /** Associated Task local-id (if any) */ + /** + * Associated Task local-id (if any) + */ public static final LongProperty TASK_LOCAL = new LongProperty( TABLE, "taskLocal"); - /** Associated Tag remote-ids (comma separated list with leading and trailing commas) */ + /** + * Associated Tag remote-ids (comma separated list with leading and trailing commas) + */ public static final StringProperty TAGS = new StringProperty( TABLE, "tag"); - /** Associated Tag local-ids (comma separated list with leading and trailing commas) */ + /** + * Associated Tag local-ids (comma separated list with leading and trailing commas) + */ public static final StringProperty TAGS_LOCAL = new StringProperty( TABLE, "tagsLocal"); - /** From user id */ + /** + * From user id + */ public static final LongProperty USER_ID = new LongProperty( TABLE, USER_ID_PROPERTY_NAME); - /** From User Object (JSON) */ + /** + * From User Object (JSON) + */ public static final StringProperty USER = new StringProperty( TABLE, USER_JSON_PROPERTY_NAME); - /** Other user id */ + /** + * Other user id + */ public static final LongProperty OTHER_USER_ID = new LongProperty( TABLE, "other_user_id"); - /** Other User Object (JSON) */ + /** + * Other User Object (JSON) + */ public static final StringProperty OTHER_USER = new StringProperty( TABLE, "other_user"); - /** Action text */ + /** + * Action text + */ public static final StringProperty ACTION = new StringProperty( TABLE, "action"); - /** Action code */ + /** + * Action code + */ public static final StringProperty ACTION_CODE = new StringProperty( TABLE, "actionCode"); - /** Message */ + /** + * Message + */ public static final StringProperty MESSAGE = new StringProperty( TABLE, "message"); - /** Target Object Name */ + /** + * Target Object Name + */ public static final StringProperty TARGET_NAME = new StringProperty( TABLE, "targetName"); - /** From User Object (JSON) */ + /** + * From User Object (JSON) + */ public static final StringProperty PICTURE = new StringProperty( TABLE, "picture"); - /** Unixtime Metadata was created */ + /** + * Unixtime Metadata was created + */ public static final LongProperty CREATION_DATE = new LongProperty( TABLE, "created"); - /** List of all properties for this model */ + /** + * List of all properties for this model + */ public static final Property[] PROPERTIES = generateProperties(Update.class); // --- constants @@ -112,7 +148,9 @@ public class Update extends RemoteModel { // --- defaults - /** Default values container */ + /** + * Default values container + */ private static final ContentValues defaultValues = new ContentValues(); @Override @@ -155,7 +193,9 @@ public class Update extends RemoteModel { @Override public long getId() { return getIdHelper(ID); - }; + } + + ; @Override public String getUuid() { diff --git a/api/src/com/todoroo/astrid/data/User.java b/api/src/com/todoroo/astrid/data/User.java index ae3a56ff4..c910c5240 100644 --- a/api/src/com/todoroo/astrid/data/User.java +++ b/api/src/com/todoroo/astrid/data/User.java @@ -22,77 +22,110 @@ import com.todoroo.astrid.api.AstridApiConstants; * Data Model which represents a user. * * @author Tim Su - * */ @SuppressWarnings("nls") public final class User extends RemoteModel { // --- table and uri - /** table for this model */ + /** + * table for this model + */ public static final Table TABLE = new Table("users", User.class); - /** content uri for this model */ + /** + * content uri for this model + */ public static final Uri CONTENT_URI = Uri.parse("content://" + AstridApiConstants.API_PACKAGE + "/" + TABLE.name); // --- properties - /** ID */ + /** + * ID + */ public static final LongProperty ID = new LongProperty( TABLE, ID_PROPERTY_NAME); - /** User Name */ + /** + * User Name + */ public static final StringProperty NAME = new StringProperty( TABLE, "name"); - /** User first name */ + /** + * User first name + */ public static final StringProperty FIRST_NAME = new StringProperty( TABLE, "first_name"); - /** User last name */ + /** + * User last name + */ public static final StringProperty LAST_NAME = new StringProperty( TABLE, "last_name"); - /** User Email */ - @Deprecated public static final StringProperty EMAIL = new StringProperty( + /** + * User Email + */ + @Deprecated + public static final StringProperty EMAIL = new StringProperty( TABLE, "email"); - /** User picture */ + /** + * User picture + */ public static final StringProperty PICTURE = new StringProperty( TABLE, "picture", Property.PROP_FLAG_JSON); - /** Remote id */ + /** + * Remote id + */ public static final StringProperty UUID = new StringProperty( TABLE, UUID_PROPERTY_NAME); - /** Pushed at date */ + /** + * Pushed at date + */ public static final LongProperty PUSHED_AT = new LongProperty( TABLE, PUSHED_AT_PROPERTY_NAME); - /** Pushed at date */ + /** + * Pushed at date + */ public static final LongProperty TASKS_PUSHED_AT = new LongProperty( TABLE, "tasks_pushed_at"); - /** Friendship status. One of the STATUS constants below */ + /** + * Friendship status. One of the STATUS constants below + */ public static final StringProperty STATUS = new StringProperty( TABLE, "status"); - /** Last autosync */ + /** + * Last autosync + */ public static final LongProperty LAST_AUTOSYNC = new LongProperty( TABLE, "lastAutosync"); - /** Friendship tatus that needs to be reported to the server. - * One of the PENDING constants below */ - @Deprecated public static final StringProperty PENDING_STATUS = new StringProperty( + /** + * Friendship tatus that needs to be reported to the server. + * One of the PENDING constants below + */ + @Deprecated + public static final StringProperty PENDING_STATUS = new StringProperty( TABLE, "pendingStatus"); - /** List of all properties for this model */ + /** + * List of all properties for this model + */ public static final Property[] PROPERTIES = generateProperties(User.class); // --- defaults - /** Default values container */ + /** + * Default values container + */ private static final ContentValues defaultValues = new ContentValues(); static { diff --git a/api/src/com/todoroo/astrid/data/UserActivity.java b/api/src/com/todoroo/astrid/data/UserActivity.java index 590c13e39..d0a2a00c7 100644 --- a/api/src/com/todoroo/astrid/data/UserActivity.java +++ b/api/src/com/todoroo/astrid/data/UserActivity.java @@ -14,61 +14,89 @@ import com.todoroo.astrid.api.AstridApiConstants; @SuppressWarnings("nls") public class UserActivity extends RemoteModel { - // --- table + // --- table - /** table for this model */ + /** + * table for this model + */ public static final Table TABLE = new Table("userActivity", UserActivity.class); - /** model class for entries in the outstanding table */ + /** + * model class for entries in the outstanding table + */ public static final Class> OUTSTANDING_MODEL = UserActivityOutstanding.class; - /** content uri for this model */ + /** + * content uri for this model + */ public static final Uri CONTENT_URI = Uri.parse("content://" + AstridApiConstants.API_PACKAGE + "/" + TABLE.name); // --- properties - /** ID */ + /** + * ID + */ public static final LongProperty ID = new LongProperty( TABLE, ID_PROPERTY_NAME); - /** Remote ID */ + /** + * Remote ID + */ public static final StringProperty UUID = new StringProperty( TABLE, UUID_PROPERTY_NAME); - /** Pushed at */ + /** + * Pushed at + */ public static final LongProperty PUSHED_AT = new LongProperty( TABLE, PUSHED_AT_PROPERTY_NAME, Property.PROP_FLAG_DATE); - /** User ID (activity initiator) */ + /** + * User ID (activity initiator) + */ public static final StringProperty USER_UUID = new StringProperty( TABLE, "user_uuid", Property.PROP_FLAG_USER_ID); - /** Action */ + /** + * Action + */ public static final StringProperty ACTION = new StringProperty( TABLE, "action"); - /** Message */ + /** + * Message + */ public static final StringProperty MESSAGE = new StringProperty( TABLE, "message"); - /** Picture */ + /** + * Picture + */ public static final StringProperty PICTURE = new StringProperty( TABLE, "picture", Property.PROP_FLAG_JSON | Property.PROP_FLAG_PICTURE); - /** Target id */ + /** + * Target id + */ public static final StringProperty TARGET_ID = new StringProperty( TABLE, "target_id"); - /** Target name */ + /** + * Target name + */ public static final StringProperty TARGET_NAME = new StringProperty( TABLE, "target_name"); - /** Created at */ + /** + * Created at + */ public static final LongProperty CREATED_AT = new LongProperty( TABLE, "created_at", Property.PROP_FLAG_DATE); - /** Deleted at */ + /** + * Deleted at + */ public static final LongProperty DELETED_AT = new LongProperty( TABLE, "deleted_at", Property.PROP_FLAG_DATE); @@ -99,7 +127,9 @@ public class UserActivity extends RemoteModel { return getUuidHelper(UUID); } - /** Default values container */ + /** + * Default values container + */ private static final ContentValues defaultValues = new ContentValues(); @Override @@ -119,7 +149,9 @@ public class UserActivity extends RemoteModel { defaultValues.put(DELETED_AT.name, 0L); } - /** List of all properties for this model */ + /** + * List of all properties for this model + */ public static final Property[] PROPERTIES = generateProperties(UserActivity.class); @Override diff --git a/api/src/com/todoroo/astrid/data/UserActivityOutstanding.java b/api/src/com/todoroo/astrid/data/UserActivityOutstanding.java index 9291f37d1..df1045163 100644 --- a/api/src/com/todoroo/astrid/data/UserActivityOutstanding.java +++ b/api/src/com/todoroo/astrid/data/UserActivityOutstanding.java @@ -11,12 +11,16 @@ import com.todoroo.andlib.data.Table; @SuppressWarnings("nls") public class UserActivityOutstanding extends OutstandingEntry { - /** table for this model */ + /** + * table for this model + */ public static final Table TABLE = new Table("user_activity_outstanding", UserActivityOutstanding.class); // --- properties - /** ID */ + /** + * ID + */ public static final LongProperty ID = new LongProperty( TABLE, ID_PROPERTY_NAME); @@ -40,7 +44,9 @@ public class UserActivityOutstanding extends OutstandingEntry { defaultValues.put(VALUE_STRING.name, ""); } - /** List of all properties for this model */ + /** + * List of all properties for this model + */ public static final Property[] PROPERTIES = generateProperties(UserActivityOutstanding.class); @Override diff --git a/api/src/com/todoroo/astrid/data/WaitingOnMe.java b/api/src/com/todoroo/astrid/data/WaitingOnMe.java index 81ca04ea0..9531132ee 100644 --- a/api/src/com/todoroo/astrid/data/WaitingOnMe.java +++ b/api/src/com/todoroo/astrid/data/WaitingOnMe.java @@ -15,21 +15,31 @@ import com.todoroo.astrid.api.AstridApiConstants; @SuppressWarnings("nls") public class WaitingOnMe extends RemoteModel { - /** table for this model */ + /** + * table for this model + */ public static final Table TABLE = new Table("waitingOnMe", WaitingOnMe.class); - /** model class for entries in the outstanding table */ + /** + * model class for entries in the outstanding table + */ public static final Class> OUTSTANDING_MODEL = WaitingOnMeOutstanding.class; - /** content uri for this model */ + /** + * content uri for this model + */ public static final Uri CONTENT_URI = Uri.parse("content://" + AstridApiConstants.API_PACKAGE + "/" + TABLE.name); - /** ID */ + /** + * ID + */ public static final LongProperty ID = new LongProperty( TABLE, ID_PROPERTY_NAME); - /** Remote ID */ + /** + * Remote ID + */ public static final StringProperty UUID = new StringProperty( TABLE, RemoteModel.UUID_PROPERTY_NAME); diff --git a/api/src/com/todoroo/astrid/data/WaitingOnMeOutstanding.java b/api/src/com/todoroo/astrid/data/WaitingOnMeOutstanding.java index 2e8479983..859dc5cc3 100644 --- a/api/src/com/todoroo/astrid/data/WaitingOnMeOutstanding.java +++ b/api/src/com/todoroo/astrid/data/WaitingOnMeOutstanding.java @@ -11,12 +11,16 @@ import com.todoroo.andlib.data.Table; @SuppressWarnings("nls") public class WaitingOnMeOutstanding extends OutstandingEntry { - /** table for this model */ + /** + * table for this model + */ public static final Table TABLE = new Table("waiting_on_me_outstanding", WaitingOnMeOutstanding.class); // --- properties - /** ID */ + /** + * ID + */ public static final LongProperty ID = new LongProperty( TABLE, ID_PROPERTY_NAME); @@ -40,7 +44,9 @@ public class WaitingOnMeOutstanding extends OutstandingEntry { defaultValues.put(VALUE_STRING.name, ""); } - /** List of all properties for this model */ + /** + * List of all properties for this model + */ public static final Property[] PROPERTIES = generateProperties(WaitingOnMeOutstanding.class); @Override diff --git a/api/src/com/todoroo/astrid/sync/SyncBackgroundService.java b/api/src/com/todoroo/astrid/sync/SyncBackgroundService.java index 6607224b1..0319362d3 100644 --- a/api/src/com/todoroo/astrid/sync/SyncBackgroundService.java +++ b/api/src/com/todoroo/astrid/sync/SyncBackgroundService.java @@ -5,8 +5,6 @@ */ package com.todoroo.astrid.sync; -import java.util.concurrent.atomic.AtomicBoolean; - import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; @@ -22,23 +20,27 @@ import com.todoroo.andlib.service.ExceptionService; import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.andlib.utility.Preferences; +import java.util.concurrent.atomic.AtomicBoolean; + /** * Performs synchronization service logic in background service to avoid * ANR (application not responding) messages. - *

      + *

      * Starting this service - * schedules a repeating alarm which handles + * schedules a repeating alarm which handles * synchronization with your serv * * @author Tim Su - * */ abstract public class SyncBackgroundService extends Service { - /** Minimum time before an auto-sync */ - private static final long AUTO_SYNC_MIN_OFFSET = 5*60*1000L; + /** + * Minimum time before an auto-sync + */ + private static final long AUTO_SYNC_MIN_OFFSET = 5 * 60 * 1000L; - @Autowired private ExceptionService exceptionService; + @Autowired + private ExceptionService exceptionService; // --- abstract methods @@ -54,11 +56,13 @@ abstract public class SyncBackgroundService extends Service { private final AtomicBoolean started = new AtomicBoolean(false); - /** Receive the alarm - start the synchronize service! */ + /** + * Receive the alarm - start the synchronize service! + */ @Override public void onStart(Intent intent, int startId) { try { - if(intent != null && !started.getAndSet(true)) { + if (intent != null && !started.getAndSet(true)) { startSynchronization(this); } } catch (Exception e) { @@ -66,14 +70,16 @@ abstract public class SyncBackgroundService extends Service { } } - /** Start the actual synchronization */ + /** + * Start the actual synchronization + */ private void startSynchronization(Context context) { - if(context == null || context.getResources() == null) + if (context == null || context.getResources() == null) return; ContextManager.setContext(context); - if(!getSyncUtilities().isLoggedIn()) + if (!getSyncUtilities().isLoggedIn()) return; getSyncProvider().synchronize(context); @@ -99,16 +105,16 @@ abstract public class SyncBackgroundService extends Service { try { syncFrequencySeconds = Preferences.getIntegerFromString( getSyncUtilities().getSyncIntervalKey(), -1); - } catch(ClassCastException e) { + } catch (ClassCastException e) { Preferences.setStringFromInteger(getSyncUtilities().getSyncIntervalKey(), 0); } Context context = ContextManager.getContext(); - if(syncFrequencySeconds <= 0) { - unscheduleService(context); - return; - } + if (syncFrequencySeconds <= 0) { + unscheduleService(context); + return; + } - // figure out synchronization frequency + // figure out synchronization frequency long interval = 1000L * syncFrequencySeconds; long offset = computeNextSyncOffset(interval); @@ -120,7 +126,7 @@ abstract public class SyncBackgroundService extends Service { createAlarmIntent(context), PendingIntent.FLAG_UPDATE_CURRENT); Log.i("Astrid", "Autosync set for " + offset / 1000 //$NON-NLS-1$ //$NON-NLS-2$ - + " seconds repeating every " + syncFrequencySeconds); //$NON-NLS-1$ + + " seconds repeating every " + syncFrequencySeconds); //$NON-NLS-1$ // cancel all existing am.cancel(pendingIntent); @@ -135,13 +141,15 @@ abstract public class SyncBackgroundService extends Service { * Removes repeating alarm for auto-synchronization */ private void unscheduleService(Context context) { - AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); + AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); PendingIntent pendingIntent = PendingIntent.getService(context, getSyncUtilities().getSyncIntervalKey(), createAlarmIntent(context), PendingIntent.FLAG_UPDATE_CURRENT); am.cancel(pendingIntent); } - /** Create the alarm intent */ + /** + * Create the alarm intent + */ private Intent createAlarmIntent(Context context) { Intent intent = new Intent(context, getClass()); return intent; @@ -154,7 +162,7 @@ abstract public class SyncBackgroundService extends Service { long lastSyncDate = getSyncUtilities().getLastSyncDate(); // if user never synchronized, give them a full offset period before bg sync - if(lastSyncDate != 0) + if (lastSyncDate != 0) return Math.max(0, lastSyncDate + interval - DateUtilities.now()); else return interval; diff --git a/api/src/com/todoroo/astrid/sync/SyncContainer.java b/api/src/com/todoroo/astrid/sync/SyncContainer.java index 0ede39ce1..c742df94c 100644 --- a/api/src/com/todoroo/astrid/sync/SyncContainer.java +++ b/api/src/com/todoroo/astrid/sync/SyncContainer.java @@ -5,19 +5,18 @@ */ package com.todoroo.astrid.sync; -import java.util.ArrayList; - import com.todoroo.andlib.utility.AndroidUtilities; import com.todoroo.astrid.data.Metadata; import com.todoroo.astrid.data.Task; +import java.util.ArrayList; + /** * Container class for transmitting tasks and including local and remote * metadata. Synchronization Providers can subclass this class if desired. * - * @see SyncProvider * @author Tim Su - * + * @see SyncProvider */ public class SyncContainer { public Task task; @@ -25,12 +24,13 @@ public class SyncContainer { /** * Check if the metadata contains anything with the given key + * * @param key * @return first match. or null */ public Metadata findMetadata(String key) { - for(Metadata item : metadata) { - if(AndroidUtilities.equals(key, item.getValue(Metadata.KEY))) + for (Metadata item : metadata) { + if (AndroidUtilities.equals(key, item.getValue(Metadata.KEY))) return item; } return null; diff --git a/api/src/com/todoroo/astrid/sync/SyncProvider.java b/api/src/com/todoroo/astrid/sync/SyncProvider.java index 2631981b0..a82933418 100644 --- a/api/src/com/todoroo/astrid/sync/SyncProvider.java +++ b/api/src/com/todoroo/astrid/sync/SyncProvider.java @@ -5,12 +5,6 @@ */ package com.todoroo.astrid.sync; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; - import android.app.Activity; import android.app.Notification; import android.content.Context; @@ -27,20 +21,25 @@ import com.todoroo.andlib.utility.DialogUtilities; import com.todoroo.astrid.api.R; import com.todoroo.astrid.data.Task; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; + /** * A helper class for writing synchronization services for Astrid. This class * contains logic for merging incoming changes and writing outgoing changes. - *

      + *

      * Use {@link #initiateManual} as the entry point for your synchronization * service, which should check if a user is logged in. If not, you should * handle that in the UI, otherwise, you should launch your background * service to perform synchronization in the background. - *

      + *

      * Your background service should {@link #synchronize}, which in turn * invokes {@link #initiateBackground} to initiate synchronization. * * @author Tim Su - * */ public abstract class SyncProvider { @@ -55,8 +54,7 @@ public abstract class SyncProvider { * Perform log in (launching activity if necessary) and sync. This is * invoked when users manually request synchronization * - * @param activity - * context + * @param activity context */ abstract protected void initiateManual(Activity activity); @@ -69,18 +67,18 @@ public abstract class SyncProvider { /** * Updates the text of a notification and the intent to open when tapped + * * @param context * @param notification * @return notification id (in Android, there is at most one notification - * in the tray for a given id) + * in the tray for a given id) */ abstract protected int updateNotification(Context context, Notification n); /** * Create a task on the remote server. * - * @param task - * task to create + * @param task task to create */ abstract protected TYPE create(TYPE task) throws IOException; @@ -88,10 +86,8 @@ public abstract class SyncProvider { * Push variables from given task to the remote server, and read the newly * updated task. * - * @param task - * task proxy to push - * @param remoteTask - * remote task that we merged with. may be null + * @param task task proxy to push + * @param remoteTask remote task that we merged with. may be null * @return task pulled on remote server */ abstract protected TYPE push(TYPE task, TYPE remote) throws IOException; @@ -99,8 +95,7 @@ public abstract class SyncProvider { /** * Fetch remote task. Used to re-read merged tasks * - * @param task - * task with id's to re-read + * @param task task with id's to re-read * @return new Task */ abstract protected TYPE pull(TYPE task) throws IOException; @@ -132,13 +127,14 @@ public abstract class SyncProvider { * Transfer remote identifier(s) from one task to another */ abstract protected void transferIdentifiers(TYPE source, - TYPE destination); + TYPE destination); // --- implementation private final Notification notification; - @Autowired protected ExceptionService exceptionService; + @Autowired + protected ExceptionService exceptionService; public SyncProvider() { DependencyInjectionService.getInstance().inject(this); @@ -152,6 +148,7 @@ public abstract class SyncProvider { /** * Synchronize this provider with sync toast + * * @param context */ public void synchronize(final Context context) { @@ -160,23 +157,24 @@ public abstract class SyncProvider { /** * Synchronize this provider + * * @param context * @param showSyncToast should we toast to indicate synchronizing? */ public void synchronize(final Context context, final boolean showSyncToast) { // display toast - if(context instanceof Activity) { - if(getUtilities().isLoggedIn() && getUtilities().shouldShowToast()) { + if (context instanceof Activity) { + if (getUtilities().isLoggedIn() && getUtilities().shouldShowToast()) { ((Activity) context).runOnUiThread(new Runnable() { @Override public void run() { - if(showSyncToast) + if (showSyncToast) makeSyncToast(context); } }); } - initiateManual((Activity)context); - } else if(context instanceof SyncBackgroundService) { + initiateManual((Activity) context); + } else if (context instanceof SyncBackgroundService) { // display notification final int notificationId = updateNotification(context, notification); final NotificationManager nm = new NotificationManager.AndroidNotificationManager(context); @@ -189,7 +187,7 @@ public abstract class SyncProvider { initiateBackground(); } finally { nm.cancel(notificationId); - ((SyncBackgroundService)context).stop(); + ((SyncBackgroundService) context).stop(); } } }).start(); @@ -208,7 +206,7 @@ public abstract class SyncProvider { /** * Helper to synchronize remote tasks with our local database. - * + *

      * This initiates the following process: 1. local changes are read 2. remote * changes are read 3. local tasks are merged with remote changes and pushed * across 4. remote changes are then read in @@ -221,9 +219,9 @@ public abstract class SyncProvider { // create internal data structures HashMap remoteNewTaskNameMap = new HashMap(); length = data.remoteUpdated.size(); - for(int i = 0; i < length; i++) { + for (int i = 0; i < length; i++) { TYPE remote = data.remoteUpdated.get(i); - if(remote.task.getId() != Task.NO_ID) + if (remote.task.getId() != Task.NO_ID) continue; remoteNewTaskNameMap.put(remote.task.getValue(Task.TITLE), i); } @@ -259,34 +257,36 @@ public abstract class SyncProvider { Collections.sort(data.remoteUpdated, new Comparator() { private static final int SENTINEL = -2; + private final int check(TYPE o1, TYPE o2, LongProperty property) { long o1Property = o1.task.getValue(property); long o2Property = o2.task.getValue(property); - if(o1Property != 0 && o2Property != 0) + if (o1Property != 0 && o2Property != 0) return 0; - else if(o1Property != 0) + else if (o1Property != 0) return -1; - else if(o2Property != 0) + else if (o2Property != 0) return 1; return SENTINEL; } + public int compare(TYPE o1, TYPE o2) { int comparison = check(o1, o2, Task.DELETION_DATE); - if(comparison != SENTINEL) + if (comparison != SENTINEL) return comparison; comparison = check(o1, o2, Task.COMPLETION_DATE); - if(comparison != SENTINEL) + if (comparison != SENTINEL) return comparison; return 0; } }); length = data.remoteUpdated.size(); - for(int i = 0; i < length; i++) { + for (int i = 0; i < length; i++) { TYPE remote = data.remoteUpdated.get(i); // don't synchronize new & deleted tasks - if(!remote.task.isSaved() && (remote.task.isDeleted())) + if (!remote.task.isSaved() && (remote.task.isDeleted())) continue; try { @@ -300,16 +300,16 @@ public abstract class SyncProvider { protected void sendLocallyUpdated(SyncData data) throws IOException { int length; length = data.localUpdated.getCount(); - for(int i = 0; i < length; i++) { + for (int i = 0; i < length; i++) { data.localUpdated.moveToNext(); TYPE local = read(data.localUpdated); try { - if(local.task == null) + if (local.task == null) continue; // if there is a conflict, merge - int remoteIndex = matchTask((ArrayList)data.remoteUpdated, local); - if(remoteIndex != -1) { + int remoteIndex = matchTask((ArrayList) data.remoteUpdated, local); + if (remoteIndex != -1) { TYPE remote = data.remoteUpdated.get(remoteIndex); remote = push(local, remote); @@ -328,10 +328,10 @@ public abstract class SyncProvider { } protected void sendLocallyCreated(SyncData data, - HashMap remoteNewTaskNameMap) throws IOException { + HashMap remoteNewTaskNameMap) throws IOException { int length; length = data.localCreated.getCount(); - for(int i = 0; i < length; i++) { + for (int i = 0; i < length; i++) { data.localCreated.moveToNext(); TYPE local = read(data.localCreated); try { @@ -371,12 +371,9 @@ public abstract class SyncProvider { * to the user (unless synchronization is happening in background) * * @param context - * @param tag - * error tag - * @param e - * exception - * @param showError - * whether to display a dialog + * @param tag error tag + * @param e exception + * @param showError whether to display a dialog */ protected void handleException(String tag, Exception e, boolean displayError) { //TODO: When Crittercism supports it, report error to them @@ -386,12 +383,12 @@ public abstract class SyncProvider { String message = null; // occurs when application was closed - if(e instanceof IllegalStateException) { + if (e instanceof IllegalStateException) { exceptionService.reportError(tag + "-caught", e); //$NON-NLS-1$ } // occurs when network error - else if(e instanceof IOException) { + else if (e instanceof IOException) { exceptionService.reportError(tag + "-io", e); //$NON-NLS-1$ message = context.getString(R.string.SyP_ioerror); } @@ -402,15 +399,17 @@ public abstract class SyncProvider { exceptionService.reportError(tag + "-unhandled", e); //$NON-NLS-1$ } - if(displayError && context instanceof Activity && message != null) { - DialogUtilities.okDialog((Activity)context, + if (displayError && context instanceof Activity && message != null) { + DialogUtilities.okDialog((Activity) context, message, null); } } // --- helper classes - /** data structure builder */ + /** + * data structure builder + */ protected static class SyncData { public ArrayList remoteUpdated; @@ -418,8 +417,8 @@ public abstract class SyncProvider { public TodorooCursor localUpdated; public SyncData(ArrayList remoteUpdated, - TodorooCursor localCreated, - TodorooCursor localUpdated) { + TodorooCursor localCreated, + TodorooCursor localUpdated) { super(); this.remoteUpdated = remoteUpdated; this.localCreated = localCreated; diff --git a/api/src/com/todoroo/astrid/sync/SyncProviderPreferences.java b/api/src/com/todoroo/astrid/sync/SyncProviderPreferences.java index 65c772bca..700261524 100644 --- a/api/src/com/todoroo/astrid/sync/SyncProviderPreferences.java +++ b/api/src/com/todoroo/astrid/sync/SyncProviderPreferences.java @@ -5,10 +5,6 @@ */ package com.todoroo.astrid.sync; -import java.util.Date; -import java.util.HashMap; -import java.util.Set; - import android.app.AlertDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; @@ -29,12 +25,15 @@ import com.todoroo.andlib.utility.DialogUtilities; import com.todoroo.andlib.utility.TodorooPreferenceActivity; import com.todoroo.astrid.api.R; +import java.util.Date; +import java.util.HashMap; +import java.util.Set; + /** * Utility class for common synchronization action: displaying synchronization * preferences and an action panel so users can initiate actions from the menu. * * @author Tim Su sync - if(!loggedIn) { + if (!loggedIn) { status = r.getString(R.string.sync_status_loggedout); statusColor = Color.rgb(19, 132, 165); } // sync is occurring - else if(getUtilities().isOngoing()) { + else if (getUtilities().isOngoing()) { status = r.getString(R.string.sync_status_ongoing); statusColor = Color.rgb(0, 0, 100); } // last sync had errors - else if(getUtilities().getLastError() != null || getUtilities().getLastAttemptedSyncDate() != 0) { + else if (getUtilities().getLastError() != null || getUtilities().getLastAttemptedSyncDate() != 0) { // last sync was failure - if(getUtilities().getLastAttemptedSyncDate() != 0) { + if (getUtilities().getLastAttemptedSyncDate() != 0) { status = r.getString(R.string.sync_status_failed, - DateUtilities.getDateStringWithTime(SyncProviderPreferences.this, - new Date(getUtilities().getLastAttemptedSyncDate()))); + DateUtilities.getDateStringWithTime(SyncProviderPreferences.this, + new Date(getUtilities().getLastAttemptedSyncDate()))); statusColor = Color.rgb(100, 0, 0); - if(getUtilities().getLastSyncDate() > 0) { + if (getUtilities().getLastSyncDate() > 0) { // subtitle = r.getString(R.string.sync_status_failed_subtitle, // DateUtilities.getDateStringWithTime(SyncProviderPreferences.this, // new Date(getUtilities().getLastSyncDate()))); @@ -154,11 +151,10 @@ abstract public class SyncProviderPreferences extends TodorooPreferenceActivity status = r.getString(R.string.sync_status_errors, dateString); statusColor = Color.rgb(100, 100, 0); } - } - else if(getUtilities().getLastSyncDate() > 0) { + } else if (getUtilities().getLastSyncDate() > 0) { status = r.getString(R.string.sync_status_success, DateUtilities.getDateStringWithTime(SyncProviderPreferences.this, - new Date(getUtilities().getLastSyncDate()))); + new Date(getUtilities().getLastSyncDate()))); statusColor = Color.rgb(0, 100, 0); } else { status = r.getString(R.string.sync_status_never); @@ -175,10 +171,9 @@ abstract public class SyncProviderPreferences extends TodorooPreferenceActivity }); View view = findViewById(R.id.status); - if(view != null) + if (view != null) view.setBackgroundColor(statusColor); - } - else if (r.getString(R.string.sync_SPr_key_last_error).equals(preference.getKey())) { + } else if (r.getString(R.string.sync_SPr_key_last_error).equals(preference.getKey())) { if (getUtilities().getLastError() != null) { // Display error final String service = getTitle().toString(); @@ -193,21 +188,21 @@ abstract public class SyncProviderPreferences extends TodorooPreferenceActivity public boolean onPreferenceClick(Preference pref) { // Show last error new AlertDialog.Builder(SyncProviderPreferences.this) - .setTitle(R.string.sync_SPr_last_error) - .setMessage(lastErrorDisplay) - .setPositiveButton(R.string.sync_SPr_send_report, new OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - Intent emailIntent = new Intent(Intent.ACTION_SEND); - emailIntent.setType("plain/text") - .putExtra(Intent.EXTRA_EMAIL, new String[] { "android-bugs@astrid.com"} ) - .putExtra(Intent.EXTRA_SUBJECT, service + " Sync Error") - .putExtra(Intent.EXTRA_TEXT, lastErrorFull); - startActivity(Intent.createChooser(emailIntent, r.getString(R.string.sync_SPr_send_report))); - } - }) - .setNegativeButton(R.string.DLG_close, null) - .create().show(); + .setTitle(R.string.sync_SPr_last_error) + .setMessage(lastErrorDisplay) + .setPositiveButton(R.string.sync_SPr_send_report, new OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + Intent emailIntent = new Intent(Intent.ACTION_SEND); + emailIntent.setType("plain/text") + .putExtra(Intent.EXTRA_EMAIL, new String[]{"android-bugs@astrid.com"}) + .putExtra(Intent.EXTRA_SUBJECT, service + " Sync Error") + .putExtra(Intent.EXTRA_TEXT, lastErrorFull); + startActivity(Intent.createChooser(emailIntent, r.getString(R.string.sync_SPr_send_report))); + } + }) + .setNegativeButton(R.string.DLG_close, null) + .create().show(); return true; } }); @@ -226,7 +221,7 @@ abstract public class SyncProviderPreferences extends TodorooPreferenceActivity r.getString(R.string.sync_forget_confirm), new OnClickListener() { @Override public void onClick(DialogInterface dialog, - int which) { + int which) { logOut(); initializePreference(getPreferenceScreen()); } @@ -234,7 +229,7 @@ abstract public class SyncProviderPreferences extends TodorooPreferenceActivity return true; } }); - if(!loggedIn) { + if (!loggedIn) { PreferenceCategory category = (PreferenceCategory) findPreference(r.getString(R.string.sync_SPr_key_options)); category.removePreference(preference); } @@ -245,7 +240,7 @@ abstract public class SyncProviderPreferences extends TodorooPreferenceActivity /** * We can define exception strings in this map that we want to replace with more user-friendly * messages. As we discover new exception types, we can expand the map. - * + *

      * NOTE: All resources are currently required to have a single string format argument * for inserting the service name into the error message */ diff --git a/api/src/com/todoroo/astrid/sync/SyncProviderUtilities.java b/api/src/com/todoroo/astrid/sync/SyncProviderUtilities.java index ae6d3e756..6c8332265 100644 --- a/api/src/com/todoroo/astrid/sync/SyncProviderUtilities.java +++ b/api/src/com/todoroo/astrid/sync/SyncProviderUtilities.java @@ -42,7 +42,9 @@ abstract public class SyncProviderUtilities { protected static final String PREF_ONGOING = "_ongoing"; //$NON-NLS-1$ - /** Get preferences object from the context */ + /** + * Get preferences object from the context + */ protected static SharedPreferences getPrefs() { return PreferenceManager.getDefaultSharedPreferences(ContextManager.getContext()); } @@ -61,54 +63,74 @@ abstract public class SyncProviderUtilities { return getPrefs().getString(getIdentifier() + PREF_TOKEN, null) != null; } - /** authentication token, or null if doesn't exist */ + /** + * authentication token, or null if doesn't exist + */ public String getToken() { return getPrefs().getString(getIdentifier() + PREF_TOKEN, null); } - /** Returns something like "Logged in as: user@gmail.com" */ + /** + * Returns something like "Logged in as: user@gmail.com" + */ abstract public String getLoggedInUserName(); - /** Sets the authentication token. Set to null to clear. */ + /** + * Sets the authentication token. Set to null to clear. + */ public void setToken(String setting) { Editor editor = getPrefs().edit(); editor.putString(getIdentifier() + PREF_TOKEN, setting); editor.commit(); } - /** @return Last Successful Sync Date, or 0 */ + /** + * @return Last Successful Sync Date, or 0 + */ public long getLastSyncDate() { return getPrefs().getLong(getIdentifier() + PREF_LAST_SYNC, 0); } - /** @return Last Attempted Sync Date, or 0 if it was successful */ + /** + * @return Last Attempted Sync Date, or 0 if it was successful + */ public long getLastAttemptedSyncDate() { return getPrefs().getLong(getIdentifier() + PREF_LAST_ATTEMPTED_SYNC, 0); } - /** @return Last Error, or null if no last error */ + /** + * @return Last Error, or null if no last error + */ public String getLastError() { return getPrefs().getString(getIdentifier() + PREF_LAST_ERROR, null); } - /** @return Last Error type, or null if no last error */ + /** + * @return Last Error type, or null if no last error + */ public String getLastErrorType() { return getPrefs().getString(getIdentifier() + PREF_LAST_ERROR_TYPE, null); } - /** @return Last Error, or null if no last error */ + /** + * @return Last Error, or null if no last error + */ public boolean isOngoing() { return getPrefs().getBoolean(getIdentifier() + PREF_ONGOING, false); } - /** Deletes Last Successful Sync Date */ + /** + * Deletes Last Successful Sync Date + */ public void clearLastSyncDate() { Editor editor = getPrefs().edit(); editor.remove(getIdentifier() + PREF_LAST_SYNC); editor.commit(); } - /** Set Last Error */ + /** + * Set Last Error + */ public void setLastError(String error, String type) { Editor editor = getPrefs().edit(); editor.putString(getIdentifier() + PREF_LAST_ERROR, error); @@ -116,14 +138,18 @@ abstract public class SyncProviderUtilities { editor.commit(); } - /** Set Ongoing */ + /** + * Set Ongoing + */ public void stopOngoing() { Editor editor = getPrefs().edit(); editor.putBoolean(getIdentifier() + PREF_ONGOING, false); editor.commit(); } - /** Set Last Successful Sync Date */ + /** + * Set Last Successful Sync Date + */ public void recordSuccessfulSync() { Editor editor = getPrefs().edit(); editor.putLong(getIdentifier() + PREF_LAST_SYNC, DateUtilities.now() + 1000); @@ -131,7 +157,9 @@ abstract public class SyncProviderUtilities { editor.commit(); } - /** Report last error if one exists */ + /** + * Report last error if one exists + */ public void reportLastError() { String lastError = getLastError(); if (!TextUtils.isEmpty(lastError)) { @@ -144,7 +172,9 @@ abstract public class SyncProviderUtilities { // Subclasses can override if necessary } - /** Set Last Attempted Sync Date */ + /** + * Set Last Attempted Sync Date + */ public void recordSyncStart() { Editor editor = getPrefs().edit(); editor.putLong(getIdentifier() + PREF_LAST_ATTEMPTED_SYNC, diff --git a/api/src/com/todoroo/astrid/sync/SyncResultCallback.java b/api/src/com/todoroo/astrid/sync/SyncResultCallback.java index 0bb844b91..8a860584b 100644 --- a/api/src/com/todoroo/astrid/sync/SyncResultCallback.java +++ b/api/src/com/todoroo/astrid/sync/SyncResultCallback.java @@ -8,12 +8,14 @@ package com.todoroo.astrid.sync; public interface SyncResultCallback { /** * Increment max sync progress + * * @param incrementBy */ public void incrementMax(int incrementBy); /** * Increment current sync progress + * * @param incrementBy */ public void incrementProgress(int incrementBy); diff --git a/api/src/com/todoroo/astrid/sync/SyncResultCallbackAdapter.java b/api/src/com/todoroo/astrid/sync/SyncResultCallbackAdapter.java index 007675649..c4bbbabdb 100644 --- a/api/src/com/todoroo/astrid/sync/SyncResultCallbackAdapter.java +++ b/api/src/com/todoroo/astrid/sync/SyncResultCallbackAdapter.java @@ -6,14 +6,12 @@ package com.todoroo.astrid.sync; - - /** * Convenience class for implementing sync result callbacks--if we need a sync * result callback that only implements a subset of the callback methods, it * can extend this empty implementation - * @author Sam * + * @author Sam */ public abstract class SyncResultCallbackAdapter implements SyncResultCallback { diff --git a/api/src/com/todoroo/astrid/sync/SyncV2BackgroundService.java b/api/src/com/todoroo/astrid/sync/SyncV2BackgroundService.java index 9e6dded89..d46c9c1f6 100644 --- a/api/src/com/todoroo/astrid/sync/SyncV2BackgroundService.java +++ b/api/src/com/todoroo/astrid/sync/SyncV2BackgroundService.java @@ -5,8 +5,6 @@ */ package com.todoroo.astrid.sync; -import java.util.concurrent.atomic.AtomicBoolean; - import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; @@ -23,23 +21,27 @@ import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.andlib.utility.Preferences; import com.todoroo.astrid.api.AstridApiConstants; +import java.util.concurrent.atomic.AtomicBoolean; + /** * Performs synchronization service logic in background service to avoid * ANR (application not responding) messages. - *

      + *

      * Starting this service - * schedules a repeating alarm which handles + * schedules a repeating alarm which handles * synchronization with your serv * * @author Tim Su - * */ abstract public class SyncV2BackgroundService extends Service { - /** Minimum time before an auto-sync */ - private static final long AUTO_SYNC_MIN_OFFSET = 5*60*1000L; + /** + * Minimum time before an auto-sync + */ + private static final long AUTO_SYNC_MIN_OFFSET = 5 * 60 * 1000L; - @Autowired private ExceptionService exceptionService; + @Autowired + private ExceptionService exceptionService; // --- abstract methods @@ -55,11 +57,13 @@ abstract public class SyncV2BackgroundService extends Service { private final AtomicBoolean started = new AtomicBoolean(false); - /** Receive the alarm - start the synchronize service! */ + /** + * Receive the alarm - start the synchronize service! + */ @Override public void onStart(Intent intent, int startId) { try { - if(intent != null && !started.getAndSet(true)) { + if (intent != null && !started.getAndSet(true)) { startSynchronization(this); } } catch (Exception e) { @@ -67,14 +71,16 @@ abstract public class SyncV2BackgroundService extends Service { } } - /** Start the actual synchronization */ + /** + * Start the actual synchronization + */ private void startSynchronization(final Context context) { - if(context == null || context.getResources() == null) + if (context == null || context.getResources() == null) return; ContextManager.setContext(context); - if(!getSyncUtilities().isLoggedIn()) + if (!getSyncUtilities().isLoggedIn()) return; SyncV2Provider provider = getSyncProvider(); @@ -108,16 +114,16 @@ abstract public class SyncV2BackgroundService extends Service { try { syncFrequencySeconds = Preferences.getIntegerFromString( getSyncUtilities().getSyncIntervalKey(), -1); - } catch(ClassCastException e) { + } catch (ClassCastException e) { Preferences.setStringFromInteger(getSyncUtilities().getSyncIntervalKey(), 0); } Context context = ContextManager.getContext(); - if(syncFrequencySeconds <= 0) { - unscheduleService(context); - return; - } + if (syncFrequencySeconds <= 0) { + unscheduleService(context); + return; + } - // figure out synchronization frequency + // figure out synchronization frequency long interval = 1000L * syncFrequencySeconds; long offset = computeNextSyncOffset(interval); @@ -129,7 +135,7 @@ abstract public class SyncV2BackgroundService extends Service { createAlarmIntent(context), PendingIntent.FLAG_UPDATE_CURRENT); Log.i("Astrid", "Autosync set for " + offset / 1000 //$NON-NLS-1$ //$NON-NLS-2$ - + " seconds repeating every " + syncFrequencySeconds); //$NON-NLS-1$ + + " seconds repeating every " + syncFrequencySeconds); //$NON-NLS-1$ // cancel all existing am.cancel(pendingIntent); @@ -144,13 +150,15 @@ abstract public class SyncV2BackgroundService extends Service { * Removes repeating alarm for auto-synchronization */ private void unscheduleService(Context context) { - AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); + AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); PendingIntent pendingIntent = PendingIntent.getService(context, getSyncUtilities().getSyncIntervalKey(), createAlarmIntent(context), PendingIntent.FLAG_UPDATE_CURRENT); am.cancel(pendingIntent); } - /** Create the alarm intent */ + /** + * Create the alarm intent + */ private Intent createAlarmIntent(Context context) { Intent intent = new Intent(context, getClass()); return intent; @@ -163,7 +171,7 @@ abstract public class SyncV2BackgroundService extends Service { long lastSyncDate = getSyncUtilities().getLastSyncDate(); // if user never synchronized, give them a full offset period before bg sync - if(lastSyncDate != 0) + if (lastSyncDate != 0) return Math.max(0, lastSyncDate + interval - DateUtilities.now()); else return interval; diff --git a/api/src/com/todoroo/astrid/sync/SyncV2Provider.java b/api/src/com/todoroo/astrid/sync/SyncV2Provider.java index ed81eddc0..45f0632a2 100644 --- a/api/src/com/todoroo/astrid/sync/SyncV2Provider.java +++ b/api/src/com/todoroo/astrid/sync/SyncV2Provider.java @@ -5,14 +5,14 @@ */ package com.todoroo.astrid.sync; -import java.io.IOException; - import android.app.Activity; import com.todoroo.andlib.service.Autowired; import com.todoroo.andlib.service.DependencyInjectionService; import com.todoroo.andlib.service.ExceptionService; +import java.io.IOException; + abstract public class SyncV2Provider { @@ -22,12 +22,12 @@ abstract public class SyncV2Provider { getUtilities().setLastError(e.toString(), type); // occurs when application was closed - if(e instanceof IllegalStateException) { + if (e instanceof IllegalStateException) { exceptionService.reportError(tag + "-caught", e); //$NON-NLS-1$ } // occurs when network error - else if(e instanceof IOException) { + else if (e instanceof IOException) { exceptionService.reportError(tag + "-io", e); //$NON-NLS-1$ } @@ -60,15 +60,17 @@ abstract public class SyncV2Provider { /** * Synchronize all of user's active tasks - * @param manual whether manually triggered + * + * @param manual whether manually triggered * @param callback callback object */ abstract public void synchronizeActiveTasks(boolean manual, SyncResultCallback callback); /** * Synchronize a single list - * @param list object representing list (TaskListActivity-dependent) - * @param manual whether was manually triggered + * + * @param list object representing list (TaskListActivity-dependent) + * @param manual whether was manually triggered * @param callback callback object */ abstract public void synchronizeList(Object list, boolean manual, SyncResultCallback callback); diff --git a/astrid/AndroidManifest.xml b/astrid/AndroidManifest.xml index 69d8e9d39..1dfc13c27 100644 --- a/astrid/AndroidManifest.xml +++ b/astrid/AndroidManifest.xml @@ -8,656 +8,746 @@ package="com.timsu.astrid" android:versionName="4.6.5" android:versionCode="306"> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/astrid/common-src/com/commonsware/cwac/tlv/TouchListView.java b/astrid/common-src/com/commonsware/cwac/tlv/TouchListView.java index 775fade05..8b30a41e5 100644 --- a/astrid/common-src/com/commonsware/cwac/tlv/TouchListView.java +++ b/astrid/common-src/com/commonsware/cwac/tlv/TouchListView.java @@ -39,40 +39,40 @@ import com.todoroo.astrid.ui.ErrorCatchingListView; @SuppressWarnings("nls") public class TouchListView extends ErrorCatchingListView { - private ImageView mDragView; - private View mOriginalView; - private WindowManager mWindowManager; - private WindowManager.LayoutParams mWindowParams; - private int mDragPos; // which item is being dragged - private int mFirstDragPos; // where was the dragged item originally - private int mDragPoint; // at what offset inside the item did the user grab it - private int mCoordOffset; // the difference between screen coordinates and coordinates in this view - private float mDragStartX, mDragCurrentX; - private long mDragStartTime; - private DragListener mDragListener; - private DropListener mDropListener; - private SwipeListener mSwipeListener; - private GrabberClickListener mClickListener; - private int mUpperBound; - private int mLowerBound; - private int mHeight; - private GestureDetector mGestureDetector; - public static final int FLING = 0; - public static final int SLIDE_RIGHT = 1; - public static final int SLIDE_LEFT = 2; - private int mRemoveMode = -1; - private final Rect mTempRect = new Rect(); - private Bitmap mDragBitmap; - private final int mTouchSlop; - private int mItemHeightNormal=-1; - private int mItemHeightExpanded=-1; - private int grabberId=-1; - private int dragndropBackgroundColor=0x00000000; - private Thread longPressThread; - - public TouchListView(Context context, AttributeSet attrs) { - this(context, attrs, 0); - } + private ImageView mDragView; + private View mOriginalView; + private WindowManager mWindowManager; + private WindowManager.LayoutParams mWindowParams; + private int mDragPos; // which item is being dragged + private int mFirstDragPos; // where was the dragged item originally + private int mDragPoint; // at what offset inside the item did the user grab it + private int mCoordOffset; // the difference between screen coordinates and coordinates in this view + private float mDragStartX, mDragCurrentX; + private long mDragStartTime; + private DragListener mDragListener; + private DropListener mDropListener; + private SwipeListener mSwipeListener; + private GrabberClickListener mClickListener; + private int mUpperBound; + private int mLowerBound; + private int mHeight; + private GestureDetector mGestureDetector; + public static final int FLING = 0; + public static final int SLIDE_RIGHT = 1; + public static final int SLIDE_LEFT = 2; + private int mRemoveMode = -1; + private final Rect mTempRect = new Rect(); + private Bitmap mDragBitmap; + private final int mTouchSlop; + private int mItemHeightNormal = -1; + private int mItemHeightExpanded = -1; + private int grabberId = -1; + private int dragndropBackgroundColor = 0x00000000; + private Thread longPressThread; + + public TouchListView(Context context, AttributeSet attrs) { + this(context, attrs, 0); + } public TouchListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); @@ -98,363 +98,362 @@ public class TouchListView extends ErrorCatchingListView { } @Override - final public void addHeaderView (View v, Object data, boolean isSelectable) { - throw new RuntimeException("Headers are not supported with TouchListView"); - } - - @Override - final public void addHeaderView (View v) { - throw new RuntimeException("Headers are not supported with TouchListView"); - } - - @Override - final public void addFooterView (View v, Object data, boolean isSelectable) { - if (mRemoveMode == SLIDE_LEFT || mRemoveMode == SLIDE_RIGHT) { - throw new RuntimeException("Footers are not supported with TouchListView in conjunction with remove_mode"); + final public void addHeaderView(View v, Object data, boolean isSelectable) { + throw new RuntimeException("Headers are not supported with TouchListView"); + } + + @Override + final public void addHeaderView(View v) { + throw new RuntimeException("Headers are not supported with TouchListView"); } - } - @Override - final public void addFooterView (View v) { - if (mRemoveMode == SLIDE_LEFT || mRemoveMode == SLIDE_RIGHT) { - throw new RuntimeException("Footers are not supported with TouchListView in conjunction with remove_mode"); + @Override + final public void addFooterView(View v, Object data, boolean isSelectable) { + if (mRemoveMode == SLIDE_LEFT || mRemoveMode == SLIDE_RIGHT) { + throw new RuntimeException("Footers are not supported with TouchListView in conjunction with remove_mode"); + } } - } - - @Override - public boolean onInterceptTouchEvent(MotionEvent ev) { - if (mDragListener != null || mDropListener != null) { - switch (ev.getAction()) { - case MotionEvent.ACTION_DOWN: - int x = (int) ev.getX(); - int y = (int) ev.getY(); - int itemnum = pointToPosition(x, y); - if (itemnum == AdapterView.INVALID_POSITION) { - break; - } - - View item = (View) getChildAt(itemnum - getFirstVisiblePosition()); - - if (isDraggableRow(item)) { - mDragPoint = y - item.getTop(); - mCoordOffset = ((int)ev.getRawY()) - y; - View dragger = item.findViewById(grabberId); - Rect r = mTempRect; + + @Override + final public void addFooterView(View v) { + if (mRemoveMode == SLIDE_LEFT || mRemoveMode == SLIDE_RIGHT) { + throw new RuntimeException("Footers are not supported with TouchListView in conjunction with remove_mode"); + } + } + + @Override + public boolean onInterceptTouchEvent(MotionEvent ev) { + if (mDragListener != null || mDropListener != null) { + switch (ev.getAction()) { + case MotionEvent.ACTION_DOWN: + int x = (int) ev.getX(); + int y = (int) ev.getY(); + int itemnum = pointToPosition(x, y); + if (itemnum == AdapterView.INVALID_POSITION) { + break; + } + + View item = (View) getChildAt(itemnum - getFirstVisiblePosition()); + + if (isDraggableRow(item)) { + mDragPoint = y - item.getTop(); + mCoordOffset = ((int) ev.getRawY()) - y; + View dragger = item.findViewById(grabberId); + Rect r = mTempRect; // dragger.getDrawingRect(r); - r.left=dragger.getLeft(); - r.right=dragger.getRight(); - r.top=dragger.getTop(); - r.bottom=dragger.getBottom(); - - if ((r.left= 0; i--) { - final View child = getChildAt(i); - child.getHitRect(frame); - if (frame.contains(x, y)) { - return getFirstVisiblePosition() + i; - } - } - return INVALID_POSITION; - } - - private int getItemForPosition(int y) { - int adjustedy = y - mDragPoint - (mItemHeightNormal/2); - int pos = myPointToPosition(0, adjustedy); - if (pos >= 0) { - if (pos <= mFirstDragPos) { - pos += 1; - } - } else if (adjustedy < 0) { - pos = 0; - } - return pos; - } - - private void adjustScrollBounds(int y) { - if (y >= mHeight / 3) { - mUpperBound = mHeight / 3; - } - if (y <= mHeight * 2 / 3) { - mLowerBound = mHeight * 2 / 3; - } - } - - /* - * Restore size and visibility for all listitems - */ - private void unExpandViews(boolean deletion) { - for (int i = 0;; i++) { - View v = getChildAt(i); - if (v == null) { - if (deletion) { - // HACK force update of mItemCount - int position = getFirstVisiblePosition(); - int y = getChildAt(0).getTop(); - setAdapter(getAdapter()); - setSelectionFromTop(position, y); - // end hack - } - layoutChildren(); // force children to be recreated where needed - v = getChildAt(i); - if (v == null) { - break; - } - } - - if (isDraggableRow(v)) { - ViewGroup.LayoutParams params = v.getLayoutParams(); - params.height = mItemHeightNormal; - v.setLayoutParams(params); - v.setVisibility(View.VISIBLE); - } - } - } - - /* Adjust visibility and size to make it appear as though - * an item is being dragged around and other items are making - * room for it: - * If dropping the item would result in it still being in the - * same place, then make the dragged listitem's size normal, - * but make the item invisible. - * Otherwise, if the dragged listitem is still on screen, make - * it as small as possible and expand the item below the insert - * point. - * If the dragged item is not on screen, only expand the item - * below the current insertpoint. - */ - private void doExpansion() { - int childnum = mDragPos - getFirstVisiblePosition(); - if (mDragPos > mFirstDragPos) { - childnum++; - } - - View first = getChildAt(mFirstDragPos - getFirstVisiblePosition()); - - for (int i = 0;; i++) { - View vv = getChildAt(i); - if (vv == null) { - break; - } - int height = mItemHeightNormal; - int visibility = View.VISIBLE; - if (vv.equals(first)) { - // processing the item that is being dragged - if (mDragPos == mFirstDragPos) { - // hovering over the original location - visibility = View.INVISIBLE; - } else { - // not hovering over it - height = 1; - } - } else if (i == childnum) { - if (mDragPos < getCount() - 1) { - height = mItemHeightExpanded; - } - } - - if (isDraggableRow(vv)) { - ViewGroup.LayoutParams params = vv.getLayoutParams(); - params.height = height; - vv.setLayoutParams(params); - vv.setVisibility(visibility); - } - } - // Request re-layout since we changed the items layout - // and not doing this would cause bogus hitbox calculation - // in myPointToPosition - layoutChildren(); - } - - @Override - public boolean onTouchEvent(MotionEvent ev) { - if (mGestureDetector != null) { - mGestureDetector.onTouchEvent(ev); - } - if ((mDragListener != null || mDropListener != null) && mDragView != null) { - int action = ev.getAction(); - switch (action) { - case MotionEvent.ACTION_UP: - case MotionEvent.ACTION_CANCEL: - Rect r = mTempRect; - mDragView.getDrawingRect(r); - stopDragging(ev); - if (mDragPos == mFirstDragPos && ev.getX() > mDragStartX + 20) { - if (mSwipeListener!= null) { - mSwipeListener.swipeRight(mFirstDragPos); - } - unExpandViews(true); - } else if (mDragPos == mFirstDragPos && ev.getX() < mDragStartX - 20) { - if (mSwipeListener!= null) { - mSwipeListener.swipeLeft(mFirstDragPos); - } - unExpandViews(true); - } else { - if (mDropListener != null && mDragPos >= 0 && mDragPos < getCount()) { - mDropListener.drop(mFirstDragPos, mDragPos); - } - unExpandViews(false); - } - break; - - case MotionEvent.ACTION_DOWN: - case MotionEvent.ACTION_MOVE: - int x = (int) ev.getX(); - int y = (int) ev.getY(); - dragView(x, y); - int itemnum = getItemForPosition(y); - if (itemnum >= 0) { - if (action == MotionEvent.ACTION_DOWN || itemnum != mDragPos) { - if (mDragListener != null) { - mDragListener.drag(mDragPos, itemnum); - } - mDragPos = itemnum; - doExpansion(); - } - int speed = 0; - adjustScrollBounds(y); - if (y > mLowerBound) { - // scroll the list up a bit - speed = y > (mHeight + mLowerBound) / 2 ? 16 : 4; - } else if (y < mUpperBound) { - // scroll the list down a bit - speed = y < mUpperBound / 2 ? -16 : -4; - } - if (speed != 0) { - int ref = pointToPosition(0, mHeight / 2); - if (ref == AdapterView.INVALID_POSITION) { - //we hit a divider or an invisible view, check somewhere else - ref = pointToPosition(0, mHeight / 2 + getDividerHeight() + 64); - } - View v = getChildAt(ref - getFirstVisiblePosition()); - if (v!= null) { - int pos = v.getTop(); - setSelectionFromTop(ref, pos - speed); - } - } - } - break; - } - return true; - } - return super.onTouchEvent(ev); - } - - private void startDragging(Bitmap bm, int x, int y) { - stopDragging(null); - - mWindowParams = new WindowManager.LayoutParams(); - mWindowParams.gravity = Gravity.TOP|Gravity.LEFT; - mWindowParams.x = x; - mWindowParams.y = y - mDragPoint + mCoordOffset; - - mWindowParams.height = WindowManager.LayoutParams.WRAP_CONTENT; - mWindowParams.width = WindowManager.LayoutParams.WRAP_CONTENT; - mWindowParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE - | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE - | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON - | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN; - mWindowParams.format = PixelFormat.TRANSLUCENT; - mWindowParams.windowAnimations = 0; - - ImageView v = new ImageView(getContext()); - v.setBackgroundColor(dragndropBackgroundColor); - v.setImageBitmap(bm); - mDragBitmap = bm; - - mWindowManager = (WindowManager)getContext().getSystemService(Context.WINDOW_SERVICE); - mWindowManager.addView(v, mWindowParams); - mDragView = v; - - if(mClickListener != null) { - longPressThread = new Thread(longPressRunnable); - longPressThread.start(); - } - } - - private final Runnable longPressRunnable = new Runnable() { - public void run() { - AndroidUtilities.sleepDeep(1000L); - if(Thread.currentThread().isInterrupted()) - return; - - if(mDragView != null && mDragPos == mFirstDragPos && + r.left = dragger.getLeft(); + r.right = dragger.getRight(); + r.top = dragger.getTop(); + r.bottom = dragger.getBottom(); + + if ((r.left < x) && (x < r.right)) { + item.setDrawingCacheEnabled(true); + // Create a copy of the drawing cache so that it does not get recycled + // by the framework when the list tries to clean up memory + Bitmap bitmap = Bitmap.createBitmap(item.getDrawingCache()); + item.setDrawingCacheEnabled(false); + + Rect listBounds = new Rect(); + + getGlobalVisibleRect(listBounds, null); + + startDragging(bitmap, listBounds.left, y); + mDragPos = itemnum; + mFirstDragPos = mDragPos; + mHeight = getHeight(); + mDragStartX = ev.getX(); + mDragStartTime = System.currentTimeMillis(); + mOriginalView = item; + + int touchSlop = mTouchSlop; + mUpperBound = Math.min(y - touchSlop, mHeight / 3); + mLowerBound = Math.max(y + touchSlop, mHeight * 2 / 3); + return false; + } + + mDragView = null; + } + + break; + } + } + return super.onInterceptTouchEvent(ev); + } + + protected boolean isDraggableRow(View view) { + return (view.findViewById(grabberId) != null); + } + + /* + * pointToPosition() doesn't consider invisible views, but we + * need to, so implement a slightly different version. + */ + private int myPointToPosition(int x, int y) { + Rect frame = mTempRect; + final int count = getChildCount(); + for (int i = count - 1; i >= 0; i--) { + final View child = getChildAt(i); + child.getHitRect(frame); + if (frame.contains(x, y)) { + return getFirstVisiblePosition() + i; + } + } + return INVALID_POSITION; + } + + private int getItemForPosition(int y) { + int adjustedy = y - mDragPoint - (mItemHeightNormal / 2); + int pos = myPointToPosition(0, adjustedy); + if (pos >= 0) { + if (pos <= mFirstDragPos) { + pos += 1; + } + } else if (adjustedy < 0) { + pos = 0; + } + return pos; + } + + private void adjustScrollBounds(int y) { + if (y >= mHeight / 3) { + mUpperBound = mHeight / 3; + } + if (y <= mHeight * 2 / 3) { + mLowerBound = mHeight * 2 / 3; + } + } + + /* + * Restore size and visibility for all listitems + */ + private void unExpandViews(boolean deletion) { + for (int i = 0; ; i++) { + View v = getChildAt(i); + if (v == null) { + if (deletion) { + // HACK force update of mItemCount + int position = getFirstVisiblePosition(); + int y = getChildAt(0).getTop(); + setAdapter(getAdapter()); + setSelectionFromTop(position, y); + // end hack + } + layoutChildren(); // force children to be recreated where needed + v = getChildAt(i); + if (v == null) { + break; + } + } + + if (isDraggableRow(v)) { + ViewGroup.LayoutParams params = v.getLayoutParams(); + params.height = mItemHeightNormal; + v.setLayoutParams(params); + v.setVisibility(View.VISIBLE); + } + } + } + + /* Adjust visibility and size to make it appear as though + * an item is being dragged around and other items are making + * room for it: + * If dropping the item would result in it still being in the + * same place, then make the dragged listitem's size normal, + * but make the item invisible. + * Otherwise, if the dragged listitem is still on screen, make + * it as small as possible and expand the item below the insert + * point. + * If the dragged item is not on screen, only expand the item + * below the current insertpoint. + */ + private void doExpansion() { + int childnum = mDragPos - getFirstVisiblePosition(); + if (mDragPos > mFirstDragPos) { + childnum++; + } + + View first = getChildAt(mFirstDragPos - getFirstVisiblePosition()); + + for (int i = 0; ; i++) { + View vv = getChildAt(i); + if (vv == null) { + break; + } + int height = mItemHeightNormal; + int visibility = View.VISIBLE; + if (vv.equals(first)) { + // processing the item that is being dragged + if (mDragPos == mFirstDragPos) { + // hovering over the original location + visibility = View.INVISIBLE; + } else { + // not hovering over it + height = 1; + } + } else if (i == childnum) { + if (mDragPos < getCount() - 1) { + height = mItemHeightExpanded; + } + } + + if (isDraggableRow(vv)) { + ViewGroup.LayoutParams params = vv.getLayoutParams(); + params.height = height; + vv.setLayoutParams(params); + vv.setVisibility(visibility); + } + } + // Request re-layout since we changed the items layout + // and not doing this would cause bogus hitbox calculation + // in myPointToPosition + layoutChildren(); + } + + @Override + public boolean onTouchEvent(MotionEvent ev) { + if (mGestureDetector != null) { + mGestureDetector.onTouchEvent(ev); + } + if ((mDragListener != null || mDropListener != null) && mDragView != null) { + int action = ev.getAction(); + switch (action) { + case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_CANCEL: + Rect r = mTempRect; + mDragView.getDrawingRect(r); + stopDragging(ev); + if (mDragPos == mFirstDragPos && ev.getX() > mDragStartX + 20) { + if (mSwipeListener != null) { + mSwipeListener.swipeRight(mFirstDragPos); + } + unExpandViews(true); + } else if (mDragPos == mFirstDragPos && ev.getX() < mDragStartX - 20) { + if (mSwipeListener != null) { + mSwipeListener.swipeLeft(mFirstDragPos); + } + unExpandViews(true); + } else { + if (mDropListener != null && mDragPos >= 0 && mDragPos < getCount()) { + mDropListener.drop(mFirstDragPos, mDragPos); + } + unExpandViews(false); + } + break; + + case MotionEvent.ACTION_DOWN: + case MotionEvent.ACTION_MOVE: + int x = (int) ev.getX(); + int y = (int) ev.getY(); + dragView(x, y); + int itemnum = getItemForPosition(y); + if (itemnum >= 0) { + if (action == MotionEvent.ACTION_DOWN || itemnum != mDragPos) { + if (mDragListener != null) { + mDragListener.drag(mDragPos, itemnum); + } + mDragPos = itemnum; + doExpansion(); + } + int speed = 0; + adjustScrollBounds(y); + if (y > mLowerBound) { + // scroll the list up a bit + speed = y > (mHeight + mLowerBound) / 2 ? 16 : 4; + } else if (y < mUpperBound) { + // scroll the list down a bit + speed = y < mUpperBound / 2 ? -16 : -4; + } + if (speed != 0) { + int ref = pointToPosition(0, mHeight / 2); + if (ref == AdapterView.INVALID_POSITION) { + //we hit a divider or an invisible view, check somewhere else + ref = pointToPosition(0, mHeight / 2 + getDividerHeight() + 64); + } + View v = getChildAt(ref - getFirstVisiblePosition()); + if (v != null) { + int pos = v.getTop(); + setSelectionFromTop(ref, pos - speed); + } + } + } + break; + } + return true; + } + return super.onTouchEvent(ev); + } + + private void startDragging(Bitmap bm, int x, int y) { + stopDragging(null); + + mWindowParams = new WindowManager.LayoutParams(); + mWindowParams.gravity = Gravity.TOP | Gravity.LEFT; + mWindowParams.x = x; + mWindowParams.y = y - mDragPoint + mCoordOffset; + + mWindowParams.height = WindowManager.LayoutParams.WRAP_CONTENT; + mWindowParams.width = WindowManager.LayoutParams.WRAP_CONTENT; + mWindowParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE + | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE + | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON + | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN; + mWindowParams.format = PixelFormat.TRANSLUCENT; + mWindowParams.windowAnimations = 0; + + ImageView v = new ImageView(getContext()); + v.setBackgroundColor(dragndropBackgroundColor); + v.setImageBitmap(bm); + mDragBitmap = bm; + + mWindowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); + mWindowManager.addView(v, mWindowParams); + mDragView = v; + + if (mClickListener != null) { + longPressThread = new Thread(longPressRunnable); + longPressThread.start(); + } + } + + private final Runnable longPressRunnable = new Runnable() { + public void run() { + AndroidUtilities.sleepDeep(1000L); + if (Thread.currentThread().isInterrupted()) + return; + + if (mDragView != null && mDragPos == mFirstDragPos && Math.abs(mDragCurrentX - mDragStartX) < 10) { - post(new Runnable() { - public void run() { - stopDragging(null); - mClickListener.onLongClick(mOriginalView); - invalidate(); - } - }); - } - } - }; - - private void dragView(int x, int y) { - float alpha = 1.0f; - int width = mDragView.getWidth(); - - if (mRemoveMode == SLIDE_RIGHT) { - if (x > width / 2) { - alpha = ((float)(width - x)) / (width / 2); - } - mWindowParams.alpha = alpha; - } - else if (mRemoveMode == SLIDE_LEFT) { - if (x < width / 2) { - alpha = ((float)x) / (width / 2); - } - mWindowParams.alpha = alpha; - } - mWindowParams.y = y - mDragPoint + mCoordOffset; - mWindowManager.updateViewLayout(mDragView, mWindowParams); - mDragCurrentX = x; - } + post(new Runnable() { + public void run() { + stopDragging(null); + mClickListener.onLongClick(mOriginalView); + invalidate(); + } + }); + } + } + }; + + private void dragView(int x, int y) { + float alpha = 1.0f; + int width = mDragView.getWidth(); + + if (mRemoveMode == SLIDE_RIGHT) { + if (x > width / 2) { + alpha = ((float) (width - x)) / (width / 2); + } + mWindowParams.alpha = alpha; + } else if (mRemoveMode == SLIDE_LEFT) { + if (x < width / 2) { + alpha = ((float) x) / (width / 2); + } + mWindowParams.alpha = alpha; + } + mWindowParams.y = y - mDragPoint + mCoordOffset; + mWindowManager.updateViewLayout(mDragView, mWindowParams); + mDragCurrentX = x; + } private void stopDragging(MotionEvent ev) { if (mDragBitmap != null) { @@ -471,10 +470,10 @@ public class TouchListView extends ErrorCatchingListView { if (ev != null && mClickListener != null) { // detect press & long press case - if(mDragPos == mFirstDragPos && + if (mDragPos == mFirstDragPos && Math.abs(mDragCurrentX - mDragStartX) < 10) { long pressTime = System.currentTimeMillis() - mDragStartTime; - if(pressTime < 1000) + if (pressTime < 1000) mClickListener.onClick(mOriginalView); else mClickListener.onLongClick(mOriginalView); @@ -482,45 +481,49 @@ public class TouchListView extends ErrorCatchingListView { } } - if(longPressThread != null) { + if (longPressThread != null) { longPressThread.interrupt(); longPressThread = null; } } - public void setDragListener(DragListener l) { - mDragListener = l; - } + public void setDragListener(DragListener l) { + mDragListener = l; + } - public void setDropListener(DropListener l) { - mDropListener = l; - } + public void setDropListener(DropListener l) { + mDropListener = l; + } - public void setSwipeListener(SwipeListener l) { - mSwipeListener = l; - } + public void setSwipeListener(SwipeListener l) { + mSwipeListener = l; + } - public void setClickListener(GrabberClickListener listener) { + public void setClickListener(GrabberClickListener listener) { this.mClickListener = listener; } - public void setDragndropBackgroundColor(int color) { + public void setDragndropBackgroundColor(int color) { this.dragndropBackgroundColor = color; } - public interface GrabberClickListener { - public void onClick(View v); - public void onLongClick(View v); - } - - public interface DragListener { - void drag(int from, int to); - } - public interface DropListener { - void drop(int from, int to); - } - public interface SwipeListener { - void swipeLeft(int which); - void swipeRight(int which); - } + public interface GrabberClickListener { + public void onClick(View v); + + public void onLongClick(View v); + } + + public interface DragListener { + void drag(int from, int to); + } + + public interface DropListener { + void drop(int from, int to); + } + + public interface SwipeListener { + void swipeLeft(int which); + + void swipeRight(int which); + } } diff --git a/astrid/common-src/com/localytics/android/Constants.java b/astrid/common-src/com/localytics/android/Constants.java index 087cc19fa..57605ae3c 100644 --- a/astrid/common-src/com/localytics/android/Constants.java +++ b/astrid/common-src/com/localytics/android/Constants.java @@ -9,11 +9,10 @@ import android.text.format.DateUtils; /** * Build constants for the Localytics library. - *

      + *

      * This is not a public API. */ -/* package */final class Constants -{ +/* package */final class Constants { /** * Version number of this library. This number is primarily important in terms of changes to the upload format. @@ -53,7 +52,7 @@ import android.text.format.DateUtils; /** * Milliseconds after which a session is considered closed and cannot be reattached to. - *

      + *

      * For example, if the user opens an app, presses home, and opens the app again in less than {@link #SESSION_EXPIRATION} * milliseconds, that will count as one session rather than two sessions. */ @@ -66,7 +65,7 @@ import android.text.format.DateUtils; /** * Boolean indicating whether logcat messages are enabled. - *

      + *

      * Before releasing a production version of an app, this should be set to false for privacy and performance reasons. When * logging is enabled, sensitive information such as the device ID may be printed to the log. */ @@ -79,7 +78,7 @@ import android.text.format.DateUtils; /** * Cached copy of the current Android API level - * + * * @see DatapointHelper#getApiLevel() */ /*package*/ static final int CURRENT_API_LEVEL = DatapointHelper.getApiLevel(); @@ -89,8 +88,7 @@ import android.text.format.DateUtils; * * @throws UnsupportedOperationException because this class cannot be instantiated. */ - private Constants() - { + private Constants() { throw new UnsupportedOperationException("This class is non-instantiable"); //$NON-NLS-1$ } } diff --git a/astrid/common-src/com/localytics/android/DatapointHelper.java b/astrid/common-src/com/localytics/android/DatapointHelper.java index 95a7d143e..87348d810 100755 --- a/astrid/common-src/com/localytics/android/DatapointHelper.java +++ b/astrid/common-src/com/localytics/android/DatapointHelper.java @@ -8,6 +8,15 @@ package com.localytics.android; +import android.Manifest.permission; +import android.content.Context; +import android.content.pm.PackageManager; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; +import android.os.Build; +import android.telephony.TelephonyManager; +import android.util.Log; + import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; @@ -18,22 +27,12 @@ import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -import android.Manifest.permission; -import android.content.Context; -import android.content.pm.PackageManager; -import android.net.ConnectivityManager; -import android.net.NetworkInfo; -import android.os.Build; -import android.telephony.TelephonyManager; -import android.util.Log; - /** * Provides a number of static functions to aid in the collection and formatting of datapoints. - *

      + *

      * Note: this is not a public API. */ -/* package */final class DatapointHelper -{ +/* package */final class DatapointHelper { /** * AndroidID known to be duplicated across many devices due to manufacturer bugs. */ @@ -49,38 +48,30 @@ import android.util.Log; * * @throws UnsupportedOperationException because this class cannot be instantiated. */ - private DatapointHelper() - { + private DatapointHelper() { throw new UnsupportedOperationException("This class is non-instantiable"); //$NON-NLS-1$ } /** * @return current Android API level. */ - /* package */static int getApiLevel() - { - try - { + /* package */ + static int getApiLevel() { + try { // Although the Build.VERSION.SDK field has existed since API 1, it is deprecated and could be removed // in the future. Therefore use reflection to retrieve it for maximum forward compatibility. final Class buildClass = Build.VERSION.class; final String sdkString = (String) buildClass.getField("SDK").get(null); //$NON-NLS-1$ return Integer.parseInt(sdkString); - } - catch (final Exception e) - { + } catch (final Exception e) { Log.w(Constants.LOG_TAG, "Caught exception", e); //$NON-NLS-1$ // Although probably not necessary, protects from the aforementioned deprecation - try - { + try { final Class buildClass = Build.VERSION.class; return buildClass.getField("SDK_INT").getInt(null); //$NON-NLS-1$ - } - catch (final Exception ignore) - { - if (Constants.IS_LOGGABLE) - { + } catch (final Exception ignore) { + if (Constants.IS_LOGGABLE) { Log.w(Constants.LOG_TAG, "Caught exception", ignore); //$NON-NLS-1$ } } @@ -96,20 +87,16 @@ import android.util.Log; * * @param context The context used to access the settings resolver * @return An 1-way hashed version of the {@link android.provider.Settings.Secure#ANDROID_ID}. May return null if an Android - * ID or the hashing algorithm is not available. + * ID or the hashing algorithm is not available. */ - public static String getAndroidIdHashOrNull(final Context context) - { + public static String getAndroidIdHashOrNull(final Context context) { // Make sure a legacy version of the SDK didn't leave behind a device ID. // If it did, this ID must be used to keep user counts accurate final File fp = new File(context.getFilesDir() + LEGACY_DEVICE_ID_FILE); - if (fp.exists() && fp.length() > 0) - { - try - { + if (fp.exists() && fp.length() > 0) { + try { BufferedReader reader = null; - try - { + try { final char[] buf = new char[100]; int numRead; reader = new BufferedReader(new FileReader(fp), 128); @@ -117,34 +104,24 @@ import android.util.Log; final String deviceId = String.copyValueOf(buf, 0, numRead); reader.close(); return deviceId; - } - catch (final FileNotFoundException e) - { - if (Constants.IS_LOGGABLE) - { + } catch (final FileNotFoundException e) { + if (Constants.IS_LOGGABLE) { Log.w(Constants.LOG_TAG, "Caught exception", e); //$NON-NLS-1$ } - } - finally - { - if (null != reader) - { + } finally { + if (null != reader) { reader.close(); } } - } - catch (final IOException e) - { - if (Constants.IS_LOGGABLE) - { + } catch (final IOException e) { + if (Constants.IS_LOGGABLE) { Log.w(Constants.LOG_TAG, "Caught exception", e); //$NON-NLS-1$ } } } final String androidId = android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID); - if (androidId == null || androidId.toLowerCase().equals(INVALID_ANDROID_ID)) - { + if (androidId == null || androidId.toLowerCase().equals(INVALID_ANDROID_ID)) { return null; } @@ -154,29 +131,24 @@ import android.util.Log; /** * Gets a 1-way hashed value of the device's unique serial number. This value is encoded using a SHA-256 one way hash and * therefore cannot be used to determine what device this data came from. - *

      + *

      * Note: {@link android.os.Build#SERIAL} was introduced in SDK 9. For older SDKs, this method will return null. * * @return An 1-way hashed version of the {@link android.os.Build#SERIAL}. May return null if a serial or the hashing - * algorithm is not available. + * algorithm is not available. */ /* * Suppress JavaDoc warnings because the {@link android.os.Build#SERIAL} fails when built with SDK 4. */ - public static String getSerialNumberHashOrNull() - { + public static String getSerialNumberHashOrNull() { /* * Obtain the device serial number using reflection, since serial number was added in SDK 9 */ String serialNumber = null; - if (Constants.CURRENT_API_LEVEL >= 9) - { - try - { + if (Constants.CURRENT_API_LEVEL >= 9) { + try { serialNumber = (String) Build.class.getField("SERIAL").get(null); //$NON-NLS-1$ - } - catch (final Exception e) - { + } catch (final Exception e) { /* * This should never happen, as SERIAL is a public field added in SDK 9. */ @@ -184,8 +156,7 @@ import android.util.Log; } } - if (serialNumber == null) - { + if (serialNumber == null) { return null; } @@ -194,24 +165,20 @@ import android.util.Log; /** * Gets the device's telephony ID (e.g. IMEI/MEID). - *

      + *

      * Note: this method will return null if {@link permission#READ_PHONE_STATE} is not available. This method will also return * null on devices that do not have telephony. * * @param context The context used to access the phone state. * @return An the {@link TelephonyManager#getDeviceId()}. Null if an ID is not available, or if - * {@link permission#READ_PHONE_STATE} is not available. + * {@link permission#READ_PHONE_STATE} is not available. */ - public static String getTelephonyDeviceIdOrNull(final Context context) - { - if (Constants.CURRENT_API_LEVEL >= 8) - { - final Boolean hasTelephony = ReflectionUtils.tryInvokeInstance(context.getPackageManager(), "hasSystemFeature", new Class[] { String.class }, new Object[] { "android.hardware.telephony" }); //$NON-NLS-1$//$NON-NLS-2$ - - if (!hasTelephony.booleanValue()) - { - if (Constants.IS_LOGGABLE) - { + public static String getTelephonyDeviceIdOrNull(final Context context) { + if (Constants.CURRENT_API_LEVEL >= 8) { + final Boolean hasTelephony = ReflectionUtils.tryInvokeInstance(context.getPackageManager(), "hasSystemFeature", new Class[]{String.class}, new Object[]{"android.hardware.telephony"}); //$NON-NLS-1$//$NON-NLS-2$ + + if (!hasTelephony.booleanValue()) { + if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Device does not have telephony; cannot read telephony id"); //$NON-NLS-1$ } @@ -224,15 +191,11 @@ import android.util.Log; * appears to be a race condition that occurs during installation. */ String id = null; - if (context.getPackageManager().checkPermission(permission.READ_PHONE_STATE, context.getPackageName()) == PackageManager.PERMISSION_GRANTED) - { + if (context.getPackageManager().checkPermission(permission.READ_PHONE_STATE, context.getPackageName()) == PackageManager.PERMISSION_GRANTED) { final TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); id = manager.getDeviceId(); - } - else - { - if (Constants.IS_LOGGABLE) - { + } else { + if (Constants.IS_LOGGABLE) { Log.w(Constants.LOG_TAG, "Application does not have permission READ_PHONE_STATE; determining device id is not possible. Please consider requesting READ_PHONE_STATE in the AndroidManifest"); //$NON-NLS-1$ } } @@ -243,21 +206,19 @@ import android.util.Log; /** * Gets a 1-way hashed value of the device's IMEI/MEID ID. This value is encoded using a SHA-256 one way hash and cannot be * used to determine what device this data came from. - *

      + *

      * Note: this method will return null if this is a non-telephony device. - *

      + *

      * Note: this method will return null if {@link permission#READ_PHONE_STATE} is not available. * * @param context The context used to access the phone state. * @return An 1-way hashed version of the {@link TelephonyManager#getDeviceId()}. Null if an ID or the hashing algorithm is - * not available, or if {@link permission#READ_PHONE_STATE} is not available. + * not available, or if {@link permission#READ_PHONE_STATE} is not available. */ - public static String getTelephonyDeviceIdHashOrNull(final Context context) - { + public static String getTelephonyDeviceIdHashOrNull(final Context context) { final String id = getTelephonyDeviceIdOrNull(context); - if (null == id) - { + if (null == id) { return null; } @@ -267,24 +228,18 @@ import android.util.Log; /** * Determines the type of network this device is connected to. * - * @param context the context used to access the device's WIFI + * @param context the context used to access the device's WIFI * @param telephonyManager The manager used to access telephony info * @return The type of network, or unknown if the information is unavailable */ - public static String getNetworkType(final Context context, final TelephonyManager telephonyManager) - { - if (context.getPackageManager().checkPermission(permission.ACCESS_WIFI_STATE, context.getPackageName()) == PackageManager.PERMISSION_GRANTED) - { + public static String getNetworkType(final Context context, final TelephonyManager telephonyManager) { + if (context.getPackageManager().checkPermission(permission.ACCESS_WIFI_STATE, context.getPackageName()) == PackageManager.PERMISSION_GRANTED) { final NetworkInfo wifiInfo = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getNetworkInfo(ConnectivityManager.TYPE_WIFI); - if (wifiInfo != null && wifiInfo.isConnectedOrConnecting()) - { + if (wifiInfo != null && wifiInfo.isConnectedOrConnecting()) { return "wifi"; //$NON-NLS-1$ } - } - else - { - if (Constants.IS_LOGGABLE) - { + } else { + if (Constants.IS_LOGGABLE) { Log.w(Constants.LOG_TAG, "Application does not have permission ACCESS_WIFI_STATE; determining Wi-Fi connectivity is unavailable"); //$NON-NLS-1$ } } @@ -298,20 +253,14 @@ import android.util.Log; * * @return A string naming the manufacturer */ - public static String getManufacturer() - { + public static String getManufacturer() { String mfg = "unknown"; //$NON-NLS-1$ - if (Constants.CURRENT_API_LEVEL > 3) - { - try - { + if (Constants.CURRENT_API_LEVEL > 3) { + try { final Class buildClass = Build.class; mfg = (String) buildClass.getField("MANUFACTURER").get(null); //$NON-NLS-1$ - } - catch (final Exception ignore) - { - if (Constants.IS_LOGGABLE) - { + } catch (final Exception ignore) { + if (Constants.IS_LOGGABLE) { Log.w(Constants.LOG_TAG, "Caught exception", ignore); //$NON-NLS-1$ } } @@ -325,21 +274,17 @@ import android.util.Log; * @param context {@link Context}. Cannot be null. * @return The application's version */ - public static String getAppVersion(final Context context) - { + public static String getAppVersion(final Context context) { final PackageManager pm = context.getPackageManager(); - try - { + try { final String versionName = pm.getPackageInfo(context.getPackageName(), 0).versionName; /* * If there is no versionName in the Android Manifest, the versionName will be null. */ - if (versionName == null) - { - if (Constants.IS_LOGGABLE) - { + if (versionName == null) { + if (Constants.IS_LOGGABLE) { Log.w(Constants.LOG_TAG, "versionName was null--is a versionName attribute set in the Android Manifest?"); //$NON-NLS-1$ } @@ -347,9 +292,7 @@ import android.util.Log; } return versionName; - } - catch (final PackageManager.NameNotFoundException e) - { + } catch (final PackageManager.NameNotFoundException e) { /* * This should never occur--our own package must exist for this code to be running */ @@ -363,29 +306,22 @@ import android.util.Log; * @param string String to hash. Cannot be null. * @return hashed version of the string using SHA-256. */ - /* package */static String getSha256(final String string) - { - if (Constants.ENABLE_PARAMETER_CHECKING) - { - if (null == string) - { + /* package */ + static String getSha256(final String string) { + if (Constants.ENABLE_PARAMETER_CHECKING) { + if (null == string) { throw new IllegalArgumentException("string cannot be null"); //$NON-NLS-1$ } } - try - { + try { final MessageDigest md = MessageDigest.getInstance("SHA-256"); //$NON-NLS-1$ final byte[] digest = md.digest(string.getBytes("UTF-8")); //$NON-NLS-1$ final BigInteger hashedNumber = new BigInteger(1, digest); return hashedNumber.toString(16); - } - catch (final NoSuchAlgorithmException e) - { + } catch (final NoSuchAlgorithmException e) { throw new RuntimeException(e); - } - catch (final UnsupportedEncodingException e) - { + } catch (final UnsupportedEncodingException e) { throw new RuntimeException(e); } } diff --git a/astrid/common-src/com/localytics/android/ExceptionHandler.java b/astrid/common-src/com/localytics/android/ExceptionHandler.java index 2ed580281..b98a5416d 100644 --- a/astrid/common-src/com/localytics/android/ExceptionHandler.java +++ b/astrid/common-src/com/localytics/android/ExceptionHandler.java @@ -9,31 +9,24 @@ import android.util.Log; /** * Exception handler for background threads used by the Localytics library. - *

      + *

      * Analytics are secondary to any other functions performed by an app, which means that analytics should never cause an app to * crash. This handler therefore suppresses all uncaught exceptions from the Localytics library. */ -/* package */final class ExceptionHandler implements Thread.UncaughtExceptionHandler -{ - public void uncaughtException(final Thread thread, final Throwable throwable) - { +/* package */final class ExceptionHandler implements Thread.UncaughtExceptionHandler { + public void uncaughtException(final Thread thread, final Throwable throwable) { /* * Wrap all the work done by the exception handler in a try-catch. It would be ironic if this exception handler itself * caused the parent process to crash. */ - try - { - if (Constants.IS_LOGGABLE) - { + try { + if (Constants.IS_LOGGABLE) { Log.e(Constants.LOG_TAG, "Localytics library threw an uncaught exception", throwable); //$NON-NLS-1$ } // TODO: Upload uncaught exceptions so that we can fix them - } - catch (final Exception e) - { - if (Constants.IS_LOGGABLE) - { + } catch (final Exception e) { + if (Constants.IS_LOGGABLE) { Log.e(Constants.LOG_TAG, "Exception handler threw an exception", e); //$NON-NLS-1$ } } diff --git a/astrid/common-src/com/localytics/android/JsonObjects.java b/astrid/common-src/com/localytics/android/JsonObjects.java index f1f76e64b..81c818f0b 100644 --- a/astrid/common-src/com/localytics/android/JsonObjects.java +++ b/astrid/common-src/com/localytics/android/JsonObjects.java @@ -5,37 +5,33 @@ */ package com.localytics.android; -import org.json.JSONArray; - import android.Manifest.permission; +import org.json.JSONArray; + /** * Set of constants for building JSON objects that get sent to the Localytics web service. */ -/* package */final class JsonObjects -{ +/* package */final class JsonObjects { /** * Private constructor prevents instantiation * * @throws UnsupportedOperationException because this class cannot be instantiated. */ - private JsonObjects() - { + private JsonObjects() { throw new UnsupportedOperationException("This class is non-instantiable"); //$NON-NLS-1$ } /** * Set of constants for the blob header JSON object. */ - public static final class BlobHeader - { + public static final class BlobHeader { /** * Private constructor prevents instantiation * * @throws UnsupportedOperationException because this class cannot be instantiated. */ - private BlobHeader() - { + private BlobHeader() { throw new UnsupportedOperationException("This class is non-instantiable"); //$NON-NLS-1$ } @@ -76,28 +72,26 @@ import android.Manifest.permission; /** * Attributes under {@link BlobHeader#KEY_ATTRIBUTES} */ - public static final class Attributes - { + public static final class Attributes { /** * Private constructor prevents instantiation * * @throws UnsupportedOperationException because this class cannot be instantiated. */ - private Attributes() - { + private Attributes() { throw new UnsupportedOperationException("This class is non-instantiable"); //$NON-NLS-1$ } /** * Type: {@code String} - *

      + *

      * Data connection type. */ public static final String KEY_DATA_CONNECTION = "dac"; //$NON-NLS-1$ /** * Type: {@code String} - *

      + *

      * Version name of the application, taken from the Android Manifest. */ public static final String KEY_CLIENT_APP_VERSION = "av"; //$NON-NLS-1$ @@ -109,34 +103,34 @@ import android.Manifest.permission; /** * Type: {@code String} - *

      + *

      */ public static final String KEY_DEVICE_COUNTRY = "dc"; //$NON-NLS-1$ /** * Type: {@code String} - *

      + *

      * Manufacturer of the device (e.g. HTC, Samsung, Motorola, Kyocera, etc.) */ public static final String KEY_DEVICE_MANUFACTURER = "dma"; //$NON-NLS-1$ /** * Type: {@code String} - *

      + *

      * Model of the device (e.g. dream, */ public static final String KEY_DEVICE_MODEL = "dmo"; //$NON-NLS-1$ /** * Type: {@code String} - *

      + *

      * Android version (e.g. 1.6 or 2.3.4). */ public static final String KEY_DEVICE_OS_VERSION = "dov"; //$NON-NLS-1$ /** * Type: {@code String} - *

      + *

      * Telephony ID of the device, if the device has telephony and the app has {@link permission#READ_PHONE_STATE}. * Otherwise null. */ @@ -144,21 +138,21 @@ import android.Manifest.permission; /** * Type: {@code String} - *

      + *

      * Platform of the device. For Android devices, this is always "android" */ public static final String KEY_DEVICE_PLATFORM = "dp"; //$NON-NLS-1$ /** * Type: {@code String} - *

      + *

      * SHA-256 hash of the device's serial number. Only reported for Android 2.3 or later. Otherwise null. */ public static final String KEY_DEVICE_SERIAL_HASH = "dms"; //$NON-NLS-1$ /** * Type: {@code int} - *

      + *

      * SDK compatibility level of the device. * * @see android.os.Build.VERSION#SDK @@ -167,7 +161,7 @@ import android.Manifest.permission; /** * Type: {@code String} - *

      + *

      * SHA-256 hash of the device's Telephony ID, if the device has telephony and the app has * {@link permission#READ_PHONE_STATE}. Otherwise null. */ @@ -175,28 +169,28 @@ import android.Manifest.permission; /** * Type: {@code String} - *

      + *

      * Country for the device's current locale settings */ public static final String KEY_LOCALE_COUNTRY = "dlc"; //$NON-NLS-1$ /** * Type: {@code String} - *

      + *

      * Language for the device's current locale settings */ public static final String KEY_LOCALE_LANGUAGE = "dll"; //$NON-NLS-1$ /** * Type: {@code String} - *

      + *

      * Api key */ public static final String KEY_LOCALYTICS_API_KEY = "au"; //$NON-NLS-1$ /** * Type: {@code String} - *

      + *

      * Localytics library version * * @see Constants#LOCALYTICS_CLIENT_LIBRARY_VERSION @@ -205,7 +199,7 @@ import android.Manifest.permission; /** * Type: {@code String} - *

      + *

      * Data type for the JSON object. * * @see #VALUE_DATA_TYPE @@ -214,14 +208,14 @@ import android.Manifest.permission; /** * Type: {@code String} - *

      + *

      * Network carrier of the device */ public static final String KEY_NETWORK_CARRIER = "nca"; //$NON-NLS-1$ /** * Type: {@code String} - *

      + *

      */ public static final String KEY_NETWORK_COUNTRY = "nc"; //$NON-NLS-1$ @@ -243,21 +237,19 @@ import android.Manifest.permission; /** * Set of constants for the session open event. */ - /* package */static final class SessionOpen - { + /* package */static final class SessionOpen { /** * Private constructor prevents instantiation * * @throws UnsupportedOperationException because this class cannot be instantiated. */ - private SessionOpen() - { + private SessionOpen() { throw new UnsupportedOperationException("This class is non-instantiable"); //$NON-NLS-1$ } /** * Type: {@code String} - *

      + *

      * Data type for the JSON object. * * @see #VALUE_DATA_TYPE @@ -271,21 +263,21 @@ import android.Manifest.permission; /** * Type: {@code long} - *

      + *

      * Epoch timestamp when the session was started in seconds. */ public static final String KEY_WALL_TIME_SECONDS = "ct"; //$NON-NLS-1$ /** * Type: {@code long} - *

      + *

      * UUID of the event, which is the same thing as the session UUID */ public static final String KEY_EVENT_UUID = "u"; //$NON-NLS-1$ /** * Type: {@code long} - *

      + *

      * Count for the number of sessions */ public static final String KEY_COUNT = "nth"; //$NON-NLS-1$ @@ -294,21 +286,19 @@ import android.Manifest.permission; /** * Set of constants for the session close event. */ - /* package */static final class SessionClose - { + /* package */static final class SessionClose { /** * Private constructor prevents instantiation * * @throws UnsupportedOperationException because this class cannot be instantiated. */ - private SessionClose() - { + private SessionClose() { throw new UnsupportedOperationException("This class is non-instantiable"); //$NON-NLS-1$ } /** * Type: {@code String} - *

      + *

      * Data type for the JSON object. * * @see #VALUE_DATA_TYPE @@ -317,42 +307,42 @@ import android.Manifest.permission; /** * Type: {@code String} - *

      + *

      * UUID of the event. */ public static final String KEY_EVENT_UUID = "u"; //$NON-NLS-1$ /** * Type: {@code String[]} (technically, a JSON array of strings) - *

      + *

      * Ordered list of flow events that occurred */ public static final String KEY_FLOW_ARRAY = "fl"; //$NON-NLS-1$ /** * Type: {@code long} - *

      + *

      * Epoch timestamp when the session was started */ public static final String KEY_SESSION_LENGTH_SECONDS = "ctl"; //$NON-NLS-1$ /** * Type: {@code long} - *

      + *

      * Start time of the parent session */ public static final String KEY_SESSION_START_TIME = "ss"; //$NON-NLS-1$ /** * Type: {@code String} - *

      + *

      * UUID of the session. */ public static final String KEY_SESSION_UUID = "su"; //$NON-NLS-1$ /** * Type: {@code long} - *

      + *

      * Epoch timestamp when the session was started in seconds. */ public static final String KEY_WALL_TIME_SECONDS = "ct"; //$NON-NLS-1$ @@ -368,21 +358,19 @@ import android.Manifest.permission; /** * Set of constants for the session event event. */ - /* package */static final class SessionEvent - { + /* package */static final class SessionEvent { /** * Private constructor prevents instantiation * * @throws UnsupportedOperationException because this class cannot be instantiated. */ - private SessionEvent() - { + private SessionEvent() { throw new UnsupportedOperationException("This class is non-instantiable"); //$NON-NLS-1$ } /** * Type: {@code String} - *

      + *

      * Data type for the JSON object. * * @see #VALUE_DATA_TYPE @@ -398,37 +386,37 @@ import android.Manifest.permission; /** * Type: {@code long} - *

      + *

      * Epoch timestamp when the session was started in seconds. */ public static final String KEY_WALL_TIME_SECONDS = "ct"; //$NON-NLS-1$ /** * Type: {@code String} - *

      + *

      * UUID of the session. */ public static final String KEY_SESSION_UUID = "su"; //$NON-NLS-1$ /** * Type: {@code String} - *

      + *

      * UUID of the event. */ public static final String KEY_EVENT_UUID = "u"; //$NON-NLS-1$ /** * Type: {@code String} - *

      + *

      * Name of the event. */ public static final String KEY_NAME = "n"; //$NON-NLS-1$ /** * Type: {@code JSONObject}. - *

      + *

      * Maps to the attributes of the event. - *

      + *

      * Note that this key is optional. If it is present, it will point to a non-null value representing the attributes of the * event. Otherwise the key will not exist, indicating the event had no attributes. */ @@ -438,21 +426,19 @@ import android.Manifest.permission; /** * Set of constants for the session opt in/out event */ - /* package */static final class OptEvent - { + /* package */static final class OptEvent { /** * Private constructor prevents instantiation * * @throws UnsupportedOperationException because this class cannot be instantiated. */ - private OptEvent() - { + private OptEvent() { throw new UnsupportedOperationException("This class is non-instantiable"); //$NON-NLS-1$ } /** * Type: {@code String} - *

      + *

      * Data type for the JSON object. * * @see #VALUE_DATA_TYPE @@ -468,21 +454,21 @@ import android.Manifest.permission; /** * Type: {@code long} - *

      + *

      * Epoch timestamp when the session was started in seconds. */ public static final String KEY_WALL_TIME_SECONDS = "ct"; //$NON-NLS-1$ /** * Type: {@code String} - *

      + *

      * API key */ public static final String KEY_API_KEY = "u"; //$NON-NLS-1$ /** * Type: {@code boolean} - *

      + *

      * True to opt-out. False to opt-in */ public static final String KEY_OPT = "out"; //$NON-NLS-1$ @@ -491,21 +477,19 @@ import android.Manifest.permission; /** * Set of constants for the session flow event. */ - /* package */static final class EventFlow - { + /* package */static final class EventFlow { /** * Private constructor prevents instantiation * * @throws UnsupportedOperationException because this class cannot be instantiated. */ - private EventFlow() - { + private EventFlow() { throw new UnsupportedOperationException("This class is non-instantiable"); //$NON-NLS-1$ } /** * Type: {@code String} - *

      + *

      * Data type for the JSON object. * * @see #VALUE_DATA_TYPE @@ -514,28 +498,28 @@ import android.Manifest.permission; /** * Type: {@code long} - *

      + *

      * UUID of the event, which is the same thing as the session UUID */ public static final String KEY_EVENT_UUID = "u"; //$NON-NLS-1$ /** * Type: {@code long} - *

      + *

      * Start time of the parents session. */ public static final String KEY_SESSION_START_TIME = "ss"; //$NON-NLS-1$ /** * Type: {@code Element[]} (technically a {@link JSONArray} of {@link Element} objects) - *

      + *

      * Ordered set of new flow elements that occurred since the last upload for this session. */ public static final String KEY_FLOW_NEW = "nw"; //$NON-NLS-1$ /** * Type: {@code Element[]} (technically a {@link JSONArray} of {@link Element} objects) - *

      + *

      * Ordered set of old flow elements that occurred during all previous uploads for this session. */ public static final String KEY_FLOW_OLD = "od"; //$NON-NLS-1$ @@ -548,15 +532,13 @@ import android.Manifest.permission; /** * Flow event element that indicates the type and name of the flow event. */ - /* package */static final class Element - { + /* package */static final class Element { /** * Private constructor prevents instantiation * * @throws UnsupportedOperationException because this class cannot be instantiated. */ - private Element() - { + private Element() { throw new UnsupportedOperationException("This class is non-instantiable"); //$NON-NLS-1$ } diff --git a/astrid/common-src/com/localytics/android/LocalyticsProvider.java b/astrid/common-src/com/localytics/android/LocalyticsProvider.java index 7ed58bdd1..82ca4967b 100644 --- a/astrid/common-src/com/localytics/android/LocalyticsProvider.java +++ b/astrid/common-src/com/localytics/android/LocalyticsProvider.java @@ -5,14 +5,6 @@ */ package com.localytics.android; -import java.io.File; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - import android.content.ContentValues; import android.content.Context; import android.database.Cursor; @@ -23,17 +15,24 @@ import android.database.sqlite.SQLiteQueryBuilder; import android.provider.BaseColumns; import android.util.Log; +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + /** * Implements the storage mechanism for the Localytics library. The interface and implementation are similar to a ContentProvider * but modified to be better suited to a library. The interface is table-oriented, rather than Uri-oriented. - *

      + *

      * This is not a public API. */ -/* package */final class LocalyticsProvider -{ +/* package */final class LocalyticsProvider { /** * Name of the Localytics database, stored in the host application's {@link Context#getDatabasePath(String)}. - *

      + *

      * This is not a public API. */ /* @@ -44,7 +43,7 @@ import android.util.Log; /** * Version of the database. - *

      + *

      * Version history: *

        *
      1. 1: Initial version
      2. @@ -79,26 +78,23 @@ import android.util.Log; /** * Obtains an instance of the Localytics Provider. Since the provider is a singleton object, only a single instance will be * returned. - *

        + *

        * Note: if {@code context} is an instance of {@link android.test.RenamingDelegatingContext}, then a new object will be * returned every time. This is not a "public" API, but is documented here as it aids unit testing. * * @param context Application context. Cannot be null. - * @param apiKey TODO + * @param apiKey TODO * @return An instance of {@link LocalyticsProvider}. * @throws IllegalArgumentException if {@code context} is null */ - public static LocalyticsProvider getInstance(final Context context, final String apiKey) - { + public static LocalyticsProvider getInstance(final Context context, final String apiKey) { /* * Note: Don't call getApplicationContext() on the context, as that would return a different context and defeat useful * contexts such as RenamingDelegatingContext. */ - if (Constants.ENABLE_PARAMETER_CHECKING) - { - if (null == context) - { + if (Constants.ENABLE_PARAMETER_CHECKING) { + if (null == context) { throw new IllegalArgumentException("context cannot be null"); //$NON-NLS-1$ } } @@ -112,12 +108,10 @@ import android.util.Log; return new LocalyticsProvider(context, apiKey); } - synchronized (sLocalyticsProviderIntrinsicLock) - { + synchronized (sLocalyticsProviderIntrinsicLock) { LocalyticsProvider provider = sLocalyticsProviderMap.get(apiKey); - if (null == provider) - { + if (null == provider) { provider = new LocalyticsProvider(context, apiKey); sLocalyticsProviderMap.put(apiKey, provider); } @@ -128,13 +122,12 @@ import android.util.Log; /** * Constructs a new Localytics Provider. - *

        + *

        * Note: this method may perform disk operations. * * @param context application context. Cannot be null. */ - private LocalyticsProvider(final Context context, final String apiKey) - { + private LocalyticsProvider(final Context context, final String apiKey) { /* * Rather than use the API key directly in the file name, it is put through SHA-256. The main reason for doing that is to * decouple the requirements of the Android file system from the possible values of the API key string. There is a very, @@ -147,39 +140,33 @@ import android.util.Log; /** * Inserts a new record. - *

        + *

        * Note: this method may perform disk operations. * * @param tableName name of the table operate on. Must be one of the recognized tables. Cannot be null. - * @param values ContentValues to insert. Cannot be null. + * @param values ContentValues to insert. Cannot be null. * @return the {@link BaseColumns#_ID} of the inserted row or -1 if an error occurred. * @throws IllegalArgumentException if tableName is null or not a valid table name. * @throws IllegalArgumentException if values are null. */ - public long insert(final String tableName, final ContentValues values) - { - if (Constants.ENABLE_PARAMETER_CHECKING) - { - if (!isValidTable(tableName)) - { + public long insert(final String tableName, final ContentValues values) { + if (Constants.ENABLE_PARAMETER_CHECKING) { + if (!isValidTable(tableName)) { throw new IllegalArgumentException(String.format("tableName %s is invalid", tableName)); //$NON-NLS-1$ } - if (null == values) - { + if (null == values) { throw new IllegalArgumentException("values cannot be null"); //$NON-NLS-1$ } } - if (Constants.IS_LOGGABLE) - { + if (Constants.IS_LOGGABLE) { Log.v(Constants.LOG_TAG, String.format("Insert table: %s, values: %s", tableName, values.toString())); //$NON-NLS-1$ } final long result = mDb.insertOrThrow(tableName, null, values); - if (Constants.IS_LOGGABLE) - { + if (Constants.IS_LOGGABLE) { Log.v(Constants.LOG_TAG, String.format("Inserted row with new id %d", Long.valueOf(result))); //$NON-NLS-1$ } @@ -188,30 +175,26 @@ import android.util.Log; /** * Performs a query. - *

        + *

        * Note: this method may perform disk operations. * - * @param tableName name of the table operate on. Must be one of the recognized tables. Cannot be null. - * @param projection The list of columns to include. If null, then all columns are included by default. - * @param selection A filter to apply to all rows, like the SQLite WHERE clause. Passing null will query all rows. This param - * may contain ? symbols, which will be replaced by values from the {@code selectionArgs} param. + * @param tableName name of the table operate on. Must be one of the recognized tables. Cannot be null. + * @param projection The list of columns to include. If null, then all columns are included by default. + * @param selection A filter to apply to all rows, like the SQLite WHERE clause. Passing null will query all rows. This param + * may contain ? symbols, which will be replaced by values from the {@code selectionArgs} param. * @param selectionArgs An optional string array of replacements for ? symbols in {@code selection}. May be null. - * @param sortOrder How the rows in the cursor should be sorted. If null, then the sort order is undefined. + * @param sortOrder How the rows in the cursor should be sorted. If null, then the sort order is undefined. * @return Cursor for the query. To the receiver: Don't forget to call .close() on the cursor when finished with it. * @throws IllegalArgumentException if tableName is null or not a valid table name. */ - public Cursor query(final String tableName, final String[] projection, final String selection, final String[] selectionArgs, final String sortOrder) - { - if (Constants.ENABLE_PARAMETER_CHECKING) - { - if (!isValidTable(tableName)) - { + public Cursor query(final String tableName, final String[] projection, final String selection, final String[] selectionArgs, final String sortOrder) { + if (Constants.ENABLE_PARAMETER_CHECKING) { + if (!isValidTable(tableName)) { throw new IllegalArgumentException(String.format("tableName %s is invalid", tableName)); //$NON-NLS-1$ } } - if (Constants.IS_LOGGABLE) - { + if (Constants.IS_LOGGABLE) { Log.v(Constants.LOG_TAG, String.format("Query table: %s, projection: %s, selection: %s, selectionArgs: %s", tableName, Arrays.toString(projection), selection, Arrays.toString(selectionArgs))); //$NON-NLS-1$ } @@ -220,8 +203,7 @@ import android.util.Log; final Cursor result = qb.query(mDb, projection, selection, selectionArgs, null, null, sortOrder); - if (Constants.IS_LOGGABLE) - { + if (Constants.IS_LOGGABLE) { Log.v(Constants.LOG_TAG, "Query result is: " + DatabaseUtils.dumpCursorToString(result)); //$NON-NLS-1$ } @@ -230,30 +212,26 @@ import android.util.Log; /** * Updates row(s). - *

        + *

        * Note: this method may perform disk operations. * - * @param tableName name of the table operate on. Must be one of the recognized tables. Cannot be null. - * @param values A ContentValues mapping from column names (see the associated BaseColumns class for the table) to new column - * values. - * @param selection A filter to limit which rows are updated, like the SQLite WHERE clause. Passing null implies all rows. - * This param may contain ? symbols, which will be replaced by values from the {@code selectionArgs} param. + * @param tableName name of the table operate on. Must be one of the recognized tables. Cannot be null. + * @param values A ContentValues mapping from column names (see the associated BaseColumns class for the table) to new column + * values. + * @param selection A filter to limit which rows are updated, like the SQLite WHERE clause. Passing null implies all rows. + * This param may contain ? symbols, which will be replaced by values from the {@code selectionArgs} param. * @param selectionArgs An optional string array of replacements for ? symbols in {@code selection}. May be null. * @return int representing the number of rows modified, which is in the range from 0 to the number of items in the table. * @throws IllegalArgumentException if tableName is null or not a valid table name. */ - public int update(final String tableName, final ContentValues values, final String selection, final String[] selectionArgs) - { - if (Constants.ENABLE_PARAMETER_CHECKING) - { - if (!isValidTable(tableName)) - { + public int update(final String tableName, final ContentValues values, final String selection, final String[] selectionArgs) { + if (Constants.ENABLE_PARAMETER_CHECKING) { + if (!isValidTable(tableName)) { throw new IllegalArgumentException(String.format("tableName %s is invalid", tableName)); //$NON-NLS-1$ } } - if (Constants.IS_LOGGABLE) - { + if (Constants.IS_LOGGABLE) { Log.v(Constants.LOG_TAG, String.format("Update table: %s, values: %s, selection: %s, selectionArgs: %s", tableName, values.toString(), selection, Arrays.toString(selectionArgs))); //$NON-NLS-1$ } @@ -262,43 +240,35 @@ import android.util.Log; /** * Deletes row(s). - *

        + *

        * Note: this method may perform disk operations. * - * @param tableName name of the table operate on. Must be one of the recognized tables. Cannot be null. - * @param selection A filter to limit which rows are deleted, like the SQLite WHERE clause. Passing null implies all rows. - * This param may contain ? symbols, which will be replaced by values from the {@code selectionArgs} param. + * @param tableName name of the table operate on. Must be one of the recognized tables. Cannot be null. + * @param selection A filter to limit which rows are deleted, like the SQLite WHERE clause. Passing null implies all rows. + * This param may contain ? symbols, which will be replaced by values from the {@code selectionArgs} param. * @param selectionArgs An optional string array of replacements for ? symbols in {@code selection}. May be null. * @return The number of rows affected, which is in the range from 0 to the number of items in the table. * @throws IllegalArgumentException if tableName is null or not a valid table name. */ - public int delete(final String tableName, final String selection, final String[] selectionArgs) - { - if (Constants.ENABLE_PARAMETER_CHECKING) - { - if (!isValidTable(tableName)) - { + public int delete(final String tableName, final String selection, final String[] selectionArgs) { + if (Constants.ENABLE_PARAMETER_CHECKING) { + if (!isValidTable(tableName)) { throw new IllegalArgumentException(String.format("tableName %s is invalid", tableName)); //$NON-NLS-1$ } } - if (Constants.IS_LOGGABLE) - { + if (Constants.IS_LOGGABLE) { Log.v(Constants.LOG_TAG, String.format("Delete table: %s, selection: %s, selectionArgs: %s", tableName, selection, Arrays.toString(selectionArgs))); //$NON-NLS-1$ } final int count; - if (null == selection) - { + if (null == selection) { count = mDb.delete(tableName, "1", null); //$NON-NLS-1$ - } - else - { + } else { count = mDb.delete(tableName, selection, selectionArgs); } - if (Constants.IS_LOGGABLE) - { + if (Constants.IS_LOGGABLE) { Log.v(Constants.LOG_TAG, String.format("Deleted %d rows", Integer.valueOf(count))); //$NON-NLS-1$ } @@ -318,25 +288,19 @@ import android.util.Log; * An alternative implementation would have been to expose the begin/end transaction methods on the Provider object. While * that would work, it makes it harder to transition to a ContentProviderOperation model in the future. */ - public void runBatchTransaction(final Runnable runnable) - { - if (Constants.ENABLE_PARAMETER_CHECKING) - { - if (null == runnable) - { + public void runBatchTransaction(final Runnable runnable) { + if (Constants.ENABLE_PARAMETER_CHECKING) { + if (null == runnable) { throw new IllegalArgumentException("runnable cannot be null"); //$NON-NLS-1$ } } mDb.beginTransaction(); - try - { + try { runnable.run(); mDb.setTransactionSuccessful(); - } - finally - { + } finally { mDb.endTransaction(); } } @@ -347,15 +311,12 @@ import android.util.Log; * @param table name of a table to check. This param may be null. * @return true if the table is valid, false if the table is invalid. If {@code table} is null, returns false. */ - private static boolean isValidTable(final String table) - { - if (null == table) - { + private static boolean isValidTable(final String table) { + if (null == table) { return false; } - if (!sValidTables.contains(table)) - { + if (!sValidTables.contains(table)) { return false; } @@ -367,8 +328,7 @@ import android.util.Log; * * @return returns a set of the valid tables. */ - private static Set getValidTables() - { + private static Set getValidTables() { final HashSet tables = new HashSet(); tables.add(ApiKeysDbColumns.TABLE_NAME); @@ -384,18 +344,16 @@ import android.util.Log; /** * Private helper that deletes files from older versions of the Localytics library. - *

        + *

        * Note: This is a private method that is only made package-accessible for unit testing. * * @param context application context * @throws IllegalArgumentException if {@code context} is null */ - /* package */static void deleteOldFiles(final Context context) - { - if (Constants.ENABLE_PARAMETER_CHECKING) - { - if (null == context) - { + /* package */ + static void deleteOldFiles(final Context context) { + if (Constants.ENABLE_PARAMETER_CHECKING) { + if (null == context) { throw new IllegalArgumentException("context cannot be null"); //$NON-NLS-1$ } } @@ -409,15 +367,11 @@ import android.util.Log; * @param directory Directory or file to delete. Cannot be null. * @return true if deletion was successful. False if deletion failed. */ - private static boolean deleteDirectory(final File directory) - { - if (directory.exists() && directory.isDirectory()) - { - for (final String child : directory.list()) - { + private static boolean deleteDirectory(final File directory) { + if (directory.exists() && directory.isDirectory()) { + for (final String child : directory.list()) { final boolean success = deleteDirectory(new File(directory, child)); - if (!success) - { + if (!success) { return false; } } @@ -430,8 +384,7 @@ import android.util.Log; /** * A private helper class to open and create the Localytics SQLite database. */ - private static final class DatabaseHelper extends SQLiteOpenHelper - { + private static final class DatabaseHelper extends SQLiteOpenHelper { /** * Constant representing the SQLite value for true */ @@ -444,18 +397,17 @@ import android.util.Log; /** * @param context Application context. Cannot be null. - * @param name File name of the database. Cannot be null or empty. A database with this name will be opened in - * {@link Context#getDatabasePath(String)}. + * @param name File name of the database. Cannot be null or empty. A database with this name will be opened in + * {@link Context#getDatabasePath(String)}. * @param version version of the database. */ - public DatabaseHelper(final Context context, final String name, final int version) - { + public DatabaseHelper(final Context context, final String name, final int version) { super(context, name, null, version); } /** * Initializes the tables of the database. - *

        + *

        * If an error occurs during initialization and an exception is thrown, {@link SQLiteDatabase#close()} will not be called * by this method. That responsibility is left to the caller. * @@ -463,10 +415,8 @@ import android.util.Log; * @throws IllegalArgumentException if db is null */ @Override - public void onCreate(final SQLiteDatabase db) - { - if (null == db) - { + public void onCreate(final SQLiteDatabase db) { + if (null == db) { throw new IllegalArgumentException("db cannot be null"); //$NON-NLS-1$ } @@ -498,17 +448,14 @@ import android.util.Log; } @Override - public void onOpen(final SQLiteDatabase db) - { + public void onOpen(final SQLiteDatabase db) { super.onOpen(db); - if (Constants.IS_LOGGABLE) - { + if (Constants.IS_LOGGABLE) { Log.v(Constants.LOG_TAG, String.format("SQLite library version is: %s", DatabaseUtils.stringForQuery(db, "select sqlite_version()", null))); //$NON-NLS-1$//$NON-NLS-2$ } - if (!db.isReadOnly()) - { + if (!db.isReadOnly()) { /* * Enable foreign key support */ @@ -530,46 +477,34 @@ import android.util.Log; } @Override - public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) - { - if (1 == oldVersion) - { + public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) { + if (1 == oldVersion) { // delete stranded sessions that don't have any events Cursor sessionsCursor = null; - try - { + try { sessionsCursor = db.query(SessionsDbColumns.TABLE_NAME, new String[] - { SessionsDbColumns._ID }, null, null, null, null, null); + {SessionsDbColumns._ID}, null, null, null, null, null); - while (sessionsCursor.moveToNext()) - { + while (sessionsCursor.moveToNext()) { Cursor eventsCursor = null; - try - { + try { String sessionId = Long.toString(sessionsCursor.getLong(sessionsCursor.getColumnIndexOrThrow(SessionsDbColumns._ID))); eventsCursor = db.query(EventsDbColumns.TABLE_NAME, new String[] - { EventsDbColumns._ID }, String.format("%s = ?", EventsDbColumns.SESSION_KEY_REF), new String[] //$NON-NLS-1$ - { sessionId }, null, null, null); + {EventsDbColumns._ID}, String.format("%s = ?", EventsDbColumns.SESSION_KEY_REF), new String[] //$NON-NLS-1$ + {sessionId}, null, null, null); - if (eventsCursor.getCount() == 0) - { - db.delete(SessionsDbColumns.TABLE_NAME, String.format("%s = ?", SessionsDbColumns._ID), new String[] { sessionId }); //$NON-NLS-1$ + if (eventsCursor.getCount() == 0) { + db.delete(SessionsDbColumns.TABLE_NAME, String.format("%s = ?", SessionsDbColumns._ID), new String[]{sessionId}); //$NON-NLS-1$ } - } - finally - { - if (null != eventsCursor) - { + } finally { + if (null != eventsCursor) { eventsCursor.close(); eventsCursor = null; } } } - } - finally - { - if (null != sessionsCursor) - { + } finally { + if (null != sessionsCursor) { sessionsCursor.close(); sessionsCursor = null; } @@ -585,18 +520,16 @@ import android.util.Log; /** * Table for the API keys used and the opt-out preferences for each API key. - *

        + *

        * This is not a public API. */ - public static final class ApiKeysDbColumns implements BaseColumns - { + public static final class ApiKeysDbColumns implements BaseColumns { /** * Private constructor prevents instantiation * * @throws UnsupportedOperationException because this class cannot be instantiated. */ - private ApiKeysDbColumns() - { + private ApiKeysDbColumns() { throw new UnsupportedOperationException("This class is non-instantiable"); //$NON-NLS-1$ } @@ -607,37 +540,37 @@ import android.util.Log; /** * TYPE: {@code String} - *

        + *

        * The Localytics API key. - *

        + *

        * Constraints: This column is unique and cannot be null. */ public static final String API_KEY = "api_key"; //$NON-NLS-1$ /** * TYPE: {@code String} - *

        + *

        * A UUID for the installation. - *

        + *

        * Constraints: This column is unique and cannot be null. */ public static final String UUID = "uuid"; //$NON-NLS-1$ /** * TYPE: {@code boolean} - *

        + *

        * A flag indicating whether the user has opted out of data collection. - *

        + *

        * Constraints: This column must be in the set {0, 1} and cannot be null. */ public static final String OPT_OUT = "opt_out"; //$NON-NLS-1$ /** * TYPE: {@code long} - *

        + *

        * A long representing the {@link System#currentTimeMillis()} when the row was created. Once created, this row will not be * modified. - *

        + *

        * Constraints: This column must be >=0. This column cannot be null. */ public static final String CREATED_TIME = "created_time"; //$NON-NLS-1$ @@ -646,18 +579,16 @@ import android.util.Log; /** * Database table for the session attributes. There is a one-to-many relationship between one event in the * {@link EventsDbColumns} table and the many attributes associated with that event. - *

        + *

        * This is not a public API. */ - public static final class AttributesDbColumns implements BaseColumns - { + public static final class AttributesDbColumns implements BaseColumns { /** * Private constructor prevents instantiation * * @throws UnsupportedOperationException because this class cannot be instantiated. */ - private AttributesDbColumns() - { + private AttributesDbColumns() { throw new UnsupportedOperationException("This class is non-instantiable"); //$NON-NLS-1$ } @@ -668,27 +599,27 @@ import android.util.Log; /** * TYPE: {@code long} - *

        + *

        * A one-to-many relationship with {@link EventsDbColumns#_ID}. - *

        + *

        * Constraints: This is a foreign key with the {@link EventsDbColumns#_ID} column. This cannot be null. */ public static final String EVENTS_KEY_REF = "events_key_ref"; //$NON-NLS-1$ /** * TYPE: {@code String} - *

        + *

        * String representing the key name of the attribute. - *

        + *

        * Constraints: This cannot be null. */ public static final String ATTRIBUTE_KEY = "attribute_key"; //$NON-NLS-1$ /** * TYPE: {@code String} - *

        + *

        * String representing the value of the attribute. - *

        + *

        * Constraints: This cannot be null. */ public static final String ATTRIBUTE_VALUE = "attribute_value"; //$NON-NLS-1$ @@ -698,18 +629,16 @@ import android.util.Log; /** * Database table for the session events. There is a one-to-many relationship between one session data entry in the * {@link SessionsDbColumns} table and the many events associated with that session. - *

        + *

        * This is not a public API. */ - public static final class EventsDbColumns implements BaseColumns - { + public static final class EventsDbColumns implements BaseColumns { /** * Private constructor prevents instantiation * * @throws UnsupportedOperationException because this class cannot be instantiated. */ - private EventsDbColumns() - { + private EventsDbColumns() { throw new UnsupportedOperationException("This class is non-instantiable"); //$NON-NLS-1$ } @@ -720,45 +649,45 @@ import android.util.Log; /** * TYPE: {@code long} - *

        + *

        * A one-to-many relationship with {@link SessionsDbColumns#_ID}. - *

        + *

        * Constraints: This is a foreign key with the {@link SessionsDbColumns#_ID} column. This cannot be null. */ public static final String SESSION_KEY_REF = "session_key_ref"; //$NON-NLS-1$ /** * TYPE: {@code String} - *

        + *

        * Unique ID of the event, as generated from {@link java.util.UUID}. - *

        + *

        * Constraints: This is unique and cannot be null. */ public static final String UUID = "uuid"; //$NON-NLS-1$ /** * TYPE: {@code String} - *

        + *

        * String representing the name of the event. - *

        + *

        * Constraints: This cannot be null. */ public static final String EVENT_NAME = "event_name"; //$NON-NLS-1$ /** * TYPE: {@code long} - *

        + *

        * A long representing the {@link android.os.SystemClock#elapsedRealtime()} when the event occurred. - *

        + *

        * Constraints: This column must be >=0. This column cannot be null. */ public static final String REAL_TIME = "real_time"; //$NON-NLS-1$ /** * TYPE: {@code long} - *

        + *

        * A long representing the {@link System#currentTimeMillis()} when the event occurred. - *

        + *

        * Constraints: This column must be >=0. This column cannot be null. */ public static final String WALL_TIME = "wall_time"; //$NON-NLS-1$ @@ -768,18 +697,16 @@ import android.util.Log; /** * Database table for tracking the history of events and screens. There is a one-to-many relationship between one session data * entry in the {@link SessionsDbColumns} table and the many historical events associated with that session. - *

        + *

        * This is not a public API. */ - public static final class EventHistoryDbColumns implements BaseColumns - { + public static final class EventHistoryDbColumns implements BaseColumns { /** * Private constructor prevents instantiation * * @throws UnsupportedOperationException because this class cannot be instantiated. */ - private EventHistoryDbColumns() - { + private EventHistoryDbColumns() { throw new UnsupportedOperationException("This class is non-instantiable"); //$NON-NLS-1$ } @@ -790,34 +717,34 @@ import android.util.Log; /** * TYPE: {@code long} - *

        + *

        * A one-to-many relationship with {@link SessionsDbColumns#_ID}. - *

        + *

        * Constraints: This is a foreign key with the {@link SessionsDbColumns#_ID} column. This cannot be null. */ public static final String SESSION_KEY_REF = "session_key_ref"; //$NON-NLS-1$ /** * TYPE: {@code String} - *

        + *

        * Unique ID of the event, as generated from {@link java.util.UUID}. - *

        + *

        * Constraints: This is unique and cannot be null. */ public static final String TYPE = "type"; //$NON-NLS-1$ /** * TYPE: {@code String} - *

        + *

        * String representing the name of the screen or event. - *

        + *

        * Constraints: This cannot be null. */ public static final String NAME = "name"; //$NON-NLS-1$ /** * TYPE: {@code boolean} - *

        + *

        * Foreign key to the upload blob that this event was processed in. May be null indicating that this event wasn't * processed yet. */ @@ -837,18 +764,16 @@ import android.util.Log; /** * Database table for the session data. There is a one-to-many relationship between one API key entry in the * {@link ApiKeysDbColumns} table and many sessions for that API key. - *

        + *

        * This is not a public API. */ - public static final class SessionsDbColumns implements BaseColumns - { + public static final class SessionsDbColumns implements BaseColumns { /** * Private constructor prevents instantiation * * @throws UnsupportedOperationException because this class cannot be instantiated. */ - private SessionsDbColumns() - { + private SessionsDbColumns() { throw new UnsupportedOperationException("This class is non-instantiable"); //$NON-NLS-1$ } @@ -859,27 +784,27 @@ import android.util.Log; /** * TYPE: {@code long} - *

        + *

        * A one-to-one relationship with {@link ApiKeysDbColumns#_ID}. - *

        + *

        * Constraints: This is a foreign key with the {@link ApiKeysDbColumns#_ID} column. This cannot be null. */ public static final String API_KEY_REF = "api_key_ref"; //$NON-NLS-1$ /** * TYPE: {@code String} - *

        + *

        * Unique ID of the event, as generated from {@link java.util.UUID}. - *

        + *

        * Constraints: This is unique and cannot be null. */ public static final String UUID = "uuid"; //$NON-NLS-1$ /** * TYPE: {@code long} - *

        + *

        * The wall time when the session started. - *

        + *

        * Constraints: This column must be >=0. This column cannot be null. */ /* @@ -890,7 +815,7 @@ import android.util.Log; /** * TYPE: {@code String} - *

        + *

        * Version of the Localytics client library. * * @see Constants#LOCALYTICS_CLIENT_LIBRARY_VERSION @@ -899,38 +824,38 @@ import android.util.Log; /** * TYPE: {@code String} - *

        + *

        * String representing the app's versionName - *

        + *

        * Constraints: This cannot be null. */ public static final String APP_VERSION = "app_version"; //$NON-NLS-1$ /** * TYPE: {@code String} - *

        + *

        * String representing the version of Android - *

        + *

        * Constraints: This cannot be null. */ public static final String ANDROID_VERSION = "android_version"; //$NON-NLS-1$ /** * TYPE: {@code int} - *

        + *

        * Integer the Android SDK - *

        + *

        * Constraints: Must be an integer and cannot be null. - * + * * @see android.os.Build.VERSION#SDK */ public static final String ANDROID_SDK = "android_sdk"; //$NON-NLS-1$ /** * TYPE: {@code String} - *

        + *

        * String representing the device model - *

        + *

        * Constraints: None * * @see android.os.Build#MODEL @@ -939,9 +864,9 @@ import android.util.Log; /** * TYPE: {@code String} - *

        + *

        * String representing the device manufacturer - *

        + *

        * Constraints: None * * @see android.os.Build#MANUFACTURER @@ -950,9 +875,9 @@ import android.util.Log; /** * TYPE: {@code String} - *

        + *

        * String representing a hash of the device Android ID - *

        + *

        * Constraints: None * * @see android.provider.Settings.Secure#ANDROID_ID @@ -961,10 +886,10 @@ import android.util.Log; /** * TYPE: {@code String} - *

        + *

        * String representing the telephony ID of the device. May be null for non-telephony devices. May also be null if the * parent application doesn't have {@link android.Manifest.permission#READ_PHONE_STATE}. - *

        + *

        * Constraints: None * * @see android.telephony.TelephonyManager#getDeviceId() @@ -973,10 +898,10 @@ import android.util.Log; /** * TYPE: {@code String} - *

        + *

        * String representing a hash of the telephony ID of the device. May be null for non-telephony devices. May also be null * if the parent application doesn't have {@link android.Manifest.permission#READ_PHONE_STATE}. - *

        + *

        * Constraints: None * * @see android.telephony.TelephonyManager#getDeviceId() @@ -985,64 +910,64 @@ import android.util.Log; /** * TYPE: {@code String} - *

        + *

        * String representing a hash of the the serial number of the device. May be null for some telephony devices. - *

        + *

        * Constraints: None */ public static final String DEVICE_SERIAL_NUMBER_HASH = "device_serial_number_hash"; //$NON-NLS-1$ /** * TYPE: {@code String} - *

        + *

        * Represents the locale language of the device. - *

        + *

        * Constraints: Cannot be null. */ public static final String LOCALE_LANGUAGE = "locale_language"; //$NON-NLS-1$ /** * TYPE: {@code String} - *

        + *

        * Represents the locale country of the device. - *

        + *

        * Constraints: Cannot be null. */ public static final String LOCALE_COUNTRY = "locale_country"; //$NON-NLS-1$ /** * TYPE: {@code String} - *

        + *

        * Represents the locale country of the device, according to the SIM card. - *

        + *

        * Constraints: Cannot be null. */ public static final String DEVICE_COUNTRY = "device_country"; //$NON-NLS-1$ /** * TYPE: {@code String} - *

        + *

        * Represents the network carrier of the device. May be null for non-telephony devices. - *

        + *

        * Constraints: None */ public static final String NETWORK_CARRIER = "network_carrier"; //$NON-NLS-1$ /** * TYPE: {@code String} - *

        + *

        * Represents the network country of the device. May be null for non-telephony devices. - *

        + *

        * Constraints: None */ public static final String NETWORK_COUNTRY = "network_country"; //$NON-NLS-1$ /** * TYPE: {@code String} - *

        + *

        * Represents the primary network connection type for the device. This could be any type, including Wi-Fi, various cell * networks, Ethernet, etc. - *

        + *

        * Constraints: None * * @see android.telephony.TelephonyManager @@ -1051,18 +976,18 @@ import android.util.Log; /** * TYPE: {@code double} - *

        + *

        * Represents the latitude of the device. May be null if no longitude is known. - *

        + *

        * Constraints: None */ public static final String LATITUDE = "latitude"; //$NON-NLS-1$ /** * TYPE: {@code double} - *

        + *

        * Represents the longitude of the device. May be null if no longitude is known. - *

        + *

        * Constraints: None */ public static final String LONGITUDE = "longitude"; //$NON-NLS-1$ @@ -1073,18 +998,16 @@ import android.util.Log; * Database table for the events associated with a given upload blob. There is a one-to-many relationship between one upload * blob in the {@link UploadBlobsDbColumns} table and the blob events. There is a one-to-one relationship between each blob * event entry and the actual events in the {@link EventsDbColumns} table. * - *

        + *

        * This is not a public API. */ - public static final class UploadBlobEventsDbColumns implements BaseColumns - { + public static final class UploadBlobEventsDbColumns implements BaseColumns { /** * Private constructor prevents instantiation * * @throws UnsupportedOperationException because this class cannot be instantiated. */ - private UploadBlobEventsDbColumns() - { + private UploadBlobEventsDbColumns() { throw new UnsupportedOperationException("This class is non-instantiable"); //$NON-NLS-1$ } @@ -1095,18 +1018,18 @@ import android.util.Log; /** * TYPE: {@code String} - *

        + *

        * A one-to-many relationship with {@link UploadBlobsDbColumns#_ID}. - *

        + *

        * Constraints: This is a foreign key with the {@link UploadBlobsDbColumns#_ID} column. This cannot be null. */ public static final String UPLOAD_BLOBS_KEY_REF = "upload_blobs_key_ref"; //$NON-NLS-1$ /** * TYPE: {@code long} - *

        + *

        * A one-to-one relationship with {@link EventsDbColumns#_ID}. - *

        + *

        * Constraints: This is a foreign key with the {@link EventsDbColumns#_ID} column. This cannot be null. */ public static final String EVENTS_KEY_REF = "events_key_ref"; //$NON-NLS-1$ @@ -1116,18 +1039,16 @@ import android.util.Log; * Database table for the upload blobs. Logically, a blob owns many events. In terms of the implementation, some indirection * is introduced by a blob having a one-to-many relationship with {@link UploadBlobsDbColumns} and * {@link UploadBlobsDbColumns} having a one-to-one relationship with {@link EventsDbColumns} - *

        + *

        * This is not a public API. */ - public static final class UploadBlobsDbColumns implements BaseColumns - { + public static final class UploadBlobsDbColumns implements BaseColumns { /** * Private constructor prevents instantiation * * @throws UnsupportedOperationException because this class cannot be instantiated. */ - private UploadBlobsDbColumns() - { + private UploadBlobsDbColumns() { throw new UnsupportedOperationException("This class is non-instantiable"); //$NON-NLS-1$ } @@ -1138,9 +1059,9 @@ import android.util.Log; /** * TYPE: {@code String} - *

        + *

        * Unique ID of the upload blob, as generated from {@link java.util.UUID}. - *

        + *

        * Constraints: This is unique and cannot be null. */ public static final String UUID = "uuid"; //$NON-NLS-1$ diff --git a/astrid/common-src/com/localytics/android/LocalyticsSession.java b/astrid/common-src/com/localytics/android/LocalyticsSession.java index f0b568f7d..bcbb1d347 100755 --- a/astrid/common-src/com/localytics/android/LocalyticsSession.java +++ b/astrid/common-src/com/localytics/android/LocalyticsSession.java @@ -8,32 +8,6 @@ package com.localytics.android; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.TreeMap; -import java.util.UUID; -import java.util.zip.GZIPOutputStream; - -import org.apache.http.HttpResponse; -import org.apache.http.StatusLine; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ByteArrayEntity; -import org.apache.http.impl.client.DefaultHttpClient; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - import android.Manifest.permission; import android.content.ContentValues; import android.content.Context; @@ -60,6 +34,32 @@ import com.localytics.android.LocalyticsProvider.SessionsDbColumns; import com.localytics.android.LocalyticsProvider.UploadBlobEventsDbColumns; import com.localytics.android.LocalyticsProvider.UploadBlobsDbColumns; +import org.apache.http.HttpResponse; +import org.apache.http.StatusLine; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ByteArrayEntity; +import org.apache.http.impl.client.DefaultHttpClient; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.TreeMap; +import java.util.UUID; +import java.util.zip.GZIPOutputStream; + /** * This class manages creating, collecting, and uploading a Localytics session. Please see the following guides for information on * how to best use this library, sample code, and other useful information: @@ -102,13 +102,12 @@ import com.localytics.android.LocalyticsProvider.UploadBlobsDbColumns; *

      3. Do not call any {@link LocalyticsSession} methods inside a loop. Instead, calls such as {@link #tagEvent(String)} should * follow user actions. This limits the amount of data which is stored and uploaded.
      4. *
    - *

    + *

    * This class is thread-safe. * * @version 2.0 */ -public final class LocalyticsSession -{ +public final class LocalyticsSession { /* * DESIGN NOTES * @@ -197,8 +196,7 @@ public final class LocalyticsSession * @param name to give to the HandlerThread. Useful for debugging, as the thread name is shown in DDMS. * @return HandlerThread whose {@link HandlerThread#start()} method has already been called. */ - private static HandlerThread getHandlerThread(final String name) - { + private static HandlerThread getHandlerThread(final String name) { final HandlerThread thread = new HandlerThread(name, android.os.Process.THREAD_PRIORITY_BACKGROUND); thread.start(); @@ -214,9 +212,9 @@ public final class LocalyticsSession /** * Handler object where all session requests of this instance of LocalyticsSession are handed off to. - *

    + *

    * This Handler is the key thread synchronization point for all work inside the LocalyticsSession. - *

    + *

    * This handler runs on {@link #sSessionHandlerThread}. */ private final Handler mSessionHandler; @@ -234,7 +232,7 @@ public final class LocalyticsSession /** * Keeps track of which Localytics clients are currently uploading, in order to allow only one upload for a given key at a * time. - *

    + *

    * This field can only be read/written to from the {@link #sSessionHandlerThread}. This invariant is maintained by only * accessing this field from within the {@link #mSessionHandler}. */ @@ -244,20 +242,17 @@ public final class LocalyticsSession * Constructs a new {@link LocalyticsSession} object. * * @param context The context used to access resources on behalf of the app. It is recommended to use - * {@link Context#getApplicationContext()} to avoid the potential memory leak incurred by maintaining references to - * {@code Activity} instances. Cannot be null. - * @param key The key unique for each application generated at www.localytics.com. Cannot be null or empty. + * {@link Context#getApplicationContext()} to avoid the potential memory leak incurred by maintaining references to + * {@code Activity} instances. Cannot be null. + * @param key The key unique for each application generated at www.localytics.com. Cannot be null or empty. * @throws IllegalArgumentException if {@code context} is null * @throws IllegalArgumentException if {@code key} is null or empty */ - public LocalyticsSession(final Context context, final String key) - { - if (context == null) - { + public LocalyticsSession(final Context context, final String key) { + if (context == null) { throw new IllegalArgumentException("context cannot be null"); //$NON-NLS-1$ } - if (TextUtils.isEmpty(key)) - { + if (TextUtils.isEmpty(key)) { throw new IllegalArgumentException("key cannot be null or empty"); //$NON-NLS-1$ } @@ -299,8 +294,7 @@ public final class LocalyticsSession * * @param isOptedOut True if the user should be be opted out and have all his Localytics data deleted. */ - public void setOptOut(final boolean isOptedOut) - { + public void setOptOut(final boolean isOptedOut) { mSessionHandler.sendMessage(mSessionHandler.obtainMessage(SessionHandler.MESSAGE_OPT_OUT, isOptedOut ? 1 : 0, 0)); } @@ -309,15 +303,14 @@ public final class LocalyticsSession * and the final close so it is recommended to open the session as early as possible, and close it at the last * moment. The session must be opened before {@link #tagEvent(String)} or {@link #tagEvent(String, Map)} can be called, so * this call should be placed in {@code Activity#onCreate(Bundle)}. - *

    + *

    * If for any reason this is called more than once without an intervening call to {@link #close()}, subsequent calls to open * will be ignored. - *

    + *

    * For applications with multiple Activities, every Activity should call open in onCreate. This will * cause each Activity to reconnect to the currently running session. */ - public void open() - { + public void open() { mSessionHandler.sendEmptyMessage(SessionHandler.MESSAGE_OPEN); } @@ -328,8 +321,7 @@ public final class LocalyticsSession * Closing does not cause the session to stop collecting data. This is a result of the application life cycle. It is possible * for onPause to be called long before the application is actually ready to close the session. */ - public void close() - { + public void close() { mSessionHandler.sendEmptyMessage(SessionHandler.MESSAGE_CLOSE); } @@ -352,8 +344,7 @@ public final class LocalyticsSession * @throws IllegalArgumentException if {@code event} is null. * @throws IllegalArgumentException if {@code event} is empty. */ - public void tagEvent(final String event) - { + public void tagEvent(final String event) { tagEvent(event, null); } @@ -372,61 +363,49 @@ public final class LocalyticsSession * *
    * - * @param event The name of the event which occurred. + * @param event The name of the event which occurred. * @param attributes The collection of attributes for this particular event. If this parameter is null or empty, then calling - * this method has the same effect as calling {@link #tagEvent(String)}. This parameter may not contain null or - * empty keys or values. + * this method has the same effect as calling {@link #tagEvent(String)}. This parameter may not contain null or + * empty keys or values. * @throws IllegalArgumentException if {@code event} is null. * @throws IllegalArgumentException if {@code event} is empty. * @throws IllegalArgumentException if {@code attributes} contains null keys, empty keys, null values, or empty values. */ - public void tagEvent(final String event, final Map attributes) - { - if (Constants.ENABLE_PARAMETER_CHECKING) - { - if (null == event) - { + public void tagEvent(final String event, final Map attributes) { + if (Constants.ENABLE_PARAMETER_CHECKING) { + if (null == event) { throw new IllegalArgumentException("event cannot be null"); //$NON-NLS-1$ } - if (0 == event.length()) - { + if (0 == event.length()) { throw new IllegalArgumentException("event cannot be empty"); //$NON-NLS-1$ } - if (null != attributes) - { + if (null != attributes) { /* * Calling this with empty attributes is a smell that indicates a possible programming error on the part of the * caller */ - if (attributes.isEmpty()) - { - if (Constants.IS_LOGGABLE) - { + if (attributes.isEmpty()) { + if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "attributes is empty. Did the caller make an error?"); //$NON-NLS-1$ } } - for (final Entry entry : attributes.entrySet()) - { + for (final Entry entry : attributes.entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); - if (null == key) - { + if (null == key) { throw new IllegalArgumentException("attributes cannot contain null keys"); //$NON-NLS-1$ } - if (null == value) - { + if (null == value) { throw new IllegalArgumentException("attributes cannot contain null values"); //$NON-NLS-1$ } - if (0 == key.length()) - { + if (0 == key.length()) { throw new IllegalArgumentException("attributes cannot contain empty keys"); //$NON-NLS-1$ } - if (0 == value.length()) - { + if (0 == value.length()) { throw new IllegalArgumentException("attributes cannot contain empty values"); //$NON-NLS-1$ } } @@ -435,12 +414,9 @@ public final class LocalyticsSession final String eventString = String.format(EVENT_FORMAT, mContext.getPackageName(), event); - if (null == attributes) - { + if (null == attributes) { mSessionHandler.sendMessage(mSessionHandler.obtainMessage(SessionHandler.MESSAGE_TAG_EVENT, new Pair>(eventString, null))); - } - else - { + } else { /* * Note: it is important to make a copy of the map, to ensure that a client can't modify the map after this method is * called. A TreeMap is used to ensure that the order that the attributes are written is deterministic. For example, @@ -448,9 +424,9 @@ public final class LocalyticsSession * consistently. */ mSessionHandler.sendMessage(mSessionHandler.obtainMessage(SessionHandler.MESSAGE_TAG_EVENT, new Pair>( - eventString, - new TreeMap( - attributes)))); + eventString, + new TreeMap( + attributes)))); } } @@ -463,15 +439,12 @@ public final class LocalyticsSession * @throws IllegalArgumentException if {@code event} is null. * @throws IllegalArgumentException if {@code event} is empty. */ - public void tagScreen(final String screen) - { - if (null == screen) - { + public void tagScreen(final String screen) { + if (null == screen) { throw new IllegalArgumentException("event cannot be null"); //$NON-NLS-1$ } - if (0 == screen.length()) - { + if (0 == screen.length()) { throw new IllegalArgumentException("event cannot be empty"); //$NON-NLS-1$ } @@ -483,8 +456,7 @@ public final class LocalyticsSession * order to guarantee as much time as possible for slow connections to complete. It is necessary to do this even if the user * has opted out because this is how the opt out is transported to the webservice. */ - public void upload() - { + public void upload() { mSessionHandler.sendMessage(mSessionHandler.obtainMessage(SessionHandler.MESSAGE_UPLOAD, null)); } @@ -514,27 +486,22 @@ public final class LocalyticsSession * step. * * @param actualValue The int value to be sorted. - * @param minValue The int value representing the inclusive minimum interval. - * @param maxValue The int value representing the inclusive maximum interval. - * @param step The int value representing the increment of each interval. + * @param minValue The int value representing the inclusive minimum interval. + * @param maxValue The int value representing the inclusive maximum interval. + * @param step The int value representing the increment of each interval. * @return a ranged attribute suitable for passing as the argument to {@link #tagEvent(String)} or - * {@link #tagEvent(String, Map)}. + * {@link #tagEvent(String, Map)}. */ - public static String createRangedAttribute(final int actualValue, final int minValue, final int maxValue, final int step) - { + public static String createRangedAttribute(final int actualValue, final int minValue, final int maxValue, final int step) { // Confirm there is at least one bucket - if (step < 1) - { - if (Constants.IS_LOGGABLE) - { + if (step < 1) { + if (Constants.IS_LOGGABLE) { Log.v(Constants.LOG_TAG, "Step must not be less than zero. Returning null."); //$NON-NLS-1$ } return null; } - if (minValue >= maxValue) - { - if (Constants.IS_LOGGABLE) - { + if (minValue >= maxValue) { + if (Constants.IS_LOGGABLE) { Log.v(Constants.LOG_TAG, "maxValue must not be less than minValue. Returning null."); //$NON-NLS-1$ } return null; @@ -543,8 +510,7 @@ public final class LocalyticsSession // Determine the number of steps, rounding up using int math final int stepQuantity = (maxValue - minValue + step) / step; final int[] steps = new int[stepQuantity + 1]; - for (int currentStep = 0; currentStep <= stepQuantity; currentStep++) - { + for (int currentStep = 0; currentStep <= stepQuantity; currentStep++) { steps[currentStep] = minValue + (currentStep) * step; } return createRangedAttribute(actualValue, steps); @@ -557,52 +523,41 @@ public final class LocalyticsSession * than 0, 0, 1-2, 3-9, 10 or greater. * * @param actualValue The int value to be bucketed. - * @param steps The sorted int array representing the bucketing intervals. + * @param steps The sorted int array representing the bucketing intervals. * @return String representation of {@code actualValue} that has been bucketed into the range provided by {@code steps}. * @throws IllegalArgumentException if {@code steps} is null. * @throws IllegalArgumentException if {@code steps} has length 0. */ @SuppressWarnings("nls") - public static String createRangedAttribute(final int actualValue, final int[] steps) - { - if (null == steps) - { + public static String createRangedAttribute(final int actualValue, final int[] steps) { + if (null == steps) { throw new IllegalArgumentException("steps cannot be null"); //$NON-NLS-1$ } - if (steps.length == 0) - { + if (steps.length == 0) { throw new IllegalArgumentException("steps length must be greater than 0"); //$NON-NLS-1$ } String bucket = null; // if less than smallest value - if (actualValue < steps[0]) - { + if (actualValue < steps[0]) { bucket = "less than " + steps[0]; } // if greater than largest value - else if (actualValue >= steps[steps.length - 1]) - { + else if (actualValue >= steps[steps.length - 1]) { bucket = steps[steps.length - 1] + " and above"; - } - else - { + } else { // binarySearch returns the index of the value, or (-(insertion point) - 1) if not found int bucketIndex = Arrays.binarySearch(steps, actualValue); - if (bucketIndex < 0) - { + if (bucketIndex < 0) { // if the index wasn't found, then we want the value before the insertion point as the lower end // the special case where the insertion point is 0 is covered above, so we don't have to worry about it here bucketIndex = (-bucketIndex) - 2; } - if (steps[bucketIndex] == (steps[bucketIndex + 1] - 1)) - { + if (steps[bucketIndex] == (steps[bucketIndex + 1] - 1)) { bucket = Integer.toString(steps[bucketIndex]); - } - else - { + } else { bucket = steps[bucketIndex] + "-" + (steps[bucketIndex + 1] - 1); //$NON-NLS-1$ } } @@ -612,11 +567,10 @@ public final class LocalyticsSession /** * Helper class to handle session-related work on the {@link LocalyticsSession#sSessionHandlerThread}. */ - /* package */static final class SessionHandler extends Handler - { + /* package */static final class SessionHandler extends Handler { /** * Empty handler message to initialize the callback. - *

    + *

    * This message must be sent before any other messages. */ public static final int MESSAGE_INIT = 0; @@ -633,14 +587,14 @@ public final class LocalyticsSession /** * Handler message to tag an event. - *

    + *

    * {@link Message#obj} is a {@link Pair} instance. This object cannot be null. */ public static final int MESSAGE_TAG_EVENT = 3; /** * Handler message to upload all data collected so far - *

    + *

    * {@link Message#obj} is a {@code Runnable} to execute when upload is complete. The thread that this runnable will * executed on is undefined. */ @@ -653,28 +607,28 @@ public final class LocalyticsSession /** * Handler message indicating an opt-out choice. - *

    + *

    * {@link Message#arg1} == 1 for true (opt out). 0 means opt-in. */ public static final int MESSAGE_OPT_OUT = 6; /** * Handler message indicating a tag screen event - *

    + *

    * {@link Message#obj} is a string representing the screen visited. */ public static final int MESSAGE_TAG_SCREEN = 7; /** * Sort order for the upload blobs. - *

    + *

    * This is a workaround for Android bug 3707 . */ private static final String UPLOAD_BLOBS_EVENTS_SORT_ORDER = String.format("CAST(%s AS TEXT)", UploadBlobEventsDbColumns.EVENTS_KEY_REF); //$NON-NLS-1$ /** * Sort order for the events. - *

    + *

    * This is a workaround for Android bug 3707 . */ private static final String EVENTS_SORT_ORDER = String.format("CAST(%s as TEXT)", EventsDbColumns._ID); //$NON-NLS-1$ @@ -716,7 +670,7 @@ public final class LocalyticsSession /** * Handler object where all upload of this instance of LocalyticsSession are handed off to. - *

    + *

    * This handler runs on {@link #sUploadHandlerThread}. */ private Handler mUploadHandler; @@ -725,25 +679,21 @@ public final class LocalyticsSession * Constructs a new Handler that runs on the given looper. * * @param context The context used to access resources on behalf of the app. It is recommended to use - * {@link Context#getApplicationContext()} to avoid the potential memory leak incurred by maintaining - * references to {@code Activity} instances. Cannot be null. - * @param key The key unique for each application generated at www.localytics.com. Cannot be null or empty. - * @param looper to run the Handler on. Cannot be null. + * {@link Context#getApplicationContext()} to avoid the potential memory leak incurred by maintaining + * references to {@code Activity} instances. Cannot be null. + * @param key The key unique for each application generated at www.localytics.com. Cannot be null or empty. + * @param looper to run the Handler on. Cannot be null. * @throws IllegalArgumentException if {@code context} is null * @throws IllegalArgumentException if {@code key} is null or empty */ - public SessionHandler(final Context context, final String key, final Looper looper) - { + public SessionHandler(final Context context, final String key, final Looper looper) { super(looper); - if (Constants.ENABLE_PARAMETER_CHECKING) - { - if (context == null) - { + if (Constants.ENABLE_PARAMETER_CHECKING) { + if (context == null) { throw new IllegalArgumentException("context cannot be null"); //$NON-NLS-1$ } - if (TextUtils.isEmpty(key)) - { + if (TextUtils.isEmpty(key)) { throw new IllegalArgumentException("key cannot be null or empty"); //$NON-NLS-1$ } } @@ -753,14 +703,10 @@ public final class LocalyticsSession } @Override - public void handleMessage(final Message msg) - { - switch (msg.what) - { - case MESSAGE_INIT: - { - if (Constants.IS_LOGGABLE) - { + public void handleMessage(final Message msg) { + switch (msg.what) { + case MESSAGE_INIT: { + if (Constants.IS_LOGGABLE) { Log.v(Constants.LOG_TAG, "Handler received MESSAGE_INIT"); //$NON-NLS-1$ } @@ -768,10 +714,8 @@ public final class LocalyticsSession break; } - case MESSAGE_OPT_OUT: - { - if (Constants.IS_LOGGABLE) - { + case MESSAGE_OPT_OUT: { + if (Constants.IS_LOGGABLE) { Log.v(Constants.LOG_TAG, "Handler received MESSAGE_OPT_OUT"); //$NON-NLS-1$ } @@ -781,10 +725,8 @@ public final class LocalyticsSession break; } - case MESSAGE_OPEN: - { - if (Constants.IS_LOGGABLE) - { + case MESSAGE_OPEN: { + if (Constants.IS_LOGGABLE) { Log.v(Constants.LOG_TAG, "Handler received MESSAGE_OPEN"); //$NON-NLS-1$ } @@ -792,10 +734,8 @@ public final class LocalyticsSession break; } - case MESSAGE_CLOSE: - { - if (Constants.IS_LOGGABLE) - { + case MESSAGE_CLOSE: { + if (Constants.IS_LOGGABLE) { Log.d(Constants.LOG_TAG, "Handler received MESSAGE_CLOSE"); //$NON-NLS-1$ } @@ -803,10 +743,8 @@ public final class LocalyticsSession break; } - case MESSAGE_TAG_EVENT: - { - if (Constants.IS_LOGGABLE) - { + case MESSAGE_TAG_EVENT: { + if (Constants.IS_LOGGABLE) { Log.d(Constants.LOG_TAG, "Handler received MESSAGE_TAG"); //$NON-NLS-1$ } @@ -819,10 +757,8 @@ public final class LocalyticsSession break; } - case MESSAGE_TAG_SCREEN: - { - if (Constants.IS_LOGGABLE) - { + case MESSAGE_TAG_SCREEN: { + if (Constants.IS_LOGGABLE) { Log.d(Constants.LOG_TAG, "Handler received MESSAGE_SCREEN"); //$NON-NLS-1$ } @@ -832,10 +768,8 @@ public final class LocalyticsSession break; } - case MESSAGE_UPLOAD: - { - if (Constants.IS_LOGGABLE) - { + case MESSAGE_UPLOAD: { + if (Constants.IS_LOGGABLE) { Log.d(Constants.LOG_TAG, "SessionHandler received MESSAGE_UPLOAD"); //$NON-NLS-1$ } @@ -848,10 +782,8 @@ public final class LocalyticsSession break; } - case MESSAGE_UPLOAD_COMPLETE: - { - if (Constants.IS_LOGGABLE) - { + case MESSAGE_UPLOAD_COMPLETE: { + if (Constants.IS_LOGGABLE) { Log.d(Constants.LOG_TAG, "Handler received MESSAGE_UPLOAD_COMPLETE"); //$NON-NLS-1$ } @@ -859,8 +791,7 @@ public final class LocalyticsSession break; } - default: - { + default: { /* * This should never happen */ @@ -871,46 +802,39 @@ public final class LocalyticsSession /** * Initialize the handler post construction. - *

    + *

    * This method must only be called once. - *

    + *

    * Note: This method is a private implementation detail. It is only made public for unit testing purposes. The public * interface is to send {@link #MESSAGE_INIT} to the Handler. * * @see #MESSAGE_INIT */ - public void init() - { + public void init() { mProvider = LocalyticsProvider.getInstance(mContext, mApiKey); /* * Check whether this session key is opted out */ Cursor cursor = null; - try - { + try { cursor = mProvider.query(ApiKeysDbColumns.TABLE_NAME, new String[] - { - ApiKeysDbColumns._ID, - ApiKeysDbColumns.OPT_OUT }, String.format("%s = ?", ApiKeysDbColumns.API_KEY), new String[] //$NON-NLS-1$ - { mApiKey }, null); + { + ApiKeysDbColumns._ID, + ApiKeysDbColumns.OPT_OUT}, String.format("%s = ?", ApiKeysDbColumns.API_KEY), new String[] //$NON-NLS-1$ + {mApiKey}, null); - if (cursor.moveToFirst()) - { + if (cursor.moveToFirst()) { // API key was previously created - if (Constants.IS_LOGGABLE) - { + if (Constants.IS_LOGGABLE) { Log.v(Constants.LOG_TAG, String.format("Loading details for API key %s", mApiKey)); //$NON-NLS-1$ } mApiKeyId = cursor.getLong(cursor.getColumnIndexOrThrow(ApiKeysDbColumns._ID)); mIsOptedOut = cursor.getInt(cursor.getColumnIndexOrThrow(ApiKeysDbColumns.OPT_OUT)) != 0; - } - else - { + } else { // perform first-time initialization of API key - if (Constants.IS_LOGGABLE) - { + if (Constants.IS_LOGGABLE) { Log.v(Constants.LOG_TAG, String.format("Performing first-time initialization for new API key %s", mApiKey)); //$NON-NLS-1$ } @@ -922,18 +846,14 @@ public final class LocalyticsSession mApiKeyId = mProvider.insert(ApiKeysDbColumns.TABLE_NAME, values); } - } - finally - { - if (cursor != null) - { + } finally { + if (cursor != null) { cursor.close(); cursor = null; } } - if (!sIsUploadingMap.containsKey(mApiKey)) - { + if (!sIsUploadingMap.containsKey(mApiKey)) { sIsUploadingMap.put(mApiKey, Boolean.FALSE); } @@ -945,48 +865,40 @@ public final class LocalyticsSession /** * Set the opt-in/out-out state for all sessions using the current API key. - *

    + *

    * This method must only be called after {@link #init()} is called. - *

    + *

    * Note: This method is a private implementation detail. It is only made package accessible for unit testing purposes. The * public interface is to send {@link #MESSAGE_OPT_OUT} to the Handler. * * @param isOptingOut true if the user is opting out. False if the user is opting back in. * @see #MESSAGE_OPT_OUT */ - /* package */void optOut(final boolean isOptingOut) - { - if (Constants.IS_LOGGABLE) - { + /* package */void optOut(final boolean isOptingOut) { + if (Constants.IS_LOGGABLE) { Log.v(Constants.LOG_TAG, String.format("Prior opt-out state is %b, requested opt-out state is %b", Boolean.valueOf(mIsOptedOut), Boolean.valueOf(isOptingOut))); //$NON-NLS-1$ } // Do nothing if opt-out is unchanged - if (mIsOptedOut == isOptingOut) - { + if (mIsOptedOut == isOptingOut) { return; } - mProvider.runBatchTransaction(new Runnable() - { + mProvider.runBatchTransaction(new Runnable() { @Override - public void run() - { + public void run() { final ContentValues values = new ContentValues(); values.put(ApiKeysDbColumns.OPT_OUT, Boolean.valueOf(isOptingOut)); - mProvider.update(ApiKeysDbColumns.TABLE_NAME, values, String.format("%s = ?", ApiKeysDbColumns._ID), new String[] { Long.toString(mApiKeyId) }); //$NON-NLS-1$ + mProvider.update(ApiKeysDbColumns.TABLE_NAME, values, String.format("%s = ?", ApiKeysDbColumns._ID), new String[]{Long.toString(mApiKeyId)}); //$NON-NLS-1$ - if (!mIsSessionOpen) - { + if (!mIsSessionOpen) { /* * Force a session to contain the opt event */ open(true); tagEvent(isOptingOut ? OPT_OUT_EVENT : OPT_IN_EVENT, null); close(); - } - else - { + } else { tagEvent(isOptingOut ? OPT_OUT_EVENT : OPT_IN_EVENT, null); } } @@ -1002,31 +914,26 @@ public final class LocalyticsSession /** * Open a session. While this method should only be called once without an intervening call to {@link #close()}, nothing * bad will happen if it is called multiple times. - *

    + *

    * This method must only be called after {@link #init()} is called. - *

    + *

    * Note: This method is a private implementation detail. It is only made package accessible for unit testing purposes. The * public interface is to send {@link #MESSAGE_OPEN} to the Handler. * * @param ignoreLimits true to ignore limits on the number of sessions. False to enforce limits. * @see #MESSAGE_OPEN */ - /* package */void open(final boolean ignoreLimits) - { - if (mIsSessionOpen) - { - if (Constants.IS_LOGGABLE) - { + /* package */void open(final boolean ignoreLimits) { + if (mIsSessionOpen) { + if (Constants.IS_LOGGABLE) { Log.w(Constants.LOG_TAG, "Session was already open"); //$NON-NLS-1$ } return; } - if (mIsOptedOut) - { - if (Constants.IS_LOGGABLE) - { + if (mIsOptedOut) { + if (Constants.IS_LOGGABLE) { Log.d(Constants.LOG_TAG, "Data collection is opted out"); //$NON-NLS-1$ } return; @@ -1042,44 +949,36 @@ public final class LocalyticsSession { Cursor eventsCursor = null; Cursor blob_eventsCursor = null; - try - { + try { eventsCursor = mProvider.query(EventsDbColumns.TABLE_NAME, new String[] - { EventsDbColumns._ID }, String.format("%s = ? AND %s >= ?", EventsDbColumns.EVENT_NAME, EventsDbColumns.WALL_TIME), new String[] { CLOSE_EVENT, Long.toString(System.currentTimeMillis() - Constants.SESSION_EXPIRATION) }, EVENTS_SORT_ORDER); //$NON-NLS-1$ + {EventsDbColumns._ID}, String.format("%s = ? AND %s >= ?", EventsDbColumns.EVENT_NAME, EventsDbColumns.WALL_TIME), new String[]{CLOSE_EVENT, Long.toString(System.currentTimeMillis() - Constants.SESSION_EXPIRATION)}, EVENTS_SORT_ORDER); //$NON-NLS-1$ blob_eventsCursor = mProvider.query(UploadBlobEventsDbColumns.TABLE_NAME, new String[] - { UploadBlobEventsDbColumns.EVENTS_KEY_REF }, null, null, UPLOAD_BLOBS_EVENTS_SORT_ORDER); + {UploadBlobEventsDbColumns.EVENTS_KEY_REF}, null, null, UPLOAD_BLOBS_EVENTS_SORT_ORDER); final int idColumn = eventsCursor.getColumnIndexOrThrow(EventsDbColumns._ID); final CursorJoiner joiner = new CursorJoiner(eventsCursor, new String[] - { EventsDbColumns._ID }, blob_eventsCursor, new String[] - { UploadBlobEventsDbColumns.EVENTS_KEY_REF }); + {EventsDbColumns._ID}, blob_eventsCursor, new String[] + {UploadBlobEventsDbColumns.EVENTS_KEY_REF}); - for (final CursorJoiner.Result joinerResult : joiner) - { - switch (joinerResult) - { - case LEFT: - { + for (final CursorJoiner.Result joinerResult : joiner) { + switch (joinerResult) { + case LEFT: { - if (-1 != closeEventId) - { + if (-1 != closeEventId) { /* * This should never happen */ - if (Constants.IS_LOGGABLE) - { + if (Constants.IS_LOGGABLE) { Log.w(Constants.LOG_TAG, "There were multiple close events within SESSION_EXPIRATION"); //$NON-NLS-1$ } long newClose = eventsCursor.getLong(eventsCursor.getColumnIndexOrThrow(EventsDbColumns._ID)); - if (newClose > closeEventId) - { + if (newClose > closeEventId) { closeEventId = newClose; } } - if (-1 == closeEventId) - { + if (-1 == closeEventId) { closeEventId = eventsCursor.getLong(idColumn); } @@ -1094,42 +993,32 @@ public final class LocalyticsSession /* * Verify that the session hasn't already been flagged for upload. That could happen if */ - } - finally - { - if (eventsCursor != null) - { + } finally { + if (eventsCursor != null) { eventsCursor.close(); } - if (blob_eventsCursor != null) - { + if (blob_eventsCursor != null) { blob_eventsCursor.close(); } } } - if (-1 != closeEventId) - { + if (-1 != closeEventId) { Log.v(Constants.LOG_TAG, "Opening old closed session and reconnecting"); //$NON-NLS-1$ mIsSessionOpen = true; openClosedSession(closeEventId); - } - else - { + } else { Cursor sessionsCursor = null; - try - { + try { sessionsCursor = mProvider.query(SessionsDbColumns.TABLE_NAME, new String[] - { - SessionsDbColumns._ID, - SessionsDbColumns.SESSION_START_WALL_TIME }, null, null, SessionsDbColumns._ID); + { + SessionsDbColumns._ID, + SessionsDbColumns.SESSION_START_WALL_TIME}, null, null, SessionsDbColumns._ID); - if (sessionsCursor.moveToLast()) - { + if (sessionsCursor.moveToLast()) { if (sessionsCursor.getLong(sessionsCursor.getColumnIndexOrThrow(SessionsDbColumns.SESSION_START_WALL_TIME)) >= System.currentTimeMillis() - - Constants.SESSION_EXPIRATION) - { + - Constants.SESSION_EXPIRATION) { // reconnect Log.v(Constants.LOG_TAG, "Opening old unclosed session and reconnecting"); //$NON-NLS-1$ mIsSessionOpen = true; @@ -1139,32 +1028,24 @@ public final class LocalyticsSession // delete empties Cursor eventsCursor = null; - try - { + try { String sessionId = Long.toString(sessionsCursor.getLong(sessionsCursor.getColumnIndexOrThrow(SessionsDbColumns._ID))); eventsCursor = mProvider.query(EventsDbColumns.TABLE_NAME, new String[] - { EventsDbColumns._ID }, String.format("%s = ?", EventsDbColumns.SESSION_KEY_REF), new String[] //$NON-NLS-1$ - { sessionId }, null); + {EventsDbColumns._ID}, String.format("%s = ?", EventsDbColumns.SESSION_KEY_REF), new String[] //$NON-NLS-1$ + {sessionId}, null); - if (eventsCursor.getCount() == 0) - { - mProvider.delete(SessionsDbColumns.TABLE_NAME, String.format("%s = ?", SessionsDbColumns._ID), new String[] { sessionId }); //$NON-NLS-1$ + if (eventsCursor.getCount() == 0) { + mProvider.delete(SessionsDbColumns.TABLE_NAME, String.format("%s = ?", SessionsDbColumns._ID), new String[]{sessionId}); //$NON-NLS-1$ } - } - finally - { - if (null != eventsCursor) - { + } finally { + if (null != eventsCursor) { eventsCursor.close(); eventsCursor = null; } } } - } - finally - { - if (null != sessionsCursor) - { + } finally { + if (null != sessionsCursor) { sessionsCursor.close(); sessionsCursor = null; } @@ -1173,27 +1054,20 @@ public final class LocalyticsSession /* * Check that the maximum number of sessions hasn't been exceeded */ - if (!ignoreLimits) - { + if (!ignoreLimits) { Cursor cursor = null; - try - { + try { cursor = mProvider.query(SessionsDbColumns.TABLE_NAME, new String[] - { SessionsDbColumns._ID }, null, null, null); + {SessionsDbColumns._ID}, null, null, null); - if (cursor.getCount() >= Constants.MAX_NUM_SESSIONS) - { - if (Constants.IS_LOGGABLE) - { + if (cursor.getCount() >= Constants.MAX_NUM_SESSIONS) { + if (Constants.IS_LOGGABLE) { Log.w(Constants.LOG_TAG, "Maximum number of sessions are already on disk--not writing any new sessions until old sessions are cleared out. Try calling upload() to store more sessions."); //$NON-NLS-1$ } return; } - } - finally - { - if (cursor != null) - { + } finally { + if (cursor != null) { cursor.close(); cursor = null; } @@ -1212,8 +1086,7 @@ public final class LocalyticsSession * * @effects Updates the database by creating a new entry in the {@link SessionsDbColumns} table. */ - private void openNewSession() - { + private void openNewSession() { final TelephonyManager telephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); final ContentValues values = new ContentValues(); @@ -1226,21 +1099,15 @@ public final class LocalyticsSession // Try and get the deviceId. If it is unavailable (or invalid) use the installation ID instead. String deviceId = DatapointHelper.getAndroidIdHashOrNull(mContext); - if (deviceId == null) - { + if (deviceId == null) { Cursor cursor = null; - try - { - cursor = mProvider.query(ApiKeysDbColumns.TABLE_NAME, null, String.format("%s = ?", ApiKeysDbColumns.API_KEY), new String[] { mApiKey }, null); //$NON-NLS-1$ - if (cursor.moveToFirst()) - { + try { + cursor = mProvider.query(ApiKeysDbColumns.TABLE_NAME, null, String.format("%s = ?", ApiKeysDbColumns.API_KEY), new String[]{mApiKey}, null); //$NON-NLS-1$ + if (cursor.moveToFirst()) { deviceId = cursor.getString(cursor.getColumnIndexOrThrow(ApiKeysDbColumns.UUID)); } - } - finally - { - if (null != cursor) - { + } finally { + if (null != cursor) { cursor.close(); cursor = null; } @@ -1264,14 +1131,11 @@ public final class LocalyticsSession values.put(SessionsDbColumns.NETWORK_COUNTRY, telephonyManager.getNetworkCountryIso()); values.put(SessionsDbColumns.NETWORK_TYPE, DatapointHelper.getNetworkType(mContext, telephonyManager)); - mProvider.runBatchTransaction(new Runnable() - { + mProvider.runBatchTransaction(new Runnable() { @Override - public void run() - { + public void run() { mSessionId = mProvider.insert(SessionsDbColumns.TABLE_NAME, values); - if (mSessionId == -1) - { + if (mSessionId == -1) { throw new RuntimeException("session insert failed"); //$NON-NLS-1$ } @@ -1291,40 +1155,31 @@ public final class LocalyticsSession * * @param closeEventId The last close event which is to be deleted so that the old session can be reopened * @effects Updates the database by deleting the last close event and sets {@link #mSessionId} to the session id of the - * last close event + * last close event */ - private void openClosedSession(final long closeEventId) - { + private void openClosedSession(final long closeEventId) { Cursor eventCursor = null; - try - { + try { eventCursor = mProvider.query(EventsDbColumns.TABLE_NAME, new String[] - { EventsDbColumns.SESSION_KEY_REF }, String.format("%s = ?", EventsDbColumns._ID), new String[] { Long.toString(closeEventId) }, null); //$NON-NLS-1$ + {EventsDbColumns.SESSION_KEY_REF}, String.format("%s = ?", EventsDbColumns._ID), new String[]{Long.toString(closeEventId)}, null); //$NON-NLS-1$ - if (eventCursor.moveToFirst()) - { + if (eventCursor.moveToFirst()) { mSessionId = eventCursor.getLong(eventCursor.getColumnIndexOrThrow(EventsDbColumns.SESSION_KEY_REF)); - mProvider.delete(EventsDbColumns.TABLE_NAME, String.format("%s = ?", EventsDbColumns._ID), new String[] { Long.toString(closeEventId) }); //$NON-NLS-1$ - } - else - { + mProvider.delete(EventsDbColumns.TABLE_NAME, String.format("%s = ?", EventsDbColumns._ID), new String[]{Long.toString(closeEventId)}); //$NON-NLS-1$ + } else { /* * This should never happen */ - if (Constants.IS_LOGGABLE) - { + if (Constants.IS_LOGGABLE) { Log.e(Constants.LOG_TAG, "Event no longer exists"); //$NON-NLS-1$ } openNewSession(); } - } - finally - { - if (eventCursor != null) - { + } finally { + if (eventCursor != null) { eventCursor.close(); } } @@ -1333,20 +1188,18 @@ public final class LocalyticsSession /** * Close a session. While this method should only be called after {@link #open(boolean)}, nothing bad will happen if it is * called and {@link #open(boolean)} wasn't called. Similarly, nothing bad will happen if close is called multiple times. - *

    + *

    * This method must only be called after {@link #init()} is called. - *

    + *

    * Note: This method is a private implementation detail. It is only made package accessible for unit testing purposes. The * public interface is to send {@link #MESSAGE_CLOSE} to the Handler. * * @see #MESSAGE_OPEN */ - /* package */void close() - { + /* package */void close() { if (!mIsSessionOpen) // do nothing if session is not open { - if (Constants.IS_LOGGABLE) - { + if (Constants.IS_LOGGABLE) { Log.w(Constants.LOG_TAG, "Session was not open, so close is not possible."); //$NON-NLS-1$ } return; @@ -1360,23 +1213,20 @@ public final class LocalyticsSession /** * Tag an event in a session. While this method shouldn't be called unless {@link #open(boolean)} is called first, this * method will simply do nothing if {@link #open(boolean)} hasn't been called. - *

    + *

    * This method must only be called after {@link #init()} is called. - *

    + *

    * Note: This method is a private implementation detail. It is only made package accessible for unit testing purposes. The * public interface is to send {@link #MESSAGE_TAG_EVENT} to the Handler. * - * @param event The name of the event which occurred. + * @param event The name of the event which occurred. * @param attributes The collection of attributes for this particular event. If this parameter is null, then calling this - * method has the same effect as calling {@link #tagEvent(String)}. + * method has the same effect as calling {@link #tagEvent(String)}. * @see #MESSAGE_TAG_EVENT */ - /* package */void tagEvent(final String event, final Map attributes) - { - if (!mIsSessionOpen) - { - if (Constants.IS_LOGGABLE) - { + /* package */void tagEvent(final String event, final Map attributes) { + if (!mIsSessionOpen) { + if (Constants.IS_LOGGABLE) { Log.w(Constants.LOG_TAG, "Tag not written because the session was not open"); //$NON-NLS-1$ } return; @@ -1397,28 +1247,20 @@ public final class LocalyticsSession /* * Special case for open event: keep the start time in sync with the start time put into the sessions table. */ - if (OPEN_EVENT.equals(event)) - { + if (OPEN_EVENT.equals(event)) { Cursor cursor = null; - try - { + try { cursor = mProvider.query(SessionsDbColumns.TABLE_NAME, new String[] - { SessionsDbColumns.SESSION_START_WALL_TIME }, String.format("%s = ?", SessionsDbColumns._ID), new String[] { Long.toString(mSessionId) }, null); //$NON-NLS-1$ + {SessionsDbColumns.SESSION_START_WALL_TIME}, String.format("%s = ?", SessionsDbColumns._ID), new String[]{Long.toString(mSessionId)}, null); //$NON-NLS-1$ - if (cursor.moveToFirst()) - { + if (cursor.moveToFirst()) { values.put(EventsDbColumns.WALL_TIME, Long.valueOf(cursor.getLong(cursor.getColumnIndexOrThrow(SessionsDbColumns.SESSION_START_WALL_TIME)))); - } - else - { + } else { // this should never happen throw new RuntimeException("Session didn't exist"); //$NON-NLS-1$ } - } - finally - { - if (null != cursor) - { + } finally { + if (null != cursor) { cursor.close(); } } @@ -1426,8 +1268,7 @@ public final class LocalyticsSession eventId = mProvider.insert(EventsDbColumns.TABLE_NAME, values); - if (-1 == eventId) - { + if (-1 == eventId) { throw new RuntimeException("Inserting event failed"); //$NON-NLS-1$ } } @@ -1435,20 +1276,16 @@ public final class LocalyticsSession /* * If attributes exist, insert them as well */ - if (null != attributes) - { + if (null != attributes) { int count = 0; - for (final Entry entry : attributes.entrySet()) - { + for (final Entry entry : attributes.entrySet()) { /* * Note: the attributes that are skipped are deterministic, because the map is actually an instance of * TreeMap. */ count++; - if (count > Constants.MAX_NUM_ATTRIBUTES) - { - if (Constants.IS_LOGGABLE) - { + if (count > Constants.MAX_NUM_ATTRIBUTES) { + if (Constants.IS_LOGGABLE) { Log.w(Constants.LOG_TAG, String.format("Map contains %s keys while the maximum number of attributes is %s. Some attributes were not written. Consider reducing the number of attributes.", Integer.valueOf(attributes.size()), Integer.valueOf(Constants.MAX_NUM_ATTRIBUTES))); //$NON-NLS-1$ } break; @@ -1461,8 +1298,7 @@ public final class LocalyticsSession final long id = mProvider.insert(AttributesDbColumns.TABLE_NAME, values); - if (-1 == id) - { + if (-1 == id) { throw new RuntimeException("Inserting attribute failed"); //$NON-NLS-1$ } } @@ -1471,8 +1307,7 @@ public final class LocalyticsSession /* * Insert the event into the history, only for application events */ - if (!OPEN_EVENT.equals(event) && !CLOSE_EVENT.equals(event) && !OPT_IN_EVENT.equals(event) && !OPT_OUT_EVENT.equals(event) && !FLOW_EVENT.equals(event)) - { + if (!OPEN_EVENT.equals(event) && !CLOSE_EVENT.equals(event) && !OPT_IN_EVENT.equals(event) && !OPT_OUT_EVENT.equals(event) && !FLOW_EVENT.equals(event)) { final ContentValues values = new ContentValues(); values.put(EventHistoryDbColumns.NAME, event.substring(mContext.getPackageName().length() + 1, event.length())); values.put(EventHistoryDbColumns.TYPE, Integer.valueOf(EventHistoryDbColumns.TYPE_EVENT)); @@ -1487,24 +1322,21 @@ public final class LocalyticsSession /** * Tag a screen in a session. While this method shouldn't be called unless {@link #open(boolean)} is called first, this * method will simply do nothing if {@link #open(boolean)} hasn't been called. - *

    + *

    * This method performs duplicate suppression, preventing multiple screens with the same value in a row within a given * session. - *

    + *

    * This method must only be called after {@link #init()} is called. - *

    + *

    * Note: This method is a private implementation detail. It is only made public for unit testing purposes. The public * interface is to send {@link #MESSAGE_TAG_SCREEN} to the Handler. * * @param screen The name of the screen which occurred. Cannot be null or empty. * @see #MESSAGE_TAG_SCREEN */ - /* package */void tagScreen(final String screen) - { - if (!mIsSessionOpen) - { - if (Constants.IS_LOGGABLE) - { + /* package */void tagScreen(final String screen) { + if (!mIsSessionOpen) { + if (Constants.IS_LOGGABLE) { Log.w(Constants.LOG_TAG, "Tag not written because the session was not open"); //$NON-NLS-1$ } return; @@ -1514,27 +1346,20 @@ public final class LocalyticsSession * Do duplicate suppression */ Cursor cursor = null; - try - { + try { cursor = mProvider.query(EventHistoryDbColumns.TABLE_NAME, new String[] - { EventHistoryDbColumns.NAME }, String.format("%s = ? AND %s = ?", EventHistoryDbColumns.TYPE, EventHistoryDbColumns.SESSION_KEY_REF), new String[] { Integer.toString(EventHistoryDbColumns.TYPE_SCREEN), Long.toString(mSessionId) }, String.format("%s DESC", EventHistoryDbColumns._ID)); //$NON-NLS-1$ //$NON-NLS-2$ + {EventHistoryDbColumns.NAME}, String.format("%s = ? AND %s = ?", EventHistoryDbColumns.TYPE, EventHistoryDbColumns.SESSION_KEY_REF), new String[]{Integer.toString(EventHistoryDbColumns.TYPE_SCREEN), Long.toString(mSessionId)}, String.format("%s DESC", EventHistoryDbColumns._ID)); //$NON-NLS-1$ //$NON-NLS-2$ - if (cursor.moveToFirst()) - { - if (screen.equals(cursor.getString(cursor.getColumnIndexOrThrow(EventHistoryDbColumns.NAME)))) - { - if (Constants.IS_LOGGABLE) - { + if (cursor.moveToFirst()) { + if (screen.equals(cursor.getString(cursor.getColumnIndexOrThrow(EventHistoryDbColumns.NAME)))) { + if (Constants.IS_LOGGABLE) { Log.v(Constants.LOG_TAG, String.format("Suppressed duplicate screen %s", screen)); //$NON-NLS-1$ } return; } } - } - finally - { - if (null != cursor) - { + } finally { + if (null != cursor) { cursor.close(); cursor = null; } @@ -1556,8 +1381,7 @@ public final class LocalyticsSession /** * Conditionally adds a flow event if no flow event exists in the current upload blob. */ - private void conditionallyAddFlowEvent() - { + private void conditionallyAddFlowEvent() { /* * Creating a flow "event" is required to act as a placeholder so that the uploader will know that an upload needs to * occur. A flow event should only be created if there isn't already a flow event that hasn't been associated with an @@ -1567,24 +1391,20 @@ public final class LocalyticsSession Cursor eventsCursor = null; Cursor blob_eventsCursor = null; - try - { + try { eventsCursor = mProvider.query(EventsDbColumns.TABLE_NAME, new String[] - { EventsDbColumns._ID }, String.format("%s = ?", EventsDbColumns.EVENT_NAME), new String[] //$NON-NLS-1$ - { FLOW_EVENT }, EVENTS_SORT_ORDER); + {EventsDbColumns._ID}, String.format("%s = ?", EventsDbColumns.EVENT_NAME), new String[] //$NON-NLS-1$ + {FLOW_EVENT}, EVENTS_SORT_ORDER); blob_eventsCursor = mProvider.query(UploadBlobEventsDbColumns.TABLE_NAME, new String[] - { UploadBlobEventsDbColumns.EVENTS_KEY_REF }, null, null, UPLOAD_BLOBS_EVENTS_SORT_ORDER); + {UploadBlobEventsDbColumns.EVENTS_KEY_REF}, null, null, UPLOAD_BLOBS_EVENTS_SORT_ORDER); final CursorJoiner joiner = new CursorJoiner(eventsCursor, new String[] - { EventsDbColumns._ID }, blob_eventsCursor, new String[] - { UploadBlobEventsDbColumns.EVENTS_KEY_REF }); - for (final CursorJoiner.Result joinerResult : joiner) - { - switch (joinerResult) - { - case LEFT: - { + {EventsDbColumns._ID}, blob_eventsCursor, new String[] + {UploadBlobEventsDbColumns.EVENTS_KEY_REF}); + for (final CursorJoiner.Result joinerResult : joiner) { + switch (joinerResult) { + case LEFT: { foundUnassociatedFlowEvent = true; break; } @@ -1594,24 +1414,19 @@ public final class LocalyticsSession break; } } - } - finally - { - if (eventsCursor != null) - { + } finally { + if (eventsCursor != null) { eventsCursor.close(); eventsCursor = null; } - if (blob_eventsCursor != null) - { + if (blob_eventsCursor != null) { blob_eventsCursor.close(); blob_eventsCursor = null; } } - if (!foundUnassociatedFlowEvent) - { + if (!foundUnassociatedFlowEvent) { tagEvent(FLOW_EVENT, null); } } @@ -1620,10 +1435,9 @@ public final class LocalyticsSession * Builds upload blobs for all events. * * @effects Mutates the database by creating a new upload blob for all events that are unassociated at the time this - * method is called. + * method is called. */ - /* package */void preUploadBuildBlobs() - { + /* package */void preUploadBuildBlobs() { /* * Group all events that aren't part of an upload blob into a new blob. While this process is a linear algorithm that * requires scanning two database tables, the performance won't be a problem for two reasons: 1. This process happens @@ -1637,31 +1451,25 @@ public final class LocalyticsSession Cursor eventsCursor = null; Cursor blob_eventsCursor = null; - try - { + try { eventsCursor = mProvider.query(EventsDbColumns.TABLE_NAME, new String[] - { - EventsDbColumns._ID, - EventsDbColumns.EVENT_NAME, - EventsDbColumns.WALL_TIME }, null, null, EVENTS_SORT_ORDER); + { + EventsDbColumns._ID, + EventsDbColumns.EVENT_NAME, + EventsDbColumns.WALL_TIME}, null, null, EVENTS_SORT_ORDER); blob_eventsCursor = mProvider.query(UploadBlobEventsDbColumns.TABLE_NAME, new String[] - { UploadBlobEventsDbColumns.EVENTS_KEY_REF }, null, null, UPLOAD_BLOBS_EVENTS_SORT_ORDER); + {UploadBlobEventsDbColumns.EVENTS_KEY_REF}, null, null, UPLOAD_BLOBS_EVENTS_SORT_ORDER); final int idColumn = eventsCursor.getColumnIndexOrThrow(EventsDbColumns._ID); final CursorJoiner joiner = new CursorJoiner(eventsCursor, new String[] - { EventsDbColumns._ID }, blob_eventsCursor, new String[] - { UploadBlobEventsDbColumns.EVENTS_KEY_REF }); - for (final CursorJoiner.Result joinerResult : joiner) - { - switch (joinerResult) - { - case LEFT: - { - if (CLOSE_EVENT.equals(eventsCursor.getString(eventsCursor.getColumnIndexOrThrow(EventsDbColumns.EVENT_NAME)))) - { - if (System.currentTimeMillis() - eventsCursor.getLong(eventsCursor.getColumnIndexOrThrow(EventsDbColumns.WALL_TIME)) < Constants.SESSION_EXPIRATION) - { + {EventsDbColumns._ID}, blob_eventsCursor, new String[] + {UploadBlobEventsDbColumns.EVENTS_KEY_REF}); + for (final CursorJoiner.Result joinerResult : joiner) { + switch (joinerResult) { + case LEFT: { + if (CLOSE_EVENT.equals(eventsCursor.getString(eventsCursor.getColumnIndexOrThrow(EventsDbColumns.EVENT_NAME)))) { + if (System.currentTimeMillis() - eventsCursor.getLong(eventsCursor.getColumnIndexOrThrow(EventsDbColumns.WALL_TIME)) < Constants.SESSION_EXPIRATION) { break; } } @@ -1674,22 +1482,17 @@ public final class LocalyticsSession break; } } - } - finally - { - if (eventsCursor != null) - { + } finally { + if (eventsCursor != null) { eventsCursor.close(); } - if (blob_eventsCursor != null) - { + if (blob_eventsCursor != null) { blob_eventsCursor.close(); } } - if (eventIds.size() > 0) - { + if (eventIds.size() > 0) { final long blobId; { final ContentValues values = new ContentValues(); @@ -1699,8 +1502,7 @@ public final class LocalyticsSession { final ContentValues values = new ContentValues(); - for (final Long x : eventIds) - { + for (final Long x : eventIds) { values.clear(); values.put(UploadBlobEventsDbColumns.UPLOAD_BLOBS_KEY_REF, Long.valueOf(blobId)); @@ -1718,22 +1520,19 @@ public final class LocalyticsSession /** * Initiate upload of all session data currently stored on disk. - *

    + *

    * This method must only be called after {@link #init()} is called. The session does not need to be open for an upload to * occur. - *

    + *

    * Note: This method is a private implementation detail. It is only made package accessible for unit testing purposes. The * public interface is to send {@link #MESSAGE_UPLOAD} to the Handler. * * @param callback An optional callback to perform once the upload completes. May be null for no callback. * @see #MESSAGE_UPLOAD */ - /* package */void upload(final Runnable callback) - { - if (sIsUploadingMap.get(mApiKey).booleanValue()) - { - if (Constants.IS_LOGGABLE) - { + /* package */void upload(final Runnable callback) { + if (sIsUploadingMap.get(mApiKey).booleanValue()) { + if (Constants.IS_LOGGABLE) { Log.d(Constants.LOG_TAG, "Already uploading"); //$NON-NLS-1$ } @@ -1741,31 +1540,24 @@ public final class LocalyticsSession return; } - try - { - mProvider.runBatchTransaction(new Runnable() - { - public void run() - { + try { + mProvider.runBatchTransaction(new Runnable() { + public void run() { preUploadBuildBlobs(); } }); sIsUploadingMap.put(mApiKey, Boolean.TRUE); mUploadHandler.sendMessage(mUploadHandler.obtainMessage(UploadHandler.MESSAGE_UPLOAD, callback)); - } - catch (final Exception e) - { - if (Constants.IS_LOGGABLE) - { + } catch (final Exception e) { + if (Constants.IS_LOGGABLE) { Log.w(Constants.LOG_TAG, "Error occurred during upload", e); //$NON-NLS-1$ } sIsUploadingMap.put(mApiKey, Boolean.FALSE); // Notify the caller the upload is "complete" - if (callback != null) - { + if (callback != null) { /* * Note that a new thread is created for the callback. This ensures that client code can't affect the * performance of the SessionHandler's thread. @@ -1779,8 +1571,7 @@ public final class LocalyticsSession /** * Helper object to the {@link SessionHandler} which helps process upload requests. */ - /* package */static final class UploadHandler extends Handler - { + /* package */static final class UploadHandler extends Handler { /** * Thread name that the upload callback runnable is executed on. @@ -1794,7 +1585,7 @@ public final class LocalyticsSession /** * Handler message to upload all data collected so far - *

    + *

    * {@link Message#obj} is a {@code Runnable} to execute when upload is complete. The thread that this runnable will * executed on is undefined. */ @@ -1803,7 +1594,7 @@ public final class LocalyticsSession /** * Handler message indicating that there is a queued upload request. When this message is processed, this handler simply * forwards the request back to {@link LocalyticsSession#mSessionHandler} with {@link SessionHandler#MESSAGE_UPLOAD}. - *

    + *

    * {@link Message#obj} is a {@code Runnable} to execute when upload is complete. The thread that this runnable will * executed on is undefined. */ @@ -1831,16 +1622,15 @@ public final class LocalyticsSession /** * Constructs a new Handler that runs on {@code looper}. - *

    + *

    * Note: This constructor may perform disk access. * - * @param context Application context. Cannot be null. + * @param context Application context. Cannot be null. * @param sessionHandler Parent {@link SessionHandler} object to notify when uploads are completed. Cannot be null. - * @param apiKey Localytics API key. Cannot be null. - * @param looper to run the Handler on. Cannot be null. + * @param apiKey Localytics API key. Cannot be null. + * @param looper to run the Handler on. Cannot be null. */ - public UploadHandler(final Context context, final Handler sessionHandler, final String apiKey, final Looper looper) - { + public UploadHandler(final Context context, final Handler sessionHandler, final String apiKey, final Looper looper) { super(looper); mContext = context; @@ -1850,16 +1640,12 @@ public final class LocalyticsSession } @Override - public void handleMessage(final Message msg) - { + public void handleMessage(final Message msg) { super.handleMessage(msg); - switch (msg.what) - { - case MESSAGE_UPLOAD: - { - if (Constants.IS_LOGGABLE) - { + switch (msg.what) { + case MESSAGE_UPLOAD: { + if (Constants.IS_LOGGABLE) { Log.d(Constants.LOG_TAG, "UploadHandler Received MESSAGE_UPLOAD"); //$NON-NLS-1$ } @@ -1868,35 +1654,26 @@ public final class LocalyticsSession */ final Runnable callback = (Runnable) msg.obj; - try - { + try { final List toUpload = convertDatabaseToJson(); - if (!toUpload.isEmpty()) - { + if (!toUpload.isEmpty()) { final StringBuilder builder = new StringBuilder(); - for (final JSONObject json : toUpload) - { + for (final JSONObject json : toUpload) { builder.append(json.toString()); builder.append('\n'); } - if (uploadSessions(String.format(ANALYTICS_URL, mApiKey), builder.toString())) - { - mProvider.runBatchTransaction(new Runnable() - { - public void run() - { + if (uploadSessions(String.format(ANALYTICS_URL, mApiKey), builder.toString())) { + mProvider.runBatchTransaction(new Runnable() { + public void run() { deleteBlobsAndSessions(mProvider); } }); } } - } - finally - { - if (callback != null) - { + } finally { + if (callback != null) { /* * Execute the callback on a separate thread, to avoid exposing this thread to the client of the * library @@ -1908,18 +1685,15 @@ public final class LocalyticsSession } break; } - case MESSAGE_RETRY_UPLOAD_REQUEST: - { - if (Constants.IS_LOGGABLE) - { + case MESSAGE_RETRY_UPLOAD_REQUEST: { + if (Constants.IS_LOGGABLE) { Log.d(Constants.LOG_TAG, "Received MESSAGE_RETRY_UPLOAD_REQUEST"); //$NON-NLS-1$ } mSessionHandler.sendMessage(mSessionHandler.obtainMessage(SessionHandler.MESSAGE_UPLOAD, msg.obj)); break; } - default: - { + default: { /* * This should never happen */ @@ -1931,27 +1705,23 @@ public final class LocalyticsSession /** * Uploads the post Body to the webservice * - * @param url where {@code body} will be posted to. Cannot be null. + * @param url where {@code body} will be posted to. Cannot be null. * @param body upload body as a string. This should be a plain old string. Cannot be null. * @return True on success, false on failure. */ - /* package */static boolean uploadSessions(final String url, final String body) - { - if (Constants.ENABLE_PARAMETER_CHECKING) - { - if (null == url) - { + /* package */ + static boolean uploadSessions(final String url, final String body) { + if (Constants.ENABLE_PARAMETER_CHECKING) { + if (null == url) { throw new IllegalArgumentException("url cannot be null"); //$NON-NLS-1$ } - if (null == body) - { + if (null == body) { throw new IllegalArgumentException("body cannot be null"); //$NON-NLS-1$ } } - if (Constants.IS_LOGGABLE) - { + if (Constants.IS_LOGGABLE) { Log.v(Constants.LOG_TAG, String.format("Upload body before compression is: %s", body.toString())); //$NON-NLS-1$ } @@ -1960,8 +1730,7 @@ public final class LocalyticsSession method.addHeader("Content-Type", "application/x-gzip"); //$NON-NLS-1$ //$NON-NLS-2$ GZIPOutputStream gos = null; - try - { + try { final byte[] originalBytes = body.getBytes("UTF-8"); //$NON-NLS-1$ final ByteArrayOutputStream baos = new ByteArrayOutputStream(originalBytes.length); gos = new GZIPOutputStream(baos); @@ -1976,57 +1745,39 @@ public final class LocalyticsSession final StatusLine status = response.getStatusLine(); final int statusCode = status.getStatusCode(); - if (Constants.IS_LOGGABLE) - { + if (Constants.IS_LOGGABLE) { Log.v(Constants.LOG_TAG, String.format("Upload complete with status %d", Integer.valueOf(statusCode))); //$NON-NLS-1$ } /* * 5xx status codes indicate a server error, so upload should be reattempted */ - if (statusCode >= 500 && statusCode <= 599) - { + if (statusCode >= 500 && statusCode <= 599) { return false; } return true; - } - catch (final UnsupportedEncodingException e) - { - if (Constants.IS_LOGGABLE) - { + } catch (final UnsupportedEncodingException e) { + if (Constants.IS_LOGGABLE) { Log.w(Constants.LOG_TAG, "UnsupportedEncodingException", e); //$NON-NLS-1$ } return false; - } - catch (final ClientProtocolException e) - { - if (Constants.IS_LOGGABLE) - { + } catch (final ClientProtocolException e) { + if (Constants.IS_LOGGABLE) { Log.w(Constants.LOG_TAG, "ClientProtocolException", e); //$NON-NLS-1$ } return false; - } - catch (final IOException e) - { - if (Constants.IS_LOGGABLE) - { + } catch (final IOException e) { + if (Constants.IS_LOGGABLE) { Log.w(Constants.LOG_TAG, "IOException", e); //$NON-NLS-1$ } return false; - } - finally - { - if (null != gos) - { - try - { + } finally { + if (null != gos) { + try { gos.close(); - } - catch (final IOException e) - { - if (Constants.IS_LOGGABLE) - { + } catch (final IOException e) { + if (Constants.IS_LOGGABLE) { Log.w(Constants.LOG_TAG, "Caught exception", e); //$NON-NLS-1$ } } @@ -2039,22 +1790,18 @@ public final class LocalyticsSession * * @return A list of JSON objecs to upload to the server */ - /* package */List convertDatabaseToJson() - { + /* package */List convertDatabaseToJson() { final List result = new LinkedList(); Cursor cursor = null; - try - { + try { cursor = mProvider.query(UploadBlobsDbColumns.TABLE_NAME, null, null, null, null); final long creationTime = getApiKeyCreationTime(mProvider, mApiKey); final int idColumn = cursor.getColumnIndexOrThrow(UploadBlobsDbColumns._ID); final int uuidColumn = cursor.getColumnIndexOrThrow(UploadBlobsDbColumns.UUID); - while (cursor.moveToNext()) - { - try - { + while (cursor.moveToNext()) { + try { final JSONObject blobHeader = new JSONObject(); blobHeader.put(JsonObjects.BlobHeader.KEY_DATA_TYPE, BlobHeader.VALUE_DATA_TYPE); @@ -2065,45 +1812,33 @@ public final class LocalyticsSession result.add(blobHeader); Cursor blobEvents = null; - try - { + try { blobEvents = mProvider.query(UploadBlobEventsDbColumns.TABLE_NAME, new String[] - { UploadBlobEventsDbColumns.EVENTS_KEY_REF }, String.format("%s = ?", UploadBlobEventsDbColumns.UPLOAD_BLOBS_KEY_REF), new String[] //$NON-NLS-1$ - { Long.toString(cursor.getLong(idColumn)) }, UploadBlobEventsDbColumns.EVENTS_KEY_REF); + {UploadBlobEventsDbColumns.EVENTS_KEY_REF}, String.format("%s = ?", UploadBlobEventsDbColumns.UPLOAD_BLOBS_KEY_REF), new String[] //$NON-NLS-1$ + {Long.toString(cursor.getLong(idColumn))}, UploadBlobEventsDbColumns.EVENTS_KEY_REF); final int eventIdColumn = blobEvents.getColumnIndexOrThrow(UploadBlobEventsDbColumns.EVENTS_KEY_REF); - while (blobEvents.moveToNext()) - { + while (blobEvents.moveToNext()) { result.add(convertEventToJson(mProvider, mContext, blobEvents.getLong(eventIdColumn), cursor.getLong(idColumn), mApiKey)); } - } - finally - { - if (null != blobEvents) - { + } finally { + if (null != blobEvents) { blobEvents.close(); } } - } - catch (final JSONException e) - { - if (Constants.IS_LOGGABLE) - { + } catch (final JSONException e) { + if (Constants.IS_LOGGABLE) { Log.w(Constants.LOG_TAG, "Caught exception", e); //$NON-NLS-1$ } } } - } - finally - { - if (cursor != null) - { + } finally { + if (cursor != null) { cursor.close(); } } - if (Constants.IS_LOGGABLE) - { + if (Constants.IS_LOGGABLE) { Log.v(Constants.LOG_TAG, String.format("JSON result is %s", result.toString())); //$NON-NLS-1$ } @@ -2112,13 +1847,13 @@ public final class LocalyticsSession /** * Deletes all blobs and sessions/events/attributes associated with those blobs. - *

    + *

    * This should be called after a successful upload completes. * * @param provider Localytics database provider. Cannot be null. */ - /* package */static void deleteBlobsAndSessions(final LocalyticsProvider provider) - { + /* package */ + static void deleteBlobsAndSessions(final LocalyticsProvider provider) { /* * Deletion needs to occur in a specific order due to database constraints. Specifically, blobevents need to be * deleted first. Then blobs themselves can be deleted. Then attributes need to be deleted first. Then events. Then @@ -2129,25 +1864,23 @@ public final class LocalyticsSession final HashSet blobsToDelete = new HashSet(); Cursor blobEvents = null; - try - { + try { blobEvents = provider.query(UploadBlobEventsDbColumns.TABLE_NAME, new String[] - { - UploadBlobEventsDbColumns._ID, - UploadBlobEventsDbColumns.EVENTS_KEY_REF, - UploadBlobEventsDbColumns.UPLOAD_BLOBS_KEY_REF }, null, null, null); + { + UploadBlobEventsDbColumns._ID, + UploadBlobEventsDbColumns.EVENTS_KEY_REF, + UploadBlobEventsDbColumns.UPLOAD_BLOBS_KEY_REF}, null, null, null); final int uploadBlobIdColumn = blobEvents.getColumnIndexOrThrow(UploadBlobEventsDbColumns.UPLOAD_BLOBS_KEY_REF); final int blobEventIdColumn = blobEvents.getColumnIndexOrThrow(UploadBlobEventsDbColumns._ID); final int eventIdColumn = blobEvents.getColumnIndexOrThrow(UploadBlobEventsDbColumns.EVENTS_KEY_REF); - while (blobEvents.moveToNext()) - { + while (blobEvents.moveToNext()) { final long blobId = blobEvents.getLong(uploadBlobIdColumn); final long blobEventId = blobEvents.getLong(blobEventIdColumn); final long eventId = blobEvents.getLong(eventIdColumn); // delete the blobevent - provider.delete(UploadBlobEventsDbColumns.TABLE_NAME, String.format("%s = ?", UploadBlobEventsDbColumns._ID), new String[] { Long.toString(blobEventId) }); //$NON-NLS-1$ + provider.delete(UploadBlobEventsDbColumns.TABLE_NAME, String.format("%s = ?", UploadBlobEventsDbColumns._ID), new String[]{Long.toString(blobEventId)}); //$NON-NLS-1$ /* * Add the blob to the list of blobs to be deleted @@ -2155,60 +1888,50 @@ public final class LocalyticsSession blobsToDelete.add(Long.valueOf(blobId)); // delete all attributes for the event - provider.delete(AttributesDbColumns.TABLE_NAME, String.format("%s = ?", AttributesDbColumns.EVENTS_KEY_REF), new String[] { Long.toString(eventId) }); //$NON-NLS-1$ + provider.delete(AttributesDbColumns.TABLE_NAME, String.format("%s = ?", AttributesDbColumns.EVENTS_KEY_REF), new String[]{Long.toString(eventId)}); //$NON-NLS-1$ /* * Check to see if the event is a close event, indicating that the session is complete and can also be deleted */ Cursor eventCursor = null; - try - { + try { eventCursor = provider.query(EventsDbColumns.TABLE_NAME, new String[] - { EventsDbColumns.SESSION_KEY_REF }, String.format("%s = ? AND %s = ?", EventsDbColumns._ID, EventsDbColumns.EVENT_NAME), new String[] //$NON-NLS-1$ - { - Long.toString(eventId), - CLOSE_EVENT }, null); + {EventsDbColumns.SESSION_KEY_REF}, String.format("%s = ? AND %s = ?", EventsDbColumns._ID, EventsDbColumns.EVENT_NAME), new String[] //$NON-NLS-1$ + { + Long.toString(eventId), + CLOSE_EVENT}, null); - if (eventCursor.moveToFirst()) - { + if (eventCursor.moveToFirst()) { final long sessionId = eventCursor.getLong(eventCursor.getColumnIndexOrThrow(EventsDbColumns.SESSION_KEY_REF)); provider.delete(EventHistoryDbColumns.TABLE_NAME, String.format("%s = ?", EventHistoryDbColumns.SESSION_KEY_REF), new String[] //$NON-NLS-1$ - { Long.toString(sessionId) }); + {Long.toString(sessionId)}); sessionsToDelete.add(Long.valueOf(eventCursor.getLong(eventCursor.getColumnIndexOrThrow(EventsDbColumns.SESSION_KEY_REF)))); } - } - finally - { - if (null != eventCursor) - { + } finally { + if (null != eventCursor) { eventCursor.close(); } } // delete the event - provider.delete(EventsDbColumns.TABLE_NAME, String.format("%s = ?", EventsDbColumns._ID), new String[] { Long.toString(eventId) }); //$NON-NLS-1$ + provider.delete(EventsDbColumns.TABLE_NAME, String.format("%s = ?", EventsDbColumns._ID), new String[]{Long.toString(eventId)}); //$NON-NLS-1$ } - } - finally - { - if (null != blobEvents) - { + } finally { + if (null != blobEvents) { blobEvents.close(); } } // delete blobs - for (final long x : blobsToDelete) - { - provider.delete(UploadBlobsDbColumns.TABLE_NAME, String.format("%s = ?", UploadBlobsDbColumns._ID), new String[] { Long.toString(x) }); //$NON-NLS-1$ + for (final long x : blobsToDelete) { + provider.delete(UploadBlobsDbColumns.TABLE_NAME, String.format("%s = ?", UploadBlobsDbColumns._ID), new String[]{Long.toString(x)}); //$NON-NLS-1$ } // delete sessions - for (final long x : sessionsToDelete) - { - provider.delete(SessionsDbColumns.TABLE_NAME, String.format("%s = ?", SessionsDbColumns._ID), new String[] { Long.toString(x) }); //$NON-NLS-1$ + for (final long x : sessionsToDelete) { + provider.delete(SessionsDbColumns.TABLE_NAME, String.format("%s = ?", SessionsDbColumns._ID), new String[]{Long.toString(x)}); //$NON-NLS-1$ } } @@ -2217,19 +1940,17 @@ public final class LocalyticsSession * Gets the creation time for an API key. * * @param provider Localytics database provider. Cannot be null. - * @param key Localytics API key. Cannot be null. + * @param key Localytics API key. Cannot be null. * @return The time in seconds since the Unix Epoch when the API key entry was created in the database. * @throws RuntimeException if the API key entry doesn't exist in the database. */ - /* package */static long getApiKeyCreationTime(final LocalyticsProvider provider, final String key) - { + /* package */ + static long getApiKeyCreationTime(final LocalyticsProvider provider, final String key) { Cursor cursor = null; - try - { - cursor = provider.query(ApiKeysDbColumns.TABLE_NAME, null, String.format("%s = ?", ApiKeysDbColumns.API_KEY), new String[] { key }, null); //$NON-NLS-1$ + try { + cursor = provider.query(ApiKeysDbColumns.TABLE_NAME, null, String.format("%s = ?", ApiKeysDbColumns.API_KEY), new String[]{key}, null); //$NON-NLS-1$ - if (cursor.moveToFirst()) - { + if (cursor.moveToFirst()) { return Math.round((float) cursor.getLong(cursor.getColumnIndexOrThrow(ApiKeysDbColumns.CREATED_TIME)) / DateUtils.SECOND_IN_MILLIS); } @@ -2237,11 +1958,8 @@ public final class LocalyticsSession * This should never happen */ throw new RuntimeException("API key entry couldn't be found"); //$NON-NLS-1$ - } - finally - { - if (null != cursor) - { + } finally { + if (null != cursor) { cursor.close(); } } @@ -2250,21 +1968,19 @@ public final class LocalyticsSession /** * Helper method to generate the attributes object for a session * - * @param provider Instance of the Localytics database provider. Cannot be null. - * @param apiKey Localytics API key. Cannot be null. + * @param provider Instance of the Localytics database provider. Cannot be null. + * @param apiKey Localytics API key. Cannot be null. * @param sessionId The {@link SessionsDbColumns#_ID} of the session. * @return a JSONObject representation of the session attributes * @throws JSONException if a problem occurred converting the element to JSON. */ - /* package */static JSONObject getAttributesFromSession(final LocalyticsProvider provider, final String apiKey, final long sessionId) throws JSONException - { + /* package */ + static JSONObject getAttributesFromSession(final LocalyticsProvider provider, final String apiKey, final long sessionId) throws JSONException { Cursor cursor = null; - try - { - cursor = provider.query(SessionsDbColumns.TABLE_NAME, null, String.format("%s = ?", SessionsDbColumns._ID), new String[] { Long.toString(sessionId) }, null); //$NON-NLS-1$ + try { + cursor = provider.query(SessionsDbColumns.TABLE_NAME, null, String.format("%s = ?", SessionsDbColumns._ID), new String[]{Long.toString(sessionId)}, null); //$NON-NLS-1$ - if (cursor.moveToFirst()) - { + if (cursor.moveToFirst()) { final JSONObject result = new JSONObject(); result.put(JsonObjects.BlobHeader.Attributes.KEY_CLIENT_APP_VERSION, cursor.getString(cursor.getColumnIndexOrThrow(SessionsDbColumns.APP_VERSION))); result.put(JsonObjects.BlobHeader.Attributes.KEY_DATA_CONNECTION, cursor.getString(cursor.getColumnIndexOrThrow(SessionsDbColumns.NETWORK_TYPE))); @@ -2291,11 +2007,8 @@ public final class LocalyticsSession } throw new RuntimeException("No session exists"); //$NON-NLS-1$ - } - finally - { - if (null != cursor) - { + } finally { + if (null != cursor) { cursor.close(); } } @@ -2303,40 +2016,37 @@ public final class LocalyticsSession /** * Converts an event into a JSON object. - *

    + *

    * There are three types of events: open, close, and application. Open and close events are Localytics events, while * application events are generated by the app. The return value of this method will vary based on the type of event that * is being converted. * * @param provider Localytics database instance. Cannot be null. - * @param context Application context. Cannot be null. - * @param eventId {@link EventsDbColumns#_ID} of the event to convert. - * @param blobId {@link UploadBlobEventsDbColumns#_ID} of the upload blob that contains this event. - * @param apiKey the Localytics API key. Cannot be null. + * @param context Application context. Cannot be null. + * @param eventId {@link EventsDbColumns#_ID} of the event to convert. + * @param blobId {@link UploadBlobEventsDbColumns#_ID} of the upload blob that contains this event. + * @param apiKey the Localytics API key. Cannot be null. * @return JSON representation of the event. * @throws JSONException if a problem occurred converting the element to JSON. */ - /* package */static JSONObject convertEventToJson(final LocalyticsProvider provider, final Context context, final long eventId, final long blobId, final String apiKey) - throws JSONException - { + /* package */ + static JSONObject convertEventToJson(final LocalyticsProvider provider, final Context context, final long eventId, final long blobId, final String apiKey) + throws JSONException { final JSONObject result = new JSONObject(); Cursor cursor = null; - try - { + try { cursor = provider.query(EventsDbColumns.TABLE_NAME, null, String.format("%s = ?", EventsDbColumns._ID), new String[] //$NON-NLS-1$ - { Long.toString(eventId) }, EventsDbColumns._ID); + {Long.toString(eventId)}, EventsDbColumns._ID); - if (cursor.moveToFirst()) - { + if (cursor.moveToFirst()) { final String eventName = cursor.getString(cursor.getColumnIndexOrThrow(EventsDbColumns.EVENT_NAME)); final long sessionId = getSessionIdForEventId(provider, eventId); final String sessionUuid = getSessionUuid(provider, sessionId); final long sessionStartTime = getSessionStartTime(provider, sessionId); - if (OPEN_EVENT.equals(eventName)) - { + if (OPEN_EVENT.equals(eventName)) { result.put(JsonObjects.SessionOpen.KEY_DATA_TYPE, JsonObjects.SessionOpen.VALUE_DATA_TYPE); result.put(JsonObjects.SessionOpen.KEY_WALL_TIME_SECONDS, Math.round((double) cursor.getLong(cursor.getColumnIndex(EventsDbColumns.WALL_TIME)) / DateUtils.SECOND_IN_MILLIS)); @@ -2346,9 +2056,7 @@ public final class LocalyticsSession * Both the database and the web service use 1-based indexing. */ result.put(JsonObjects.SessionOpen.KEY_COUNT, sessionId); - } - else if (CLOSE_EVENT.equals(eventName)) - { + } else if (CLOSE_EVENT.equals(eventName)) { result.put(JsonObjects.SessionClose.KEY_DATA_TYPE, JsonObjects.SessionClose.VALUE_DATA_TYPE); result.put(JsonObjects.SessionClose.KEY_EVENT_UUID, cursor.getString(cursor.getColumnIndexOrThrow(EventsDbColumns.UUID))); result.put(JsonObjects.SessionClose.KEY_SESSION_UUID, sessionUuid); @@ -2360,28 +2068,21 @@ public final class LocalyticsSession * length is a special case, as it depends on the start time embedded in the session table */ Cursor sessionCursor = null; - try - { + try { sessionCursor = provider.query(SessionsDbColumns.TABLE_NAME, new String[] - { SessionsDbColumns.SESSION_START_WALL_TIME }, String.format("%s = ?", SessionsDbColumns._ID), new String[] { Long.toString(cursor.getLong(cursor.getColumnIndexOrThrow(EventsDbColumns.SESSION_KEY_REF))) }, null); //$NON-NLS-1$ + {SessionsDbColumns.SESSION_START_WALL_TIME}, String.format("%s = ?", SessionsDbColumns._ID), new String[]{Long.toString(cursor.getLong(cursor.getColumnIndexOrThrow(EventsDbColumns.SESSION_KEY_REF)))}, null); //$NON-NLS-1$ - if (sessionCursor.moveToFirst()) - { + if (sessionCursor.moveToFirst()) { result.put(JsonObjects.SessionClose.KEY_SESSION_LENGTH_SECONDS, Math.round((double) cursor.getLong(cursor.getColumnIndex(EventsDbColumns.WALL_TIME)) / DateUtils.SECOND_IN_MILLIS) - Math.round((double) sessionCursor.getLong(sessionCursor.getColumnIndexOrThrow(SessionsDbColumns.SESSION_START_WALL_TIME)) - / DateUtils.SECOND_IN_MILLIS)); - } - else - { + / DateUtils.SECOND_IN_MILLIS)); + } else { // this should never happen throw new RuntimeException("Session didn't exist"); //$NON-NLS-1$ } - } - finally - { - if (null != sessionCursor) - { + } finally { + if (null != sessionCursor) { sessionCursor.close(); sessionCursor = null; } @@ -2391,41 +2092,31 @@ public final class LocalyticsSession * The close also contains a special case element for the screens history */ Cursor eventHistoryCursor = null; - try - { + try { eventHistoryCursor = provider.query(EventHistoryDbColumns.TABLE_NAME, new String[] - { EventHistoryDbColumns.NAME }, String.format("%s = ? AND %s = ?", EventHistoryDbColumns.SESSION_KEY_REF, EventHistoryDbColumns.TYPE), new String[] { Long.toString(sessionId), Integer.toString(EventHistoryDbColumns.TYPE_SCREEN) }, EventHistoryDbColumns._ID); //$NON-NLS-1$ + {EventHistoryDbColumns.NAME}, String.format("%s = ? AND %s = ?", EventHistoryDbColumns.SESSION_KEY_REF, EventHistoryDbColumns.TYPE), new String[]{Long.toString(sessionId), Integer.toString(EventHistoryDbColumns.TYPE_SCREEN)}, EventHistoryDbColumns._ID); //$NON-NLS-1$ final JSONArray screens = new JSONArray(); - while (eventHistoryCursor.moveToNext()) - { + while (eventHistoryCursor.moveToNext()) { screens.put(eventHistoryCursor.getString(eventHistoryCursor.getColumnIndexOrThrow(EventHistoryDbColumns.NAME))); } - if (screens.length() > 0) - { + if (screens.length() > 0) { result.put(JsonObjects.SessionClose.KEY_FLOW_ARRAY, screens); } - } - finally - { - if (null != eventHistoryCursor) - { + } finally { + if (null != eventHistoryCursor) { eventHistoryCursor.close(); eventHistoryCursor = null; } } - } - else if (OPT_IN_EVENT.equals(eventName) || OPT_OUT_EVENT.equals(eventName)) - { + } else if (OPT_IN_EVENT.equals(eventName) || OPT_OUT_EVENT.equals(eventName)) { result.put(JsonObjects.OptEvent.KEY_DATA_TYPE, JsonObjects.OptEvent.VALUE_DATA_TYPE); result.put(JsonObjects.OptEvent.KEY_API_KEY, apiKey); result.put(JsonObjects.OptEvent.KEY_OPT, OPT_OUT_EVENT.equals(eventName) ? Boolean.TRUE.toString() : Boolean.FALSE.toString()); result.put(JsonObjects.OptEvent.KEY_WALL_TIME_SECONDS, Math.round((double) cursor.getLong(cursor.getColumnIndex(EventsDbColumns.WALL_TIME)) / DateUtils.SECOND_IN_MILLIS)); - } - else if (FLOW_EVENT.equals(eventName)) - { + } else if (FLOW_EVENT.equals(eventName)) { result.put(JsonObjects.EventFlow.KEY_DATA_TYPE, JsonObjects.EventFlow.VALUE_DATA_TYPE); result.put(JsonObjects.EventFlow.KEY_EVENT_UUID, cursor.getString(cursor.getColumnIndexOrThrow(EventsDbColumns.UUID))); result.put(JsonObjects.EventFlow.KEY_SESSION_START_TIME, Math.round((double) sessionStartTime / DateUtils.SECOND_IN_MILLIS)); @@ -2438,53 +2129,40 @@ public final class LocalyticsSession * Default sort order is ascending by _ID, so these will be sorted chronologically. */ Cursor eventHistoryCursor = null; - try - { + try { eventHistoryCursor = provider.query(EventHistoryDbColumns.TABLE_NAME, new String[] - { - EventHistoryDbColumns.TYPE, - EventHistoryDbColumns.PROCESSED_IN_BLOB, - EventHistoryDbColumns.NAME }, String.format("%s = ? AND %s <= ?", EventHistoryDbColumns.SESSION_KEY_REF, EventHistoryDbColumns.PROCESSED_IN_BLOB), new String[] { Long.toString(sessionId), Long.toString(blobId) }, EventHistoryDbColumns._ID); //$NON-NLS-1$ + { + EventHistoryDbColumns.TYPE, + EventHistoryDbColumns.PROCESSED_IN_BLOB, + EventHistoryDbColumns.NAME}, String.format("%s = ? AND %s <= ?", EventHistoryDbColumns.SESSION_KEY_REF, EventHistoryDbColumns.PROCESSED_IN_BLOB), new String[]{Long.toString(sessionId), Long.toString(blobId)}, EventHistoryDbColumns._ID); //$NON-NLS-1$ final JSONArray newScreens = new JSONArray(); final JSONArray oldScreens = new JSONArray(); - while (eventHistoryCursor.moveToNext()) - { + while (eventHistoryCursor.moveToNext()) { final String name = eventHistoryCursor.getString(eventHistoryCursor.getColumnIndexOrThrow(EventHistoryDbColumns.NAME)); final String type; - if (EventHistoryDbColumns.TYPE_EVENT == eventHistoryCursor.getInt(eventHistoryCursor.getColumnIndexOrThrow(EventHistoryDbColumns.TYPE))) - { + if (EventHistoryDbColumns.TYPE_EVENT == eventHistoryCursor.getInt(eventHistoryCursor.getColumnIndexOrThrow(EventHistoryDbColumns.TYPE))) { type = JsonObjects.EventFlow.Element.TYPE_EVENT; - } - else - { + } else { type = JsonObjects.EventFlow.Element.TYPE_SCREEN; } - if (blobId == eventHistoryCursor.getLong(eventHistoryCursor.getColumnIndexOrThrow(EventHistoryDbColumns.PROCESSED_IN_BLOB))) - { + if (blobId == eventHistoryCursor.getLong(eventHistoryCursor.getColumnIndexOrThrow(EventHistoryDbColumns.PROCESSED_IN_BLOB))) { newScreens.put(new JSONObject().put(type, name)); - } - else - { + } else { oldScreens.put(new JSONObject().put(type, name)); } } result.put(JsonObjects.EventFlow.KEY_FLOW_NEW, newScreens); result.put(JsonObjects.EventFlow.KEY_FLOW_OLD, oldScreens); - } - finally - { - if (null != eventHistoryCursor) - { + } finally { + if (null != eventHistoryCursor) { eventHistoryCursor.close(); eventHistoryCursor = null; } } - } - else - { + } else { /* * This is a normal application event */ @@ -2498,24 +2176,18 @@ public final class LocalyticsSession final JSONObject attributes = convertAttributesToJson(provider, eventId); - if (null != attributes) - { + if (null != attributes) { result.put(JsonObjects.SessionEvent.KEY_ATTRIBUTES, attributes); } } - } - else - { + } else { /* * This should never happen */ throw new RuntimeException(); } - } - finally - { - if (null != cursor) - { + } finally { + if (null != cursor) { cursor.close(); } } @@ -2527,19 +2199,17 @@ public final class LocalyticsSession * Private helper to get the {@link SessionsDbColumns#_ID} for a given {@link EventsDbColumns#_ID}. * * @param provider Localytics database instance. Cannot be null. - * @param eventId {@link EventsDbColumns#_ID} of the event to look up + * @param eventId {@link EventsDbColumns#_ID} of the event to look up * @return The {@link SessionsDbColumns#_ID} of the session that owns the event. */ - /* package */static long getSessionIdForEventId(final LocalyticsProvider provider, final long eventId) - { + /* package */ + static long getSessionIdForEventId(final LocalyticsProvider provider, final long eventId) { Cursor cursor = null; - try - { + try { cursor = provider.query(EventsDbColumns.TABLE_NAME, new String[] - { EventsDbColumns.SESSION_KEY_REF }, String.format("%s = ?", EventsDbColumns._ID), new String[] { Long.toString(eventId) }, null); //$NON-NLS-1$ + {EventsDbColumns.SESSION_KEY_REF}, String.format("%s = ?", EventsDbColumns._ID), new String[]{Long.toString(eventId)}, null); //$NON-NLS-1$ - if (cursor.moveToFirst()) - { + if (cursor.moveToFirst()) { return cursor.getLong(cursor.getColumnIndexOrThrow(EventsDbColumns.SESSION_KEY_REF)); } @@ -2547,11 +2217,8 @@ public final class LocalyticsSession * This should never happen */ throw new RuntimeException(); - } - finally - { - if (null != cursor) - { + } finally { + if (null != cursor) { cursor.close(); } } @@ -2560,20 +2227,18 @@ public final class LocalyticsSession /** * Private helper to get the {@link SessionsDbColumns#UUID} for a given {@link SessionsDbColumns#_ID}. * - * @param provider Localytics database instance. Cannot be null. + * @param provider Localytics database instance. Cannot be null. * @param sessionId {@link SessionsDbColumns#_ID} of the event to look up * @return The {@link SessionsDbColumns#UUID} of the session. */ - /* package */static String getSessionUuid(final LocalyticsProvider provider, final long sessionId) - { + /* package */ + static String getSessionUuid(final LocalyticsProvider provider, final long sessionId) { Cursor cursor = null; - try - { + try { cursor = provider.query(SessionsDbColumns.TABLE_NAME, new String[] - { SessionsDbColumns.UUID }, String.format("%s = ?", SessionsDbColumns._ID), new String[] { Long.toString(sessionId) }, null); //$NON-NLS-1$ + {SessionsDbColumns.UUID}, String.format("%s = ?", SessionsDbColumns._ID), new String[]{Long.toString(sessionId)}, null); //$NON-NLS-1$ - if (cursor.moveToFirst()) - { + if (cursor.moveToFirst()) { return cursor.getString(cursor.getColumnIndexOrThrow(SessionsDbColumns.UUID)); } @@ -2581,11 +2246,8 @@ public final class LocalyticsSession * This should never happen */ throw new RuntimeException(); - } - finally - { - if (null != cursor) - { + } finally { + if (null != cursor) { cursor.close(); } } @@ -2594,20 +2256,18 @@ public final class LocalyticsSession /** * Private helper to get the {@link SessionsDbColumns#SESSION_START_WALL_TIME} for a given {@link SessionsDbColumns#_ID}. * - * @param provider Localytics database instance. Cannot be null. + * @param provider Localytics database instance. Cannot be null. * @param sessionId {@link SessionsDbColumns#_ID} of the event to look up * @return The {@link SessionsDbColumns#SESSION_START_WALL_TIME} of the session. */ - /* package */static long getSessionStartTime(final LocalyticsProvider provider, final long sessionId) - { + /* package */ + static long getSessionStartTime(final LocalyticsProvider provider, final long sessionId) { Cursor cursor = null; - try - { + try { cursor = provider.query(SessionsDbColumns.TABLE_NAME, new String[] - { SessionsDbColumns.SESSION_START_WALL_TIME }, String.format("%s = ?", SessionsDbColumns._ID), new String[] { Long.toString(sessionId) }, null); //$NON-NLS-1$ + {SessionsDbColumns.SESSION_START_WALL_TIME}, String.format("%s = ?", SessionsDbColumns._ID), new String[]{Long.toString(sessionId)}, null); //$NON-NLS-1$ - if (cursor.moveToFirst()) - { + if (cursor.moveToFirst()) { return cursor.getLong(cursor.getColumnIndexOrThrow(SessionsDbColumns.SESSION_START_WALL_TIME)); } @@ -2615,11 +2275,8 @@ public final class LocalyticsSession * This should never happen */ throw new RuntimeException(); - } - finally - { - if (null != cursor) - { + } finally { + if (null != cursor) { cursor.close(); } } @@ -2629,20 +2286,18 @@ public final class LocalyticsSession * Private helper to convert an event's attributes into a {@link JSONObject} representation. * * @param provider Localytics database instance. Cannot be null. - * @param eventId {@link EventsDbColumns#_ID} of the event whose attributes are to be loaded. + * @param eventId {@link EventsDbColumns#_ID} of the event whose attributes are to be loaded. * @return {@link JSONObject} representing the attributes of the event. The order of attributes is undefined and may - * change from call to call of this method. If the event has no attributes, returns null. + * change from call to call of this method. If the event has no attributes, returns null. * @throws JSONException if an error occurs converting the attributes to JSON */ - /* package */static JSONObject convertAttributesToJson(final LocalyticsProvider provider, final long eventId) throws JSONException - { + /* package */ + static JSONObject convertAttributesToJson(final LocalyticsProvider provider, final long eventId) throws JSONException { Cursor cursor = null; - try - { - cursor = provider.query(AttributesDbColumns.TABLE_NAME, null, String.format("%s = ?", AttributesDbColumns.EVENTS_KEY_REF), new String[] { Long.toString(eventId) }, null); //$NON-NLS-1$ + try { + cursor = provider.query(AttributesDbColumns.TABLE_NAME, null, String.format("%s = ?", AttributesDbColumns.EVENTS_KEY_REF), new String[]{Long.toString(eventId)}, null); //$NON-NLS-1$ - if (cursor.getCount() == 0) - { + if (cursor.getCount() == 0) { return null; } @@ -2650,17 +2305,13 @@ public final class LocalyticsSession final int keyColumn = cursor.getColumnIndexOrThrow(AttributesDbColumns.ATTRIBUTE_KEY); final int valueColumn = cursor.getColumnIndexOrThrow(AttributesDbColumns.ATTRIBUTE_VALUE); - while (cursor.moveToNext()) - { + while (cursor.moveToNext()) { attributes.put(cursor.getString(keyColumn), cursor.getString(valueColumn)); } return attributes; - } - finally - { - if (null != cursor) - { + } finally { + if (null != cursor) { cursor.close(); } } @@ -2672,8 +2323,7 @@ public final class LocalyticsSession * @param blobId {@link UploadBlobsDbColumns#_ID} of the upload blob. * @return id of the parent session. */ - /* package */long getSessionIdForBlobId(final long blobId) - { + /* package */long getSessionIdForBlobId(final long blobId) { /* * This implementation needs to walk up the tree of database elements. */ @@ -2681,28 +2331,21 @@ public final class LocalyticsSession long eventId; { Cursor cursor = null; - try - { + try { cursor = mProvider.query(UploadBlobEventsDbColumns.TABLE_NAME, new String[] - { UploadBlobEventsDbColumns.EVENTS_KEY_REF }, String.format("%s = ?", UploadBlobEventsDbColumns.UPLOAD_BLOBS_KEY_REF), new String[] //$NON-NLS-1$ - { Long.toString(blobId) }, null); + {UploadBlobEventsDbColumns.EVENTS_KEY_REF}, String.format("%s = ?", UploadBlobEventsDbColumns.UPLOAD_BLOBS_KEY_REF), new String[] //$NON-NLS-1$ + {Long.toString(blobId)}, null); - if (cursor.moveToFirst()) - { + if (cursor.moveToFirst()) { eventId = cursor.getLong(cursor.getColumnIndexOrThrow(UploadBlobEventsDbColumns.EVENTS_KEY_REF)); - } - else - { + } else { /* * This should never happen */ throw new RuntimeException("No events associated with blob"); //$NON-NLS-1$ } - } - finally - { - if (null != cursor) - { + } finally { + if (null != cursor) { cursor.close(); } } @@ -2711,28 +2354,21 @@ public final class LocalyticsSession long sessionId; { Cursor cursor = null; - try - { + try { cursor = mProvider.query(EventsDbColumns.TABLE_NAME, new String[] - { EventsDbColumns.SESSION_KEY_REF }, String.format("%s = ?", EventsDbColumns._ID), new String[] //$NON-NLS-1$ - { Long.toString(eventId) }, null); + {EventsDbColumns.SESSION_KEY_REF}, String.format("%s = ?", EventsDbColumns._ID), new String[] //$NON-NLS-1$ + {Long.toString(eventId)}, null); - if (cursor.moveToFirst()) - { + if (cursor.moveToFirst()) { sessionId = cursor.getLong(cursor.getColumnIndexOrThrow(EventsDbColumns.SESSION_KEY_REF)); - } - else - { + } else { /* * This should never happen */ throw new RuntimeException("No session associated with event"); //$NON-NLS-1$ } - } - finally - { - if (null != cursor) - { + } finally { + if (null != cursor) { cursor.close(); } } @@ -2748,14 +2384,12 @@ public final class LocalyticsSession /* * Once support for Android 1.6 is dropped, using Android's built-in Pair class would be preferable */ - private static final class Pair - { + private static final class Pair { public final F first; public final S second; - public Pair(final F first, final S second) - { + public Pair(final F first, final S second) { this.first = first; this.second = second; } diff --git a/astrid/common-src/com/localytics/android/ReflectionUtils.java b/astrid/common-src/com/localytics/android/ReflectionUtils.java index 202c700ac..ff1a6146a 100644 --- a/astrid/common-src/com/localytics/android/ReflectionUtils.java +++ b/astrid/common-src/com/localytics/android/ReflectionUtils.java @@ -9,105 +9,85 @@ import java.lang.reflect.InvocationTargetException; /** * Static utilities for performing reflection against newer Android SDKs. - *

    + *

    * This is not a general-purpose reflection class but is rather specifically designed for calling methods that must exist in newer * versions of Android. */ -public final class ReflectionUtils -{ +public final class ReflectionUtils { /** * Private constructor prevents instantiation * * @throws UnsupportedOperationException because this class cannot be instantiated. */ - private ReflectionUtils() - { + private ReflectionUtils() { throw new UnsupportedOperationException("This class is non-instantiable"); //$NON-NLS-1$ } /** * Use reflection to invoke a static method for a class object and method name * - * @param Type that the method should return + * @param Type that the method should return * @param classObject Class on which to invoke {@code methodName}. Cannot be null. - * @param methodName Name of the method to invoke. Cannot be null. - * @param types explicit types for the objects. This is useful if the types are primitives, rather than objects. - * @param args arguments for the method. May be null if the method takes no arguments. + * @param methodName Name of the method to invoke. Cannot be null. + * @param types explicit types for the objects. This is useful if the types are primitives, rather than objects. + * @param args arguments for the method. May be null if the method takes no arguments. * @return The result of invoking the named method on the given class for the args * @throws RuntimeException if the class or method doesn't exist */ - public static T tryInvokeStatic(final Class classObject, final String methodName, final Class[] types, final Object[] args) - { + public static T tryInvokeStatic(final Class classObject, final String methodName, final Class[] types, final Object[] args) { return (T) helper(null, classObject, null, methodName, types, args); } /** * Use reflection to invoke a static method for a class object and method name * - * @param Type that the method should return - * @param className Name of the class on which to invoke {@code methodName}. Cannot be null. + * @param Type that the method should return + * @param className Name of the class on which to invoke {@code methodName}. Cannot be null. * @param methodName Name of the method to invoke. Cannot be null. - * @param types explicit types for the objects. This is useful if the types are primitives, rather than objects. - * @param args arguments for the method. May be null if the method takes no arguments. + * @param types explicit types for the objects. This is useful if the types are primitives, rather than objects. + * @param args arguments for the method. May be null if the method takes no arguments. * @return The result of invoking the named method on the given class for the args * @throws RuntimeException if the class or method doesn't exist */ - public static T tryInvokeStatic(final String className, final String methodName, final Class[] types, final Object[] args) - { + public static T tryInvokeStatic(final String className, final String methodName, final Class[] types, final Object[] args) { return (T) helper(className, null, null, methodName, types, args); } /** * Use reflection to invoke a static method for a class object and method name * - * @param Type that the method should return - * @param target Object instance on which to invoke {@code methodName}. Cannot be null. + * @param Type that the method should return + * @param target Object instance on which to invoke {@code methodName}. Cannot be null. * @param methodName Name of the method to invoke. Cannot be null. - * @param types explicit types for the objects. This is useful if the types are primitives, rather than objects. - * @param args arguments for the method. May be null if the method takes no arguments. + * @param types explicit types for the objects. This is useful if the types are primitives, rather than objects. + * @param args arguments for the method. May be null if the method takes no arguments. * @return The result of invoking the named method on the given class for the args * @throws RuntimeException if the class or method doesn't exist */ - public static T tryInvokeInstance(final Object target, final String methodName, final Class[] types, final Object[] args) - { + public static T tryInvokeInstance(final Object target, final String methodName, final Class[] types, final Object[] args) { return (T) helper(target, null, null, methodName, types, args); } @SuppressWarnings("unchecked") - private static T helper(final Object target, final Class classObject, final String className, final String methodName, final Class[] argTypes, final Object[] args) - { - try - { + private static T helper(final Object target, final Class classObject, final String className, final String methodName, final Class[] argTypes, final Object[] args) { + try { Class cls; - if (classObject != null) - { + if (classObject != null) { cls = classObject; - } - else if (target != null) - { + } else if (target != null) { cls = target.getClass(); - } - else - { + } else { cls = Class.forName(className); } return (T) cls.getMethod(methodName, argTypes).invoke(target, args); - } - catch (final NoSuchMethodException e) - { + } catch (final NoSuchMethodException e) { throw new RuntimeException(e); - } - catch (final IllegalAccessException e) - { + } catch (final IllegalAccessException e) { throw new RuntimeException(e); - } - catch (final InvocationTargetException e) - { + } catch (final InvocationTargetException e) { throw new RuntimeException(e); - } - catch (final ClassNotFoundException e) - { + } catch (final ClassNotFoundException e) { throw new RuntimeException(e); } } diff --git a/astrid/common-src/com/mdimension/jchronic/AstridChronic.java b/astrid/common-src/com/mdimension/jchronic/AstridChronic.java index 42948e5ea..3ef53b0b8 100644 --- a/astrid/common-src/com/mdimension/jchronic/AstridChronic.java +++ b/astrid/common-src/com/mdimension/jchronic/AstridChronic.java @@ -5,9 +5,6 @@ */ package com.mdimension.jchronic; -import java.util.LinkedList; -import java.util.List; - import com.mdimension.jchronic.handlers.Handler; import com.mdimension.jchronic.numerizer.Numerizer; import com.mdimension.jchronic.repeaters.Repeater; @@ -20,176 +17,178 @@ import com.mdimension.jchronic.tags.TimeZone; import com.mdimension.jchronic.utils.Span; import com.mdimension.jchronic.utils.Token; +import java.util.LinkedList; +import java.util.List; + @SuppressWarnings("nls") public class AstridChronic { - public static final String VERSION = "0.2.3"; - - private AstridChronic() { - // DO NOTHING - } - - public static Span parse(String text) { - return AstridChronic.parse(text, new Options()); - } - - /** - * Parses a string containing a natural language date or time. If the parser - * can find a date or time, either a Time or Chronic::Span will be returned - * (depending on the value of :guess). If no date or time can be found, - * +nil+ will be returned. - * - * Options are: - * - * [:context] - * :past or :future (defaults to :future) - * - * If your string represents a birthday, you can set :context to :past - * and if an ambiguous string is given, it will assume it is in the - * past. Specify :future or omit to set a future context. - * - * [:now] - * Time (defaults to Time.now) - * - * By setting :now to a Time, all computations will be based off - * of that time instead of Time.now - * - * [:guess] - * +true+ or +false+ (defaults to +true+) - * - * By default, the parser will guess a single point in time for the - * given date or time. If you'd rather have the entire time span returned, - * set :guess to +false+ and a Chronic::Span will be returned. - * - * [:ambiguous_time_range] - * Integer or :none (defaults to 6 (6am-6pm)) - * - * If an Integer is given, ambiguous times (like 5:00) will be - * assumed to be within the range of that time in the AM to that time - * in the PM. For example, if you set it to 7, then the parser will - * look for the time between 7am and 7pm. In the case of 5:00, it would - * assume that means 5:00pm. If :none is given, no assumption - * will be made, and the first matching instance of that time will - * be used. - */ - @SuppressWarnings("unchecked") - public static Span parse(String text, Options options) { - // store now for later =) - //_now = options.getNow(); - - // put the text into a normal format to ease scanning - String normalizedText = AstridChronic.preNormalize(text); - - // get base tokens for each word - List tokens = AstridChronic.baseTokenize(normalizedText); - - try { - tokens = Repeater.scan(tokens, options); - } catch (Throwable e) { - throw new RuntimeException("Failed to scan tokens.", e); - } + public static final String VERSION = "0.2.3"; - tokens = Grabber.scan(tokens, options); - tokens = Pointer.scan(tokens, options); - tokens = Scalar.scan(tokens, options); - tokens = Ordinal.scan(tokens, options); - tokens = Separator.scan(tokens, options); - tokens = TimeZone.scan(tokens, options); - - List taggedTokens = new LinkedList(); - for (Token token : tokens) { - if (token.isTagged()) { - taggedTokens.add(token); - } + private AstridChronic() { + // DO NOTHING } - tokens = taggedTokens; - if (options.isDebug()) { - System.out.println("Chronic.parse: " + tokens); + public static Span parse(String text) { + return AstridChronic.parse(text, new Options()); } - Span span = Handler.tokensToSpan(tokens, options); + /** + * Parses a string containing a natural language date or time. If the parser + * can find a date or time, either a Time or Chronic::Span will be returned + * (depending on the value of :guess). If no date or time can be found, + * +nil+ will be returned. + *

    + * Options are: + *

    + * [:context] + * :past or :future (defaults to :future) + *

    + * If your string represents a birthday, you can set :context to :past + * and if an ambiguous string is given, it will assume it is in the + * past. Specify :future or omit to set a future context. + *

    + * [:now] + * Time (defaults to Time.now) + *

    + * By setting :now to a Time, all computations will be based off + * of that time instead of Time.now + *

    + * [:guess] + * +true+ or +false+ (defaults to +true+) + *

    + * By default, the parser will guess a single point in time for the + * given date or time. If you'd rather have the entire time span returned, + * set :guess to +false+ and a Chronic::Span will be returned. + *

    + * [:ambiguous_time_range] + * Integer or :none (defaults to 6 (6am-6pm)) + *

    + * If an Integer is given, ambiguous times (like 5:00) will be + * assumed to be within the range of that time in the AM to that time + * in the PM. For example, if you set it to 7, then the parser will + * look for the time between 7am and 7pm. In the case of 5:00, it would + * assume that means 5:00pm. If :none is given, no assumption + * will be made, and the first matching instance of that time will + * be used. + */ + @SuppressWarnings("unchecked") + public static Span parse(String text, Options options) { + // store now for later =) + //_now = options.getNow(); + + // put the text into a normal format to ease scanning + String normalizedText = AstridChronic.preNormalize(text); + + // get base tokens for each word + List tokens = AstridChronic.baseTokenize(normalizedText); + + try { + tokens = Repeater.scan(tokens, options); + } catch (Throwable e) { + throw new RuntimeException("Failed to scan tokens.", e); + } + + tokens = Grabber.scan(tokens, options); + tokens = Pointer.scan(tokens, options); + tokens = Scalar.scan(tokens, options); + tokens = Ordinal.scan(tokens, options); + tokens = Separator.scan(tokens, options); + tokens = TimeZone.scan(tokens, options); + + List taggedTokens = new LinkedList(); + for (Token token : tokens) { + if (token.isTagged()) { + taggedTokens.add(token); + } + } + tokens = taggedTokens; + + if (options.isDebug()) { + System.out.println("Chronic.parse: " + tokens); + } + + Span span = Handler.tokensToSpan(tokens, options); + + // guess a time within a span if required + if (options.isGuess()) { + span = guess(span); + } + + return span; + } - // guess a time within a span if required - if (options.isGuess()) { - span = guess(span); + /** + * Clean up the specified input text by stripping unwanted characters, + * converting idioms to their canonical form, converting number words + * to numbers (three => 3), and converting ordinal words to numeric + * ordinals (third => 3rd) + */ + protected static String preNormalize(String text) { + String normalizedText = text.toLowerCase(); + normalizedText = Chronic.numericizeNumbers(normalizedText); + normalizedText = normalizedText.replaceAll("['\"\\.]", ""); + normalizedText = normalizedText.replaceAll("([/\\-,@])", " $1 "); + normalizedText = normalizedText.replaceAll("\\btoday\\b", "this day"); + normalizedText = normalizedText.replaceAll("\\btomm?orr?ow\\b", "next day"); + normalizedText = normalizedText.replaceAll("\\byesterday\\b", "last day"); + normalizedText = normalizedText.replaceAll("\\bnoon\\b", "12:00"); + normalizedText = normalizedText.replaceAll("\\bmidnight\\b", "24:00"); + normalizedText = normalizedText.replaceAll("\\bbefore now\\b", "past"); + normalizedText = normalizedText.replaceAll("\\bnow\\b", "this second"); + normalizedText = normalizedText.replaceAll("\\b(ago|before)\\b", "past"); + normalizedText = normalizedText.replaceAll("\\bthis past\\b", "last"); + normalizedText = normalizedText.replaceAll("\\bthis last\\b", "last"); + normalizedText = normalizedText.replaceAll("\\b(?:in|during) the (morning)\\b", "$1"); + normalizedText = normalizedText.replaceAll("\\b(?:in the|during the|at) (afternoon|evening|night)\\b", "$1"); + normalizedText = normalizedText.replaceAll("\\btonight\\b", "this night"); + normalizedText = normalizedText.replaceAll("(?=\\w)([ap]m|oclock)\\b", " $1"); + normalizedText = normalizedText.replaceAll("\\b(hence|after|from)\\b", "future"); + normalizedText = AstridChronic.numericizeOrdinals(normalizedText); + return normalizedText; } - return span; - } - - /** - * Clean up the specified input text by stripping unwanted characters, - * converting idioms to their canonical form, converting number words - * to numbers (three => 3), and converting ordinal words to numeric - * ordinals (third => 3rd) - */ - protected static String preNormalize(String text) { - String normalizedText = text.toLowerCase(); - normalizedText = Chronic.numericizeNumbers(normalizedText); - normalizedText = normalizedText.replaceAll("['\"\\.]", ""); - normalizedText = normalizedText.replaceAll("([/\\-,@])", " $1 "); - normalizedText = normalizedText.replaceAll("\\btoday\\b", "this day"); - normalizedText = normalizedText.replaceAll("\\btomm?orr?ow\\b", "next day"); - normalizedText = normalizedText.replaceAll("\\byesterday\\b", "last day"); - normalizedText = normalizedText.replaceAll("\\bnoon\\b", "12:00"); - normalizedText = normalizedText.replaceAll("\\bmidnight\\b", "24:00"); - normalizedText = normalizedText.replaceAll("\\bbefore now\\b", "past"); - normalizedText = normalizedText.replaceAll("\\bnow\\b", "this second"); - normalizedText = normalizedText.replaceAll("\\b(ago|before)\\b", "past"); - normalizedText = normalizedText.replaceAll("\\bthis past\\b", "last"); - normalizedText = normalizedText.replaceAll("\\bthis last\\b", "last"); - normalizedText = normalizedText.replaceAll("\\b(?:in|during) the (morning)\\b", "$1"); - normalizedText = normalizedText.replaceAll("\\b(?:in the|during the|at) (afternoon|evening|night)\\b", "$1"); - normalizedText = normalizedText.replaceAll("\\btonight\\b", "this night"); - normalizedText = normalizedText.replaceAll("(?=\\w)([ap]m|oclock)\\b", " $1"); - normalizedText = normalizedText.replaceAll("\\b(hence|after|from)\\b", "future"); - normalizedText = AstridChronic.numericizeOrdinals(normalizedText); - return normalizedText; - } - - /** - * Convert number words to numbers (three => 3) - */ - protected static String numericizeNumbers(String text) { - return Numerizer.numerize(text); - } - - /** - * Convert ordinal words to numeric ordinals (third => 3rd) - */ - protected static String numericizeOrdinals(String text) { - return text; - } - - /** - * Split the text on spaces and convert each word into - * a Token - */ - protected static List baseTokenize(String text) { - String[] words = text.split(" "); - List tokens = new LinkedList(); - for (String word : words) { - tokens.add(new Token(word)); + /** + * Convert number words to numbers (three => 3) + */ + protected static String numericizeNumbers(String text) { + return Numerizer.numerize(text); } - return tokens; - } - - /** - * Guess a specific time within the given span - */ - // DIFF: We return Span instead of Date - protected static Span guess(Span span) { - if (span == null) { - return null; + + /** + * Convert ordinal words to numeric ordinals (third => 3rd) + */ + protected static String numericizeOrdinals(String text) { + return text; } - long guessValue; - if (span.getWidth() > 1) { - guessValue = span.getBegin() + (span.getWidth() / 2); + + /** + * Split the text on spaces and convert each word into + * a Token + */ + protected static List baseTokenize(String text) { + String[] words = text.split(" "); + List tokens = new LinkedList(); + for (String word : words) { + tokens.add(new Token(word)); + } + return tokens; } - else { - guessValue = span.getBegin(); + + /** + * Guess a specific time within the given span + */ + // DIFF: We return Span instead of Date + protected static Span guess(Span span) { + if (span == null) { + return null; + } + long guessValue; + if (span.getWidth() > 1) { + guessValue = span.getBegin() + (span.getWidth() / 2); + } else { + guessValue = span.getBegin(); + } + Span guess = new Span(guessValue, guessValue); + return guess; } - Span guess = new Span(guessValue, guessValue); - return guess; - } } diff --git a/astrid/common-src/edu/mit/mobile/android/imagecache/DiskCache.java b/astrid/common-src/edu/mit/mobile/android/imagecache/DiskCache.java index ba53687c5..83e4bfdbe 100644 --- a/astrid/common-src/edu/mit/mobile/android/imagecache/DiskCache.java +++ b/astrid/common-src/edu/mit/mobile/android/imagecache/DiskCache.java @@ -17,6 +17,13 @@ package edu.mit.mobile.android.imagecache; * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ + +import android.os.Build; +import android.os.StatFs; +import android.util.Log; + +import com.todoroo.astrid.utility.Constants; + import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; @@ -37,35 +44,26 @@ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; -import android.os.Build; -import android.os.StatFs; -import android.util.Log; - -import com.todoroo.astrid.utility.Constants; - /** *

    * A simple disk cache. *

    - * + *

    *

    * By default, the maximum size of the cache is automatically set based on the amount of free space * available to the cache. Alternatively, a fixed size can be specified using * {@link #setCacheMaxSize(long)}. *

    - * + *

    *

    * By default, the cache will automatically maintain its size by periodically checking to see if it * estimates that a trim is needed and if it is, proceeding to running {@link #trim()} on a worker * thread. This feature can be controlled by {@link #setAutoTrimFrequency(int)}. *

    * + * @param the key to store/retrieve the value + * @param the value that will be stored to disk * @author Steve Pomeroy - * - * @param - * the key to store/retrieve the value - * @param - * the value that will be stored to disk */ public abstract class DiskCache { private static final String TAG = "DiskCache"; @@ -126,12 +124,9 @@ public abstract class DiskCache { /** * Creates a new disk cache. * - * @param cacheBase - * The base directory within which all the cache files will be stored. - * @param cachePrefix - * If you want a prefix to the filenames, place one here. Otherwise, pass null. - * @param cacheSuffix - * A suffix to the cache filename. Null is also ok here. + * @param cacheBase The base directory within which all the cache files will be stored. + * @param cachePrefix If you want a prefix to the filenames, place one here. Otherwise, pass null. + * @param cacheSuffix A suffix to the cache filename. Null is also ok here. */ public DiskCache(File cacheBase, String cachePrefix, String cacheSuffix) { mCacheBase = cacheBase; @@ -159,8 +154,7 @@ public abstract class DiskCache { * size based on the available disk space. This can be explicitly set by passing this * {@link #AUTO_MAX_CACHE_SIZE}. * - * @param maxSize - * maximum size of the cache, in bytes. + * @param maxSize maximum size of the cache, in bytes. */ public void setCacheMaxSize(long maxSize) { mMaxDiskUsage = maxSize; @@ -170,9 +164,8 @@ public abstract class DiskCache { * After this many puts, if it looks like there's a low space condition, {@link #trim()} will * automatically be called. * - * @param autoTrimFrequency - * Set to {@link #AUTO_TRIM_DISABLED} to turn off auto trim. The default is - * {@link #DEFAULT_AUTO_TRIM_FREQUENCY}. + * @param autoTrimFrequency Set to {@link #AUTO_TRIM_DISABLED} to turn off auto trim. The default is + * {@link #DEFAULT_AUTO_TRIM_FREQUENCY}. */ public void setAutoTrimFrequency(int autoTrimFrequency) { mAutoTrimFrequency = autoTrimFrequency; @@ -232,10 +225,8 @@ public abstract class DiskCache { * Writes the value stored in the cache to disk by calling * {@link #toDisk(Object, Object, OutputStream)}. * - * @param key - * The key to find the value. - * @param value - * the data to be written to disk. + * @param key The key to find the value. + * @param value the data to be written to disk. */ public final synchronized void put(K key, V value) throws IOException, FileNotFoundException { final File saveHere = getFile(key); @@ -401,7 +392,7 @@ public abstract class DiskCache { * * @param key * @return true if the cached item has been removed or was already removed, false if it was not - * able to be removed. + * able to be removed. */ public synchronized boolean clear(K key) { final File readFrom = getFile(key); @@ -425,7 +416,7 @@ public abstract class DiskCache { * * @param cacheFile * @return true if the cached item has been removed or was already removed, false if it was not - * able to be removed. + * able to be removed. */ private synchronized boolean clear(File cacheFile) { @@ -445,11 +436,11 @@ public abstract class DiskCache { /** * Clears the cache files from disk. - * + *

    * Note: this only clears files that match the given prefix/suffix. * * @return true if the operation succeeded without error. It is possible that it will fail and - * the cache ends up being partially cleared. + * the cache ends up being partially cleared. */ public synchronized boolean clear() { boolean success = true; @@ -499,7 +490,9 @@ public abstract class DiskCache { return (mCachePrefix != null ? path.startsWith(mCachePrefix) : true) && (mCacheSuffix != null ? path.endsWith(mCacheSuffix) : true); } - }; + } + + ; private final Comparator mLastModifiedOldestFirstComparator = new Comparator() { diff --git a/astrid/common-src/edu/mit/mobile/android/imagecache/DrawableMemCache.java b/astrid/common-src/edu/mit/mobile/android/imagecache/DrawableMemCache.java index 81e354bc1..695e23d56 100644 --- a/astrid/common-src/edu/mit/mobile/android/imagecache/DrawableMemCache.java +++ b/astrid/common-src/edu/mit/mobile/android/imagecache/DrawableMemCache.java @@ -17,6 +17,7 @@ package edu.mit.mobile.android.imagecache; * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ + import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; diff --git a/astrid/common-src/edu/mit/mobile/android/imagecache/ImageCache.java b/astrid/common-src/edu/mit/mobile/android/imagecache/ImageCache.java index bdceb136a..5884eb0ba 100644 --- a/astrid/common-src/edu/mit/mobile/android/imagecache/ImageCache.java +++ b/astrid/common-src/edu/mit/mobile/android/imagecache/ImageCache.java @@ -17,22 +17,22 @@ package edu.mit.mobile.android.imagecache; * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLConnection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.concurrent.PriorityBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.content.Context; +import android.content.res.Resources; +import android.graphics.Bitmap; +import android.graphics.Bitmap.CompressFormat; +import android.graphics.BitmapFactory; +import android.graphics.drawable.BitmapDrawable; +import android.graphics.drawable.Drawable; +import android.net.Uri; +import android.os.Handler; +import android.os.Message; +import android.util.Log; +import android.util.SparseArray; +import android.widget.ImageView; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; @@ -51,28 +51,29 @@ import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.HttpParams; -import android.annotation.SuppressLint; -import android.app.Activity; -import android.content.Context; -import android.content.res.Resources; -import android.graphics.Bitmap; -import android.graphics.Bitmap.CompressFormat; -import android.graphics.BitmapFactory; -import android.graphics.drawable.BitmapDrawable; -import android.graphics.drawable.Drawable; -import android.net.Uri; -import android.os.Handler; -import android.os.Message; -import android.util.Log; -import android.util.SparseArray; -import android.widget.ImageView; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URL; +import java.net.URLConnection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.concurrent.PriorityBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; /** *

    * An image download-and-cacher that also knows how to efficiently generate thumbnails of various * sizes. *

    - * + *

    *

    * The cache is shared with the entire process, so make sure you * {@link #registerOnImageLoadListener(OnImageLoadListener)} and @@ -81,7 +82,6 @@ import android.widget.ImageView; *

    * * @author Steve Pomeroy - * */ public class ImageCache extends DiskCache { private static final String TAG = ImageCache.class.getSimpleName(); @@ -98,7 +98,7 @@ public class ImageCache extends DiskCache { private final HashSet mImageLoadListeners = new HashSet(); - public static final int DEFAULT_CACHE_SIZE = (24 /* MiB */* 1024 * 1024); // in bytes + public static final int DEFAULT_CACHE_SIZE = (24 /* MiB */ * 1024 * 1024); // in bytes private DrawableMemCache mMemCache = new DrawableMemCache(DEFAULT_CACHE_SIZE); @@ -143,12 +143,15 @@ public class ImageCache extends DiskCache { mCache.notifyListeners((LoadResult) msg.obj); break; } - }; + } + + ; } private final ImageLoadHandler mHandler = new ImageLoadHandler(this); // TODO make it so this is customizable on the instance level. + /** * Gets an instance of the cache. * @@ -207,8 +210,7 @@ public class ImageCache extends DiskCache { /** * Sets the maximum size of the memory cache. Note, this will clear the memory cache. * - * @param maxSize - * the maximum size of the memory cache in bytes. + * @param maxSize the maximum size of the memory cache in bytes. */ public void setMemCacheMaxSize(int maxSize) { mMemCache = new DrawableMemCache(maxSize); @@ -328,7 +330,7 @@ public class ImageCache extends DiskCache { * indirectly by {@link #loadImage(int, Uri, int, int)}, any registered listeners will get * called. *

    - * + *

    *

    * This should probably be called from {@link Activity#onResume()}. *

    @@ -343,7 +345,7 @@ public class ImageCache extends DiskCache { *

    * Unregisters the listener with the cache. This will not cancel any pending load requests. *

    - * + *

    *

    * This should probably be called from {@link Activity#onPause()}. *

    @@ -367,8 +369,7 @@ public class ImageCache extends DiskCache { } /** - * @param uri - * the image uri + * @param uri the image uri * @return a key unique to the given uri */ public String getKey(Uri uri) { @@ -378,8 +379,7 @@ public class ImageCache extends DiskCache { /** * Gets the given key as a drawable, retrieving it from memory cache if it's present. * - * @param key - * a key generated by {@link #getKey(Uri)} or {@link #getKey(Uri, int, int)} + * @param key a key generated by {@link #getKey(Uri)} or {@link #getKey(Uri, int, int)} * @return the drawable if it's in the memory cache or null. */ public Drawable getDrawable(String key) { @@ -398,8 +398,7 @@ public class ImageCache extends DiskCache { /** * Puts a drawable into memory cache. * - * @param key - * a key generated by {@link #getKey(Uri)} or {@link #getKey(Uri, int, int)} + * @param key a key generated by {@link #getKey(Uri)} or {@link #getKey(Uri, int, int)} * @param drawable */ public void putDrawable(String key, Drawable drawable) { @@ -477,12 +476,9 @@ public class ImageCache extends DiskCache { /** * Returns an opaque cache key representing the given uri, width and height. * - * @param uri - * an image uri - * @param width - * the desired image max width - * @param height - * the desired image max height + * @param uri an image uri + * @param width the desired image max width + * @param height the desired image max height * @return a cache key unique to the given parameters */ public String getKey(Uri uri, int width, int height) { @@ -568,7 +564,9 @@ public class ImageCache extends DiskCache { @Override public int compareTo(ImageLoadTask another) { return Long.valueOf(another.when).compareTo(when); - }; + } + + ; } private void oomClear() { @@ -580,19 +578,14 @@ public class ImageCache extends DiskCache { * Checks the cache for an image matching the given criteria and returns it. If it isn't * immediately available, calls {@link #scheduleLoadImage}. * - * @param id - * An ID to keep track of image load requests. For one-off loads, this can just be - * the ID of the {@link ImageView}. Otherwise, an unique ID can be acquired using - * {@link #getNewID()}. - * - * @param image - * the image to be loaded. Can be a local file or a network resource. - * @param width - * the maximum width of the resulting image - * @param height - * the maximum height of the resulting image + * @param id An ID to keep track of image load requests. For one-off loads, this can just be + * the ID of the {@link ImageView}. Otherwise, an unique ID can be acquired using + * {@link #getNewID()}. + * @param image the image to be loaded. Can be a local file or a network resource. + * @param width the maximum width of the resulting image + * @param height the maximum height of the resulting image * @return the cached bitmap if it's available immediately or null if it needs to be loaded - * asynchronously. + * asynchronously. */ public Drawable loadImage(int id, Uri image, int width, int height) throws IOException { if (DEBUG) { @@ -628,17 +621,12 @@ public class ImageCache extends DiskCache { * Schedules a load of the given image. When the image has finished loading and scaling, all * registered {@link OnImageLoadListener}s will be called. * - * @param id - * An ID to keep track of image load requests. For one-off loads, this can just be - * the ID of the {@link ImageView}. Otherwise, an unique ID can be acquired using - * {@link #getNewID()}. - * - * @param image - * the image to be loaded. Can be a local file or a network resource. - * @param width - * the maximum width of the resulting image - * @param height - * the maximum height of the resulting image + * @param id An ID to keep track of image load requests. For one-off loads, this can just be + * the ID of the {@link ImageView}. Otherwise, an unique ID can be acquired using + * {@link #getNewID()}. + * @param image the image to be loaded. Can be a local file or a network resource. + * @param width the maximum width of the resulting image + * @param height the maximum height of the resulting image */ public void scheduleLoadImage(int id, Uri image, int width, int height) { if (DEBUG) { @@ -665,7 +653,6 @@ public class ImageCache extends DiskCache { /** * Cancels all the asynchronous image loads. Note: currently does not function properly. - * */ public void cancelLoads() { jobs.clear(); @@ -698,12 +685,9 @@ public class ImageCache extends DiskCache { /** * Blocking call to scale a local file. Scales using preserving aspect ratio * - * @param localFile - * local image file to be scaled - * @param width - * maximum width - * @param height - * maximum height + * @param localFile local image file to be scaled + * @param width maximum width + * @param height maximum height * @return the scaled image * @throws ClientProtocolException * @throws IOException @@ -764,11 +748,9 @@ public class ImageCache extends DiskCache { * Blocking call to download an image. The image is placed directly into the disk cache at the * given key. * - * @param uri - * the location of the image + * @param uri the location of the image * @return a decoded bitmap - * @throws ClientProtocolException - * if the HTTP response code wasn't 200 or any other HTTP errors + * @throws ClientProtocolException if the HTTP response code wasn't 200 or any other HTTP errors * @throws IOException */ protected void downloadImage(String key, Uri uri) throws ClientProtocolException, IOException { @@ -823,19 +805,15 @@ public class ImageCache extends DiskCache { * asynchronous image loads have completed. * * @author Steve Pomeroy - * */ public interface OnImageLoadListener { /** * Called when the image has been loaded and scaled. * - * @param id - * the ID provided by {@link ImageCache#loadImage(int, Uri, int, int)} or - * {@link ImageCache#scheduleLoadImage(int, Uri, int, int)} - * @param imageUri - * the uri of the image that was originally requested - * @param image - * the loaded and scaled image + * @param id the ID provided by {@link ImageCache#loadImage(int, Uri, int, int)} or + * {@link ImageCache#scheduleLoadImage(int, Uri, int, int)} + * @param imageUri the uri of the image that was originally requested + * @param image the loaded and scaled image */ public void onImageLoaded(int id, Uri imageUri, Drawable image); } diff --git a/astrid/common-src/edu/mit/mobile/android/imagecache/KeyedLock.java b/astrid/common-src/edu/mit/mobile/android/imagecache/KeyedLock.java index 98a6d82b9..9bb075dd0 100644 --- a/astrid/common-src/edu/mit/mobile/android/imagecache/KeyedLock.java +++ b/astrid/common-src/edu/mit/mobile/android/imagecache/KeyedLock.java @@ -1,17 +1,16 @@ package edu.mit.mobile.android.imagecache; +import android.util.Log; + import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.ReentrantLock; -import android.util.Log; - /** * A synchronization lock that creates a separate lock for each key. * - * @author Steve Pomeroy - * * @param + * @author Steve Pomeroy */ public class KeyedLock { private static final String TAG = KeyedLock.class.getSimpleName(); diff --git a/astrid/plugin-src/com/timsu/astrid/GCMIntentService.java b/astrid/plugin-src/com/timsu/astrid/GCMIntentService.java index f6abe0795..dd562e226 100644 --- a/astrid/plugin-src/com/timsu/astrid/GCMIntentService.java +++ b/astrid/plugin-src/com/timsu/astrid/GCMIntentService.java @@ -1,7 +1,5 @@ package com.timsu.astrid; -import java.io.IOException; - import android.app.Notification; import android.app.PendingIntent; import android.content.Context; @@ -50,6 +48,8 @@ import com.todoroo.astrid.sync.SyncResultCallbackAdapter; import com.todoroo.astrid.tags.TagFilterExposer; import com.todoroo.astrid.utility.Constants; +import java.io.IOException; + @SuppressWarnings("nls") public class GCMIntentService extends GCMBaseIntentService { @@ -62,13 +62,14 @@ public class GCMIntentService extends GCMBaseIntentService { public static final String PREF_C2DM_REGISTRATION = "c2dm_key"; public static String getDeviceID() { - String id = Secure.getString(ContextManager.getContext().getContentResolver(), Secure.ANDROID_ID);; - if(AndroidUtilities.getSdkVersion() > 8) { //Gingerbread and above + String id = Secure.getString(ContextManager.getContext().getContentResolver(), Secure.ANDROID_ID); + ; + if (AndroidUtilities.getSdkVersion() > 8) { //Gingerbread and above //the following uses relection to get android.os.Build.SERIAL to avoid having to build with Gingerbread try { - if(!Build.UNKNOWN.equals(Build.SERIAL)) + if (!Build.UNKNOWN.equals(Build.SERIAL)) id = Build.SERIAL; - } catch(Exception e) { + } catch (Exception e) { // Ah well } } @@ -119,7 +120,7 @@ public class GCMIntentService extends GCMBaseIntentService { @Override protected void onMessage(Context context, Intent intent) { if (actFmPreferenceService.isLoggedIn()) { - if(intent.hasExtra("web_update")) + if (intent.hasExtra("web_update")) if (DateUtilities.now() - actFmPreferenceService.getLastSyncDate() > MIN_MILLIS_BETWEEN_FULL_SYNCS && !actFmPreferenceService.isOngoing()) new ActFmSyncV2Provider().synchronizeActiveTasks(false, refreshOnlyCallback); else @@ -129,9 +130,11 @@ public class GCMIntentService extends GCMBaseIntentService { } } - /** Handle web task or list changed */ + /** + * Handle web task or list changed + */ protected void handleWebUpdate(Intent intent) { - if(intent.hasExtra("tag_id")) { + if (intent.hasExtra("tag_id")) { String uuid = intent.getStringExtra("tag_id"); TodorooCursor cursor = tagDataService.query( Query.select(TagData.PUSHED_AT).where(TagData.UUID.eq( @@ -139,7 +142,7 @@ public class GCMIntentService extends GCMBaseIntentService { long pushedAt = 0; try { TagData tagData = new TagData(); - if(cursor.getCount() > 0) { + if (cursor.getCount() > 0) { cursor.moveToNext(); tagData.readFromCursor(cursor); pushedAt = tagData.getValue(TagData.PUSHED_AT); @@ -148,7 +151,7 @@ public class GCMIntentService extends GCMBaseIntentService { cursor.close(); } ActFmSyncThread.getInstance().enqueueMessage(new BriefMe(TagData.class, uuid, pushedAt), ActFmSyncThread.DEFAULT_REFRESH_RUNNABLE); - } else if(intent.hasExtra("task_id")) { + } else if (intent.hasExtra("task_id")) { String uuid = intent.getStringExtra("task_id"); TodorooCursor cursor = taskService.query( Query.select(Task.PROPERTIES).where(Task.UUID.eq( @@ -156,7 +159,7 @@ public class GCMIntentService extends GCMBaseIntentService { long pushedAt = 0; try { final Task task = new Task(); - if(cursor.getCount() > 0) { + if (cursor.getCount() > 0) { cursor.moveToNext(); task.readFromCursor(cursor); pushedAt = task.getValue(Task.PUSHED_AT); @@ -170,15 +173,17 @@ public class GCMIntentService extends GCMBaseIntentService { // --- message handling - /** Handle message. Run on separate thread. */ + /** + * Handle message. Run on separate thread. + */ private void handleMessage(Intent intent) { String message = intent.getStringExtra("alert"); Context context = ContextManager.getContext(); - if(TextUtils.isEmpty(message)) + if (TextUtils.isEmpty(message)) return; long lastNotification = Preferences.getLong(PREF_LAST_GCM, 0); - if(DateUtilities.now() - lastNotification < 5000L) + if (DateUtilities.now() - lastNotification < 5000L) return; Preferences.setLong(PREF_LAST_GCM, DateUtilities.now()); Intent notifyIntent = null; @@ -203,10 +208,10 @@ public class GCMIntentService extends GCMBaseIntentService { // fetch data - if(intent.hasExtra("tag_id")) { + if (intent.hasExtra("tag_id")) { notifyIntent = createTagIntent(context, intent); notifId = intent.getStringExtra("tag_id").hashCode(); - } else if(intent.hasExtra("task_id")) { + } else if (intent.hasExtra("task_id")) { notifyIntent = createTaskIntent(intent); notifId = intent.getStringExtra("task_id").hashCode(); } else { @@ -228,7 +233,7 @@ public class GCMIntentService extends GCMBaseIntentService { Notification notification = new Notification(icon, message, System.currentTimeMillis()); String title; - if(intent.hasExtra("title")) + if (intent.hasExtra("title")) title = "Astrid: " + intent.getStringExtra("title"); else title = ContextManager.getString(R.string.app_name); @@ -238,13 +243,13 @@ public class GCMIntentService extends GCMBaseIntentService { boolean sounds = !"false".equals(intent.getStringExtra("sound")); notification.defaults = 0; - if(sounds && !Notifications.isQuietHours()) { + if (sounds && !Notifications.isQuietHours()) { notification.defaults |= Notification.DEFAULT_SOUND; notification.defaults |= Notification.DEFAULT_VIBRATE; } nm.notify(notifId, notification); - if(intent.hasExtra("tag_id")) { + if (intent.hasExtra("tag_id")) { Intent broadcastIntent = new Intent(TagViewFragment.BROADCAST_TAG_ACTIVITY); broadcastIntent.putExtras(intent); ContextManager.getContext().sendBroadcast(broadcastIntent, AstridApiConstants.PERMISSION_READ); @@ -252,21 +257,21 @@ public class GCMIntentService extends GCMBaseIntentService { } private int calculateIcon(Intent intent) { - if(intent.hasExtra("type")) { + if (intent.hasExtra("type")) { String type = intent.getStringExtra("type"); - if("f".equals(type)) + if ("f".equals(type)) return R.drawable.notif_c2dm_done; - if("s".equals(type)) + if ("s".equals(type)) return R.drawable.notif_c2dm_assign; - if("l".equals(type)) + if ("l".equals(type)) return R.drawable.notif_c2dm_assign; } else { String message = intent.getStringExtra("alert"); - if(message.contains(" finished ")) + if (message.contains(" finished ")) return R.drawable.notif_c2dm_done; - if(message.contains(" invited you to ")) + if (message.contains(" invited you to ")) return R.drawable.notif_c2dm_assign; - if(message.contains(" sent you ")) + if (message.contains(" sent you ")) return R.drawable.notif_c2dm_assign; } return R.drawable.notif_c2dm_msg; @@ -280,7 +285,7 @@ public class GCMIntentService extends GCMBaseIntentService { long pushedAt = 0; try { final Task task = new Task(); - if(cursor.getCount() == 0) { + if (cursor.getCount() == 0) { task.setValue(Task.TITLE, intent.getStringExtra("title")); task.setValue(Task.UUID, intent.getStringExtra("task_id")); task.setValue(Task.USER_ID, Task.USER_ID_UNASSIGNED); @@ -312,7 +317,7 @@ public class GCMIntentService extends GCMBaseIntentService { long pushedAt = 0; try { final TagData tagData = new TagData(); - if(cursor.getCount() == 0) { + if (cursor.getCount() == 0) { tagData.setValue(TagData.NAME, intent.getStringExtra("title")); tagData.setValue(TagData.UUID, intent.getStringExtra("tag_id")); tagData.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true); @@ -324,9 +329,9 @@ public class GCMIntentService extends GCMBaseIntentService { } ActFmSyncThread.getInstance().enqueueMessage(new BriefMe(TagData.class, uuid, pushedAt), null); - FilterWithCustomIntent filter = (FilterWithCustomIntent)TagFilterExposer.filterFromTagData(context, tagData); + FilterWithCustomIntent filter = (FilterWithCustomIntent) TagFilterExposer.filterFromTagData(context, tagData); - if(intent.hasExtra("activity_id")) { + if (intent.hasExtra("activity_id")) { UserActivity update = new UserActivity(); update.setValue(UserActivity.UUID, intent.getStringExtra("activity_id")); update.setValue(UserActivity.USER_UUID, intent.getStringExtra("user_id")); @@ -334,7 +339,7 @@ public class GCMIntentService extends GCMBaseIntentService { update.setValue(UserActivity.ACTION, "tag_comment"); update.setValue(UserActivity.TARGET_NAME, intent.getStringExtra("title")); String message = intent.getStringExtra("alert"); - if(message.contains(":")) + if (message.contains(":")) message = message.substring(message.indexOf(':') + 2); update.setValue(UserActivity.MESSAGE, message); update.setValue(UserActivity.CREATED_AT, DateUtilities.now()); @@ -359,16 +364,16 @@ public class GCMIntentService extends GCMBaseIntentService { } private boolean shouldLaunchActivity(Intent intent) { - if(intent.hasExtra("type")) { + if (intent.hasExtra("type")) { String type = intent.getStringExtra("type"); - if("f".equals(type)) return true; - if("s".equals(type)) return false; - if("l".equals(type)) return false; + if ("f".equals(type)) return true; + if ("s".equals(type)) return false; + if ("l".equals(type)) return false; } else { String message = intent.getStringExtra("alert"); - if(message.contains(" finished ")) return true; - if(message.contains(" invited you to ")) return false; - if(message.contains(" sent you ")) return false; + if (message.contains(" finished ")) return true; + if (message.contains(" invited you to ")) return false; + if (message.contains(" sent you ")) return false; } return true; } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmBackgroundService.java b/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmBackgroundService.java index 71b36794a..7fdf3d97a 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmBackgroundService.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmBackgroundService.java @@ -20,11 +20,11 @@ import com.todoroo.astrid.sync.SyncV2Provider; * schedules a repeating alarm which handles the synchronization * * @author Tim Su - * */ public class ActFmBackgroundService extends SyncV2BackgroundService { - @Autowired ActFmPreferenceService actFmPreferenceService; + @Autowired + ActFmPreferenceService actFmPreferenceService; public ActFmBackgroundService() { DependencyInjectionService.getInstance().inject(this); diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmCameraModule.java b/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmCameraModule.java index 37b7c87ce..cb4416b7b 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmCameraModule.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmCameraModule.java @@ -5,10 +5,6 @@ */ package com.todoroo.astrid.actfm; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; - import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; @@ -26,6 +22,10 @@ import com.timsu.astrid.R; import com.todoroo.andlib.utility.AndroidUtilities; import com.todoroo.andlib.utility.DateUtilities; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; + public class ActFmCameraModule { protected static final int REQUEST_CODE_CAMERA = 1; @@ -44,7 +44,7 @@ public class ActFmCameraModule { PackageManager pm = activity.getPackageManager(); final boolean cameraAvailable = pm.queryIntentActivities(cameraIntent, 0).size() > 0; - if(cameraAvailable) + if (cameraAvailable) options.add(activity.getString(R.string.actfm_picture_camera)); options.add(activity.getString(R.string.actfm_picture_gallery)); @@ -58,7 +58,7 @@ public class ActFmCameraModule { @SuppressWarnings("nls") @Override public void onClick(DialogInterface d, int which) { - if(which == 0 && cameraAvailable) { + if (which == 0 && cameraAvailable) { lastTempFile = getTempFile(activity); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (lastTempFile != null) { @@ -79,8 +79,8 @@ public class ActFmCameraModule { // show a menu of available options new AlertDialog.Builder(activity) - .setAdapter(adapter, listener) - .show().setOwnerActivity(activity); + .setAdapter(adapter, listener) + .show().setOwnerActivity(activity); } @@ -90,7 +90,7 @@ public class ActFmCameraModule { final Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); PackageManager pm = fragment.getActivity().getPackageManager(); final boolean cameraAvailable = pm.queryIntentActivities(cameraIntent, 0).size() > 0; - if(cameraAvailable) + if (cameraAvailable) options.add(fragment.getString(R.string.actfm_picture_camera)); options.add(fragment.getString(R.string.actfm_picture_gallery)); @@ -105,7 +105,7 @@ public class ActFmCameraModule { @SuppressWarnings("nls") @Override public void onClick(DialogInterface d, int which) { - if(which == 0 && cameraAvailable) { + if (which == 0 && cameraAvailable) { lastTempFile = getTempFile(fragment.getActivity()); if (lastTempFile != null) cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(lastTempFile)); @@ -124,15 +124,15 @@ public class ActFmCameraModule { // show a menu of available options new AlertDialog.Builder(fragment.getActivity()) - .setAdapter(adapter, listener) - .show().setOwnerActivity(fragment.getActivity()); + .setAdapter(adapter, listener) + .show().setOwnerActivity(fragment.getActivity()); } @SuppressWarnings("nls") private static File getTempFile(Activity activity) { try { String storageState = Environment.getExternalStorageState(); - if(storageState.equals(Environment.MEDIA_MOUNTED)) { + if (storageState.equals(Environment.MEDIA_MOUNTED)) { String path = Environment.getExternalStorageDirectory().getName() + File.separatorChar + "Android/data/" + activity.getPackageName() + "/files/"; File photoFile = File.createTempFile("comment_pic_" + DateUtilities.now(), ".jpg", new File(path)); return photoFile; @@ -148,11 +148,11 @@ public class ActFmCameraModule { } private static Bitmap bitmapFromUri(Activity activity, Uri uri) { - String[] projection = { MediaStore.Images.Media.DATA }; + String[] projection = {MediaStore.Images.Media.DATA}; Cursor cursor = activity.managedQuery(uri, projection, null, null, null); String path; - if(cursor != null) { + if (cursor != null) { int column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); @@ -165,28 +165,27 @@ public class ActFmCameraModule { } public static boolean activityResult(Activity activity, int requestCode, int resultCode, Intent data, - CameraResultCallback cameraResult) { - if(requestCode == ActFmCameraModule.REQUEST_CODE_CAMERA && resultCode == Activity.RESULT_OK) { + CameraResultCallback cameraResult) { + if (requestCode == ActFmCameraModule.REQUEST_CODE_CAMERA && resultCode == Activity.RESULT_OK) { Bitmap bitmap; if (data == null) { // large from camera if (lastTempFile != null) { bitmap = bitmapFromUri(activity, Uri.fromFile(lastTempFile)); lastTempFile.deleteOnExit(); lastTempFile = null; - } - else + } else bitmap = null; } else bitmap = data.getParcelableExtra("data"); //$NON-NLS-1$ - if(bitmap != null) { + if (bitmap != null) { activity.setResult(Activity.RESULT_OK); cameraResult.handleCameraResult(bitmap); } return true; - } else if(requestCode == ActFmCameraModule.REQUEST_CODE_PICTURE && resultCode == Activity.RESULT_OK) { + } else if (requestCode == ActFmCameraModule.REQUEST_CODE_PICTURE && resultCode == Activity.RESULT_OK) { Uri uri = data.getData(); Bitmap bitmap = bitmapFromUri(activity, uri); - if(bitmap != null) { + if (bitmap != null) { activity.setResult(Activity.RESULT_OK); cameraResult.handleCameraResult(bitmap); } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmGoogleAuthActivity.java b/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmGoogleAuthActivity.java index e7a87e4a2..427f4f4f3 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmGoogleAuthActivity.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmGoogleAuthActivity.java @@ -5,10 +5,6 @@ */ package com.todoroo.astrid.actfm; -import java.io.IOException; -import java.util.ArrayList; -import java.util.concurrent.TimeUnit; - import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AccountManagerCallback; @@ -32,12 +28,15 @@ import com.todoroo.andlib.service.ContextManager; import com.todoroo.andlib.utility.DialogUtilities; import com.todoroo.astrid.service.StatisticsService; +import java.io.IOException; +import java.util.ArrayList; +import java.util.concurrent.TimeUnit; + /** * This activity allows users to sign in or log in to Google Tasks * through the Android account manager * * @author Sam Bosley - * */ public class ActFmGoogleAuthActivity extends ListActivity { @@ -126,7 +125,7 @@ public class ActFmGoogleAuthActivity extends ListActivity { @Override public void run() { int error = e instanceof IOException ? R.string.gtasks_GLA_errorIOAuth : - R.string.gtasks_GLA_errorAuth; + R.string.gtasks_GLA_errorAuth; Toast.makeText(ActFmGoogleAuthActivity.this, error, Toast.LENGTH_LONG).show(); @@ -180,7 +179,7 @@ public class ActFmGoogleAuthActivity extends ListActivity { @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); - if(requestCode == REQUEST_AUTHENTICATE && resultCode == RESULT_OK){ + if (requestCode == REQUEST_AUTHENTICATE && resultCode == RESULT_OK) { final ProgressDialog pd = DialogUtilities.progressDialog(this, this.getString(R.string.gtasks_GLA_authenticating)); pd.show(); final Account a = accountManager.getAccountByName(accountName); diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmLoginActivity.java b/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmLoginActivity.java index 195fde17c..3ea766d00 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmLoginActivity.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmLoginActivity.java @@ -5,15 +5,6 @@ */ package com.todoroo.astrid.actfm; -import java.io.IOException; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map.Entry; -import java.util.Random; -import java.util.Set; - -import org.json.JSONObject; - import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; @@ -115,11 +106,19 @@ import com.todoroo.astrid.subtasks.SubtasksHelper; import com.todoroo.astrid.subtasks.SubtasksHelper.TreeRemapHelper; import com.todoroo.astrid.tags.TaskToTagMetadata; +import org.json.JSONObject; + +import java.io.IOException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map.Entry; +import java.util.Random; +import java.util.Set; + /** * This activity allows users to sign in or log in to Astrid.com * * @author Tim Su - * */ public class ActFmLoginActivity extends SherlockFragmentActivity { @@ -160,7 +159,8 @@ public class ActFmLoginActivity extends SherlockFragmentActivity { private TagMetadataDao tagMetadataDao; - @Autowired protected SyncV2Service syncService; + @Autowired + protected SyncV2Service syncService; private final ActFmInvoker actFmInvoker = new ActFmInvoker(); private Random rand; @@ -196,7 +196,7 @@ public class ActFmLoginActivity extends SherlockFragmentActivity { ContextManager.setContext(this); setContentView(getContentViewResource()); - if(getTitleResource() != 0) + if (getTitleResource() != 0) setTitle(getTitleResource()); if (getSupportActionBar() != null) @@ -275,14 +275,15 @@ public class ActFmLoginActivity extends SherlockFragmentActivity { protected SpannableString getLinkStringWithCustomInterval(String base, String linkComponent, - int start, int endOffset, final OnClickListener listener) { - SpannableString link = new SpannableString (String.format("%s %s", //$NON-NLS-1$ + int start, int endOffset, final OnClickListener listener) { + SpannableString link = new SpannableString(String.format("%s %s", //$NON-NLS-1$ base, linkComponent)); ClickableSpan linkSpan = new ClickableSpan() { @Override public void onClick(View widget) { listener.onClick(widget); } + @Override public void updateDrawState(TextPaint ds) { ds.setUnderlineText(true); @@ -297,13 +298,13 @@ public class ActFmLoginActivity extends SherlockFragmentActivity { protected void initializeUI() { errors = (TextView) findViewById(R.id.error); LoginButton loginButton = (LoginButton) findViewById(R.id.fb_login); - if(loginButton == null) + if (loginButton == null) return; loginButton.setReadPermissions(Arrays.asList("email", "offline_access")); View googleLogin = findViewById(R.id.gg_login); - if(AmazonMarketStrategy.isKindleFire()) + if (AmazonMarketStrategy.isKindleFire()) googleLogin.setVisibility(View.GONE); googleLogin.setOnClickListener(googleListener); @@ -382,22 +383,22 @@ public class ActFmLoginActivity extends SherlockFragmentActivity { bodyScroll).setIcon(R.drawable.icon_32).setTitle( R.string.actfm_ALA_signup_title).setPositiveButton( android.R.string.ok, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dlg, int which) { - String firstName = firstNameField.getText().toString(); - String lastName =lastNameField.getText().toString(); - - AndroidUtilities.hideSoftInputForViews(ActFmLoginActivity.this, firstNameField, lastNameField, email); - authenticate(email.getText().toString(), - firstName, lastName, ActFmInvoker.PROVIDER_PASSWORD, generateRandomPassword()); - StatisticsService.reportEvent(StatisticsConstants.ACTFM_SIGNUP_PW); - } - }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dlg, int which) { - AndroidUtilities.hideSoftInputForViews(ActFmLoginActivity.this, firstNameField, lastNameField, email); - } - }).show(); + @Override + public void onClick(DialogInterface dlg, int which) { + String firstName = firstNameField.getText().toString(); + String lastName = lastNameField.getText().toString(); + + AndroidUtilities.hideSoftInputForViews(ActFmLoginActivity.this, firstNameField, lastNameField, email); + authenticate(email.getText().toString(), + firstName, lastName, ActFmInvoker.PROVIDER_PASSWORD, generateRandomPassword()); + StatisticsService.reportEvent(StatisticsConstants.ACTFM_SIGNUP_PW); + } + }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dlg, int which) { + AndroidUtilities.hideSoftInputForViews(ActFmLoginActivity.this, firstNameField, lastNameField, email); + } + }).show(); } }; @@ -449,20 +450,20 @@ public class ActFmLoginActivity extends SherlockFragmentActivity { bodyScroll).setIcon(R.drawable.icon_32).setTitle( R.string.actfm_ALA_login_title).setPositiveButton( android.R.string.ok, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dlg, int which) { - AndroidUtilities.hideSoftInputForViews(ActFmLoginActivity.this, email, password); - authenticate(email.getText().toString(), - "", "", ActFmInvoker.PROVIDER_PASSWORD, //$NON-NLS-1$//$NON-NLS-2$ - password.getText().toString()); - StatisticsService.reportEvent(StatisticsConstants.ACTFM_LOGIN_PW); - } - }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dlg, int which) { - AndroidUtilities.hideSoftInputForViews(ActFmLoginActivity.this, email, password); - } - }).show(); + @Override + public void onClick(DialogInterface dlg, int which) { + AndroidUtilities.hideSoftInputForViews(ActFmLoginActivity.this, email, password); + authenticate(email.getText().toString(), + "", "", ActFmInvoker.PROVIDER_PASSWORD, //$NON-NLS-1$//$NON-NLS-2$ + password.getText().toString()); + StatisticsService.reportEvent(StatisticsConstants.ACTFM_LOGIN_PW); + } + }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dlg, int which) { + AndroidUtilities.hideSoftInputForViews(ActFmLoginActivity.this, email, password); + } + }).show(); } }; @@ -507,9 +508,9 @@ public class ActFmLoginActivity extends SherlockFragmentActivity { String oSimilar = "oO0"; String puncSimilar = ".,"; - boolean match = (iSimilar.indexOf(last) > 0 && iSimilar.indexOf(check) > 0) - || (oSimilar.indexOf(last) > 0 && oSimilar.indexOf(check) > 0) - || (puncSimilar.indexOf(last) > 0 && puncSimilar.indexOf(check) > 0); + boolean match = (iSimilar.indexOf(last) > 0 && iSimilar.indexOf(check) > 0) + || (oSimilar.indexOf(last) > 0 && oSimilar.indexOf(check) > 0) + || (puncSimilar.indexOf(last) > 0 && puncSimilar.indexOf(check) > 0); if (match) return false; @@ -541,18 +542,18 @@ public class ActFmLoginActivity extends SherlockFragmentActivity { private void facebookSuccess(Session session) { progressDialog = DialogUtilities.progressDialog(this, getString(R.string.DLG_please_wait)); - Request request = Request.newMeRequest(session, new GraphUserCallback() { - @Override - public void onCompleted(GraphUser user, Response response) { - try { - String email = user.getInnerJSONObject().optString("email"); //$NON-NLS-1$ - authenticate(email, user.getFirstName(), user.getLastName(), ActFmInvoker.PROVIDER_FACEBOOK, Session.getActiveSession().getAccessToken()); - } catch (Exception e) { - handleError(e); - } - } - }); - request.executeAsync(); + Request request = Request.newMeRequest(session, new GraphUserCallback() { + @Override + public void onCompleted(GraphUser user, Response response) { + try { + String email = user.getInnerJSONObject().optString("email"); //$NON-NLS-1$ + authenticate(email, user.getFirstName(), user.getLastName(), ActFmInvoker.PROVIDER_FACEBOOK, Session.getActiveSession().getAccessToken()); + } catch (Exception e) { + handleError(e); + } + } + }); + request.executeAsync(); } private UiLifecycleHelper uiHelper; @@ -570,7 +571,7 @@ public class ActFmLoginActivity extends SherlockFragmentActivity { @SuppressWarnings("nls") public void authenticate(final String email, final String firstName, final String lastName, final String provider, - final String secret) { + final String secret) { if (progressDialog == null) progressDialog = DialogUtilities.progressDialog(this, getString(R.string.DLG_please_wait)); @@ -663,7 +664,8 @@ public class ActFmLoginActivity extends SherlockFragmentActivity { } }).start(); } - }); + } + ); } else { finishSignIn(result, token, false); } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmPreferences.java b/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmPreferences.java index 54bf6da23..f9afeeb6b 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmPreferences.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmPreferences.java @@ -39,12 +39,13 @@ import com.todoroo.astrid.utility.Constants; * initiate actions from the menu. * * @author timsu - * */ public class ActFmPreferences extends SyncProviderPreferences { - @Autowired ActFmPreferenceService actFmPreferenceService; - @Autowired GtasksPreferenceService gtasksPreferenceService; + @Autowired + ActFmPreferenceService actFmPreferenceService; + @Autowired + GtasksPreferenceService gtasksPreferenceService; @Override public int getPreferenceResource() { @@ -145,12 +146,11 @@ public class ActFmPreferences extends SyncProviderPreferences { title += email; } status.setTitle(getString(R.string.actfm_status_title_logged_in, title)); - } - else + } else status.setTitle(R.string.sync_SPr_group_status); if (r.getString(R.string.actfm_https_key).equals(preference.getKey())) { - if ((Boolean)value) + if ((Boolean) value) preference.setSummary(R.string.actfm_https_enabled); else preference.setSummary(R.string.actfm_https_disabled); @@ -174,7 +174,7 @@ public class ActFmPreferences extends SyncProviderPreferences { r.getString(R.string.sync_forget_confirm), new OnClickListener() { @Override public void onClick(DialogInterface dialog, - int which) { + int which) { logOut(); initializePreference(getPreferenceScreen()); } @@ -182,7 +182,7 @@ public class ActFmPreferences extends SyncProviderPreferences { return true; } }); - if(!loggedIn) { + if (!loggedIn) { getPreferenceScreen().removePreference(preference); } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmSyncActionExposer.java b/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmSyncActionExposer.java index 229a42e62..bcbe524f8 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmSyncActionExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmSyncActionExposer.java @@ -20,11 +20,11 @@ import com.todoroo.astrid.service.AstridDependencyInjector; /** * Exposes sync action - * */ public class ActFmSyncActionExposer extends BroadcastReceiver { - @Autowired ActFmPreferenceService actFmPreferenceService; + @Autowired + ActFmPreferenceService actFmPreferenceService; static { AstridDependencyInjector.initialize(); @@ -36,7 +36,7 @@ public class ActFmSyncActionExposer extends BroadcastReceiver { DependencyInjectionService.getInstance().inject(this); // if we aren't logged in, don't expose sync action - if(!actFmPreferenceService.isLoggedIn()) + if (!actFmPreferenceService.isLoggedIn()) return; SyncAction syncAction = new SyncAction(context.getString(R.string.actfm_APr_header), diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/CommentsActivity.java b/astrid/plugin-src/com/todoroo/astrid/actfm/CommentsActivity.java index af812cd4d..bcae97ea2 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/CommentsActivity.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/CommentsActivity.java @@ -49,10 +49,10 @@ public class CommentsActivity extends AstridActivity { @Override public boolean onOptionsItemSelected(MenuItem item) { - switch(item.getItemId()) { - case android.R.id.home: - finish(); - break; + switch (item.getItemId()) { + case android.R.id.home: + finish(); + break; } return super.onOptionsItemSelected(item); } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/CommentsFragment.java b/astrid/plugin-src/com/todoroo/astrid/actfm/CommentsFragment.java index d84650ac1..939fc9200 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/CommentsFragment.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/CommentsFragment.java @@ -5,11 +5,6 @@ */ package com.todoroo.astrid.actfm; -import java.util.List; - -import org.json.JSONArray; -import org.json.JSONObject; - import android.app.Activity; import android.content.Intent; import android.content.res.Resources; @@ -58,11 +53,16 @@ import com.todoroo.astrid.data.UserActivity; import com.todoroo.astrid.helper.AsyncImageView; import com.todoroo.astrid.service.StatisticsService; +import org.json.JSONArray; +import org.json.JSONObject; + +import java.util.List; + import edu.mit.mobile.android.imagecache.ImageCache; public abstract class CommentsFragment extends SherlockListFragment { -// private TagData tagData; + // private TagData tagData; protected UpdateAdapter updateAdapter; protected EditText addCommentField; protected ViewGroup listHeader; @@ -84,9 +84,12 @@ public abstract class CommentsFragment extends SherlockListFragment { protected Resources resources; - @Autowired ActFmSyncService actFmSyncService; - @Autowired ActFmPreferenceService actFmPreferenceService; - @Autowired UserActivityDao userActivityDao; + @Autowired + ActFmSyncService actFmSyncService; + @Autowired + ActFmPreferenceService actFmPreferenceService; + @Autowired + UserActivityDao userActivityDao; public CommentsFragment() { DependencyInjectionService.getInstance().inject(this); @@ -95,7 +98,7 @@ public abstract class CommentsFragment extends SherlockListFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View v = inflater.inflate(getLayout(), container, false); @@ -172,7 +175,7 @@ public abstract class CommentsFragment extends SherlockListFragment { addCommentField.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView view, int actionId, KeyEvent event) { - if(actionId == EditorInfo.IME_NULL && addCommentField.getText().length() > 0) { + if (actionId == EditorInfo.IME_NULL && addCommentField.getText().length() > 0) { addComment(); return true; } @@ -184,10 +187,12 @@ public abstract class CommentsFragment extends SherlockListFragment { public void afterTextChanged(Editable s) { commentButton.setVisibility((s.length() > 0) ? View.VISIBLE : View.GONE); } + @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // } + @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // @@ -235,7 +240,7 @@ public abstract class CommentsFragment extends SherlockListFragment { Cursor cursor = null; ListView listView = ((ListView) view.findViewById(android.R.id.list)); - if(updateAdapter == null) { + if (updateAdapter == null) { cursor = getCursor(); activity.startManagingCursor(cursor); String source = getSourceIdentifier(); @@ -262,11 +267,10 @@ public abstract class CommentsFragment extends SherlockListFragment { View activityContainer = view.findViewById(R.id.no_activity_container); if (cursor.getCount() == 0) { activityContainer.setVisibility(View.VISIBLE); - TextView textView = (TextView)activityContainer.findViewById(R.id.no_activity_message); - if(actFmPreferenceService.isLoggedIn()) { + TextView textView = (TextView) activityContainer.findViewById(R.id.no_activity_message); + if (actFmPreferenceService.isLoggedIn()) { textView.setText(activity.getString(R.string.ENA_no_comments)); - } - else { + } else { textView.setText(activity.getString(R.string.UpS_no_activity_log_in)); activityContainer.setOnClickListener(new OnClickListener() { @@ -278,8 +282,7 @@ public abstract class CommentsFragment extends SherlockListFragment { }); } listView.setVisibility(View.GONE); - } - else { + } else { activityContainer.setVisibility(View.GONE); listView.setVisibility(View.VISIBLE); } @@ -351,19 +354,19 @@ public abstract class CommentsFragment extends SherlockListFragment { @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - if(menu.size() > 0) + if (menu.size() > 0) return; MenuItem item; boolean showCommentsRefresh = actFmPreferenceService.isLoggedIn(); if (showCommentsRefresh) { - Activity activity = getActivity(); + Activity activity = getActivity(); if (activity instanceof TaskListActivity) { TaskListActivity tla = (TaskListActivity) activity; showCommentsRefresh = tla.getTaskEditFragment() == null; } } - if(showCommentsRefresh) { + if (showCommentsRefresh) { item = menu.add(Menu.NONE, MENU_REFRESH_ID, Menu.NONE, R.string.ENA_refresh_comments); item.setIcon(R.drawable.icn_menu_refresh_dark); @@ -375,13 +378,14 @@ public abstract class CommentsFragment extends SherlockListFragment { // handle my own menus switch (item.getItemId()) { - case MENU_REFRESH_ID: { + case MENU_REFRESH_ID: { - refreshActivity(true); - return true; - } + refreshActivity(true); + return true; + } - default: return false; + default: + return false; } } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/EditPeopleControlSet.java b/astrid/plugin-src/com/todoroo/astrid/actfm/EditPeopleControlSet.java index 1ca214b6a..d4bf272d7 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/EditPeopleControlSet.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/EditPeopleControlSet.java @@ -5,14 +5,6 @@ */ package com.todoroo.astrid.actfm; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - import android.app.Activity; import android.content.Context; import android.content.DialogInterface; @@ -74,6 +66,14 @@ import com.todoroo.astrid.ui.PeopleContainer.ParseSharedException; import com.todoroo.astrid.ui.PopupControlSet; import com.todoroo.astrid.utility.ResourceDrawableCache; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; + public class EditPeopleControlSet extends PopupControlSet { public static final String EXTRA_TASK_ID = "task"; //$NON-NLS-1$ @@ -82,21 +82,29 @@ public class EditPeopleControlSet extends PopupControlSet { private Task task; - @Autowired ActFmPreferenceService actFmPreferenceService; + @Autowired + ActFmPreferenceService actFmPreferenceService; - @Autowired ActFmSyncService actFmSyncService; + @Autowired + ActFmSyncService actFmSyncService; - @Autowired TaskService taskService; + @Autowired + TaskService taskService; - @Autowired UserDao userDao; + @Autowired + UserDao userDao; - @Autowired MetadataService metadataService; + @Autowired + MetadataService metadataService; - @Autowired ExceptionService exceptionService; + @Autowired + ExceptionService exceptionService; - @Autowired TagDataService tagDataService; + @Autowired + TagDataService tagDataService; - @Autowired ABChooser abChooser; + @Autowired + ABChooser abChooser; private final Fragment fragment; @@ -174,7 +182,7 @@ public class EditPeopleControlSet extends PopupControlSet { TodorooCursor tags = TagService.getInstance().getTagDataForTask(task.getId(), TagData.NAME, TagData.MEMBER_COUNT, TagData.MEMBERS, TagData.USER); try { TagData tagData = new TagData(); - for(tags.moveToFirst(); !tags.isAfterLast(); tags.moveToNext()) { + for (tags.moveToFirst(); !tags.isAfterLast(); tags.moveToNext()) { tagData.readFromCursor(tags); addMembersFromTagData(tagData, sharedPeople); } @@ -199,7 +207,7 @@ public class EditPeopleControlSet extends PopupControlSet { JSONObject user = members.getJSONObject(i); sharedPeople.add(user); } - if(!TextUtils.isEmpty(tagData.getValue(TagData.USER))) { + if (!TextUtils.isEmpty(tagData.getValue(TagData.USER))) { JSONObject user = new JSONObject(tagData.getValue(TagData.USER)); sharedPeople.add(user); } @@ -256,7 +264,7 @@ public class EditPeopleControlSet extends PopupControlSet { coreUsersJson.add(myself); boolean hasTags = t.getTransitory("tags") != null && - ((HashSet)t.getTransitory("tags")).size() > 0; + ((HashSet) t.getTransitory("tags")).size() > 0; boolean addUnassigned = actFmPreferenceService.isLoggedIn() && hasTags; if (addUnassigned) { JSONObject unassigned = new JSONObject(); @@ -265,7 +273,7 @@ public class EditPeopleControlSet extends PopupControlSet { coreUsersJson.add(unassigned); } - if(Task.isRealUserId(t.getValue(Task.USER_ID))) { + if (Task.isRealUserId(t.getValue(Task.USER_ID))) { try { JSONObject user = new JSONObject(t.getValue(Task.USER)); coreUsersJson.add(0, user); @@ -292,7 +300,7 @@ public class EditPeopleControlSet extends PopupControlSet { contactPickerUser = new AssignedToUser(activity.getString(R.string.actfm_EPA_choose_contact), new JSONObject().put("default_picture", R.drawable.icn_friends) - .put(CONTACT_CHOOSER_USER, true)); + .put(CONTACT_CHOOSER_USER, true)); int contactsIndex = addUnassigned ? 2 : 1; boolean addContactPicker = Preferences.getBoolean(R.string.p_use_contact_picker, true) && contactPickerAvailable(); if (addContactPicker) @@ -354,19 +362,19 @@ public class EditPeopleControlSet extends PopupControlSet { @SuppressWarnings("nls") private ArrayList convertJsonUsersToAssignedUsers(ArrayList jsonUsers, - HashSet userIds, HashSet emails, HashMap names) { + HashSet userIds, HashSet emails, HashMap names) { ArrayList users = new ArrayList(); - for(int i = 0; i < jsonUsers.size(); i++) { + for (int i = 0; i < jsonUsers.size(); i++) { JSONObject person = jsonUsers.get(i); - if(person == null) + if (person == null) continue; String id = getLongOrStringId(person, Task.USER_ID_EMAIL); - if(ActFmPreferenceService.userId().equals(id) || ((Task.USER_ID_UNASSIGNED.equals(id) || Task.isRealUserId(id)) && userIds.contains(id))) + if (ActFmPreferenceService.userId().equals(id) || ((Task.USER_ID_UNASSIGNED.equals(id) || Task.isRealUserId(id)) && userIds.contains(id))) continue; userIds.add(id); String email = person.optString("email"); - if(!TextUtils.isEmpty(email) && emails.contains(email)) + if (!TextUtils.isEmpty(email) && emails.contains(email)) continue; emails.add(email); @@ -378,16 +386,16 @@ public class EditPeopleControlSet extends PopupControlSet { AssignedToUser atu = new AssignedToUser(name, person); users.add(atu); - if(names.containsKey(name)) { + if (names.containsKey(name)) { AssignedToUser user = names.get(name); - if(user != null && user.user.has("email")) { + if (user != null && user.user.has("email")) { user.label += " (" + user.user.optString("email") + ")"; names.put(name, null); } - if(!TextUtils.isEmpty(email)) + if (!TextUtils.isEmpty(email)) atu.label += " (" + email + ")"; - } else if(TextUtils.isEmpty(name) || "null".equals(name)) { - if(!TextUtils.isEmpty(email)) + } else if (TextUtils.isEmpty(name) || "null".equals(name)) { + if (!TextUtils.isEmpty(email)) atu.label = email; else users.remove(atu); @@ -470,12 +478,11 @@ public class EditPeopleControlSet extends PopupControlSet { } - private class AssignedUserAdapter extends ArrayAdapter { private final int positionOffset; - public AssignedUserAdapter(Context context, ArrayList people, int positionOffset) { + public AssignedUserAdapter(Context context, ArrayList people, int positionOffset) { super(context, R.layout.assigned_adapter_row, people); this.positionOffset = positionOffset; } @@ -483,7 +490,7 @@ public class EditPeopleControlSet extends PopupControlSet { @SuppressWarnings("nls") @Override public View getView(int position, View convertView, ViewGroup parent) { - if(convertView == null) + if (convertView == null) convertView = activity.getLayoutInflater().inflate(R.layout.assigned_adapter_row, parent, false); CheckedTextView ctv = (CheckedTextView) convertView.findViewById(android.R.id.text1); super.getView(position, ctv, parent); @@ -514,7 +521,7 @@ public class EditPeopleControlSet extends PopupControlSet { assignedList.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView arg0, View arg1, int position, - long id) { + long id) { AssignedToUser user = (AssignedToUser) assignedList.getAdapter().getItem(position); if (user.user.has(CONTACT_CHOOSER_USER)) { @@ -597,19 +604,20 @@ public class EditPeopleControlSet extends PopupControlSet { /** * Save sharing settings + * * @param toast toast to show after saving is finished * @return false if login is required & save should be halted */ @SuppressWarnings("nls") public boolean saveSharingSettings(String toast) { - if(task == null) + if (task == null) return false; boolean dirty = false; try { JSONObject userJson = null; TextView assignedView = null; - if(!TextUtils.isEmpty(assignedCustom.getText())) { + if (!TextUtils.isEmpty(assignedCustom.getText())) { userJson = PeopleContainer.createUserJson(assignedCustom); assignedView = assignedCustom; } else { @@ -631,12 +639,12 @@ public class EditPeopleControlSet extends PopupControlSet { activity.getString(R.string.actfm_EPA_invalid_email, userJson.optString("email"))); } - if(userJson == null || Task.USER_ID_SELF.equals(getLongOrStringId(userJson, Task.USER_ID_EMAIL))) { + if (userJson == null || Task.USER_ID_SELF.equals(getLongOrStringId(userJson, Task.USER_ID_EMAIL))) { dirty = Task.USER_ID_SELF.equals(task.getValue(Task.USER_ID)) ? dirty : true; task.setValue(Task.USER_ID, Task.USER_ID_SELF); task.setValue(Task.USER, ""); assignedToMe = true; - } else if(Task.USER_ID_UNASSIGNED.equals(getLongOrStringId(userJson, Task.USER_ID_SELF))) { + } else if (Task.USER_ID_UNASSIGNED.equals(getLongOrStringId(userJson, Task.USER_ID_SELF))) { dirty = Task.USER_ID_UNASSIGNED.equals(task.getValue(Task.USER_ID)) ? dirty : true; task.setValue(Task.USER_ID, Task.USER_ID_UNASSIGNED); task.setValue(Task.USER, ""); @@ -645,7 +653,7 @@ public class EditPeopleControlSet extends PopupControlSet { String taskUserEmail = ""; try { @SuppressWarnings("deprecation") // For backwards compatibility - JSONObject taskUser = new JSONObject(task.getValue(Task.USER)); + JSONObject taskUser = new JSONObject(task.getValue(Task.USER)); taskUserId = getLongOrStringId(taskUser, Task.USER_ID_EMAIL); taskUserEmail = taskUser.optString("email"); } catch (JSONException e) { @@ -668,7 +676,7 @@ public class EditPeopleControlSet extends PopupControlSet { task.setValue(Task.USER, ""); } - if(dirty && !actFmPreferenceService.isLoggedIn()) { + if (dirty && !actFmPreferenceService.isLoggedIn()) { DialogInterface.OnClickListener okListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface d, int which) { @@ -701,7 +709,7 @@ public class EditPeopleControlSet extends PopupControlSet { return true; } catch (ParseSharedException e) { - if(e.view != null) { + if (e.view != null) { e.view.setTextColor(Color.RED); e.view.requestFocus(); } @@ -716,6 +724,7 @@ public class EditPeopleControlSet extends PopupControlSet { /** * Warning - only valid after a call to saveSharingSettings + * * @return */ public boolean isAssignedToMe() { @@ -727,7 +736,7 @@ public class EditPeopleControlSet extends PopupControlSet { */ public boolean willBeAssignedToMe() { JSONObject userJson = null; - if(!TextUtils.isEmpty(assignedCustom.getText())) { + if (!TextUtils.isEmpty(assignedCustom.getText())) { userJson = PeopleContainer.createUserJson(assignedCustom); } else { if (!hasLoadedUI() || assignedList.getCheckedItemPosition() == ListView.INVALID_POSITION) { @@ -741,7 +750,7 @@ public class EditPeopleControlSet extends PopupControlSet { userJson = item.user; } - if(userJson == null || Task.USER_ID_SELF.equals(getLongOrStringId(userJson, Task.USER_ID_EMAIL))) { + if (userJson == null || Task.USER_ID_SELF.equals(getLongOrStringId(userJson, Task.USER_ID_EMAIL))) { return true; } @@ -752,10 +761,13 @@ public class EditPeopleControlSet extends PopupControlSet { return assignedDisplay.getText().toString(); } - /** Resume save - * @param data */ + /** + * Resume save + * + * @param data + */ public void onActivityResult(int requestCode, int resultCode, Intent data) { - if(requestCode == loginRequestCode && resultCode == Activity.RESULT_OK) { + if (requestCode == loginRequestCode && resultCode == Activity.RESULT_OK) { // clear user values & reset them to trigger a save task.clearValue(Task.USER_ID); task.clearValue(Task.USER); @@ -764,8 +776,8 @@ public class EditPeopleControlSet extends PopupControlSet { } else if (requestCode == TaskEditFragment.REQUEST_CODE_CONTACT && resultCode == Activity.RESULT_OK) { Uri contactData = data.getData(); String contactId = contactData.getLastPathSegment(); - String[] args = { contactId }; - String[] projection = { ContactsContract.CommonDataKinds.Email.DATA }; + String[] args = {contactId}; + String[] projection = {ContactsContract.CommonDataKinds.Email.DATA}; String selection = ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?"; //$NON-NLS-1$ Cursor emailCursor = activity.managedQuery(ContactsContract.CommonDataKinds.Email.CONTENT_URI, projection, selection, args, null); if (emailCursor.getCount() > 0) { @@ -773,7 +785,7 @@ public class EditPeopleControlSet extends PopupControlSet { int emailIndex = emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA); String email = emailCursor.getString(emailIndex); if (!TextUtils.isEmpty(email)) { - String[] nameProjection = { ContactsContract.Contacts.DISPLAY_NAME }; + String[] nameProjection = {ContactsContract.Contacts.DISPLAY_NAME}; Cursor nameCursor = activity.managedQuery(contactData, nameProjection, null, null, null); if (nameCursor.getCount() > 0) { nameCursor.moveToFirst(); @@ -851,7 +863,7 @@ public class EditPeopleControlSet extends PopupControlSet { protected void additionalDialogSetup() { super.additionalDialogSetup(); dialog.getWindow() - .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN - | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); + .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN + | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); } } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/TagCommentsFragment.java b/astrid/plugin-src/com/todoroo/astrid/actfm/TagCommentsFragment.java index a6dd77a6c..5ed009453 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/TagCommentsFragment.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/TagCommentsFragment.java @@ -129,8 +129,7 @@ public class TagCommentsFragment extends CommentsFragment { if (!TextUtils.isEmpty(description)) { descriptionTitle.setText(description); descriptionTitle.setVisibility(View.VISIBLE); - } - else { + } else { descriptionTitle.setVisibility(View.GONE); } @@ -175,7 +174,7 @@ public class TagCommentsFragment extends CommentsFragment { @Override protected void setLastViewed() { - if(tagData != null && RemoteModel.isValidUuid(tagData.getValue(TagData.UUID))) { + if (tagData != null && RemoteModel.isValidUuid(tagData.getValue(TagData.UUID))) { Preferences.setLong(UPDATES_LAST_VIEWED + tagData.getValue(TagData.UUID), DateUtilities.now()); Activity activity = getActivity(); if (activity instanceof TaskListActivity) diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/TagSettingsActivity.java b/astrid/plugin-src/com/todoroo/astrid/actfm/TagSettingsActivity.java index bc76afd39..cc9ffe0e4 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/TagSettingsActivity.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/TagSettingsActivity.java @@ -5,10 +5,6 @@ */ package com.todoroo.astrid.actfm; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - import android.app.Activity; import android.content.Context; import android.content.DialogInterface; @@ -72,6 +68,10 @@ import com.todoroo.astrid.utility.AstridPreferences; import com.todoroo.astrid.utility.ResourceDrawableCache; import com.todoroo.astrid.welcome.HelpInfoPopover; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + import edu.mit.mobile.android.imagecache.ImageCache; public class TagSettingsActivity extends SherlockFragmentActivity { @@ -92,19 +92,26 @@ public class TagSettingsActivity extends SherlockFragmentActivity { private TagData tagData; private Filter filter; // Used for creating shortcuts, only initialized if necessary - @Autowired TagService tagService; + @Autowired + TagService tagService; - @Autowired TagDataService tagDataService; + @Autowired + TagDataService tagDataService; - @Autowired ActFmSyncService actFmSyncService; + @Autowired + ActFmSyncService actFmSyncService; - @Autowired ActFmPreferenceService actFmPreferenceService; + @Autowired + ActFmPreferenceService actFmPreferenceService; - @Autowired ExceptionService exceptionService; + @Autowired + ExceptionService exceptionService; - @Autowired UserDao userDao; + @Autowired + UserDao userDao; - @Autowired TagMetadataDao tagMetadataDao; + @Autowired + TagMetadataDao tagMetadataDao; private PeopleContainer tagMembers; private AsyncImageView picture; @@ -158,7 +165,7 @@ public class TagSettingsActivity extends SherlockFragmentActivity { setUpSettingsPage(); - if(savedInstanceState != null && savedInstanceState.containsKey(MEMBERS_IN_PROGRESS)) { + if (savedInstanceState != null && savedInstanceState.containsKey(MEMBERS_IN_PROGRESS)) { final String members = savedInstanceState.getString(MEMBERS_IN_PROGRESS); new Thread(new Runnable() { @Override @@ -239,11 +246,10 @@ public class TagSettingsActivity extends SherlockFragmentActivity { }); if (isNewTag) { leaveListButton.setVisibility(View.GONE); - } - else if (tagData.getValue(TagData.MEMBER_COUNT) > 0) { + } else if (tagData.getValue(TagData.MEMBER_COUNT) > 0) { leaveListButton.setText(getString(R.string.tag_leave_button)); } - if(actFmPreferenceService.isLoggedIn()) { + if (actFmPreferenceService.isLoggedIn()) { findViewById(R.id.tag_silenced_container).setVisibility(View.VISIBLE); } @@ -329,7 +335,7 @@ public class TagSettingsActivity extends SherlockFragmentActivity { exceptionService.displayAndReportError(this, "save-people", e); return; } catch (ParseSharedException e) { - if(e.view != null) { + if (e.view != null) { e.view.setTextColor(Color.RED); e.view.requestFocus(); } @@ -339,8 +345,8 @@ public class TagSettingsActivity extends SherlockFragmentActivity { if (members == null) members = new JSONArray(); - if(members.length() > 0 && !actFmPreferenceService.isLoggedIn()) { - if(newName.length() > 0 && oldName.length() == 0) { + if (members.length() > 0 && !actFmPreferenceService.isLoggedIn()) { + if (newName.length() > 0 && oldName.length() == 0) { tagDataService.save(tagData); } @@ -376,7 +382,7 @@ public class TagSettingsActivity extends SherlockFragmentActivity { tagData.setValue(TagData.MEMBER_COUNT, members.length()); tagData.setFlag(TagData.FLAGS, TagData.FLAG_SILENT, isSilent.isChecked()); - InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); + InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(tagName.getWindowToken(), 0); tagDataService.save(tagData); @@ -399,8 +405,7 @@ public class TagSettingsActivity extends SherlockFragmentActivity { String tagPicture = RemoteModel.PictureHelper.getPictureHash(tagData); imageCache.put(tagPicture, bitmap); tagData.setValue(TagData.PICTURE, tagPicture); - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } } @@ -537,7 +542,7 @@ public class TagSettingsActivity extends SherlockFragmentActivity { @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); - if(tagMembers.getChildCount() > 1) { + if (tagMembers.getChildCount() > 1) { JSONArray members = tagMembers.toJSONArray(); outState.putString(MEMBERS_IN_PROGRESS, members.toString()); } @@ -555,7 +560,7 @@ public class TagSettingsActivity extends SherlockFragmentActivity { }; if (ActFmCameraModule.activityResult(this, requestCode, resultCode, data, callback)) { // Handled - } else if(requestCode == REQUEST_ACTFM_LOGIN && resultCode == Activity.RESULT_OK) { + } else if (requestCode == REQUEST_ACTFM_LOGIN && resultCode == Activity.RESULT_OK) { saveSettings(); } else { super.onActivityResult(requestCode, resultCode, data); @@ -590,24 +595,24 @@ public class TagSettingsActivity extends SherlockFragmentActivity { @Override public boolean onOptionsItemSelected(MenuItem item) { - switch(item.getItemId()) { - case MENU_DISCARD_ID: - finish(); - break; - case MENU_SAVE_ID: - saveSettings(); - break; - case android.R.id.home: - saveSettings(); - if (!isFinishing()) + switch (item.getItemId()) { + case MENU_DISCARD_ID: finish(); - break; + break; + case MENU_SAVE_ID: + saveSettings(); + break; + case android.R.id.home: + saveSettings(); + if (!isFinishing()) + finish(); + break; } return super.onOptionsItemSelected(item); } protected void showDeleteDialog(TagData td) { - if(td == null) + if (td == null) return; int string; @@ -620,11 +625,11 @@ public class TagSettingsActivity extends SherlockFragmentActivity { DialogUtilities.okCancelDialog(this, getString(string, td.getValue(TagData.NAME)), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - deleteTag(); - } - }, null ); + @Override + public void onClick(DialogInterface dialog, int which) { + deleteTag(); + } + }, null); } protected void deleteTag() { diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/TagViewFragment.java b/astrid/plugin-src/com/todoroo/astrid/actfm/TagViewFragment.java index 254b2871c..25e3157d2 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/TagViewFragment.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/TagViewFragment.java @@ -5,13 +5,6 @@ */ package com.todoroo.astrid.actfm; -import java.util.List; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - import android.app.Activity; import android.content.BroadcastReceiver; import android.content.ComponentName; @@ -90,6 +83,13 @@ import com.todoroo.astrid.utility.Flags; import com.todoroo.astrid.utility.ResourceDrawableCache; import com.todoroo.astrid.welcome.HelpInfoPopover; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; + public class TagViewFragment extends TaskListFragment { public static final String BROADCAST_TAG_ACTIVITY = AstridApiConstants.API_PACKAGE + ".TAG_ACTIVITY"; //$NON-NLS-1$ @@ -112,25 +112,35 @@ public class TagViewFragment extends TaskListFragment { protected TagData tagData; - @Autowired TagDataService tagDataService; + @Autowired + TagDataService tagDataService; - @Autowired TagService tagService; + @Autowired + TagService tagService; - @Autowired TagDataDao tagDataDao; + @Autowired + TagDataDao tagDataDao; - @Autowired ActFmSyncService actFmSyncService; + @Autowired + ActFmSyncService actFmSyncService; - @Autowired ActFmPreferenceService actFmPreferenceService; + @Autowired + ActFmPreferenceService actFmPreferenceService; - @Autowired SyncV2Service syncService; + @Autowired + SyncV2Service syncService; - @Autowired UserDao userDao; + @Autowired + UserDao userDao; - @Autowired MetadataDao metadataDao; + @Autowired + MetadataDao metadataDao; - @Autowired TagMetadataDao tagMetadataDao; + @Autowired + TagMetadataDao tagMetadataDao; - @Autowired TaskListMetadataDao taskListMetadataDao; + @Autowired + TaskListMetadataDao taskListMetadataDao; protected View taskListView; @@ -216,7 +226,7 @@ public class TagViewFragment extends TaskListFragment { @Override protected void addSyncRefreshMenuItem(Menu menu, int themeFlags) { - if(actFmPreferenceService.isLoggedIn()) { + if (actFmPreferenceService.isLoggedIn()) { addMenuItem(menu, R.string.actfm_TVA_menu_refresh, ThemeService.getDrawable(R.drawable.icn_menu_refresh, themeFlags), MENU_REFRESH_ID, true); } else { @@ -238,8 +248,8 @@ public class TagViewFragment extends TaskListFragment { @Override protected void initializeData() { - synchronized(this) { - if(dataLoaded) + synchronized (this) { + if (dataLoaded) return; dataLoaded = true; } @@ -253,7 +263,7 @@ public class TagViewFragment extends TaskListFragment { uuid = Long.toString(extras.getLong(EXTRA_TAG_REMOTE_ID)); - if(tag == null && RemoteModel.NO_UUID.equals(uuid)) + if (tag == null && RemoteModel.NO_UUID.equals(uuid)) return; TodorooCursor cursor; @@ -265,7 +275,7 @@ public class TagViewFragment extends TaskListFragment { try { tagData = new TagData(); - if(cursor.getCount() == 0) { + if (cursor.getCount() == 0) { tagData.setValue(TagData.NAME, tag); tagData.setValue(TagData.UUID, uuid); tagDataService.save(tagData); @@ -295,12 +305,12 @@ public class TagViewFragment extends TaskListFragment { @Override public void loadTaskListContent(boolean requery) { super.loadTaskListContent(requery); - if(taskAdapter == null || taskAdapter.getCursor() == null) + if (taskAdapter == null || taskAdapter.getCursor() == null) return; int count = taskAdapter.getCursor().getCount(); - if(tagData != null && sortFlags <= SortHelper.FLAG_REVERSE_SORT && + if (tagData != null && sortFlags <= SortHelper.FLAG_REVERSE_SORT && count != tagData.getValue(TagData.TASK_COUNT)) { tagData.setValue(TagData.TASK_COUNT, count); tagDataService.save(tagData); @@ -340,7 +350,7 @@ public class TagViewFragment extends TaskListFragment { return; if (tagData != null) { long lastAutosync = tagData.getValue(TagData.LAST_AUTOSYNC); - if(DateUtilities.now() - lastAutosync > AUTOSYNC_INTERVAL) { + if (DateUtilities.now() - lastAutosync > AUTOSYNC_INTERVAL) { tagData.setValue(TagData.LAST_AUTOSYNC, DateUtilities.now()); tagDataDao.saveExisting(tagData); refreshData(); @@ -348,15 +358,17 @@ public class TagViewFragment extends TaskListFragment { } } - /** refresh the list with latest data from the web */ + /** + * refresh the list with latest data from the web + */ private void refreshData() { if (actFmPreferenceService.isLoggedIn() && tagData != null && !RemoteModel.isUuidEmpty(tagData.getUuid())) { - ((TextView)taskListView.findViewById(android.R.id.empty)).setText(R.string.DLG_loading); + ((TextView) taskListView.findViewById(android.R.id.empty)).setText(R.string.DLG_loading); SyncMessageCallback callback = new SyncMessageCallback() { @Override public void runOnSuccess() { - synchronized(this) { + synchronized (this) { Activity activity = getActivity(); if (activity != null) { activity.runOnUiThread(new Runnable() { @@ -365,7 +377,7 @@ public class TagViewFragment extends TaskListFragment { try { reloadTagData(false); refresh(); - ((TextView)taskListView.findViewById(android.R.id.empty)).setText(R.string.TLA_no_items); + ((TextView) taskListView.findViewById(android.R.id.empty)).setText(R.string.TLA_no_items); } catch (Exception e) { // Can happen when swipe between lists is on } @@ -374,6 +386,7 @@ public class TagViewFragment extends TaskListFragment { } } } + @Override public void runOnErrors(List errors) { Activity activity = getActivity(); @@ -443,7 +456,8 @@ public class TagViewFragment extends TaskListFragment { tagMetadataDao.deleteWhere(TagMetadata.TAG_UUID.eq(uuid)); tla.switchToActiveTasks(); } - }); + } + ); } }); } @@ -466,7 +480,7 @@ public class TagViewFragment extends TaskListFragment { } if (tagData == null) return; - LinearLayout membersView = (LinearLayout)getView().findViewById(R.id.shared_with); + LinearLayout membersView = (LinearLayout) getView().findViewById(R.id.shared_with); membersView.setOnClickListener(settingsListener); boolean addedMembers = false; try { @@ -535,9 +549,9 @@ public class TagViewFragment extends TaskListFragment { if (addedMembers) { try { - // Handle creator + // Handle creator JSONObject owner; - if(!Task.USER_ID_SELF.equals(tagData.getValue(TagData.USER_ID))) { + if (!Task.USER_ID_SELF.equals(tagData.getValue(TagData.USER_ID))) { String userString = tagData.getValue(TagData.USER); if (!TextUtils.isEmpty(userString)) { owner = new JSONObject(tagData.getValue(TagData.USER)); @@ -585,8 +599,8 @@ public class TagViewFragment extends TaskListFragment { DisplayMetrics displayMetrics = new DisplayMetrics(); getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); AsyncImageView image = new AsyncImageView(getActivity()); - image.setLayoutParams(new LinearLayout.LayoutParams((int)(43 * displayMetrics.density), - (int)(43 * displayMetrics.density))); + image.setLayoutParams(new LinearLayout.LayoutParams((int) (43 * displayMetrics.density), + (int) (43 * displayMetrics.density))); image.setDefaultImageDrawable(ResourceDrawableCache.getImageDrawableFromId(resources, R.drawable.icn_default_person_image)); @@ -616,6 +630,7 @@ public class TagViewFragment extends TaskListFragment { private OnClickListener listenerForImage(final JSONObject member, final String id, final String displayName) { return new OnClickListener() { final String email = member.optString("email"); //$NON-NLS-1$ + @SuppressWarnings("deprecation") @Override public void onClick(View v) { @@ -688,9 +703,9 @@ public class TagViewFragment extends TaskListFragment { @SuppressWarnings("nls") @Override public void onReceive(Context context, Intent intent) { - if(!intent.hasExtra("tag_id")) + if (!intent.hasExtra("tag_id")) return; - if(tagData == null || !tagData.getValue(TagData.UUID).toString().equals(intent.getStringExtra("tag_id"))) + if (tagData == null || !tagData.getValue(TagData.UUID).toString().equals(intent.getStringExtra("tag_id"))) return; getActivity().runOnUiThread(new Runnable() { @@ -783,12 +798,12 @@ public class TagViewFragment extends TaskListFragment { public boolean handleOptionsMenuItemSelected(int id, Intent intent) { // handle my own menus switch (id) { - case MENU_REFRESH_ID: - refreshData(); - return true; - case MENU_LIST_SETTINGS_ID: - settingsListener.onClick(null); - return true; + case MENU_REFRESH_ID: + refreshData(); + return true; + case MENU_LIST_SETTINGS_ID: + settingsListener.onClick(null); + return true; } return super.handleOptionsMenuItemSelected(id, intent); @@ -803,7 +818,7 @@ public class TagViewFragment extends TaskListFragment { protected void toggleDragDrop(boolean newState) { Class customComponent; - if(newState) + if (newState) customComponent = SubtasksTagListFragment.class; else { filter.setFilterQueryOverride(null); @@ -813,7 +828,7 @@ public class TagViewFragment extends TaskListFragment { ((FilterWithCustomIntent) filter).customTaskList = new ComponentName(getActivity(), customComponent); extras.putParcelable(TOKEN_FILTER, filter); - ((AstridActivity)getActivity()).setupTasklistFragmentWithFilterAndCustomTaskList(filter, + ((AstridActivity) getActivity()).setupTasklistFragmentWithFilterAndCustomTaskList(filter, extras, customComponent); } @@ -821,7 +836,7 @@ public class TagViewFragment extends TaskListFragment { protected void refresh() { setUpMembersGallery(); loadTaskListContent(true); - ((TextView)taskListView.findViewById(android.R.id.empty)).setText(R.string.TLA_no_items); + ((TextView) taskListView.findViewById(android.R.id.empty)).setText(R.string.TLA_no_items); } } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/WaitingOnMeFragment.java b/astrid/plugin-src/com/todoroo/astrid/actfm/WaitingOnMeFragment.java index 68e2f8b13..3ea74d394 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/WaitingOnMeFragment.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/WaitingOnMeFragment.java @@ -1,7 +1,5 @@ package com.todoroo.astrid.actfm; -import java.util.concurrent.atomic.AtomicReference; - import android.database.Cursor; import android.graphics.Typeface; import android.text.TextUtils; @@ -22,6 +20,8 @@ import com.todoroo.astrid.dao.WaitingOnMeDao; import com.todoroo.astrid.data.Task; import com.todoroo.astrid.data.WaitingOnMe; +import java.util.concurrent.atomic.AtomicReference; + public class WaitingOnMeFragment extends TaskListFragment { @Autowired @@ -51,8 +51,8 @@ public class WaitingOnMeFragment extends TaskListFragment { private static class WaitingOnMeTaskAdapter extends TaskAdapter { public WaitingOnMeTaskAdapter(TaskListFragment fragment, int resource, - Cursor c, AtomicReference query, boolean autoRequery, - OnCompletedTaskListener onCompletedTaskListener) { + Cursor c, AtomicReference query, boolean autoRequery, + OnCompletedTaskListener onCompletedTaskListener) { super(fragment, resource, c, query, autoRequery, onCompletedTaskListener); } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmInvoker.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmInvoker.java index 2bb744451..95804a0e7 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmInvoker.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmInvoker.java @@ -5,23 +5,6 @@ */ package com.todoroo.astrid.actfm.sync; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.nio.charset.Charset; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.TimeZone; - -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.http.HttpEntity; -import org.apache.http.entity.mime.MultipartEntity; -import org.apache.http.entity.mime.content.StringBody; -import org.json.JSONException; -import org.json.JSONObject; - import android.text.TextUtils; import android.util.Log; @@ -36,23 +19,43 @@ import com.todoroo.andlib.utility.Pair; import com.todoroo.andlib.utility.Preferences; import com.todoroo.astrid.utility.Constants; +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.http.HttpEntity; +import org.apache.http.entity.mime.MultipartEntity; +import org.apache.http.entity.mime.content.StringBody; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.nio.charset.Charset; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.TimeZone; + @SuppressWarnings("nls") public class ActFmInvoker { - /** NOTE: these values are development values & will not work on production */ + /** + * NOTE: these values are development values & will not work on production + */ private static final String URL = "//10.0.2.2:3000/api/"; private static final String APP_ID = "a4732a32859dbcd3e684331acd36432c"; private static final String APP_SECRET = "e389bfc82a0d932332f9a8bd8203735f"; public static final String PROVIDER_FACEBOOK = "facebook"; - public static final String PROVIDER_GOOGLE= "google"; + public static final String PROVIDER_GOOGLE = "google"; public static final String PROVIDER_PASSWORD = "password"; private static final int API_VERSION = 7; public static final boolean SYNC_DEBUG = Constants.DEBUG || true; - @Autowired private RestClient restClient; + @Autowired + private RestClient restClient; private String token = null; @@ -68,6 +71,7 @@ public class ActFmInvoker { /** * Create new api invoker service with a token + * * @token access token */ public ActFmInvoker(String token) { @@ -85,7 +89,7 @@ public class ActFmInvoker { * Authentication user with Act.fm server, returning a token */ public JSONObject authenticate(String email, String firstName, String lastName, String provider, - String secret) throws ActFmServiceException, IOException { + String secret) throws ActFmServiceException, IOException { JSONObject result = invoke( "user_signin", "email", email, @@ -107,10 +111,8 @@ public class ActFmInvoker { /** * Invokes API method using HTTP GET * - * @param method - * API method to invoke - * @param getParameters - * Name/Value pairs. Values will be URL encoded. + * @param method API method to invoke + * @param getParameters Name/Value pairs. Values will be URL encoded. * @return response object */ public JSONObject invoke(String method, Object... getParameters) throws IOException, @@ -121,14 +123,12 @@ public class ActFmInvoker { /** * Invokes API method using HTTP GET * - * @param method - * API method to invoke - * @param getParameters - * Name/Value pairs. Values will be URL encoded. + * @param method API method to invoke + * @param getParameters Name/Value pairs. Values will be URL encoded. * @return response object */ public JSONObject invokeWithApi(String api, String method, Object... getParameters) throws IOException, - ActFmServiceException { + ActFmServiceException { try { String request = createFetchUrl(api, method, getParameters); @@ -140,7 +140,7 @@ public class ActFmInvoker { if (SYNC_DEBUG) AndroidUtilities.logJSONObject("act-fm-invoke-response", object); - if(object.getString("status").equals("error")) + if (object.getString("status").equals("error")) throw new ActFmServiceException(object.getString("message"), object); return object; } catch (JSONException e) { @@ -153,16 +153,13 @@ public class ActFmInvoker { /** * Invokes API method using HTTP POST * - * @param method - * API method to invoke - * @param data - * data to transmit - * @param getParameters - * Name/Value pairs. Values will be URL encoded. + * @param method API method to invoke + * @param data data to transmit + * @param getParameters Name/Value pairs. Values will be URL encoded. * @return response object */ public JSONObject post(String method, HttpEntity data, Object... getParameters) throws IOException, - ActFmServiceException { + ActFmServiceException { try { String request = createFetchUrl(null, method, getParameters); @@ -175,7 +172,7 @@ public class ActFmInvoker { if (SYNC_DEBUG) AndroidUtilities.logJSONObject("act-fm-post-response", object); - if(object.getString("status").equals("error")) + if (object.getString("status").equals("error")) throw new ActFmServiceException(object.getString("message"), object); return object; } catch (JSONException e) { @@ -186,11 +183,11 @@ public class ActFmInvoker { } public JSONObject postSync(String data, MultipartEntity entity, boolean changesHappened, String tok) throws IOException, - ActFmServiceException { + ActFmServiceException { try { String timeString = DateUtilities.timeToIso8601(DateUtilities.now(), true); - Object[] params = { "token", tok, "data", data, "time", timeString }; + Object[] params = {"token", tok, "data", data, "time", timeString}; if (changesHappened) { String gcm = Preferences.getStringValue(GCMIntentService.PREF_REGISTRATION); @@ -221,7 +218,7 @@ public class ActFmInvoker { if (SYNC_DEBUG) AndroidUtilities.logJSONObject("act-fm-post-response", object); - if(object.getString("status").equals("error")) + if (object.getString("status").equals("error")) throw new ActFmServiceException(object.getString("message"), object); return object; } catch (JSONException e) { @@ -233,6 +230,7 @@ public class ActFmInvoker { /** * Creates a URL for invoking an HTTP GET/POST on the given method + * * @param method * @param getParameters * @return @@ -241,21 +239,21 @@ public class ActFmInvoker { */ private String createFetchUrl(String api, String method, Object... getParameters) throws UnsupportedEncodingException, NoSuchAlgorithmException { ArrayList> params = new ArrayList>(); - for(int i = 0; i < getParameters.length; i += 2) { - if(getParameters[i+1] instanceof ArrayList) { - ArrayList list = (ArrayList) getParameters[i+1]; - for(int j = 0; j < list.size(); j++) + for (int i = 0; i < getParameters.length; i += 2) { + if (getParameters[i + 1] instanceof ArrayList) { + ArrayList list = (ArrayList) getParameters[i + 1]; + for (int j = 0; j < list.size(); j++) params.add(new Pair(getParameters[i].toString() + "[]", list.get(j))); } else - params.add(new Pair(getParameters[i].toString(), getParameters[i+1])); + params.add(new Pair(getParameters[i].toString(), getParameters[i + 1])); } params.add(new Pair("app_id", APP_ID)); boolean syncMethod = "synchronize".equals(method); if (!syncMethod) params.add(new Pair("time", System.currentTimeMillis() / 1000L)); - if(token != null) { + if (token != null) { boolean foundTokenKey = false; for (Pair curr : params) { if (curr.getLeft().equals("token")) { @@ -270,9 +268,9 @@ public class ActFmInvoker { Collections.sort(params, new Comparator>() { @Override public int compare(Pair object1, - Pair object2) { + Pair object2) { int result = object1.getLeft().compareTo(object2.getLeft()); - if(result == 0) + if (result == 0) return object1.getRight().toString().compareTo(object2.getRight().toString()); return result; } @@ -294,8 +292,8 @@ public class ActFmInvoker { requestBuilder.append(API_VERSION).append("/"); requestBuilder.append(method).append('?'); StringBuilder sigBuilder = new StringBuilder(method); - for(Pair entry : params) { - if(entry.getRight() == null) + for (Pair entry : params) { + if (entry.getRight() == null) continue; String key = entry.getLeft(); diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmPreferenceService.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmPreferenceService.java index 6772b08af..1b8c581ff 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmPreferenceService.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmPreferenceService.java @@ -5,9 +5,6 @@ */ package com.todoroo.astrid.actfm.sync; -import org.json.JSONException; -import org.json.JSONObject; - import android.text.TextUtils; import com.timsu.astrid.R; @@ -21,15 +18,19 @@ import com.todoroo.astrid.service.StatisticsService; import com.todoroo.astrid.sync.SyncProviderUtilities; import com.todoroo.astrid.utility.AstridPreferences; +import org.json.JSONException; +import org.json.JSONObject; + /** * Methods for working with GTasks preferences * * @author timsu - * */ public class ActFmPreferenceService extends SyncProviderUtilities { - /** add-on identifier */ + /** + * add-on identifier + */ public static final String IDENTIFIER = "actfm"; //$NON-NLS-1$ @Override @@ -50,7 +51,7 @@ public class ActFmPreferenceService extends SyncProviderUtilities { @Override public boolean shouldShowToast() { - if(Preferences.getBoolean(AstridPreferences.P_FIRST_TASK, true)) + if (Preferences.getBoolean(AstridPreferences.P_FIRST_TASK, true)) return false; return super.shouldShowToast(); } @@ -87,31 +88,49 @@ public class ActFmPreferenceService extends SyncProviderUtilities { } } - /** Act.fm current user id */ + /** + * Act.fm current user id + */ public static final String PREF_USER_ID = IDENTIFIER + "_user"; //$NON-NLS-1$ - /** Act.fm current user name */ + /** + * Act.fm current user name + */ public static final String PREF_NAME = IDENTIFIER + "_name"; //$NON-NLS-1$ - /** Act.fm current user first name */ + /** + * Act.fm current user first name + */ public static final String PREF_FIRST_NAME = IDENTIFIER + "_first_name"; //$NON-NLS-1$ - /** Act.fm current user last name */ + /** + * Act.fm current user last name + */ public static final String PREF_LAST_NAME = IDENTIFIER + "_last_name"; //$NON-NLS-1$ - /** Act.fm current user premium status */ + /** + * Act.fm current user premium status + */ public static final String PREF_PREMIUM = IDENTIFIER + "_premium"; //$NON-NLS-1$ - /** Local knowledge of current premium status */ + /** + * Local knowledge of current premium status + */ public static final String PREF_LOCAL_PREMIUM = IDENTIFIER + "_local_premium"; //$NON-NLS-1$ - /** Act.fm current user picture */ + /** + * Act.fm current user picture + */ public static final String PREF_PICTURE = IDENTIFIER + "_picture"; //$NON-NLS-1$ - /** Act.fm current user email */ + /** + * Act.fm current user email + */ public static final String PREF_EMAIL = IDENTIFIER + "_email"; //$NON-NLS-1$ - /** Act.fm last sync server time */ + /** + * Act.fm last sync server time + */ public static final String PREF_SERVER_TIME = IDENTIFIER + "_time"; //$NON-NLS-1$ private static JSONObject user = null; @@ -122,7 +141,7 @@ public class ActFmPreferenceService extends SyncProviderUtilities { } public synchronized static JSONObject thisUser() { - if(user == null) { + if (user == null) { user = new JSONObject(); populateUser(); } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmServiceException.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmServiceException.java index 034a23d9d..163e45fff 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmServiceException.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmServiceException.java @@ -5,17 +5,16 @@ */ package com.todoroo.astrid.actfm.sync; -import java.io.IOException; - import org.json.JSONObject; +import java.io.IOException; + /** * Exception that wraps an exception encountered during API invocation or * processing. * * @author timsu - * */ public class ActFmServiceException extends IOException { diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncMonitor.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncMonitor.java index 1d4c85716..77b6966e6 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncMonitor.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncMonitor.java @@ -2,6 +2,7 @@ package com.todoroo.astrid.actfm.sync; public class ActFmSyncMonitor { private ActFmSyncMonitor() {/**/} + private static final ActFmSyncMonitor INSTANCE = new ActFmSyncMonitor(); public static ActFmSyncMonitor getInstance() { diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncService.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncService.java index 8489898c4..8a77726d0 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncService.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncService.java @@ -5,14 +5,6 @@ */ package com.todoroo.astrid.actfm.sync; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - import android.text.TextUtils; import android.util.Log; @@ -28,11 +20,18 @@ import com.todoroo.astrid.service.TagDataService; import com.todoroo.astrid.service.abtesting.ABTestEventReportingService; import com.todoroo.astrid.tags.reusable.FeaturedListFilterExposer; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + /** * Service for synchronizing data on Astrid.com server with local. * * @author Tim Su - * */ @SuppressWarnings("nls") public final class ActFmSyncService { @@ -58,7 +57,8 @@ public final class ActFmSyncService { JSONArray abTestInfo = abTestEventReportingService.getTestsWithVariantsArray(); try { for (int i = 0; i < abTestInfo.length(); i++) { - params.add("ab_variants[]"); params.add(abTestInfo.getString(i)); + params.add("ab_variants[]"); + params.add(abTestInfo.getString(i)); } } catch (JSONException e) { Log.e("Error parsing AB test info", abTestInfo.toString(), e); @@ -91,10 +91,13 @@ public final class ActFmSyncService { throw new ActFmServiceException("Not logged in", null); ArrayList params = new ArrayList(); - params.add("purchase_token"); params.add(purchaseToken); - params.add("product_id"); params.add(productId); + params.add("purchase_token"); + params.add(purchaseToken); + params.add("product_id"); + params.add(productId); addAbTestEventInfo(params); - params.add("token"); params.add(token); + params.add("token"); + params.add(token); actFmInvoker.invoke("premium_update_android", params.toArray(new Object[params.size()])); Preferences.setBoolean(BillingConstants.PREF_NEEDS_SERVER_UPDATE, false); @@ -102,7 +105,7 @@ public final class ActFmSyncService { onSuccess.run(); } catch (Exception e) { if (e instanceof ActFmServiceException) { - ActFmServiceException ae = (ActFmServiceException)e; + ActFmServiceException ae = (ActFmServiceException) e; if (ae.result != null && ae.result.optString("status").equals("error")) { if (ae.result.optString("code").equals("invalid_purchase_token")) { // Not a valid purchase--expired or duolicate Preferences.setBoolean(ActFmPreferenceService.PREF_LOCAL_PREMIUM, false); @@ -125,12 +128,15 @@ public final class ActFmSyncService { String existingC2DM = Preferences.getStringValue(GCMIntentService.PREF_C2DM_REGISTRATION); ArrayList params = new ArrayList(); - params.add("gcm"); params.add(regId); + params.add("gcm"); + params.add(regId); if (!TextUtils.isEmpty(deviceId)) { - params.add("device_id"); params.add(deviceId); + params.add("device_id"); + params.add(deviceId); } if (!TextUtils.isEmpty(existingC2DM)) { // Unregisters C2DM with the server for migration purposes - params.add("c2dm"); params.add(existingC2DM); + params.add("c2dm"); + params.add(existingC2DM); } invoke("user_set_gcm", params.toArray(new Object[params.size()])); @@ -147,16 +153,18 @@ public final class ActFmSyncService { // --- generic invokation - /** invoke authenticated method against the server */ + /** + * invoke authenticated method against the server + */ public JSONObject invoke(String method, Object... getParameters) throws IOException, - ActFmServiceException { - if(!checkForToken()) + ActFmServiceException { + if (!checkForToken()) throw new ActFmServiceException("not logged in", null); Object[] parameters = new Object[getParameters.length + 2]; parameters[0] = "token"; parameters[1] = token; - for(int i = 0; i < getParameters.length; i++) - parameters[i+2] = getParameters[i]; + for (int i = 0; i < getParameters.length; i++) + parameters[i + 2] = getParameters[i]; return actFmInvoker.invoke(method, parameters); } @@ -165,7 +173,7 @@ public final class ActFmSyncService { } private boolean checkForToken() { - if(!actFmPreferenceService.isLoggedIn()) + if (!actFmPreferenceService.isLoggedIn()) return false; token = actFmPreferenceService.getToken(); return true; @@ -202,18 +210,18 @@ public final class ActFmSyncService { if (featuredList) model.setFlag(TagData.FLAGS, TagData.FLAG_FEATURED, true); - if(json.has("picture")) + if (json.has("picture")) model.setValue(TagData.PICTURE, json.optString("picture", "")); - if(json.has("thumb")) + if (json.has("thumb")) model.setValue(TagData.THUMB, json.optString("thumb", "")); - if(json.has("is_silent")) - model.setFlag(TagData.FLAGS, TagData.FLAG_SILENT,json.getBoolean("is_silent")); + if (json.has("is_silent")) + model.setFlag(TagData.FLAGS, TagData.FLAG_SILENT, json.getBoolean("is_silent")); - if(!json.isNull("description")) + if (!json.isNull("description")) model.setValue(TagData.TAG_DESCRIPTION, json.getString("description")); - if(json.has("members")) { + if (json.has("members")) { JSONArray members = json.getJSONArray("members"); model.setValue(TagData.MEMBERS, members.toString()); model.setValue(TagData.MEMBER_COUNT, members.length()); @@ -222,7 +230,7 @@ public final class ActFmSyncService { if (json.has("deleted_at")) model.setValue(TagData.DELETION_DATE, readDate(json, "deleted_at")); - if(json.has("tasks")) + if (json.has("tasks")) model.setValue(TagData.TASK_COUNT, json.getInt("tasks")); } } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncThread.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncThread.java index 9e5799f2c..64f739d55 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncThread.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncThread.java @@ -1,19 +1,5 @@ package com.todoroo.astrid.actfm.sync; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.http.entity.mime.MultipartEntity; -import org.json.JSONArray; -import org.json.JSONObject; - import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; @@ -76,6 +62,20 @@ import com.todoroo.astrid.data.WaitingOnMe; import com.todoroo.astrid.utility.Constants; import com.todoroo.astrid.widget.TasksWidget; +import org.apache.http.entity.mime.MultipartEntity; +import org.json.JSONArray; +import org.json.JSONObject; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + public class ActFmSyncThread { private static final String ERROR_TAG = "actfm-sync-thread"; //$NON-NLS-1$ @@ -133,6 +133,7 @@ public class ActFmSyncThread { public static interface SyncMessageCallback { public void runOnSuccess(); + public void runOnErrors(List errors); } @@ -149,7 +150,7 @@ public class ActFmSyncThread { public static ActFmSyncThread getInstance() { if (instance == null) { - synchronized(ActFmSyncThread.class) { + synchronized (ActFmSyncThread.class) { if (instance == null) { initializeSyncComponents(PluginServices.getTaskDao(), PluginServices.getTagDataDao(), PluginServices.getUserActivityDao(), PluginServices.getTaskAttachmentDao(), PluginServices.getTaskListMetadataDao(), PluginServices.getWaitingOnMeDao()); @@ -160,9 +161,9 @@ public class ActFmSyncThread { } public static ActFmSyncThread initializeSyncComponents(TaskDao taskDao, TagDataDao tagDataDao, UserActivityDao userActivityDao, - TaskAttachmentDao taskAttachmentDao, TaskListMetadataDao taskListMetadataDao, WaitingOnMeDao waitingOnMeDao) { + TaskAttachmentDao taskAttachmentDao, TaskListMetadataDao taskListMetadataDao, WaitingOnMeDao waitingOnMeDao) { if (instance == null) { - synchronized(ActFmSyncThread.class) { + synchronized (ActFmSyncThread.class) { if (instance == null) { List> syncQueue = Collections.synchronizedList(new LinkedList>()); ActFmSyncMonitor monitor = ActFmSyncMonitor.getInstance(); @@ -206,8 +207,8 @@ public class ActFmSyncThread { } public static void clearTablePushedAtValues() { - String[] pushedAtPrefs = new String[] { NameMaps.PUSHED_AT_TASKS, NameMaps.PUSHED_AT_TAGS, NameMaps.PUSHED_AT_ACTIVITY, - NameMaps.PUSHED_AT_USERS, NameMaps.PUSHED_AT_TASK_LIST_METADATA, NameMaps.PUSHED_AT_WAITING_ON_ME }; + String[] pushedAtPrefs = new String[]{NameMaps.PUSHED_AT_TASKS, NameMaps.PUSHED_AT_TAGS, NameMaps.PUSHED_AT_ACTIVITY, + NameMaps.PUSHED_AT_USERS, NameMaps.PUSHED_AT_TASK_LIST_METADATA, NameMaps.PUSHED_AT_WAITING_ON_ME}; for (String key : pushedAtPrefs) Preferences.clear(key); } @@ -219,7 +220,7 @@ public class ActFmSyncThread { pendingMessages.add(message); if (callback != null) pendingCallbacks.put(message, callback); - synchronized(monitor) { + synchronized (monitor) { monitor.notifyAll(); } } @@ -249,8 +250,8 @@ public class ActFmSyncThread { try { int batchSize = 4; List> messageBatch = new ArrayList>(); - while(true) { - synchronized(monitor) { + while (true) { + synchronized (monitor) { while ((pendingMessages.isEmpty() && !timeForBackgroundSync()) || !actFmPreferenceService.isLoggedIn() || !syncMigration) { try { if ((pendingMessages.isEmpty() || !actFmPreferenceService.isLoggedIn()) && notificationId >= 0) { @@ -482,10 +483,10 @@ public class ActFmSyncThread { try { NotificationCompat.Builder builder = new NotificationCompat.Builder(ContextManager.getContext()); builder.setContentText(ContextManager.getString(R.string.actfm_sync_ongoing)) - .setContentTitle(ContextManager.getString(R.string.app_name)) - .setOngoing(true) - .setSmallIcon(android.R.drawable.stat_notify_sync) - .setContentIntent(PendingIntent.getActivity(ContextManager.getContext().getApplicationContext(), 0, new Intent(), 0)); + .setContentTitle(ContextManager.getString(R.string.app_name)) + .setOngoing(true) + .setSmallIcon(android.R.drawable.stat_notify_sync) + .setContentIntent(PendingIntent.getActivity(ContextManager.getContext().getApplicationContext(), 0, new Intent(), 0)); notificationManager.notify(0, builder.getNotification()); @@ -498,7 +499,7 @@ public class ActFmSyncThread { } private boolean checkForToken() { - if(!actFmPreferenceService.isLoggedIn()) + if (!actFmPreferenceService.isLoggedIn()) return false; token = actFmPreferenceService.getToken(); return true; @@ -512,6 +513,7 @@ public class ActFmSyncThread { public static class NetworkStateChangedReceiver extends BroadcastReceiver { private static long lastSyncFromNetworkChange = 0; private static final String PREF_LAST_SYNC_FROM_NETWORK_CHANGE = "p_last_sync_from_net_change"; //$NON-NLS-1$ + @Override public void onReceive(Context context, Intent intent) { lastSyncFromNetworkChange = Preferences.getLong(PREF_LAST_SYNC_FROM_NETWORK_CHANGE, 0L); diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncV2Provider.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncV2Provider.java index 8bbf4a91e..5d2229006 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncV2Provider.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncV2Provider.java @@ -5,10 +5,6 @@ */ package com.todoroo.astrid.actfm.sync; -import java.io.IOException; - -import org.json.JSONObject; - import android.app.Activity; import android.content.DialogInterface; @@ -26,9 +22,12 @@ import com.todoroo.astrid.service.AstridDependencyInjector; import com.todoroo.astrid.sync.SyncResultCallback; import com.todoroo.astrid.sync.SyncV2Provider; +import org.json.JSONObject; + +import java.io.IOException; + /** * Exposes sync action - * */ public class ActFmSyncV2Provider extends SyncV2Provider { @@ -94,7 +93,7 @@ public class ActFmSyncV2Provider extends SyncV2Provider { @Override public void synchronizeActiveTasks(final boolean manual, - final SyncResultCallback callback) { + final SyncResultCallback callback) { new Thread(new Runnable() { public void run() { @@ -106,7 +105,9 @@ public class ActFmSyncV2Provider extends SyncV2Provider { }).start(); } - /** fetch user status hash*/ + /** + * fetch user status hash + */ @SuppressWarnings("nls") public void updateUserStatus() { if (Preferences.getStringValue(GCMIntentService.PREF_NEEDS_REGISTRATION) != null) { @@ -145,7 +146,7 @@ public class ActFmSyncV2Provider extends SyncV2Provider { // --- synchronize list @Override public void synchronizeList(Object list, final boolean manual, - final SyncResultCallback callback) { + final SyncResultCallback callback) { // Nothing to do } } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncWaitingPool.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncWaitingPool.java index 37e93b1ec..c0f2505ba 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncWaitingPool.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncWaitingPool.java @@ -1,21 +1,21 @@ package com.todoroo.astrid.actfm.sync; +import com.todoroo.andlib.utility.AndroidUtilities; +import com.todoroo.astrid.actfm.sync.messages.ClientToServerMessage; + import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import com.todoroo.andlib.utility.AndroidUtilities; -import com.todoroo.astrid.actfm.sync.messages.ClientToServerMessage; - public class ActFmSyncWaitingPool { private static volatile ActFmSyncWaitingPool instance; public static ActFmSyncWaitingPool getInstance() { if (instance == null) { - synchronized(ActFmSyncWaitingPool.class) { + synchronized (ActFmSyncWaitingPool.class) { if (instance == null) { instance = new ActFmSyncWaitingPool(); } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/AstridNewSyncMigrator.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/AstridNewSyncMigrator.java index e59d1c70d..c16ee806f 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/AstridNewSyncMigrator.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/AstridNewSyncMigrator.java @@ -1,8 +1,5 @@ package com.todoroo.astrid.actfm.sync; -import java.util.HashSet; -import java.util.Set; - import android.text.TextUtils; import android.util.Log; @@ -52,21 +49,35 @@ import com.todoroo.astrid.subtasks.SubtasksHelper; import com.todoroo.astrid.subtasks.SubtasksUpdater; import com.todoroo.astrid.tags.TaskToTagMetadata; +import java.util.HashSet; +import java.util.Set; + @SuppressWarnings("nls") public class AstridNewSyncMigrator { - @Autowired private MetadataService metadataService; - @Autowired private TagDataService tagDataService; - @Autowired private TagDataDao tagDataDao; - @Autowired private TaskDao taskDao; - @Autowired private UpdateDao updateDao; - @Autowired private UserActivityDao userActivityDao; - @Autowired private UserDao userDao; - @Autowired private TaskAttachmentDao taskAttachmentDao; - @Autowired private TaskListMetadataDao taskListMetadataDao; - - @Autowired private TaskOutstandingDao taskOutstandingDao; - @Autowired private TagOutstandingDao tagOutstandingDao; + @Autowired + private MetadataService metadataService; + @Autowired + private TagDataService tagDataService; + @Autowired + private TagDataDao tagDataDao; + @Autowired + private TaskDao taskDao; + @Autowired + private UpdateDao updateDao; + @Autowired + private UserActivityDao userActivityDao; + @Autowired + private UserDao userDao; + @Autowired + private TaskAttachmentDao taskAttachmentDao; + @Autowired + private TaskListMetadataDao taskListMetadataDao; + + @Autowired + private TaskOutstandingDao taskOutstandingDao; + @Autowired + private TagOutstandingDao tagOutstandingDao; private static final String LOG_TAG = "sync-migrate"; @@ -138,7 +149,7 @@ public class AstridNewSyncMigrator { Crittercism.logHandledException(e); } } - } catch (Exception e){ + } catch (Exception e) { Crittercism.logHandledException(e); } finally { if (emergentTags != null) @@ -294,7 +305,6 @@ public class AstridNewSyncMigrator { } - // -------------- // Drop any entries from the Users table that don't have a UUID // -------------- @@ -440,7 +450,8 @@ public class AstridNewSyncMigrator { MetadataCriteria.withKey(TaskToTagMetadata.KEY), Criterion.or(TaskToTagMetadata.TASK_UUID.eq(0), TaskToTagMetadata.TASK_UUID.isNull(), TaskToTagMetadata.TAG_UUID.eq(0), TaskToTagMetadata.TAG_UUID.isNull()))); - incompleteMetadata = metadataService.query(incompleteQuery);; + incompleteMetadata = metadataService.query(incompleteQuery); + ; Metadata m = new Metadata(); for (incompleteMetadata.moveToFirst(); !incompleteMetadata.isAfterLast(); incompleteMetadata.moveToNext()) { try { @@ -540,6 +551,7 @@ public class AstridNewSyncMigrator { private interface UUIDAssertionExtras { boolean shouldCreateOutstandingEntries(TYPE instance); + void afterSave(TYPE instance, boolean createdOutstanding); } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/EmptyTitleOutstandingEntryMigration.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/EmptyTitleOutstandingEntryMigration.java index fa4f5d4fa..1c360d8bb 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/EmptyTitleOutstandingEntryMigration.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/EmptyTitleOutstandingEntryMigration.java @@ -1,8 +1,5 @@ package com.todoroo.astrid.actfm.sync; -import java.util.ArrayList; -import java.util.List; - import android.util.Log; import com.todoroo.andlib.data.TodorooCursor; @@ -21,6 +18,9 @@ import com.todoroo.astrid.data.TaskAttachment; import com.todoroo.astrid.data.TaskAttachmentOutstanding; import com.todoroo.astrid.data.TaskOutstanding; +import java.util.ArrayList; +import java.util.List; + public class EmptyTitleOutstandingEntryMigration { private static final String ERROR_TAG = "empty-title-migrate"; //$NON-NLS-1$ @@ -46,24 +46,24 @@ public class EmptyTitleOutstandingEntryMigration { .join(Join.left(Task.TABLE, Task.ID.eq(TaskOutstanding.TASK_ID))) .where(Criterion.and(TaskOutstanding.COLUMN_STRING.eq(Task.TITLE.name), Criterion.and(TaskOutstanding.VALUE_STRING.isNotNull(), TaskOutstanding.VALUE_STRING.neq("")))) //$NON-NLS-1$ - .groupBy(TaskOutstanding.TASK_ID)); - List ids = new ArrayList(); - List uuids = new ArrayList(); - for (outstandingWithTitle.moveToFirst(); !outstandingWithTitle.isAfterLast(); outstandingWithTitle.moveToNext()) { - try { - ids.add(outstandingWithTitle.get(TaskOutstanding.TASK_ID)); - uuids.add(outstandingWithTitle.get(Task.UUID)); - } catch (Exception e) { - Log.e(ERROR_TAG, "Error reading from cursor", e); //$NON-NLS-1$ - } + .groupBy(TaskOutstanding.TASK_ID)); + List ids = new ArrayList(); + List uuids = new ArrayList(); + for (outstandingWithTitle.moveToFirst(); !outstandingWithTitle.isAfterLast(); outstandingWithTitle.moveToNext()) { + try { + ids.add(outstandingWithTitle.get(TaskOutstanding.TASK_ID)); + uuids.add(outstandingWithTitle.get(Task.UUID)); + } catch (Exception e) { + Log.e(ERROR_TAG, "Error reading from cursor", e); //$NON-NLS-1$ } + } - taskOutstandingDao.deleteWhere(Criterion.and(TaskOutstanding.TASK_ID.in(ids.toArray(new Long[ids.size()])), - TaskOutstanding.COLUMN_STRING.eq(Task.TITLE.name), - Criterion.or(TaskOutstanding.VALUE_STRING.isNull(), TaskOutstanding.VALUE_STRING.eq("")))); //$NON-NLS-1$ + taskOutstandingDao.deleteWhere(Criterion.and(TaskOutstanding.TASK_ID.in(ids.toArray(new Long[ids.size()])), + TaskOutstanding.COLUMN_STRING.eq(Task.TITLE.name), + Criterion.or(TaskOutstanding.VALUE_STRING.isNull(), TaskOutstanding.VALUE_STRING.eq("")))); //$NON-NLS-1$ - new ConstructOutstandingTableFromMasterTable(NameMaps.TABLE_ID_ATTACHMENTS, - taskAttachmentDao, taskAttachmentOutstandingDao, TaskAttachment.CREATED_AT).execute(TaskAttachment.TASK_UUID.in(uuids.toArray(new String[uuids.size()]))); + new ConstructOutstandingTableFromMasterTable(NameMaps.TABLE_ID_ATTACHMENTS, + taskAttachmentDao, taskAttachmentOutstandingDao, TaskAttachment.CREATED_AT).execute(TaskAttachment.TASK_UUID.in(uuids.toArray(new String[uuids.size()]))); } catch (Exception e) { Log.e(ERROR_TAG, "Unhandled exception", e); //$NON-NLS-1$ } finally { diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/SyncDatabaseListener.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/SyncDatabaseListener.java index e238b920a..d3f6a1ca7 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/SyncDatabaseListener.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/SyncDatabaseListener.java @@ -11,6 +11,7 @@ public class SyncDatabaseListener implements ModelU private final ModelType modelType; protected final ActFmSyncThread actFmSyncThread; + public SyncDatabaseListener(ActFmSyncThread actFmSyncThread, ModelType modelType) { this.actFmSyncThread = actFmSyncThread; this.modelType = modelType; diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/SyncUpgradePrompt.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/SyncUpgradePrompt.java index 6bc95a2c9..c8ab87543 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/SyncUpgradePrompt.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/SyncUpgradePrompt.java @@ -32,22 +32,22 @@ public class SyncUpgradePrompt { // Logged into google but not astrid d = getDialog(activity, R.string.sync_upgr_gtasks_only_title, R.string.sync_upgr_gtasks_only_body, R.string.sync_upgr_gtasks_only_btn1, new Runnable() { - @Override - public void run() { - activity.startActivity(new Intent(activity, ActFmLoginActivity.class)); - } - }, + @Override + public void run() { + activity.startActivity(new Intent(activity, ActFmLoginActivity.class)); + } + }, R.string.sync_upgr_gtasks_only_btn2, null); } else { // Logged into neither d = getDialog(activity, R.string.sync_upgr_neither_title, R.string.sync_upgr_neither_body, R.string.sync_upgr_neither_btn1, new Runnable() { - @Override - public void run() { - activity.startActivity(new Intent(activity, ActFmLoginActivity.class)); - } - }); + @Override + public void run() { + activity.startActivity(new Intent(activity, ActFmLoginActivity.class)); + } + }); } setLastPromptDate(DateUtilities.now()); } else if (PluginServices.getGtasksPreferenceService().isLoggedIn()) { @@ -56,12 +56,12 @@ public class SyncUpgradePrompt { R.string.sync_upgr_both_btn1, null, R.string.sync_upgr_both_btn2, new Runnable() { - @Override - public void run() { - new ActFmSyncV2Provider().signOut(activity); - Toast.makeText(activity, R.string.sync_upgr_logged_out, Toast.LENGTH_LONG).show(); - } - }); + @Override + public void run() { + new ActFmSyncV2Provider().signOut(activity); + Toast.makeText(activity, R.string.sync_upgr_logged_out, Toast.LENGTH_LONG).show(); + } + }); setLastPromptDate(Long.MAX_VALUE); } else { // Logged into just astrid--don't need to show prompts anymore diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/AcknowledgeChange.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/AcknowledgeChange.java index dab4c17db..2f85ab47e 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/AcknowledgeChange.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/AcknowledgeChange.java @@ -1,17 +1,17 @@ package com.todoroo.astrid.actfm.sync.messages; -import java.util.ArrayList; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - import android.util.Log; import com.todoroo.andlib.data.AbstractModel; import com.todoroo.astrid.core.PluginServices; import com.todoroo.astrid.dao.OutstandingEntryDao; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; + public class AcknowledgeChange extends ServerToClientMessage { private static final String ERROR_TAG = "actfm-acknowledge-change"; //$NON-NLS-1$ diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/BriefMe.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/BriefMe.java index 5574c7830..a3dd29190 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/BriefMe.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/BriefMe.java @@ -1,15 +1,15 @@ package com.todoroo.astrid.actfm.sync.messages; -import org.apache.http.entity.mime.MultipartEntity; -import org.json.JSONException; -import org.json.JSONObject; - import android.util.Log; import com.todoroo.andlib.utility.Preferences; import com.todoroo.astrid.dao.RemoteModelDao; import com.todoroo.astrid.data.RemoteModel; +import org.apache.http.entity.mime.MultipartEntity; +import org.json.JSONException; +import org.json.JSONObject; + public class BriefMe extends ClientToServerMessage { private static final String ERROR_TAG = "actfm-brief-me"; //$NON-NLS-1$ @@ -30,7 +30,7 @@ public class BriefMe extends ClientToServerMessage modelClass, String uuid, long pushedAt, Object...extraParameters) { + public BriefMe(Class modelClass, String uuid, long pushedAt, Object... extraParameters) { super(modelClass, uuid, pushedAt); this.extraParameters = extraParameters; } @@ -38,7 +38,7 @@ public class BriefMe extends ClientToServerMessage 0) { - for (int i = 0; i < extraParameters.length - 1; i+=2) { + for (int i = 0; i < extraParameters.length - 1; i += 2) { try { String key = (String) extraParameters[i]; Object value = extraParameters[i + 1]; diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ChangesHappened.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ChangesHappened.java index 8b46796f3..092cfc711 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ChangesHappened.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ChangesHappened.java @@ -1,16 +1,5 @@ package com.todoroo.astrid.actfm.sync.messages; -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; - -import org.apache.http.entity.mime.MultipartEntity; -import org.apache.http.entity.mime.content.FileBody; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - import android.text.TextUtils; import android.util.Log; @@ -41,6 +30,17 @@ import com.todoroo.astrid.data.UserActivityOutstanding; import com.todoroo.astrid.data.WaitingOnMe; import com.todoroo.astrid.data.WaitingOnMeOutstanding; +import org.apache.http.entity.mime.MultipartEntity; +import org.apache.http.entity.mime.content.FileBody; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + @SuppressWarnings("nls") public class ChangesHappened> extends ClientToServerMessage { @@ -53,32 +53,32 @@ public class ChangesHappened instantiateChangesHappened(long id, ModelType modelType) { - switch(modelType) { - case TYPE_TASK: - return new ChangesHappened(id, Task.class, - PluginServices.getTaskDao(), PluginServices.getTaskOutstandingDao()); - case TYPE_TAG: - return new ChangesHappened(id, TagData.class, - PluginServices.getTagDataDao(), PluginServices.getTagOutstandingDao()); - case TYPE_ACTIVITY: - return new ChangesHappened(id, UserActivity.class, - PluginServices.getUserActivityDao(), PluginServices.getUserActivityOutstandingDao()); - case TYPE_ATTACHMENT: - return new ChangesHappened(id, TaskAttachment.class, - PluginServices.getTaskAttachmentDao(), PluginServices.getTaskAttachmentOutstandingDao()); - case TYPE_TASK_LIST_METADATA: - return new TaskListMetadataChangesHappened(id, TaskListMetadata.class, - PluginServices.getTaskListMetadataDao(), PluginServices.getTaskListMetadataOutstandingDao()); - case TYPE_WAITING_ON_ME: - return new ChangesHappened(id, WaitingOnMe.class, - PluginServices.getWaitingOnMeDao(), PluginServices.getWaitingOnMeOutstandingDao()); - default: - return null; + switch (modelType) { + case TYPE_TASK: + return new ChangesHappened(id, Task.class, + PluginServices.getTaskDao(), PluginServices.getTaskOutstandingDao()); + case TYPE_TAG: + return new ChangesHappened(id, TagData.class, + PluginServices.getTagDataDao(), PluginServices.getTagOutstandingDao()); + case TYPE_ACTIVITY: + return new ChangesHappened(id, UserActivity.class, + PluginServices.getUserActivityDao(), PluginServices.getUserActivityOutstandingDao()); + case TYPE_ATTACHMENT: + return new ChangesHappened(id, TaskAttachment.class, + PluginServices.getTaskAttachmentDao(), PluginServices.getTaskAttachmentOutstandingDao()); + case TYPE_TASK_LIST_METADATA: + return new TaskListMetadataChangesHappened(id, TaskListMetadata.class, + PluginServices.getTaskListMetadataDao(), PluginServices.getTaskListMetadataOutstandingDao()); + case TYPE_WAITING_ON_ME: + return new ChangesHappened(id, WaitingOnMe.class, + PluginServices.getWaitingOnMeDao(), PluginServices.getWaitingOnMeOutstandingDao()); + default: + return null; } } public ChangesHappened(long id, Class modelClass, RemoteModelDao modelDao, - OutstandingEntryDao outstandingDao) { + OutstandingEntryDao outstandingDao) { super(id, modelClass, modelDao); this.outstandingClass = DaoReflectionHelpers.getOutstandingClass(modelClass); @@ -201,7 +201,7 @@ public class ChangesHappened cursor = outstandingDao.query(Query.select(DaoReflectionHelpers.getModelProperties(outstandingClass)) - .where(OutstandingEntry.ENTITY_ID_PROPERTY.eq(id)).orderBy(Order.asc(OutstandingEntry.CREATED_AT_PROPERTY))); + .where(OutstandingEntry.ENTITY_ID_PROPERTY.eq(id)).orderBy(Order.asc(OutstandingEntry.CREATED_AT_PROPERTY))); try { for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { try { diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ClientToServerMessage.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ClientToServerMessage.java index fff800665..5b39f0051 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ClientToServerMessage.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ClientToServerMessage.java @@ -1,9 +1,5 @@ package com.todoroo.astrid.actfm.sync.messages; -import org.apache.http.entity.mime.MultipartEntity; -import org.json.JSONException; -import org.json.JSONObject; - import com.crittercism.app.Crittercism; import com.todoroo.andlib.data.AbstractModel; import com.todoroo.andlib.data.Table; @@ -12,6 +8,10 @@ import com.todoroo.astrid.dao.DaoReflectionHelpers; import com.todoroo.astrid.dao.RemoteModelDao; import com.todoroo.astrid.data.RemoteModel; +import org.apache.http.entity.mime.MultipartEntity; +import org.json.JSONException; +import org.json.JSONObject; + @SuppressWarnings("nls") public abstract class ClientToServerMessage { @@ -116,5 +116,6 @@ public abstract class ClientToServerMessage { } protected abstract boolean serializeExtrasToJSON(JSONObject serializeTo, MultipartEntity entity) throws JSONException; + protected abstract String getTypeString(); } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ConstructOutstandingTableFromMasterTable.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ConstructOutstandingTableFromMasterTable.java index 8926d8a11..35f7c1e56 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ConstructOutstandingTableFromMasterTable.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ConstructOutstandingTableFromMasterTable.java @@ -24,7 +24,7 @@ public class ConstructOutstandingTableFromMasterTable dao, - OutstandingEntryDao outstandingDao, LongProperty createdAtProperty) { + OutstandingEntryDao outstandingDao, LongProperty createdAtProperty) { this.table = table; this.dao = dao; this.outstandingDao = outstandingDao; diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/Debug.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/Debug.java index f8bbc667f..843840628 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/Debug.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/Debug.java @@ -1,10 +1,10 @@ package com.todoroo.astrid.actfm.sync.messages; -import org.json.JSONObject; - import android.text.TextUtils; import android.util.Log; +import org.json.JSONObject; + public class Debug extends ServerToClientMessage { public Debug(JSONObject json) { diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/FetchHistory.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/FetchHistory.java index ae8c58833..dcffa4459 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/FetchHistory.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/FetchHistory.java @@ -1,12 +1,5 @@ package com.todoroo.astrid.actfm.sync.messages; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Iterator; - -import org.json.JSONArray; -import org.json.JSONObject; - import android.text.TextUtils; import android.util.Log; @@ -25,6 +18,13 @@ import com.todoroo.astrid.data.RemoteModel; import com.todoroo.astrid.data.Task; import com.todoroo.astrid.data.User; +import org.json.JSONArray; +import org.json.JSONObject; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; + public class FetchHistory { private static final String ERROR_TAG = "actfm-fetch-history"; //$NON-NLS-1$ @@ -52,7 +52,7 @@ public class FetchHistory { private ActFmPreferenceService actFmPreferenceService; public FetchHistory(RemoteModelDao dao, LongProperty historyTimeProperty, IntegerProperty historyHasMoreProperty, - String table, String uuid, String taskTitle, long modifiedAfter, int offset, SyncMessageCallback done) { + String table, String uuid, String taskTitle, long modifiedAfter, int offset, SyncMessageCallback done) { DependencyInjectionService.getInstance().inject(this); this.dao = dao; this.historyTimeProperty = historyTimeProperty; @@ -85,14 +85,17 @@ public class FetchHistory { params.add(uuid); if (modifiedAfter > 0) { - params.add("modified_after"); params.add(modifiedAfter / 1000L); + params.add("modified_after"); + params.add(modifiedAfter / 1000L); } if (offset > 0) { - params.add("offset"); params.add(offset); + params.add("offset"); + params.add(offset); } - params.add("token"); params.add(token); + params.add("token"); + params.add(token); try { JSONObject result = actFmInvoker.invoke("model_history_list", params.toArray(new Object[params.size()])); JSONArray list = result.optJSONArray("list"); diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/JSONChangeToPropertyVisitor.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/JSONChangeToPropertyVisitor.java index f1b52f310..bea292df8 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/JSONChangeToPropertyVisitor.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/JSONChangeToPropertyVisitor.java @@ -1,8 +1,5 @@ package com.todoroo.astrid.actfm.sync.messages; -import org.json.JSONException; -import org.json.JSONObject; - import android.util.Log; import com.todoroo.andlib.data.AbstractModel; @@ -16,6 +13,9 @@ import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.actfm.sync.ActFmPreferenceService; import com.todoroo.astrid.data.Task; +import org.json.JSONException; +import org.json.JSONObject; + @SuppressWarnings("nls") public class JSONChangeToPropertyVisitor implements PropertyVisitor { @@ -61,7 +61,7 @@ public class JSONChangeToPropertyVisitor implements PropertyVisitor extends ServerToClientMessage { @@ -340,7 +340,7 @@ public class MakeChanges extends ServerToClientMessage if (!TextUtils.isEmpty(valueString)) { try { deletedValue = DateUtilities.parseIso8601(valueString); - } catch (Exception e){ + } catch (Exception e) { // } } @@ -437,5 +437,4 @@ public class MakeChanges extends ServerToClientMessage } - } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/NameMaps.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/NameMaps.java index 91e675734..590e3048c 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/NameMaps.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/NameMaps.java @@ -1,10 +1,5 @@ package com.todoroo.astrid.actfm.sync.messages; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - import com.todoroo.andlib.data.Property; import com.todoroo.andlib.data.Table; import com.todoroo.andlib.utility.AndroidUtilities; @@ -17,6 +12,11 @@ import com.todoroo.astrid.data.User; import com.todoroo.astrid.data.UserActivity; import com.todoroo.astrid.data.WaitingOnMe; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + @SuppressWarnings("nls") public class NameMaps { @@ -73,8 +73,8 @@ public class NameMaps { // ---- Column name mappings ------- // -------------------------------- private static void putPropertyToServerName(Property property, String serverName, - Map, String> propertyMap, Map> localNameMap, Map serverNameMap, - Set excludedFromOutstandingSet, boolean writeable) { + Map, String> propertyMap, Map> localNameMap, Map serverNameMap, + Set excludedFromOutstandingSet, boolean writeable) { propertyMap.put(property, serverName); localNameMap.put(property.name, property); serverNameMap.put(property.name, serverName); @@ -130,22 +130,22 @@ public class NameMaps { TASK_COLUMN_NAMES_TO_PROPERTIES = new HashMap>(); TASK_PROPERTIES_EXCLUDED = new HashSet(); - putTaskPropertyToServerName(Task.TITLE, "title", true); - putTaskPropertyToServerName(Task.IMPORTANCE, "importance", true); - putTaskPropertyToServerName(Task.DUE_DATE, "due", true); - putTaskPropertyToServerName(Task.HIDE_UNTIL, "hide_until", true); - putTaskPropertyToServerName(Task.CREATION_DATE, "created_at", true); - putTaskPropertyToServerName(Task.COMPLETION_DATE, "completed_at", true); - putTaskPropertyToServerName(Task.RECURRENCE, "repeat", true); - putTaskPropertyToServerName(Task.DELETION_DATE, "deleted_at", true); - putTaskPropertyToServerName(Task.NOTES, "notes", true); - putTaskPropertyToServerName(Task.RECURRENCE, "repeat", true); - putTaskPropertyToServerName(Task.USER_ID, "user_id", true); - putTaskPropertyToServerName(Task.CREATOR_ID, "creator_id", false); - putTaskPropertyToServerName(Task.UUID, "uuid", false); - putTaskPropertyToServerName(Task.IS_PUBLIC, "public", true); - putTaskPropertyToServerName(Task.IS_READONLY, "read_only", false); - putTaskPropertyToServerName(Task.CLASSIFICATION, "classification", false); + putTaskPropertyToServerName(Task.TITLE, "title", true); + putTaskPropertyToServerName(Task.IMPORTANCE, "importance", true); + putTaskPropertyToServerName(Task.DUE_DATE, "due", true); + putTaskPropertyToServerName(Task.HIDE_UNTIL, "hide_until", true); + putTaskPropertyToServerName(Task.CREATION_DATE, "created_at", true); + putTaskPropertyToServerName(Task.COMPLETION_DATE, "completed_at", true); + putTaskPropertyToServerName(Task.RECURRENCE, "repeat", true); + putTaskPropertyToServerName(Task.DELETION_DATE, "deleted_at", true); + putTaskPropertyToServerName(Task.NOTES, "notes", true); + putTaskPropertyToServerName(Task.RECURRENCE, "repeat", true); + putTaskPropertyToServerName(Task.USER_ID, "user_id", true); + putTaskPropertyToServerName(Task.CREATOR_ID, "creator_id", false); + putTaskPropertyToServerName(Task.UUID, "uuid", false); + putTaskPropertyToServerName(Task.IS_PUBLIC, "public", true); + putTaskPropertyToServerName(Task.IS_READONLY, "read_only", false); + putTaskPropertyToServerName(Task.CLASSIFICATION, "classification", false); TASK_PROPERTIES_SERVER_TO_LOCAL = AndroidUtilities.reverseMap(TASK_PROPERTIES_LOCAL_TO_SERVER); } @@ -168,6 +168,7 @@ public class NameMaps { putPropertyToServerName(property, serverName, TAG_DATA_PROPERTIES_LOCAL_TO_SERVER, TAG_DATA_COLUMN_NAMES_TO_PROPERTIES, TAG_DATA_COLUMNS_LOCAL_TO_SERVER, TAG_PROPERTIES_EXCLUDED, writeable); } + static { // Hardcoded local columns mapped to corresponding server names TAG_DATA_PROPERTIES_LOCAL_TO_SERVER = new HashMap, String>(); @@ -175,15 +176,15 @@ public class NameMaps { TAG_DATA_COLUMN_NAMES_TO_PROPERTIES = new HashMap>(); TAG_PROPERTIES_EXCLUDED = new HashSet(); - putTagPropertyToServerName(TagData.USER_ID, "user_id", true); - putTagPropertyToServerName(TagData.NAME, "name", true); - putTagPropertyToServerName(TagData.CREATION_DATE, "created_at", true); - putTagPropertyToServerName(TagData.DELETION_DATE, "deleted_at", true); - putTagPropertyToServerName(TagData.UUID, "uuid", false); - putTagPropertyToServerName(TagData.TASK_COUNT, "task_count", false); - putTagPropertyToServerName(TagData.TAG_DESCRIPTION, "description", true); - putTagPropertyToServerName(TagData.PICTURE, "picture", true); - putTagPropertyToServerName(TagData.IS_FOLDER, "is_folder", false); + putTagPropertyToServerName(TagData.USER_ID, "user_id", true); + putTagPropertyToServerName(TagData.NAME, "name", true); + putTagPropertyToServerName(TagData.CREATION_DATE, "created_at", true); + putTagPropertyToServerName(TagData.DELETION_DATE, "deleted_at", true); + putTagPropertyToServerName(TagData.UUID, "uuid", false); + putTagPropertyToServerName(TagData.TASK_COUNT, "task_count", false); + putTagPropertyToServerName(TagData.TAG_DESCRIPTION, "description", true); + putTagPropertyToServerName(TagData.PICTURE, "picture", true); + putTagPropertyToServerName(TagData.IS_FOLDER, "is_folder", false); // Reverse the mapping to construct the server to local map TAG_DATA_PROPERTIES_SERVER_TO_LOCAL = AndroidUtilities.reverseMap(TAG_DATA_PROPERTIES_LOCAL_TO_SERVER); @@ -193,7 +194,6 @@ public class NameMaps { public static final String MEMBER_REMOVED_COLUMN = "member_removed"; - // ---------- // Users // ---------- @@ -214,11 +214,11 @@ public class NameMaps { USER_COLUMNS_LOCAL_TO_SERVER = new HashMap(); USER_PROPERTIES_EXCLUDED = new HashSet(); - putUserPropertyToServerName(User.UUID, "uuid", false); - putUserPropertyToServerName(User.PICTURE, "picture", false); + putUserPropertyToServerName(User.UUID, "uuid", false); + putUserPropertyToServerName(User.PICTURE, "picture", false); putUserPropertyToServerName(User.FIRST_NAME, "first_name", false); - putUserPropertyToServerName(User.LAST_NAME, "last_name", false); - putUserPropertyToServerName(User.STATUS, "connection", true); + putUserPropertyToServerName(User.LAST_NAME, "last_name", false); + putUserPropertyToServerName(User.STATUS, "connection", true); // Reverse the mapping to construct the server to local map @@ -245,15 +245,15 @@ public class NameMaps { USER_ACTIVITY_COLUMNS_LOCAL_TO_SERVER = new HashMap(); USER_ACTIVITY_PROPERTIES_EXCLUDED = new HashSet(); - putUserActivityPropertyToServerName(UserActivity.UUID, "uuid", false); - putUserActivityPropertyToServerName(UserActivity.USER_UUID, "user_id", false); - putUserActivityPropertyToServerName(UserActivity.ACTION, "action", true); - putUserActivityPropertyToServerName(UserActivity.MESSAGE, "message", true); - putUserActivityPropertyToServerName(UserActivity.PICTURE, "picture", true); - putUserActivityPropertyToServerName(UserActivity.TARGET_ID, "target_id", true); + putUserActivityPropertyToServerName(UserActivity.UUID, "uuid", false); + putUserActivityPropertyToServerName(UserActivity.USER_UUID, "user_id", false); + putUserActivityPropertyToServerName(UserActivity.ACTION, "action", true); + putUserActivityPropertyToServerName(UserActivity.MESSAGE, "message", true); + putUserActivityPropertyToServerName(UserActivity.PICTURE, "picture", true); + putUserActivityPropertyToServerName(UserActivity.TARGET_ID, "target_id", true); putUserActivityPropertyToServerName(UserActivity.TARGET_NAME, "target_name", false); - putUserActivityPropertyToServerName(UserActivity.CREATED_AT, "created_at", true); - putUserActivityPropertyToServerName(UserActivity.DELETED_AT, "deleted_at", true); + putUserActivityPropertyToServerName(UserActivity.CREATED_AT, "created_at", true); + putUserActivityPropertyToServerName(UserActivity.DELETED_AT, "deleted_at", true); // Reverse the mapping to construct the server to local map @@ -282,15 +282,15 @@ public class NameMaps { TASK_ATTACHMENT_COLUMNS_LOCAL_TO_SERVER = new HashMap(); TASK_ATTACHMENT_PROPERTIES_EXCLUDED = new HashSet(); - putTaskAttachmentPropertyToServerName(TaskAttachment.UUID, "uuid", false); - putTaskAttachmentPropertyToServerName(TaskAttachment.USER_UUID, "user_id", false); - putTaskAttachmentPropertyToServerName(TaskAttachment.TASK_UUID, "task_id", true); - putTaskAttachmentPropertyToServerName(TaskAttachment.NAME, "name", false); - putTaskAttachmentPropertyToServerName(TaskAttachment.URL, "url", false); - putTaskAttachmentPropertyToServerName(TaskAttachment.SIZE, "size", false); + putTaskAttachmentPropertyToServerName(TaskAttachment.UUID, "uuid", false); + putTaskAttachmentPropertyToServerName(TaskAttachment.USER_UUID, "user_id", false); + putTaskAttachmentPropertyToServerName(TaskAttachment.TASK_UUID, "task_id", true); + putTaskAttachmentPropertyToServerName(TaskAttachment.NAME, "name", false); + putTaskAttachmentPropertyToServerName(TaskAttachment.URL, "url", false); + putTaskAttachmentPropertyToServerName(TaskAttachment.SIZE, "size", false); putTaskAttachmentPropertyToServerName(TaskAttachment.CONTENT_TYPE, "content_type", false); - putTaskAttachmentPropertyToServerName(TaskAttachment.CREATED_AT, "created_at", true); - putTaskAttachmentPropertyToServerName(TaskAttachment.DELETED_AT, "deleted_at", true); + putTaskAttachmentPropertyToServerName(TaskAttachment.CREATED_AT, "created_at", true); + putTaskAttachmentPropertyToServerName(TaskAttachment.DELETED_AT, "deleted_at", true); // Reverse the mapping to construct the server to local map @@ -317,14 +317,14 @@ public class NameMaps { TASK_LIST_METADATA_COLUMNS_LOCAL_TO_SERVER = new HashMap(); TASK_LIST_METADATA_PROPERTIES_EXCLUDED = new HashSet(); - putTaskListMetadataPropertyToServerName(TaskListMetadata.UUID, "uuid", false); - putTaskListMetadataPropertyToServerName(TaskListMetadata.TAG_UUID, "tag_id", true); - putTaskListMetadataPropertyToServerName(TaskListMetadata.FILTER, "filter", true); - putTaskListMetadataPropertyToServerName(TaskListMetadata.TASK_IDS, "task_ids", true); - putTaskListMetadataPropertyToServerName(TaskListMetadata.SORT, "sort", false); - putTaskListMetadataPropertyToServerName(TaskListMetadata.SETTINGS, "settings", false); + putTaskListMetadataPropertyToServerName(TaskListMetadata.UUID, "uuid", false); + putTaskListMetadataPropertyToServerName(TaskListMetadata.TAG_UUID, "tag_id", true); + putTaskListMetadataPropertyToServerName(TaskListMetadata.FILTER, "filter", true); + putTaskListMetadataPropertyToServerName(TaskListMetadata.TASK_IDS, "task_ids", true); + putTaskListMetadataPropertyToServerName(TaskListMetadata.SORT, "sort", false); + putTaskListMetadataPropertyToServerName(TaskListMetadata.SETTINGS, "settings", false); putTaskListMetadataPropertyToServerName(TaskListMetadata.CHILD_TAG_IDS, "child_tag_ids", false); - putTaskListMetadataPropertyToServerName(TaskListMetadata.IS_COLLAPSED, "is_collapsed", false); + putTaskListMetadataPropertyToServerName(TaskListMetadata.IS_COLLAPSED, "is_collapsed", false); // Reverse the mapping to construct the server to local map TASK_LIST_METADATA_PROPERTIES_SERVER_TO_LOCAL = AndroidUtilities.reverseMap(TASK_LIST_METADATA_PROPERTIES_LOCAL_TO_SERVER); @@ -350,14 +350,14 @@ public class NameMaps { WAITING_ON_ME_COLUMNS_LOCAL_TO_SERVER = new HashMap(); WAITING_ON_ME_PROPERTIES_EXCLUDED = new HashSet(); - putWaitingOnMePropertyToServerName(WaitingOnMe.UUID, "uuid", false); + putWaitingOnMePropertyToServerName(WaitingOnMe.UUID, "uuid", false); putWaitingOnMePropertyToServerName(WaitingOnMe.WAITING_USER_ID, "waiting_user_id", false); - putWaitingOnMePropertyToServerName(WaitingOnMe.TASK_UUID, "task_id", false); - putWaitingOnMePropertyToServerName(WaitingOnMe.WAIT_TYPE, "wait_type", false); - putWaitingOnMePropertyToServerName(WaitingOnMe.CREATED_AT, "created_at", false); - putWaitingOnMePropertyToServerName(WaitingOnMe.DELETED_AT, "deleted_at", true); - putWaitingOnMePropertyToServerName(WaitingOnMe.READ_AT, "read_at", true); - putWaitingOnMePropertyToServerName(WaitingOnMe.ACKNOWLEDGED, "acknowledged", true); + putWaitingOnMePropertyToServerName(WaitingOnMe.TASK_UUID, "task_id", false); + putWaitingOnMePropertyToServerName(WaitingOnMe.WAIT_TYPE, "wait_type", false); + putWaitingOnMePropertyToServerName(WaitingOnMe.CREATED_AT, "created_at", false); + putWaitingOnMePropertyToServerName(WaitingOnMe.DELETED_AT, "deleted_at", true); + putWaitingOnMePropertyToServerName(WaitingOnMe.READ_AT, "read_at", true); + putWaitingOnMePropertyToServerName(WaitingOnMe.ACKNOWLEDGED, "acknowledged", true); // Reverse the mapping to construct the server to local map WAITING_ON_ME_PROPERTIES_SERVER_TO_LOCAL = AndroidUtilities.reverseMap(WAITING_ON_ME_PROPERTIES_LOCAL_TO_SERVER); @@ -369,7 +369,7 @@ public class NameMaps { // ---------- private static B mapColumnName(String table, A col, Map taskMap, Map tagMap, Map userMap, - Map userActivityMap, Map taskAttachmentMap, Map taskListMetadataMap, Map waitingOnMeMap) { + Map userActivityMap, Map taskAttachmentMap, Map taskListMetadataMap, Map waitingOnMeMap) { Map map = null; if (TABLE_ID_TASKS.equals(table)) map = taskMap; @@ -394,8 +394,8 @@ public class NameMaps { public static boolean shouldRecordOutstandingColumnForTable(String table, String column) { if (TABLE_ID_TASKS.equals(table)) { - if (TASK_COLUMN_NAMES_TO_PROPERTIES.containsKey(column)) - return !TASK_PROPERTIES_EXCLUDED.contains(column); + if (TASK_COLUMN_NAMES_TO_PROPERTIES.containsKey(column)) + return !TASK_PROPERTIES_EXCLUDED.contains(column); } else if (TABLE_ID_TAGS.equals(table)) { if (TAG_DATA_COLUMN_NAMES_TO_PROPERTIES.containsKey(column)) return !TAG_PROPERTIES_EXCLUDED.contains(column); diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/NowBriefed.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/NowBriefed.java index 78c89799a..378a683bc 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/NowBriefed.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/NowBriefed.java @@ -1,9 +1,5 @@ package com.todoroo.astrid.actfm.sync.messages; -import java.text.ParseException; - -import org.json.JSONObject; - import android.text.TextUtils; import android.util.Log; @@ -16,6 +12,10 @@ import com.todoroo.astrid.data.TagData; import com.todoroo.astrid.data.Task; import com.todoroo.astrid.data.User; +import org.json.JSONObject; + +import java.text.ParseException; + @SuppressWarnings("nls") public class NowBriefed extends ServerToClientMessage { diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ReplayOutstandingEntries.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ReplayOutstandingEntries.java index 260f624ac..c5e215e79 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ReplayOutstandingEntries.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ReplayOutstandingEntries.java @@ -74,7 +74,7 @@ public class ReplayOutstandingEntries property = NameMaps.localColumnNameToProperty(table, column); // set values to model diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/RequestDoubleCheck.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/RequestDoubleCheck.java index 5f405f783..c0c9a697e 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/RequestDoubleCheck.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/RequestDoubleCheck.java @@ -1,12 +1,12 @@ package com.todoroo.astrid.actfm.sync.messages; +import com.todoroo.astrid.dao.RemoteModelDao; +import com.todoroo.astrid.data.RemoteModel; + import org.apache.http.entity.mime.MultipartEntity; import org.json.JSONException; import org.json.JSONObject; -import com.todoroo.astrid.dao.RemoteModelDao; -import com.todoroo.astrid.data.RemoteModel; - public class RequestDoubleCheck extends ClientToServerMessage { public RequestDoubleCheck(long id, Class modelClass, RemoteModelDao modelDao) { diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ServerToClientMessage.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ServerToClientMessage.java index f31fe6eee..fa6444089 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ServerToClientMessage.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ServerToClientMessage.java @@ -1,7 +1,5 @@ package com.todoroo.astrid.actfm.sync.messages; -import org.json.JSONObject; - import com.todoroo.astrid.core.PluginServices; import com.todoroo.astrid.data.TagData; import com.todoroo.astrid.data.Task; @@ -11,6 +9,8 @@ import com.todoroo.astrid.data.User; import com.todoroo.astrid.data.UserActivity; import com.todoroo.astrid.data.WaitingOnMe; +import org.json.JSONObject; + @SuppressWarnings("nls") public abstract class ServerToClientMessage { diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/TaskListMetadataChangesHappened.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/TaskListMetadataChangesHappened.java index ba73feb7f..280998014 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/TaskListMetadataChangesHappened.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/TaskListMetadataChangesHappened.java @@ -1,8 +1,5 @@ package com.todoroo.astrid.actfm.sync.messages; -import java.util.HashSet; -import java.util.Set; - import android.text.TextUtils; import com.todoroo.astrid.dao.TaskListMetadataDao; @@ -11,6 +8,9 @@ import com.todoroo.astrid.data.RemoteModel; import com.todoroo.astrid.data.TaskListMetadata; import com.todoroo.astrid.data.TaskListMetadataOutstanding; +import java.util.HashSet; +import java.util.Set; + public class TaskListMetadataChangesHappened extends ChangesHappened { private final TaskListMetadataDao dao; diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/UserData.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/UserData.java index 2f6387830..3653b67f4 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/UserData.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/UserData.java @@ -1,7 +1,5 @@ package com.todoroo.astrid.actfm.sync.messages; -import org.json.JSONObject; - import android.text.TextUtils; import com.todoroo.andlib.sql.Criterion; @@ -12,6 +10,8 @@ import com.todoroo.astrid.data.TagMetadata; import com.todoroo.astrid.data.Task; import com.todoroo.astrid.tags.TagMemberMetadata; +import org.json.JSONObject; + public class UserData extends ServerToClientMessage { public UserData(JSONObject json) { diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/UserMigrated.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/UserMigrated.java index 15c94394e..d740bc2c1 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/UserMigrated.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/UserMigrated.java @@ -1,11 +1,11 @@ package com.todoroo.astrid.actfm.sync.messages; -import org.json.JSONObject; - import com.todoroo.andlib.utility.Preferences; import com.todoroo.astrid.actfm.sync.ActFmPreferenceService; import com.todoroo.astrid.data.RemoteModel; +import org.json.JSONObject; + public class UserMigrated extends ServerToClientMessage { public UserMigrated(JSONObject json) { diff --git a/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmControlSet.java b/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmControlSet.java index 780f6dc04..859d719ff 100644 --- a/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmControlSet.java +++ b/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmControlSet.java @@ -5,9 +5,6 @@ */ package com.todoroo.astrid.alarms; -import java.util.Date; -import java.util.LinkedHashSet; - import android.app.Activity; import android.view.LayoutInflater; import android.view.View; @@ -26,11 +23,13 @@ import com.todoroo.astrid.ui.DateAndTimeDialog; import com.todoroo.astrid.ui.DateAndTimeDialog.DateAndTimeDialogListener; import com.todoroo.astrid.ui.DateAndTimePicker; +import java.util.Date; +import java.util.LinkedHashSet; + /** * Control set to manage adding and removing tags * * @author Tim Su - * */ public final class AlarmControlSet extends TaskEditControlSet { @@ -48,7 +47,7 @@ public final class AlarmControlSet extends TaskEditControlSet { alertsContainer.removeAllViews(); TodorooCursor cursor = AlarmService.getInstance().getAlarms(model.getId()); try { - for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) + for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) addAlarm(new Date(cursor.get(AlarmFields.TIME))); } finally { cursor.close(); @@ -79,14 +78,14 @@ public final class AlarmControlSet extends TaskEditControlSet { @Override protected String writeToModelAfterInitialized(Task task) { LinkedHashSet alarms = new LinkedHashSet(); - for(int i = 0; i < alertsContainer.getChildCount(); i++) { + for (int i = 0; i < alertsContainer.getChildCount(); i++) { Long dateValue = (Long) alertsContainer.getChildAt(i).getTag(); - if(dateValue == null) + if (dateValue == null) continue; alarms.add(dateValue); } - if(AlarmService.getInstance().synchronizeAlarms(task.getId(), alarms)) + if (AlarmService.getInstance().synchronizeAlarms(task.getId(), alarms)) task.setValue(Task.MODIFICATION_DATE, DateUtilities.now()); return null; @@ -131,7 +130,7 @@ public final class AlarmControlSet extends TaskEditControlSet { display.setText(DateAndTimePicker.getDisplayString(activity, alert.getTime())); ImageButton reminderRemoveButton; - reminderRemoveButton = (ImageButton)alertItem.findViewById(R.id.button1); + reminderRemoveButton = (ImageButton) alertItem.findViewById(R.id.button1); reminderRemoveButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { alertsContainer.removeView(alertItem); diff --git a/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmDetailExposer.java b/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmDetailExposer.java index cb6b7d3b3..72ad0e65a 100644 --- a/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmDetailExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmDetailExposer.java @@ -5,8 +5,6 @@ */ package com.todoroo.astrid.alarms; -import java.util.Date; - import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; @@ -18,11 +16,12 @@ import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.api.AstridApiConstants; import com.todoroo.astrid.data.Metadata; +import java.util.Date; + /** * Exposes Task Detail for tags, i.e. "Tags: frogs, animals" * * @author Tim Su - * */ public class AlarmDetailExposer extends BroadcastReceiver { @@ -31,11 +30,11 @@ public class AlarmDetailExposer extends BroadcastReceiver { ContextManager.setContext(context); // get tags associated with this task long taskId = intent.getLongExtra(AstridApiConstants.EXTRAS_TASK_ID, -1); - if(taskId == -1) + if (taskId == -1) return; String taskDetail = getTaskDetails(context, taskId); - if(taskDetail == null) + if (taskDetail == null) return; // transmit @@ -50,25 +49,25 @@ public class AlarmDetailExposer extends BroadcastReceiver { TodorooCursor cursor = AlarmService.getInstance().getAlarms(id); long nextTime = -1; try { - for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { + for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { long time = cursor.get(AlarmFields.TIME); - if(time > DateUtilities.now()) { + if (time > DateUtilities.now()) { nextTime = time; break; } } - if(nextTime == -1) + if (nextTime == -1) return null; int flags = DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_SHOW_TIME; Date today = new Date(); Date alarm = new Date(nextTime); - if(today.getYear() == alarm.getYear()) + if (today.getYear() == alarm.getYear()) flags |= DateUtils.FORMAT_NO_YEAR; - if(alarm.getTime() - today.getTime() > DateUtilities.ONE_DAY) + if (alarm.getTime() - today.getTime() > DateUtilities.ONE_DAY) flags |= DateUtils.FORMAT_SHOW_DATE; CharSequence durationString = DateUtils.formatDateTime(context, nextTime, - flags); + flags); return " " + durationString; //$NON-NLS-1$ } finally { cursor.close(); diff --git a/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmFields.java b/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmFields.java index 98d093a72..409ec45f8 100644 --- a/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmFields.java +++ b/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmFields.java @@ -13,27 +13,36 @@ import com.todoroo.astrid.data.Metadata; * Metadata entry for a task alarm * * @author Tim Su - * */ public class AlarmFields { - /** metadata key */ + /** + * metadata key + */ public static final String METADATA_KEY = "alarm"; //$NON-NLS-1$ - /** time of alarm */ + /** + * time of alarm + */ public static final LongProperty TIME = new LongProperty(Metadata.TABLE, Metadata.VALUE1.name); - /** alarm type */ + /** + * alarm type + */ public static final IntegerProperty TYPE = new IntegerProperty(Metadata.TABLE, Metadata.VALUE2.name); // --- constants - /** this alarm is single-shot */ + /** + * this alarm is single-shot + */ public static final int TYPE_SINGLE = 1; - /** this alarm repeats itself until turned off */ + /** + * this alarm repeats itself until turned off + */ public static final int TYPE_REPEATING = 2; } diff --git a/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmService.java b/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmService.java index 141e0adde..4dd5a4ec1 100644 --- a/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmService.java +++ b/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmService.java @@ -5,10 +5,6 @@ */ package com.todoroo.astrid.alarms; -import java.util.ArrayList; -import java.util.Date; -import java.util.LinkedHashSet; - import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; @@ -33,11 +29,14 @@ import com.todoroo.astrid.service.MetadataService; import com.todoroo.astrid.service.MetadataService.SynchronizeMetadataCallback; import com.todoroo.astrid.utility.Constants; +import java.util.ArrayList; +import java.util.Date; +import java.util.LinkedHashSet; + /** * Provides operations for working with alerts * * @author Tim Su - * */ public class AlarmService { @@ -46,7 +45,7 @@ public class AlarmService { private static AlarmService instance = null; public static synchronized AlarmService getInstance() { - if(instance == null) + if (instance == null) instance = new AlarmService(); return instance; } @@ -63,11 +62,12 @@ public class AlarmService { public TodorooCursor getAlarms(long taskId) { return PluginServices.getMetadataService().query(Query.select( Metadata.PROPERTIES).where(MetadataCriteria.byTaskAndwithKey( - taskId, AlarmFields.METADATA_KEY)).orderBy(Order.asc(AlarmFields.TIME))); + taskId, AlarmFields.METADATA_KEY)).orderBy(Order.asc(AlarmFields.TIME))); } /** * Save the given array of alarms into the database + * * @param taskId * @param tags * @return true if data was changed @@ -76,7 +76,7 @@ public class AlarmService { MetadataService service = PluginServices.getMetadataService(); ArrayList metadata = new ArrayList(); - for(Long alarm : alarms) { + for (Long alarm : alarms) { Metadata item = new Metadata(); item.setValue(Metadata.KEY, AlarmFields.METADATA_KEY); item.setValue(AlarmFields.TIME, alarm); @@ -85,7 +85,7 @@ public class AlarmService { } final Context context = ContextManager.getContext(); - final AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); + final AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); boolean changed = service.synchronizeMetadata(taskId, metadata, Metadata.KEY.eq(AlarmFields.METADATA_KEY), new SynchronizeMetadataCallback() { @Override @@ -96,7 +96,7 @@ public class AlarmService { } }, true); - if(changed) + if (changed) scheduleAlarms(taskId); return changed; } @@ -105,6 +105,7 @@ public class AlarmService { /** * Gets a listing of all alarms that are active + * * @param properties * @return todoroo cursor. PLEASE CLOSE THIS CURSOR! */ @@ -116,6 +117,7 @@ public class AlarmService { /** * Gets a listing of alarms by task + * * @param properties * @return todoroo cursor. PLEASE CLOSE THIS CURSOR! */ @@ -133,7 +135,7 @@ public class AlarmService { TodorooCursor cursor = getActiveAlarms(); try { Metadata alarm = new Metadata(); - for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { + for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { alarm.readFromCursor(cursor); scheduleAlarm(alarm); } @@ -148,13 +150,14 @@ public class AlarmService { /** * Schedules alarms for a single task + * * @param task */ public void scheduleAlarms(long taskId) { TodorooCursor cursor = getActiveAlarmsForTask(taskId); try { Metadata alarm = new Metadata(); - for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { + for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { alarm.readFromCursor(cursor); scheduleAlarm(alarm); } @@ -172,34 +175,33 @@ public class AlarmService { intent.putExtra(Notifications.ID_KEY, taskId); intent.putExtra(Notifications.EXTRAS_TYPE, ReminderService.TYPE_ALARM); - return PendingIntent.getBroadcast(context, (int)alarm.getId(), + return PendingIntent.getBroadcast(context, (int) alarm.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT); } /** * Schedules alarms for a single task * - * @param shouldPerformPropertyCheck - * whether to check if task has requisite properties + * @param shouldPerformPropertyCheck whether to check if task has requisite properties */ @SuppressWarnings("nls") private void scheduleAlarm(Metadata alarm) { - if(alarm == null) + if (alarm == null) return; long taskId = alarm.getValue(Metadata.TASK); Context context = ContextManager.getContext(); - AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); + AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); PendingIntent pendingIntent = pendingIntentForAlarm(alarm, taskId); long time = alarm.getValue(AlarmFields.TIME); - if(time == 0 || time == NO_ALARM) + if (time == 0 || time == NO_ALARM) am.cancel(pendingIntent); - else if(time > DateUtilities.now()) { - if(Constants.DEBUG) + else if (time > DateUtilities.now()) { + if (Constants.DEBUG) Log.e("Astrid", "Alarm (" + taskId + ", " + ReminderService.TYPE_ALARM + - ", " + alarm.getId() + ") set for " + new Date(time)); + ", " + alarm.getId() + ") set for " + new Date(time)); am.set(AlarmManager.RTC_WAKEUP, time, pendingIntent); } } diff --git a/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmTaskRepeatListener.java b/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmTaskRepeatListener.java index 30f44feb0..e0ecb8cf9 100644 --- a/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmTaskRepeatListener.java +++ b/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmTaskRepeatListener.java @@ -5,8 +5,6 @@ */ package com.todoroo.astrid.alarms; -import java.util.LinkedHashSet; - import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; @@ -17,30 +15,32 @@ import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.api.AstridApiConstants; import com.todoroo.astrid.data.Metadata; +import java.util.LinkedHashSet; + public class AlarmTaskRepeatListener extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { ContextManager.setContext(context); long taskId = intent.getLongExtra(AstridApiConstants.EXTRAS_TASK_ID, -1); - if(taskId == -1) + if (taskId == -1) return; long oldDueDate = intent.getLongExtra(AstridApiConstants.EXTRAS_OLD_DUE_DATE, 0); - if(oldDueDate == 0) + if (oldDueDate == 0) oldDueDate = DateUtilities.now(); long newDueDate = intent.getLongExtra(AstridApiConstants.EXTRAS_NEW_DUE_DATE, -1); - if(newDueDate <= 0 || newDueDate <= oldDueDate) + if (newDueDate <= 0 || newDueDate <= oldDueDate) return; TodorooCursor cursor = AlarmService.getInstance().getAlarms(taskId); try { - if(cursor.getCount() == 0) + if (cursor.getCount() == 0) return; Metadata metadata = new Metadata(); LinkedHashSet alarms = new LinkedHashSet(cursor.getCount()); - for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { + for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { metadata.readFromCursor(cursor); alarms.add(metadata.getValue(AlarmFields.TIME) + (newDueDate - oldDueDate)); } diff --git a/astrid/plugin-src/com/todoroo/astrid/backup/BackupActivity.java b/astrid/plugin-src/com/todoroo/astrid/backup/BackupActivity.java index 3a3a35c4c..96f28e40d 100644 --- a/astrid/plugin-src/com/todoroo/astrid/backup/BackupActivity.java +++ b/astrid/plugin-src/com/todoroo/astrid/backup/BackupActivity.java @@ -24,14 +24,14 @@ public class BackupActivity extends Activity { setContentView(R.layout.backup_activity); setTitle(R.string.backup_BAc_title); - ((Button)findViewById(R.id.importButton)).setOnClickListener(new OnClickListener() { + ((Button) findViewById(R.id.importButton)).setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { importTasks(); } }); - ((Button)findViewById(R.id.exportButton)).setOnClickListener(new OnClickListener() { + ((Button) findViewById(R.id.exportButton)).setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { exportTasks(); @@ -45,13 +45,13 @@ public class BackupActivity extends Activity { public void onFilePicked(String filePath) { TasksXmlImporter.importTasks(BackupActivity.this, filePath, new Runnable() { - @Override - public void run() { - setResult(RESULT_OK); - finish(); - Flags.set(Flags.REFRESH); - } - }); + @Override + public void run() { + setResult(RESULT_OK); + finish(); + Flags.set(Flags.REFRESH); + } + }); } }; new FilePickerBuilder(this, diff --git a/astrid/plugin-src/com/todoroo/astrid/backup/BackupConstants.java b/astrid/plugin-src/com/todoroo/astrid/backup/BackupConstants.java index bb2e517fd..327683d46 100644 --- a/astrid/plugin-src/com/todoroo/astrid/backup/BackupConstants.java +++ b/astrid/plugin-src/com/todoroo/astrid/backup/BackupConstants.java @@ -5,9 +5,10 @@ */ package com.todoroo.astrid.backup; +import android.os.Environment; + import java.io.File; -import android.os.Environment; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -15,7 +16,6 @@ import edu.umd.cs.findbugs.annotations.CheckForNull; * Constants for backup XML attributes and nodes. * * @author Tim Su - * */ @SuppressWarnings("nls") public class BackupConstants { @@ -24,21 +24,31 @@ public class BackupConstants { // --- general xml - /** Tag containing Astrid backup data */ + /** + * Tag containing Astrid backup data + */ public static final String ASTRID_TAG = "astrid"; - /** Attribute indicating application version */ + /** + * Attribute indicating application version + */ public static final String ASTRID_ATTR_VERSION = "version"; - /** Attribute indicating backup file format */ + /** + * Attribute indicating backup file format + */ public static final String ASTRID_ATTR_FORMAT = "format"; // --- format 2 - /** Tag containing a task */ + /** + * Tag containing a task + */ public static final String TASK_TAG = "task"; - /** Tag containing a metadata item */ + /** + * Tag containing a metadata item + */ public static final String METADATA_TAG = "metadata"; // --- format 1 diff --git a/astrid/plugin-src/com/todoroo/astrid/backup/BackupDateUtilities.java b/astrid/plugin-src/com/todoroo/astrid/backup/BackupDateUtilities.java index 147ea8e1e..804dc1fcb 100644 --- a/astrid/plugin-src/com/todoroo/astrid/backup/BackupDateUtilities.java +++ b/astrid/plugin-src/com/todoroo/astrid/backup/BackupDateUtilities.java @@ -5,18 +5,17 @@ */ package com.todoroo.astrid.backup; +import android.util.Log; + import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; -import android.util.Log; - /** * Date Utility functions for backups * * @author Tim Su - * */ @SuppressWarnings("nls") public class BackupDateUtilities { @@ -25,6 +24,7 @@ public class BackupDateUtilities { /** * Format a Date into ISO 8601 Complaint format. + * * @return date string, or empty string if input was null */ public static String getIso8601String(Date d) { diff --git a/astrid/plugin-src/com/todoroo/astrid/backup/BackupPreferences.java b/astrid/plugin-src/com/todoroo/astrid/backup/BackupPreferences.java index 966ada565..f55319021 100644 --- a/astrid/plugin-src/com/todoroo/astrid/backup/BackupPreferences.java +++ b/astrid/plugin-src/com/todoroo/astrid/backup/BackupPreferences.java @@ -5,8 +5,6 @@ */ package com.todoroo.astrid.backup; -import java.util.Date; - import android.content.Intent; import android.content.res.Resources; import android.graphics.Color; @@ -26,12 +24,13 @@ import com.todoroo.andlib.utility.TodorooPreferenceActivity; import com.todoroo.astrid.actfm.ActFmLoginActivity; import com.todoroo.astrid.actfm.sync.ActFmPreferenceService; +import java.util.Date; + /** * Displays synchronization preferences and an action panel so users can * initiate actions from the menu. * * @author timsu - * */ public class BackupPreferences extends TodorooPreferenceActivity { @@ -63,7 +62,7 @@ public class BackupPreferences extends TodorooPreferenceActivity { @Override public void onChildViewAdded(View parent, View child) { View view = findViewById(R.id.status); - if(view != null) + if (view != null) view.setBackgroundColor(statusColor); } }); @@ -93,9 +92,7 @@ public class BackupPreferences extends TodorooPreferenceActivity { } /** - * - * @param resource - * if null, updates all resources + * @param resource if null, updates all resources */ @Override public void updatePreferences(Preference preference, Object value) { @@ -104,7 +101,7 @@ public class BackupPreferences extends TodorooPreferenceActivity { // auto if (r.getString(R.string.backup_BPr_auto_key).equals( preference.getKey())) { - if (value != null && !(Boolean)value) + if (value != null && !(Boolean) value) preference.setSummary(R.string.backup_BPr_auto_disabled); else preference.setSummary(R.string.backup_BPr_auto_enabled); @@ -118,7 +115,7 @@ public class BackupPreferences extends TodorooPreferenceActivity { // last backup was error final long last = Preferences.getLong(PREF_BACKUP_LAST_DATE, 0); final String error = Preferences.getStringValue(PREF_BACKUP_LAST_ERROR); - if(error != null) { + if (error != null) { status = r.getString(R.string.backup_status_failed); subtitle = r.getString(R.string.backup_status_failed_subtitle); statusColor = Color.rgb(100, 0, 0); @@ -128,10 +125,10 @@ public class BackupPreferences extends TodorooPreferenceActivity { return true; } }); - } else if(last > 0) { + } else if (last > 0) { status = r.getString(R.string.backup_status_success, DateUtilities.getDateStringWithTime(BackupPreferences.this, - new Date(last))); + new Date(last))); statusColor = Color.rgb(0, 100, 0); preference.setOnPreferenceClickListener(null); } else { @@ -143,7 +140,7 @@ public class BackupPreferences extends TodorooPreferenceActivity { preference.setSummary(subtitle); View view = findViewById(R.id.status); - if(view != null) + if (view != null) view.setBackgroundColor(statusColor); } diff --git a/astrid/plugin-src/com/todoroo/astrid/backup/BackupService.java b/astrid/plugin-src/com/todoroo/astrid/backup/BackupService.java index b8e394ee7..113ed9b2c 100644 --- a/astrid/plugin-src/com/todoroo/astrid/backup/BackupService.java +++ b/astrid/plugin-src/com/todoroo/astrid/backup/BackupService.java @@ -5,11 +5,6 @@ */ package com.todoroo.astrid.backup; -import java.io.File; -import java.io.FileFilter; -import java.util.Arrays; -import java.util.Comparator; - import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; @@ -24,6 +19,11 @@ import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.andlib.utility.Preferences; import com.todoroo.astrid.core.PluginServices; +import java.io.File; +import java.io.FileFilter; +import java.util.Arrays; +import java.util.Comparator; + /** * Inspired heavily by SynchronizationService */ @@ -61,6 +61,7 @@ public class BackupService extends Service { /** * Test hook for backup + * * @param context */ public void testBackup(Context context) { @@ -127,12 +128,12 @@ public class BackupService extends Service { } }; File astridDir = backupDirectorySetting.getBackupDirectory(); - if(astridDir == null) + if (astridDir == null) return; // grab all backup files, sort by modified date, delete old ones File[] files = astridDir.listFiles(backupFileFilter); - if(files == null) + if (files == null) return; Arrays.sort(files, new Comparator() { @@ -141,16 +142,16 @@ public class BackupService extends Service { return -Long.valueOf(file1.lastModified()).compareTo(Long.valueOf(file2.lastModified())); } }); - for(int i = DAYS_TO_KEEP_BACKUP; i < files.length; i++) { - if(!files[i].delete()) + for (int i = DAYS_TO_KEEP_BACKUP; i < files.length; i++) { + if (!files[i].delete()) Log.i("astrid-backups", "Unable to delete: " + files[i]); //$NON-NLS-1$ //$NON-NLS-2$ } } /** * Interface for setting where backups go - * @author Tim Su * + * @author Tim Su */ public interface BackupDirectorySetting { public File getBackupDirectory(); diff --git a/astrid/plugin-src/com/todoroo/astrid/backup/FilePickerBuilder.java b/astrid/plugin-src/com/todoroo/astrid/backup/FilePickerBuilder.java index a3012aaf1..7a0b8ae48 100644 --- a/astrid/plugin-src/com/todoroo/astrid/backup/FilePickerBuilder.java +++ b/astrid/plugin-src/com/todoroo/astrid/backup/FilePickerBuilder.java @@ -5,9 +5,6 @@ */ package com.todoroo.astrid.backup; -import java.io.File; -import java.io.FilenameFilter; - import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; @@ -16,6 +13,9 @@ import android.util.Log; import com.timsu.astrid.R; import com.todoroo.andlib.utility.AndroidUtilities; +import java.io.File; +import java.io.FilenameFilter; + @SuppressWarnings("nls") public class FilePickerBuilder extends AlertDialog.Builder implements DialogInterface.OnClickListener { @@ -54,7 +54,7 @@ public class FilePickerBuilder extends AlertDialog.Builder implements DialogInte AndroidUtilities.sortFilesByDateDesc(filesAsFile); files = new String[filesAsFile.length]; - for(int i = 0; i < files.length; i++) + for (int i = 0; i < files.length; i++) files[i] = filesAsFile[i].getName(); setItems(files, this); diff --git a/astrid/plugin-src/com/todoroo/astrid/backup/TasksXmlExporter.java b/astrid/plugin-src/com/todoroo/astrid/backup/TasksXmlExporter.java index 86085d8ce..493c960ce 100644 --- a/astrid/plugin-src/com/todoroo/astrid/backup/TasksXmlExporter.java +++ b/astrid/plugin-src/com/todoroo/astrid/backup/TasksXmlExporter.java @@ -5,12 +5,6 @@ */ package com.todoroo.astrid.backup; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; - -import org.xmlpull.v1.XmlSerializer; - import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; @@ -39,6 +33,12 @@ import com.todoroo.astrid.service.MetadataService; import com.todoroo.astrid.service.TaskService; import com.todoroo.astrid.utility.AstridPreferences; +import org.xmlpull.v1.XmlSerializer; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; + public class TasksXmlExporter { // --- public interface @@ -46,13 +46,13 @@ public class TasksXmlExporter { /** * Import tasks from the given file * - * @param context context - * @param exportType from service, manual, or on upgrade - * @param runAfterExport runnable to run after exporting + * @param context context + * @param exportType from service, manual, or on upgrade + * @param runAfterExport runnable to run after exporting * @param backupDirectoryOverride new backupdirectory, or null to use default */ public static void exportTasks(Context context, ExportType exportType, - Runnable runAfterExport, File backupDirectoryOverride, String versionName) { + Runnable runAfterExport, File backupDirectoryOverride, String versionName) { new TasksXmlExporter(context, exportType, runAfterExport, backupDirectoryOverride, versionName); } @@ -90,7 +90,7 @@ public class TasksXmlExporter { } private TasksXmlExporter(final Context context, final ExportType exportType, - final Runnable runAfterExport, File backupDirectoryOverride, String versionName) { + final Runnable runAfterExport, File backupDirectoryOverride, String versionName) { this.context = context; this.exportCount = 0; this.backupDirectory = backupDirectoryOverride == null ? @@ -99,7 +99,7 @@ public class TasksXmlExporter { handler = new Handler(); progressDialog = new ProgressDialog(context); - if(exportType == ExportType.EXPORT_TYPE_MANUAL) { + if (exportType == ExportType.EXPORT_TYPE_MANUAL) { progressDialog.setIcon(android.R.drawable.ic_dialog_info); progressDialog.setTitle(R.string.export_progress_title); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); @@ -107,8 +107,8 @@ public class TasksXmlExporter { progressDialog.setCancelable(false); progressDialog.setIndeterminate(false); progressDialog.show(); - if(context instanceof Activity) - progressDialog.setOwnerActivity((Activity)context); + if (context instanceof Activity) + progressDialog.setOwnerActivity((Activity) context); } new Thread(new Runnable() { @@ -119,7 +119,7 @@ public class TasksXmlExporter { exportType); int tasks = taskService.countTasks(); - if(tasks > 0) + if (tasks > 0) doTasksExport(output); Preferences.setLong(BackupPreferences.PREF_BACKUP_LAST_DATE, @@ -129,22 +129,22 @@ public class TasksXmlExporter { if (exportType == ExportType.EXPORT_TYPE_MANUAL) onFinishExport(output); } catch (IOException e) { - switch(exportType) { - case EXPORT_TYPE_MANUAL: - exceptionService.displayAndReportError(context, - context.getString(R.string.backup_TXI_error), e); - break; - case EXPORT_TYPE_SERVICE: - exceptionService.reportError("background-backup", e); //$NON-NLS-1$ - Preferences.setString(BackupPreferences.PREF_BACKUP_LAST_ERROR, e.toString()); - break; - case EXPORT_TYPE_ON_UPGRADE: - exceptionService.reportError("background-backup", e); //$NON-NLS-1$ - Preferences.setString(BackupPreferences.PREF_BACKUP_LAST_ERROR, e.toString()); - break; + switch (exportType) { + case EXPORT_TYPE_MANUAL: + exceptionService.displayAndReportError(context, + context.getString(R.string.backup_TXI_error), e); + break; + case EXPORT_TYPE_SERVICE: + exceptionService.reportError("background-backup", e); //$NON-NLS-1$ + Preferences.setString(BackupPreferences.PREF_BACKUP_LAST_ERROR, e.toString()); + break; + case EXPORT_TYPE_ON_UPGRADE: + exceptionService.reportError("background-backup", e); //$NON-NLS-1$ + Preferences.setString(BackupPreferences.PREF_BACKUP_LAST_ERROR, e.toString()); + break; } } finally { - if(runAfterExport != null) + if (runAfterExport != null) runAfterExport.run(); } } @@ -184,7 +184,7 @@ public class TasksXmlExporter { try { Task task = new Task(); int length = cursor.getCount(); - for(int i = 0; i < length; i++) { + for (int i = 0; i < length; i++) { cursor.moveToNext(); task.readFromCursor(cursor); @@ -206,7 +206,7 @@ public class TasksXmlExporter { Metadata.PROPERTIES).where(MetadataCriteria.byTask(task.getId()))); try { Metadata metadata = new Metadata(); - for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { + for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { metadata.readFromCursor(cursor); xml.startTag(null, BackupConstants.METADATA_TAG); @@ -220,12 +220,14 @@ public class TasksXmlExporter { /** * Turn a model into xml attributes + * * @param model */ private void serializeModel(AbstractModel model, Property[] properties, Property... excludes) { - outer: for(Property property : properties) { - for(Property exclude : excludes) - if(property.name.equals(exclude.name)) + outer: + for (Property property : properties) { + for (Property exclude : excludes) + if (property.name.equals(exclude.name)) continue outer; try { @@ -233,7 +235,7 @@ public class TasksXmlExporter { } catch (Exception e) { Log.e("astrid-exporter", //$NON-NLS-1$ "Caught exception while reading " + property.name + //$NON-NLS-1$ - " from " + model.getDatabaseValues(), e); //$NON-NLS-1$ + " from " + model.getDatabaseValues(), e); //$NON-NLS-1$ } } } @@ -301,7 +303,7 @@ public class TasksXmlExporter { public Void visitString(Property property, AbstractModel data) { try { String value = data.getValue(property); - if(value == null) + if (value == null) return null; xml.attribute(null, property.name, value); } catch (UnsupportedOperationException e) { @@ -322,14 +324,14 @@ public class TasksXmlExporter { @Override public void run() { - if(exportCount == 0) + if (exportCount == 0) Toast.makeText(context, context.getString(R.string.export_toast_no_tasks), Toast.LENGTH_LONG).show(); else { CharSequence text = String.format(context.getString(R.string.export_toast), context.getResources().getQuantityString(R.plurals.Ntasks, exportCount, exportCount), outputFile); Toast.makeText(context, text, Toast.LENGTH_LONG).show(); - if(progressDialog.isShowing() && context instanceof Activity) + if (progressDialog.isShowing() && context instanceof Activity) DialogUtilities.dismissDialog((Activity) context, progressDialog); } } @@ -338,6 +340,7 @@ public class TasksXmlExporter { /** * Creates directories if necessary and returns fully qualified file + * * @param directory * @return output file name * @throws IOException @@ -348,18 +351,18 @@ public class TasksXmlExporter { // Check for /sdcard/astrid directory. If it doesn't exist, make it. if (astridDir.exists() || astridDir.mkdir()) { String fileName = ""; //$NON-NLS-1$ - switch(exportType) { - case EXPORT_TYPE_SERVICE: - fileName = String.format(BackupConstants.BACKUP_FILE_NAME, BackupDateUtilities.getDateForExport()); - break; - case EXPORT_TYPE_MANUAL: - fileName = String.format(BackupConstants.EXPORT_FILE_NAME, BackupDateUtilities.getDateForExport()); - break; - case EXPORT_TYPE_ON_UPGRADE: - fileName = String.format(BackupConstants.UPGRADE_FILE_NAME, latestSetVersionName); - break; - default: - throw new IllegalArgumentException("Invalid export type"); //$NON-NLS-1$ + switch (exportType) { + case EXPORT_TYPE_SERVICE: + fileName = String.format(BackupConstants.BACKUP_FILE_NAME, BackupDateUtilities.getDateForExport()); + break; + case EXPORT_TYPE_MANUAL: + fileName = String.format(BackupConstants.EXPORT_FILE_NAME, BackupDateUtilities.getDateForExport()); + break; + case EXPORT_TYPE_ON_UPGRADE: + fileName = String.format(BackupConstants.UPGRADE_FILE_NAME, latestSetVersionName); + break; + default: + throw new IllegalArgumentException("Invalid export type"); //$NON-NLS-1$ } return astridDir.getAbsolutePath() + File.separator + fileName; } else { diff --git a/astrid/plugin-src/com/todoroo/astrid/backup/TasksXmlImporter.java b/astrid/plugin-src/com/todoroo/astrid/backup/TasksXmlImporter.java index 98ee4851f..a46b0c5cb 100644 --- a/astrid/plugin-src/com/todoroo/astrid/backup/TasksXmlImporter.java +++ b/astrid/plugin-src/com/todoroo/astrid/backup/TasksXmlImporter.java @@ -5,16 +5,6 @@ */ package com.todoroo.astrid.backup; -import java.io.FileReader; -import java.io.IOException; -import java.util.Date; -import java.util.LinkedHashSet; -import java.util.StringTokenizer; - -import org.xmlpull.v1.XmlPullParser; -import org.xmlpull.v1.XmlPullParserException; -import org.xmlpull.v1.XmlPullParserFactory; - import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; @@ -52,6 +42,16 @@ import com.todoroo.astrid.service.TaskService; import com.todoroo.astrid.service.UpgradeService; import com.todoroo.astrid.tags.TagService; +import org.xmlpull.v1.XmlPullParser; +import org.xmlpull.v1.XmlPullParserException; +import org.xmlpull.v1.XmlPullParserFactory; + +import java.io.FileReader; +import java.io.IOException; +import java.util.Date; +import java.util.LinkedHashSet; +import java.util.StringTokenizer; + public class TasksXmlImporter { // --- public interface @@ -92,6 +92,7 @@ public class TasksXmlImporter { /** * Import tasks. + * * @param runAfterImport optional runnable after import */ private TasksXmlImporter(final Context context, String input, Runnable runAfterImport) { @@ -108,8 +109,8 @@ public class TasksXmlImporter { progressDialog.setIndeterminate(true); try { progressDialog.show(); - if(context instanceof Activity) - progressDialog.setOwnerActivity((Activity)context); + if (context instanceof Activity) + progressDialog.setOwnerActivity((Activity) context); } catch (BadTokenException e) { // Running from a unit test or some such thing } @@ -147,14 +148,14 @@ public class TasksXmlImporter { // Process if (tag.equals(BackupConstants.ASTRID_TAG)) { String format = xpp.getAttributeValue(null, BackupConstants.ASTRID_ATTR_FORMAT); - if(TextUtils.equals(format, FORMAT1)) + if (TextUtils.equals(format, FORMAT1)) new Format1TaskImporter(xpp); - else if(TextUtils.equals(format, FORMAT2)) + else if (TextUtils.equals(format, FORMAT2)) new Format2TaskImporter(xpp); else throw new UnsupportedOperationException( "Did not know how to import tasks with xml format '" + - format + "'"); + format + "'"); } } } @@ -164,8 +165,8 @@ public class TasksXmlImporter { handler.post(new Runnable() { @Override public void run() { - if(progressDialog.isShowing() && context instanceof Activity) - DialogUtilities.dismissDialog((Activity) context, progressDialog); + if (progressDialog.isShowing() && context instanceof Activity) + DialogUtilities.dismissDialog((Activity) context, progressDialog); showSummary(); } }); @@ -191,7 +192,7 @@ public class TasksXmlImporter { handler.post(runAfterImport); } } - }); + }); builder.show(); } @@ -201,6 +202,7 @@ public class TasksXmlImporter { // =============================================================== FORMAT2 private static final String FORMAT2 = "2"; //$NON-NLS-1$ + private class Format2TaskImporter { private int version; @@ -235,7 +237,7 @@ public class TasksXmlImporter { errorCount++; Log.e("astrid-importer", //$NON-NLS-1$ "Caught exception while reading from " + //$NON-NLS-1$ - xpp.getText(), e); + xpp.getText(), e); } } } @@ -261,24 +263,24 @@ public class TasksXmlImporter { // if the task's name and creation date match an existing task, skip long existingTask = 0; TodorooCursor cursor = taskService.query(Query.select(Task.ID, - Task.COMPLETION_DATE, Task.DELETION_DATE). + Task.COMPLETION_DATE, Task.DELETION_DATE). where(Criterion.and(Task.TITLE.eq(title), Task.CREATION_DATE.eq(created)))); try { - if(cursor.getCount() > 0) { + if (cursor.getCount() > 0) { cursor.moveToNext(); // fix for failed migration in 4.0.6 - if(version < UpgradeService.V4_0_6) { - if(!completionDate.equals("0") && + if (version < UpgradeService.V4_0_6) { + if (!completionDate.equals("0") && !completionDate.equals(Long.toString(cursor.get(Task.COMPLETION_DATE)))) existingTask = cursor.get(Task.ID); - if(!deletionDate.equals("0") && + if (!deletionDate.equals("0") && !deletionDate.equals(Long.toString(cursor.get(Task.DELETION_DATE)))) existingTask = cursor.get(Task.ID); } - if(existingTask == 0) { + if (existingTask == 0) { skipCount++; return; } @@ -289,10 +291,10 @@ public class TasksXmlImporter { // else, make a new task model and add away. deserializeModel(currentTask, Task.PROPERTIES); - if(version < UpgradeService.V4_0_6) + if (version < UpgradeService.V4_0_6) adjustDueDateScheme(currentTask); - if(existingTask > 0) + if (existingTask > 0) currentTask.setId(existingTask); else currentTask.setId(Task.NO_ID); @@ -319,7 +321,7 @@ public class TasksXmlImporter { } private void parseMetadata() { - if(!currentTask.isSaved()) + if (!currentTask.isSaved()) return; metadata.clear(); deserializeModel(metadata, Metadata.PROPERTIES); @@ -330,16 +332,17 @@ public class TasksXmlImporter { /** * Turn a model into xml attributes + * * @param model */ private void deserializeModel(AbstractModel model, Property[] properties) { - for(Property property : properties) { + for (Property property : properties) { try { property.accept(xmlReadingVisitor, model); } catch (Exception e) { Log.e("astrid-importer", //$NON-NLS-1$ "Caught exception while writing " + property.name + //$NON-NLS-1$ - " from " + xpp.getText(), e); //$NON-NLS-1$ + " from " + xpp.getText(), e); //$NON-NLS-1$ } } } @@ -350,9 +353,9 @@ public class TasksXmlImporter { @Override public Void visitInteger(Property property, - AbstractModel data) { + AbstractModel data) { String value = xpp.getAttributeValue(null, property.name); - if(value != null) + if (value != null) data.setValue(property, TasksXmlExporter.XML_NULL.equals(value) ? null : Integer.parseInt(value)); return null; @@ -361,7 +364,7 @@ public class TasksXmlImporter { @Override public Void visitLong(Property property, AbstractModel data) { String value = xpp.getAttributeValue(null, property.name); - if(value != null) + if (value != null) data.setValue(property, TasksXmlExporter.XML_NULL.equals(value) ? null : Long.parseLong(value)); return null; @@ -369,9 +372,9 @@ public class TasksXmlImporter { @Override public Void visitDouble(Property property, - AbstractModel data) { + AbstractModel data) { String value = xpp.getAttributeValue(null, property.name); - if(value != null) + if (value != null) data.setValue(property, TasksXmlExporter.XML_NULL.equals(value) ? null : Double.parseDouble(value)); return null; @@ -379,9 +382,9 @@ public class TasksXmlImporter { @Override public Void visitString(Property property, - AbstractModel data) { + AbstractModel data) { String value = xpp.getAttributeValue(null, property.name); - if(value != null) + if (value != null) data.setValue(property, value); return null; } @@ -392,6 +395,7 @@ public class TasksXmlImporter { // =============================================================== FORMAT1 private static final String FORMAT1 = null; + private class Format1TaskImporter { private final XmlPullParser xpp; @@ -408,7 +412,7 @@ public class TasksXmlImporter { String tag = xpp.getName(); try { - if(BackupConstants.TASK_TAG.equals(tag) && xpp.getEventType() == XmlPullParser.END_TAG) + if (BackupConstants.TASK_TAG.equals(tag) && xpp.getEventType() == XmlPullParser.END_TAG) saveTags(); else if (tag == null || xpp.getEventType() == XmlPullParser.END_TAG) continue; @@ -433,7 +437,7 @@ public class TasksXmlImporter { errorCount++; Log.e("astrid-importer", //$NON-NLS-1$ "Caught exception while reading from " + //$NON-NLS-1$ - xpp.getText(), e); + xpp.getText(), e); } } } @@ -471,7 +475,7 @@ public class TasksXmlImporter { } private void saveTags() { - if(currentTask != null && tags.size() > 0) { + if (currentTask != null && tags.size() > 0) { TagService.getInstance().synchronizeTags(currentTask.getId(), currentTask.getValue(Task.UUID), tags); } tags.clear(); @@ -500,9 +504,9 @@ public class TasksXmlImporter { // if the task's name and creation date match an existing task, skip TodorooCursor cursor = taskService.query(Query.select(Task.ID). where(Criterion.and(Task.TITLE.eq(taskName), - Task.CREATION_DATE.like(creationDate.getTime()/1000L + "%")))); + Task.CREATION_DATE.like(creationDate.getTime() / 1000L + "%")))); try { - if(cursor.getCount() > 0) { + if (cursor.getCount() > 0) { skipCount++; return null; } @@ -516,14 +520,14 @@ public class TasksXmlImporter { for (int i = 0; i < numAttributes; i++) { String fieldName = xpp.getAttributeName(i); String fieldValue = xpp.getAttributeValue(i); - if(!setTaskField(task, fieldName, fieldValue)) { + if (!setTaskField(task, fieldName, fieldValue)) { Log.i("astrid-xml-import", "Task: " + taskName + ": Unknown field '" + fieldName + "' with value '" + fieldValue + "' disregarded."); } } - if(upgradeNotes != null) { - if(task.containsValue(Task.NOTES) && task.getValue(Task.NOTES).length() > 0) + if (upgradeNotes != null) { + if (task.containsValue(Task.NOTES) && task.getValue(Task.NOTES).length() > 0) task.setValue(Task.NOTES, task.getValue(Task.NOTES) + "\n" + upgradeNotes); else task.setValue(Task.NOTES, upgradeNotes); @@ -536,37 +540,31 @@ public class TasksXmlImporter { return task; } - /** helper method to set field on a task */ + /** + * helper method to set field on a task + */ @SuppressWarnings("nls") private final boolean setTaskField(Task task, String field, String value) { - if(field.equals(LegacyTaskModel.ID)) { + if (field.equals(LegacyTaskModel.ID)) { // ignore - } - else if(field.equals(LegacyTaskModel.NAME)) { + } else if (field.equals(LegacyTaskModel.NAME)) { task.setValue(Task.TITLE, value); - } - else if(field.equals(LegacyTaskModel.NOTES)) { + } else if (field.equals(LegacyTaskModel.NOTES)) { task.setValue(Task.NOTES, value); - } - else if(field.equals(LegacyTaskModel.PROGRESS_PERCENTAGE)) { + } else if (field.equals(LegacyTaskModel.PROGRESS_PERCENTAGE)) { // ignore - } - else if(field.equals(LegacyTaskModel.IMPORTANCE)) { + } else if (field.equals(LegacyTaskModel.IMPORTANCE)) { task.setValue(Task.IMPORTANCE, LegacyImportance.valueOf(value).ordinal()); - } - else if(field.equals(LegacyTaskModel.ESTIMATED_SECONDS)) { + } else if (field.equals(LegacyTaskModel.ESTIMATED_SECONDS)) { task.setValue(Task.ESTIMATED_SECONDS, Integer.parseInt(value)); - } - else if(field.equals(LegacyTaskModel.ELAPSED_SECONDS)) { + } else if (field.equals(LegacyTaskModel.ELAPSED_SECONDS)) { task.setValue(Task.ELAPSED_SECONDS, Integer.parseInt(value)); - } - else if(field.equals(LegacyTaskModel.TIMER_START)) { + } else if (field.equals(LegacyTaskModel.TIMER_START)) { task.setValue(Task.TIMER_START, BackupDateUtilities.getDateFromIso8601String(value).getTime()); - } - else if(field.equals(LegacyTaskModel.DEFINITE_DUE_DATE)) { + } else if (field.equals(LegacyTaskModel.DEFINITE_DUE_DATE)) { String preferred = xpp.getAttributeValue(null, LegacyTaskModel.PREFERRED_DUE_DATE); - if(preferred != null) { + if (preferred != null) { Date preferredDate = BackupDateUtilities.getDateFromIso8601String(value); upgradeNotes = "Project Deadline: " + DateUtilities.getDateString(ContextManager.getContext(), @@ -574,64 +572,51 @@ public class TasksXmlImporter { } task.setValue(Task.DUE_DATE, BackupDateUtilities.getTaskDueDateFromIso8601String(value).getTime()); - } - else if(field.equals(LegacyTaskModel.PREFERRED_DUE_DATE)) { + } else if (field.equals(LegacyTaskModel.PREFERRED_DUE_DATE)) { String definite = xpp.getAttributeValue(null, LegacyTaskModel.DEFINITE_DUE_DATE); - if(definite != null) + if (definite != null) ; // handled above else task.setValue(Task.DUE_DATE, BackupDateUtilities.getTaskDueDateFromIso8601String(value).getTime()); - } - else if(field.equals(LegacyTaskModel.HIDDEN_UNTIL)) { + } else if (field.equals(LegacyTaskModel.HIDDEN_UNTIL)) { task.setValue(Task.HIDE_UNTIL, BackupDateUtilities.getDateFromIso8601String(value).getTime()); - } - else if(field.equals(LegacyTaskModel.BLOCKING_ON)) { + } else if (field.equals(LegacyTaskModel.BLOCKING_ON)) { // ignore - } - else if(field.equals(LegacyTaskModel.POSTPONE_COUNT)) { + } else if (field.equals(LegacyTaskModel.POSTPONE_COUNT)) { task.setValue(Task.POSTPONE_COUNT, Integer.parseInt(value)); - } - else if(field.equals(LegacyTaskModel.NOTIFICATIONS)) { + } else if (field.equals(LegacyTaskModel.NOTIFICATIONS)) { task.setValue(Task.REMINDER_PERIOD, Integer.parseInt(value) * 1000L); - } - else if(field.equals(LegacyTaskModel.CREATION_DATE)) { + } else if (field.equals(LegacyTaskModel.CREATION_DATE)) { task.setValue(Task.CREATION_DATE, BackupDateUtilities.getDateFromIso8601String(value).getTime()); - } - else if(field.equals(LegacyTaskModel.COMPLETION_DATE)) { + } else if (field.equals(LegacyTaskModel.COMPLETION_DATE)) { String completion = xpp.getAttributeValue(null, LegacyTaskModel.PROGRESS_PERCENTAGE); - if("100".equals(completion)) { + if ("100".equals(completion)) { task.setValue(Task.COMPLETION_DATE, - BackupDateUtilities.getDateFromIso8601String(value).getTime()); + BackupDateUtilities.getDateFromIso8601String(value).getTime()); } - } - else if(field.equals(LegacyTaskModel.NOTIFICATION_FLAGS)) { + } else if (field.equals(LegacyTaskModel.NOTIFICATION_FLAGS)) { task.setValue(Task.REMINDER_FLAGS, Integer.parseInt(value)); - } - else if(field.equals(LegacyTaskModel.LAST_NOTIFIED)) { + } else if (field.equals(LegacyTaskModel.LAST_NOTIFIED)) { task.setValue(Task.REMINDER_LAST, BackupDateUtilities.getDateFromIso8601String(value).getTime()); - } - else if(field.equals("repeat_interval")) { + } else if (field.equals("repeat_interval")) { // handled below - } - else if(field.equals("repeat_value")) { + } else if (field.equals("repeat_value")) { int repeatValue = Integer.parseInt(value); String repeatInterval = xpp.getAttributeValue(null, "repeat_interval"); - if(repeatValue > 0 && repeatInterval != null) { + if (repeatValue > 0 && repeatInterval != null) { LegacyRepeatInterval interval = LegacyRepeatInterval.valueOf(repeatInterval); LegacyRepeatInfo repeatInfo = new LegacyRepeatInfo(interval, repeatValue); RRule rrule = repeatInfo.toRRule(); task.setValue(Task.RECURRENCE, rrule.toIcal()); } - } - else if(field.equals(LegacyTaskModel.FLAGS)) { - if(Integer.parseInt(value) == LegacyTaskModel.FLAG_SYNC_ON_COMPLETE) + } else if (field.equals(LegacyTaskModel.FLAGS)) { + if (Integer.parseInt(value) == LegacyTaskModel.FLAG_SYNC_ON_COMPLETE) syncOnComplete = true; - } - else { + } else { return false; } diff --git a/astrid/plugin-src/com/todoroo/astrid/calls/MissedCallActivity.java b/astrid/plugin-src/com/todoroo/astrid/calls/MissedCallActivity.java index 632354709..d082eb264 100644 --- a/astrid/plugin-src/com/todoroo/astrid/calls/MissedCallActivity.java +++ b/astrid/plugin-src/com/todoroo/astrid/calls/MissedCallActivity.java @@ -5,8 +5,6 @@ */ package com.todoroo.astrid.calls; -import java.io.InputStream; - import android.app.Activity; import android.app.AlertDialog; import android.content.ContentUris; @@ -39,6 +37,8 @@ import com.todoroo.astrid.service.StartupService; import com.todoroo.astrid.service.TaskService; import com.todoroo.astrid.service.ThemeService; +import java.io.InputStream; + public class MissedCallActivity extends Activity { public static final String EXTRA_NUMBER = "number"; //$NON-NLS-1$ @@ -51,7 +51,8 @@ public class MissedCallActivity extends Activity { // Prompt user to ignore all missed calls after this many ignore presses private static final int IGNORE_PROMPT_COUNT = 3; - @Autowired private TaskService taskService; + @Autowired + private TaskService taskService; private final OnClickListener dismissListener = new OnClickListener() { @Override @@ -86,7 +87,8 @@ public class MissedCallActivity extends Activity { public void onClick(DialogInterface dialog, int which) { dismissListener.onClick(v); } - }); + } + ); } else { dismissListener.onClick(v); } @@ -127,24 +129,24 @@ public class MissedCallActivity extends Activity { ignoreSettingsButton = findViewById(R.id.ignore_settings); dismissButton = findViewById(R.id.dismiss); ((TextView) findViewById(R.id.reminder_title)) - .setText(getString(R.string.MCA_title, - TextUtils.isEmpty(name) ? number : name, timeString)); - - ImageView pictureView = ((ImageView) findViewById(R.id.contact_picture)); - if (contactId >= 0) { - Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId); - InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(), uri); - Bitmap b = null; - try { - b = BitmapFactory.decodeStream(input); - } catch (OutOfMemoryError e) { - // - } - if (b != null) { - pictureView.setImageBitmap(b); - pictureView.setVisibility(View.VISIBLE); - } - } + .setText(getString(R.string.MCA_title, + TextUtils.isEmpty(name) ? number : name, timeString)); + + ImageView pictureView = ((ImageView) findViewById(R.id.contact_picture)); + if (contactId >= 0) { + Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId); + InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(), uri); + Bitmap b = null; + try { + b = BitmapFactory.decodeStream(input); + } catch (OutOfMemoryError e) { + // + } + if (b != null) { + pictureView.setImageBitmap(b); + pictureView.setVisibility(View.VISIBLE); + } + } Resources r = getResources(); returnCallButton.setBackgroundColor(r.getColor(color)); @@ -210,11 +212,11 @@ public class MissedCallActivity extends Activity { } }); new AlertDialog.Builder(MissedCallActivity.this) - .setTitle(dialogTitle) - .setView(sd) - .setPositiveButton(android.R.string.ok, sd) - .setNegativeButton(android.R.string.cancel, null) - .show().setOwnerActivity(MissedCallActivity.this); + .setTitle(dialogTitle) + .setView(sd) + .setPositiveButton(android.R.string.ok, sd) + .setNegativeButton(android.R.string.cancel, null) + .show().setOwnerActivity(MissedCallActivity.this); } }); } diff --git a/astrid/plugin-src/com/todoroo/astrid/calls/PhoneStateChangedReceiver.java b/astrid/plugin-src/com/todoroo/astrid/calls/PhoneStateChangedReceiver.java index fc1e18171..8ddc03788 100644 --- a/astrid/plugin-src/com/todoroo/astrid/calls/PhoneStateChangedReceiver.java +++ b/astrid/plugin-src/com/todoroo/astrid/calls/PhoneStateChangedReceiver.java @@ -5,8 +5,6 @@ */ package com.todoroo.astrid.calls; -import java.util.Date; - import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; @@ -23,6 +21,8 @@ import com.todoroo.andlib.utility.AndroidUtilities; import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.andlib.utility.Preferences; +import java.util.Date; + @SuppressWarnings("nls") public class PhoneStateChangedReceiver extends BroadcastReceiver { @@ -60,22 +60,22 @@ public class PhoneStateChangedReceiver extends BroadcastReceiver { Cursor calls; try { calls = context.getContentResolver().query( - Calls.CONTENT_URI, - new String[] { Calls.NUMBER, Calls.DATE, Calls.CACHED_NAME }, - Calls.TYPE + " = ? AND " + Calls.NEW + " = ?", - new String[] { Integer.toString(Calls.MISSED_TYPE), "1" }, - Calls.DATE + " DESC" - ); + Calls.CONTENT_URI, + new String[]{Calls.NUMBER, Calls.DATE, Calls.CACHED_NAME}, + Calls.TYPE + " = ? AND " + Calls.NEW + " = ?", + new String[]{Integer.toString(Calls.MISSED_TYPE), "1"}, + Calls.DATE + " DESC" + ); } catch (Exception e) { // Sometimes database is locked, retry once AndroidUtilities.sleepDeep(300L); try { calls = context.getContentResolver().query( Calls.CONTENT_URI, - new String[] { Calls.NUMBER, Calls.DATE, Calls.CACHED_NAME }, + new String[]{Calls.NUMBER, Calls.DATE, Calls.CACHED_NAME}, Calls.TYPE + " = ? AND " + Calls.NEW + " = ?", - new String[] { Integer.toString(Calls.MISSED_TYPE), "1" }, + new String[]{Integer.toString(Calls.MISSED_TYPE), "1"}, Calls.DATE + " DESC" - ); + ); } catch (Exception e2) { calls = null; } @@ -143,7 +143,7 @@ public class PhoneStateChangedReceiver extends BroadcastReceiver { private long getContactIdFromNumber(Context context, String number) { Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number)); - Cursor c = context.getContentResolver().query(contactUri, new String[] { ContactsContract.PhoneLookup._ID }, null, null, null); + Cursor c = context.getContentResolver().query(contactUri, new String[]{ContactsContract.PhoneLookup._ID}, null, null, null); try { if (c.moveToFirst()) { diff --git a/astrid/plugin-src/com/todoroo/astrid/core/CoreFilterExposer.java b/astrid/plugin-src/com/todoroo/astrid/core/CoreFilterExposer.java index 3b547cb75..ed406f9f5 100644 --- a/astrid/plugin-src/com/todoroo/astrid/core/CoreFilterExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/core/CoreFilterExposer.java @@ -5,9 +5,6 @@ */ package com.todoroo.astrid.core; -import java.util.ArrayList; -import java.util.List; - import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentValues; @@ -40,11 +37,13 @@ import com.todoroo.astrid.data.WaitingOnMe; import com.todoroo.astrid.service.ThemeService; import com.todoroo.astrid.tags.TaskToTagMetadata; +import java.util.ArrayList; +import java.util.List; + /** * Exposes Astrid's built in filters to the {@link FilterListFragment} * * @author Tim Su - * */ public final class CoreFilterExposer extends BroadcastReceiver implements AstridFilterExposer { @@ -78,6 +77,7 @@ public final class CoreFilterExposer extends BroadcastReceiver implements Astrid /** * Build inbox filter + * * @return */ public static Filter buildInboxFilter(Resources r) { @@ -87,9 +87,9 @@ public final class CoreFilterExposer extends BroadcastReceiver implements Astrid Criterion.not(Task.ID.in(Query.select(Metadata.TASK).from(Metadata.TABLE).where( Criterion.and(MetadataCriteria.withKey(TaskToTagMetadata.KEY), TaskToTagMetadata.TAG_NAME.like("x_%", "x"))))))), //$NON-NLS-1$ //$NON-NLS-2$ - null); + null); int themeFlags = ThemeService.getFilterThemeFlags(); - inbox.listingIcon = ((BitmapDrawable)r.getDrawable( + inbox.listingIcon = ((BitmapDrawable) r.getDrawable( ThemeService.getDrawable(R.drawable.filter_inbox, themeFlags))).getBitmap(); return inbox; } @@ -105,28 +105,29 @@ public final class CoreFilterExposer extends BroadcastReceiver implements Astrid Criterion.and(TaskCriteria.activeVisibleMine(), Task.DUE_DATE.gt(0), Task.DUE_DATE.lte(PermaSql.VALUE_EOD))), - todayValues); - todayFilter.listingIcon = ((BitmapDrawable)r.getDrawable( + todayValues); + todayFilter.listingIcon = ((BitmapDrawable) r.getDrawable( ThemeService.getDrawable(R.drawable.filter_calendar, themeFlags))).getBitmap(); return todayFilter; } public static Filter getWaitingOnMeFilter(Resources r) { - FilterWithCustomIntent waitingOnMe = new FilterWithCustomIntent(r.getString(R.string.BFE_waiting_on_me), r.getString(R.string.BFE_waiting_on_me), - new QueryTemplate().join(Join.inner(WaitingOnMe.TABLE, Task.UUID.eq(WaitingOnMe.TASK_UUID))).where( - Criterion.and(WaitingOnMe.DELETED_AT.eq(0), - Criterion.or(WaitingOnMe.ACKNOWLEDGED.isNull(), WaitingOnMe.ACKNOWLEDGED.neq(1)))) - .groupBy(Task.UUID), null); - waitingOnMe.customTaskList = new ComponentName(ContextManager.getContext(), WaitingOnMeFragment.class); - int themeFlags = ThemeService.getFilterThemeFlags(); - waitingOnMe.listingIcon = ((BitmapDrawable) r.getDrawable( - ThemeService.getDrawable(R.drawable.waiting_on_me, themeFlags))).getBitmap(); - return waitingOnMe; + FilterWithCustomIntent waitingOnMe = new FilterWithCustomIntent(r.getString(R.string.BFE_waiting_on_me), r.getString(R.string.BFE_waiting_on_me), + new QueryTemplate().join(Join.inner(WaitingOnMe.TABLE, Task.UUID.eq(WaitingOnMe.TASK_UUID))).where( + Criterion.and(WaitingOnMe.DELETED_AT.eq(0), + Criterion.or(WaitingOnMe.ACKNOWLEDGED.isNull(), WaitingOnMe.ACKNOWLEDGED.neq(1)))) + .groupBy(Task.UUID), null); + waitingOnMe.customTaskList = new ComponentName(ContextManager.getContext(), WaitingOnMeFragment.class); + int themeFlags = ThemeService.getFilterThemeFlags(); + waitingOnMe.listingIcon = ((BitmapDrawable) r.getDrawable( + ThemeService.getDrawable(R.drawable.waiting_on_me, themeFlags))).getBitmap(); + return waitingOnMe; } /** * Is this the inbox? + * * @param filter * @return */ diff --git a/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterActivity.java b/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterActivity.java index 42bbecc17..93f1c39bc 100644 --- a/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterActivity.java +++ b/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterActivity.java @@ -5,13 +5,6 @@ */ package com.todoroo.astrid.core; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - import android.content.BroadcastReceiver; import android.content.ContentValues; import android.content.Context; @@ -60,11 +53,17 @@ import com.todoroo.astrid.service.StatisticsService; import com.todoroo.astrid.service.ThemeService; import com.todoroo.astrid.utility.AstridPreferences; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + /** * Activity that allows users to build custom filters * * @author Tim Su - * */ public class CustomFilterActivity extends SherlockFragmentActivity { @@ -85,32 +84,42 @@ public class CustomFilterActivity extends SherlockFragmentActivity { public static final int TYPE_INTERSECT = 2; public static final int TYPE_UNIVERSE = 3; - /** criteria for this instance */ + /** + * criteria for this instance + */ public CustomFilterCriterion criterion; - /** which of the entries is selected (MultipleSelect) */ + /** + * which of the entries is selected (MultipleSelect) + */ public int selectedIndex = -1; - /** text of selection (TextInput) */ + /** + * text of selection (TextInput) + */ public String selectedText = null; - /** type of join */ + /** + * type of join + */ public int type = TYPE_INTERSECT; - /** statistics for {@link FilterView} */ + /** + * statistics for {@link FilterView} + */ public int start, end, max; @SuppressWarnings("nls") public String getTitleFromCriterion() { - if(criterion instanceof MultipleSelectCriterion) { - if(selectedIndex >= 0 && ((MultipleSelectCriterion)criterion).entryTitles != null && - selectedIndex < ((MultipleSelectCriterion)criterion).entryTitles.length) { - String title = ((MultipleSelectCriterion)criterion).entryTitles[selectedIndex]; + if (criterion instanceof MultipleSelectCriterion) { + if (selectedIndex >= 0 && ((MultipleSelectCriterion) criterion).entryTitles != null && + selectedIndex < ((MultipleSelectCriterion) criterion).entryTitles.length) { + String title = ((MultipleSelectCriterion) criterion).entryTitles[selectedIndex]; return criterion.text.replace("?", title); } return criterion.text; - } else if(criterion instanceof TextInputCriterion) { - if(selectedText == null) + } else if (criterion instanceof TextInputCriterion) { + if (selectedText == null) return criterion.text; return criterion.text.replace("?", selectedText); } @@ -118,15 +127,15 @@ public class CustomFilterActivity extends SherlockFragmentActivity { } public String getValueFromCriterion() { - if(type == TYPE_UNIVERSE) + if (type == TYPE_UNIVERSE) return null; - if(criterion instanceof MultipleSelectCriterion) { - if(selectedIndex >= 0 && ((MultipleSelectCriterion)criterion).entryValues != null && - selectedIndex < ((MultipleSelectCriterion)criterion).entryValues.length) { - return ((MultipleSelectCriterion)criterion).entryValues[selectedIndex]; + if (criterion instanceof MultipleSelectCriterion) { + if (selectedIndex >= 0 && ((MultipleSelectCriterion) criterion).entryValues != null && + selectedIndex < ((MultipleSelectCriterion) criterion).entryValues.length) { + return ((MultipleSelectCriterion) criterion).entryValues[selectedIndex]; } return criterion.text; - } else if(criterion instanceof TextInputCriterion) { + } else if (criterion instanceof TextInputCriterion) { return selectedText; } throw new UnsupportedOperationException("Unknown criterion type"); //$NON-NLS-1$ @@ -138,7 +147,7 @@ public class CustomFilterActivity extends SherlockFragmentActivity { private boolean isDialog; private CustomFilterAdapter adapter; - private final Map criteria = Collections.synchronizedMap(new LinkedHashMap()); + private final Map criteria = Collections.synchronizedMap(new LinkedHashMap()); private final FilterCriteriaReceiver filterCriteriaReceiver = new FilterCriteriaReceiver(); @@ -166,7 +175,7 @@ public class CustomFilterActivity extends SherlockFragmentActivity { database.openForReading(); populateCriteria(); - filterName = (TextView)findViewById(R.id.filterName); + filterName = (TextView) findViewById(R.id.filterName); List startingCriteria = new ArrayList(); startingCriteria.add(getStartingUniverse()); adapter = new CustomFilterAdapter(this, startingCriteria); @@ -197,7 +206,7 @@ public class CustomFilterActivity extends SherlockFragmentActivity { // built in criteria: due date { - String[] entryValues = new String[] { + String[] entryValues = new String[]{ "0", PermaSql.VALUE_EOD_YESTERDAY, PermaSql.VALUE_EOD, @@ -219,20 +228,20 @@ public class CustomFilterActivity extends SherlockFragmentActivity { Task.DUE_DATE.gt(0)), Task.DUE_DATE.lte("?"))).toString(), values, r.getStringArray(R.array.CFC_dueBefore_entries), - entryValues, ((BitmapDrawable)r.getDrawable(R.drawable.tango_calendar)).getBitmap(), + entryValues, ((BitmapDrawable) r.getDrawable(R.drawable.tango_calendar)).getBitmap(), getString(R.string.CFC_dueBefore_name)); criteria.put(IDENTIFIER_DUEDATE, criterion); } // built in criteria: importance { - String[] entryValues = new String[] { - Integer.toString(Task.IMPORTANCE_DO_OR_DIE), - Integer.toString(Task.IMPORTANCE_MUST_DO), - Integer.toString(Task.IMPORTANCE_SHOULD_DO), - Integer.toString(Task.IMPORTANCE_NONE), - }; - String[] entries = new String[] { + String[] entryValues = new String[]{ + Integer.toString(Task.IMPORTANCE_DO_OR_DIE), + Integer.toString(Task.IMPORTANCE_MUST_DO), + Integer.toString(Task.IMPORTANCE_SHOULD_DO), + Integer.toString(Task.IMPORTANCE_NONE), + }; + String[] entries = new String[]{ "!!!", "!!", "!", "o" }; ContentValues values = new ContentValues(); @@ -244,7 +253,7 @@ public class CustomFilterActivity extends SherlockFragmentActivity { Criterion.and(TaskCriteria.activeVisibleMine(), Task.IMPORTANCE.lte("?"))).toString(), values, entries, - entryValues, ((BitmapDrawable)r.getDrawable(R.drawable.tango_warning)).getBitmap(), + entryValues, ((BitmapDrawable) r.getDrawable(R.drawable.tango_warning)).getBitmap(), getString(R.string.CFC_importance_name)); criteria.put(IDENTIFIER_IMPORTANCE, criterion); } @@ -259,9 +268,9 @@ public class CustomFilterActivity extends SherlockFragmentActivity { Query.select(Task.ID).from(Task.TABLE).where( Criterion.and(TaskCriteria.activeVisibleMine(), Task.TITLE.like("%?%"))).toString(), - null, getString(R.string.CFC_title_contains_name), "", - ((BitmapDrawable)r.getDrawable(R.drawable.tango_alpha)).getBitmap(), - getString(R.string.CFC_title_contains_name)); + null, getString(R.string.CFC_title_contains_name), "", + ((BitmapDrawable) r.getDrawable(R.drawable.tango_alpha)).getBitmap(), + getString(R.string.CFC_title_contains_name)); criteria.put(IDENTIFIER_TITLE, criterion); } } @@ -302,14 +311,14 @@ public class CustomFilterActivity extends SherlockFragmentActivity { } private void setUpListeners() { - ((Button)findViewById(R.id.add)).setOnClickListener(new View.OnClickListener() { + ((Button) findViewById(R.id.add)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listView.showContextMenu(); } }); - final Button saveAndView = ((Button)findViewById(R.id.saveAndView)); + final Button saveAndView = ((Button) findViewById(R.id.saveAndView)); saveAndView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -320,20 +329,22 @@ public class CustomFilterActivity extends SherlockFragmentActivity { filterName.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) { - if(s.length() == 0) { + if (s.length() == 0) { saveAndView.setText(R.string.CFA_button_view); } else { saveAndView.setText(R.string.CFA_button_save); } } + @Override public void beforeTextChanged(CharSequence s, int start, int count, - int after) { + int after) { // } + @Override public void onTextChanged(CharSequence s, int start, int before, - int count) { + int count) { // } }); @@ -341,8 +352,8 @@ public class CustomFilterActivity extends SherlockFragmentActivity { listView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() { @Override public void onCreateContextMenu(ContextMenu menu, View v, - ContextMenuInfo menuInfo) { - if(menu.hasVisibleItems()) { + ContextMenuInfo menuInfo) { + if (menu.hasVisibleItems()) { /* If it has items already, then the user did not click on the "Add Criteria" button, but instead long held on a row in the list view, which caused CustomFilterAdapter.onCreateContextMenu to be invoked before this onCreateContextMenu method was invoked. @@ -376,11 +387,11 @@ public class CustomFilterActivity extends SherlockFragmentActivity { @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { - if(menu.size() > 0) + if (menu.size() > 0) menu.clear(); // view holder - if(v.getTag() != null) { + if (v.getTag() != null) { adapter.onCreateContextMenu(menu, v); } } @@ -390,44 +401,44 @@ public class CustomFilterActivity extends SherlockFragmentActivity { StringBuilder sql = new StringBuilder(" WHERE "); StringBuilder suggestedTitle = new StringBuilder(); ContentValues values = new ContentValues(); - for(int i = 0; i < adapter.getCount(); i++) { + for (int i = 0; i < adapter.getCount(); i++) { CriterionInstance instance = adapter.getItem(i); String value = instance.getValueFromCriterion(); - if(value == null && instance.criterion.sql != null && instance.criterion.sql.contains("?")) + if (value == null && instance.criterion.sql != null && instance.criterion.sql.contains("?")) value = ""; String title = instance.getTitleFromCriterion(); - switch(instance.type) { - case CriterionInstance.TYPE_ADD: - sql.append("OR "); - suggestedTitle.append(getString(R.string.CFA_type_add)).append(' '). - append(title).append(' '); - break; - case CriterionInstance.TYPE_SUBTRACT: - sql.append("AND NOT "); - suggestedTitle.append(getString(R.string.CFA_type_subtract)).append(' '). - append(title).append(' '); - break; - case CriterionInstance.TYPE_INTERSECT: - sql.append("AND "); - suggestedTitle.append(title).append(' '); - break; - case CriterionInstance.TYPE_UNIVERSE: + switch (instance.type) { + case CriterionInstance.TYPE_ADD: + sql.append("OR "); + suggestedTitle.append(getString(R.string.CFA_type_add)).append(' '). + append(title).append(' '); + break; + case CriterionInstance.TYPE_SUBTRACT: + sql.append("AND NOT "); + suggestedTitle.append(getString(R.string.CFA_type_subtract)).append(' '). + append(title).append(' '); + break; + case CriterionInstance.TYPE_INTERSECT: + sql.append("AND "); + suggestedTitle.append(title).append(' '); + break; + case CriterionInstance.TYPE_UNIVERSE: } // special code for all tasks universe - if(instance.criterion.sql == null) + if (instance.criterion.sql == null) sql.append(TaskCriteria.activeVisibleMine()).append(' '); else { String subSql = instance.criterion.sql.replace("?", UnaryCriterion.sanitize(value)); sql.append(Task.ID).append(" IN (").append(subSql).append(") "); } - if(instance.criterion.valuesForNewTasks != null && + if (instance.criterion.valuesForNewTasks != null && instance.type == CriterionInstance.TYPE_INTERSECT) { - for(Entry entry : instance.criterion.valuesForNewTasks.valueSet()) { + for (Entry entry : instance.criterion.valuesForNewTasks.valueSet()) { values.put(entry.getKey().replace("?", value), entry.getValue().toString().replace("?", value)); } @@ -435,7 +446,7 @@ public class CustomFilterActivity extends SherlockFragmentActivity { } String title; - if(filterName.getText().length() > 0) { + if (filterName.getText().length() > 0) { // persist saved filter title = filterName.getText().toString().trim(); SavedFilter.persist(adapter, title, sql.toString(), values); @@ -458,29 +469,29 @@ public class CustomFilterActivity extends SherlockFragmentActivity { int max = 0, last = -1; StringBuilder sql = new StringBuilder(Query.select(new CountProperty()).from(Task.TABLE).toString()). - append(" WHERE "); + append(" WHERE "); - for(int i = 0; i < adapter.getCount(); i++) { + for (int i = 0; i < adapter.getCount(); i++) { CriterionInstance instance = adapter.getItem(i); String value = instance.getValueFromCriterion(); - if(value == null && instance.criterion.sql != null && instance.criterion.sql.contains("?")) + if (value == null && instance.criterion.sql != null && instance.criterion.sql.contains("?")) value = ""; - switch(instance.type) { - case CriterionInstance.TYPE_ADD: - sql.append("OR "); - break; - case CriterionInstance.TYPE_SUBTRACT: - sql.append("AND NOT "); - break; - case CriterionInstance.TYPE_INTERSECT: - sql.append("AND "); - break; - case CriterionInstance.TYPE_UNIVERSE: + switch (instance.type) { + case CriterionInstance.TYPE_ADD: + sql.append("OR "); + break; + case CriterionInstance.TYPE_SUBTRACT: + sql.append("AND NOT "); + break; + case CriterionInstance.TYPE_INTERSECT: + sql.append("AND "); + break; + case CriterionInstance.TYPE_UNIVERSE: } // special code for all tasks universe - if(instance.criterion.sql == null) + if (instance.criterion.sql == null) sql.append(TaskCriteria.activeVisibleMine()).append(' '); else { String subSql = instance.criterion.sql.replace("?", UnaryCriterion.sanitize(value)); @@ -500,7 +511,7 @@ public class CustomFilterActivity extends SherlockFragmentActivity { } } - for(int i = 0; i < adapter.getCount(); i++) { + for (int i = 0; i < adapter.getCount(); i++) { CriterionInstance instance = adapter.getItem(i); instance.max = max; } @@ -509,7 +520,7 @@ public class CustomFilterActivity extends SherlockFragmentActivity { } @SuppressWarnings("nls") - private V getNth(int index, Map map) { + private V getNth(int index, Map map) { int i = 0; for (V v : map.values()) { if (i == index) return v; @@ -529,7 +540,7 @@ public class CustomFilterActivity extends SherlockFragmentActivity { @Override public boolean onContextItemSelected(android.view.MenuItem item) { - if(item.getGroupId() == MENU_GROUP_FILTER) { + if (item.getGroupId() == MENU_GROUP_FILTER) { // give an initial value for the row before adding it CustomFilterCriterion criterion = getNth(item.getItemId(), criteria); final CriterionInstance instance = new CriterionInstance(); @@ -544,14 +555,14 @@ public class CustomFilterActivity extends SherlockFragmentActivity { } // item type context item - else if(item.getGroupId() == MENU_GROUP_CONTEXT_TYPE) { + else if (item.getGroupId() == MENU_GROUP_CONTEXT_TYPE) { CriterionInstance instance = adapter.getItem(item.getOrder()); instance.type = item.getItemId(); updateList(); } // delete context item - else if(item.getGroupId() == MENU_GROUP_CONTEXT_DELETE) { + else if (item.getGroupId() == MENU_GROUP_CONTEXT_DELETE) { CriterionInstance instance = adapter.getItem(item.getOrder()); adapter.remove(instance); updateList(); @@ -565,7 +576,7 @@ public class CustomFilterActivity extends SherlockFragmentActivity { public void onReceive(Context context, Intent intent) { try { final Parcelable[] filters = intent.getExtras(). - getParcelableArray(AstridApiConstants.EXTRAS_RESPONSE); + getParcelableArray(AstridApiConstants.EXTRAS_RESPONSE); for (Parcelable filter : filters) { CustomFilterCriterion filterCriterion = (CustomFilterCriterion) filter; criteria.put(filterCriterion.identifier, filterCriterion); diff --git a/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterAdapter.java b/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterAdapter.java index b349a54d7..9cc800db7 100644 --- a/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterAdapter.java +++ b/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterAdapter.java @@ -5,8 +5,6 @@ */ package com.todoroo.astrid.core; -import java.util.List; - import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; @@ -28,11 +26,12 @@ import com.todoroo.astrid.api.TextInputCriterion; import com.todoroo.astrid.core.CustomFilterActivity.CriterionInstance; import com.todoroo.astrid.data.AddOn; +import java.util.List; + /** * Adapter for {@link AddOn}s * * @author Tim Su - * */ public class CustomFilterAdapter extends ArrayAdapter { @@ -52,9 +51,9 @@ public class CustomFilterAdapter extends ArrayAdapter { @Override public void onClick(View v) { ViewHolder viewHolder = (ViewHolder) v.getTag(); - if(viewHolder == null) + if (viewHolder == null) return; - if(viewHolder.item.type == CriterionInstance.TYPE_UNIVERSE) + if (viewHolder.item.type == CriterionInstance.TYPE_UNIVERSE) return; showOptionsFor(viewHolder.item, new Runnable() { @@ -70,13 +69,13 @@ public class CustomFilterAdapter extends ArrayAdapter { public void onCreateContextMenu(ContextMenu menu, View v) { // view holder ViewHolder viewHolder = (ViewHolder) v.getTag(); - if(viewHolder == null || viewHolder.item.type == CriterionInstance.TYPE_UNIVERSE) + if (viewHolder == null || viewHolder.item.type == CriterionInstance.TYPE_UNIVERSE) return; int index = getPosition(viewHolder.item); menu.setHeaderTitle(viewHolder.name.getText()); - if(viewHolder.icon.getVisibility() == View.VISIBLE) + if (viewHolder.icon.getVisibility() == View.VISIBLE) menu.setHeaderIcon(viewHolder.icon.getDrawable()); @@ -101,13 +100,14 @@ public class CustomFilterAdapter extends ArrayAdapter { /** * Show options menu for the given criterioninstance + * * @param item */ public void showOptionsFor(final CriterionInstance item, final Runnable onComplete) { AlertDialog.Builder dialog = new AlertDialog.Builder(activity). - setTitle(item.criterion.name); + setTitle(item.criterion.name); - if(item.criterion instanceof MultipleSelectCriterion) { + if (item.criterion instanceof MultipleSelectCriterion) { MultipleSelectCriterion multiSelectCriterion = (MultipleSelectCriterion) item.criterion; final String[] titles = multiSelectCriterion.entryTitles; ArrayAdapter adapter = new ArrayAdapter(activity, @@ -116,12 +116,12 @@ public class CustomFilterAdapter extends ArrayAdapter { @Override public void onClick(DialogInterface click, int which) { item.selectedIndex = which; - if(onComplete != null) + if (onComplete != null) onComplete.run(); } }; dialog.setAdapter(adapter, listener); - } else if(item.criterion instanceof TextInputCriterion) { + } else if (item.criterion instanceof TextInputCriterion) { TextInputCriterion textInCriterion = (TextInputCriterion) item.criterion; FrameLayout frameLayout = new FrameLayout(activity); frameLayout.setPadding(10, 0, 10, 0); @@ -132,14 +132,14 @@ public class CustomFilterAdapter extends ArrayAdapter { FrameLayout.LayoutParams.FILL_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT)); dialog.setMessage(textInCriterion.prompt).setView(frameLayout). - setPositiveButton(android.R.string.ok, new OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int which) { - item.selectedText = editText.getText().toString(); - if(onComplete != null) - onComplete.run(); - } - }); + setPositiveButton(android.R.string.ok, new OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int which) { + item.selectedText = editText.getText().toString(); + if (onComplete != null) + onComplete.run(); + } + }); } dialog.show().setOwnerActivity(activity); @@ -149,17 +149,17 @@ public class CustomFilterAdapter extends ArrayAdapter { @Override public View getView(int position, View convertView, ViewGroup parent) { - if(convertView == null) { + if (convertView == null) { convertView = inflater.inflate(R.layout.custom_filter_row, parent, false); ViewHolder viewHolder = new ViewHolder(); viewHolder.type = (ImageView) convertView.findViewById(R.id.type); viewHolder.icon = (ImageView) convertView.findViewById(R.id.icon); - viewHolder.name= (TextView) convertView.findViewById(R.id.name); + viewHolder.name = (TextView) convertView.findViewById(R.id.name); viewHolder.filterView = (FilterView) convertView.findViewById(R.id.filter); convertView.setTag(viewHolder); } - ViewHolder viewHolder = (ViewHolder)convertView.getTag(); + ViewHolder viewHolder = (ViewHolder) convertView.getTag(); viewHolder.item = getItem(position); initializeView(convertView); @@ -187,23 +187,23 @@ public class CustomFilterAdapter extends ArrayAdapter { viewHolder.type.setVisibility(item.type == CriterionInstance.TYPE_UNIVERSE ? View.GONE : View.VISIBLE); - switch(item.type) { - case CriterionInstance.TYPE_ADD: - viewHolder.type.setImageResource(R.drawable.arrow_join); - title = activity.getString(R.string.CFA_type_add) + " " + title; - break; - case CriterionInstance.TYPE_SUBTRACT: - viewHolder.type.setImageResource(R.drawable.arrow_branch); - title = activity.getString(R.string.CFA_type_subtract) + " " + title; - break; - case CriterionInstance.TYPE_INTERSECT: - viewHolder.type.setImageResource(R.drawable.arrow_down); - break; + switch (item.type) { + case CriterionInstance.TYPE_ADD: + viewHolder.type.setImageResource(R.drawable.arrow_join); + title = activity.getString(R.string.CFA_type_add) + " " + title; + break; + case CriterionInstance.TYPE_SUBTRACT: + viewHolder.type.setImageResource(R.drawable.arrow_branch); + title = activity.getString(R.string.CFA_type_subtract) + " " + title; + break; + case CriterionInstance.TYPE_INTERSECT: + viewHolder.type.setImageResource(R.drawable.arrow_down); + break; } viewHolder.icon.setVisibility(item.criterion.icon == null ? View.GONE : - View.VISIBLE); - if(item.criterion.icon != null) + View.VISIBLE); + if (item.criterion.icon != null) viewHolder.icon.setImageBitmap(item.criterion.icon); viewHolder.name.setText(title); diff --git a/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterExposer.java b/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterExposer.java index f3ada3bef..690dcdc2a 100644 --- a/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterExposer.java @@ -5,8 +5,6 @@ */ package com.todoroo.astrid.core; -import java.util.ArrayList; - import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; @@ -41,19 +39,22 @@ import com.todoroo.astrid.gtasks.GtasksPreferenceService; import com.todoroo.astrid.service.TagDataService; import com.todoroo.astrid.service.ThemeService; +import java.util.ArrayList; + /** * Exposes Astrid's built in filters to the {@link FilterListFragment} * * @author Tim Su - * */ public final class CustomFilterExposer extends BroadcastReceiver implements AstridFilterExposer { private static final String TOKEN_FILTER_ID = "id"; //$NON-NLS-1$ private static final String TOKEN_FILTER_NAME = "name"; //$NON-NLS-1$ - @Autowired TagDataService tagDataService; - @Autowired GtasksPreferenceService gtasksPreferenceService; + @Autowired + TagDataService tagDataService; + @Autowired + GtasksPreferenceService gtasksPreferenceService; @Override public void onReceive(Context context, Intent intent) { @@ -81,7 +82,7 @@ public final class CustomFilterExposer extends BroadcastReceiver implements Astr TodorooCursor cursor = null; if (useCustomFilters) cursor = dao.query(Query.select(StoreObject.PROPERTIES).where( - StoreObject.TYPE.eq(SavedFilter.TYPE)).orderBy(Order.asc(SavedFilter.NAME))); + StoreObject.TYPE.eq(SavedFilter.TYPE)).orderBy(Order.asc(SavedFilter.NAME))); try { ArrayList list = new ArrayList(); @@ -91,9 +92,9 @@ public final class CustomFilterExposer extends BroadcastReceiver implements Astr r.getString(R.string.BFE_Recent), new QueryTemplate().where( TaskCriteria.ownedByMe()).orderBy( - Order.desc(Task.MODIFICATION_DATE)).limit(15), - null); - recent.listingIcon = ((BitmapDrawable)r.getDrawable( + Order.desc(Task.MODIFICATION_DATE)).limit(15), + null); + recent.listingIcon = ((BitmapDrawable) r.getDrawable( ThemeService.getDrawable(R.drawable.filter_pencil, themeFlags))).getBitmap(); list.add(recent); @@ -104,16 +105,16 @@ public final class CustomFilterExposer extends BroadcastReceiver implements Astr if (useCustomFilters && cursor != null) { StoreObject savedFilter = new StoreObject(); - for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { + for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { savedFilter.readFromCursor(cursor); Filter f = SavedFilter.load(savedFilter); Intent deleteIntent = new Intent(context, DeleteActivity.class); deleteIntent.putExtra(TOKEN_FILTER_ID, savedFilter.getId()); deleteIntent.putExtra(TOKEN_FILTER_NAME, f.title); - f.contextMenuLabels = new String[] { context.getString(R.string.BFE_Saved_delete) }; - f.contextMenuIntents = new Intent[] { deleteIntent }; - f.listingIcon = ((BitmapDrawable)r.getDrawable( + f.contextMenuLabels = new String[]{context.getString(R.string.BFE_Saved_delete)}; + f.contextMenuIntents = new Intent[]{deleteIntent}; + f.listingIcon = ((BitmapDrawable) r.getDrawable( ThemeService.getDrawable(R.drawable.filter_sliders, themeFlags))).getBitmap(); list.add(f); } @@ -133,8 +134,8 @@ public final class CustomFilterExposer extends BroadcastReceiver implements Astr new QueryTemplate().where(Criterion.and(TaskCriteria.isActive(), Criterion.or(Task.CREATOR_ID.eq(0), Task.CREATOR_ID.eq(ActFmPreferenceService.userId())), Task.USER_ID.neq(0))), - null); - f.listingIcon = ((BitmapDrawable)r.getDrawable( + null); + f.listingIcon = ((BitmapDrawable) r.getDrawable( ThemeService.getDrawable(R.drawable.filter_assigned, themeFlags))).getBitmap(); return f; } @@ -143,7 +144,6 @@ public final class CustomFilterExposer extends BroadcastReceiver implements Astr * Simple activity for deleting stuff * * @author Tim Su - * */ public static class DeleteActivity extends Activity { @@ -153,7 +153,7 @@ public final class CustomFilterExposer extends BroadcastReceiver implements Astr setTheme(android.R.style.Theme_Dialog); final long id = getIntent().getLongExtra(TOKEN_FILTER_ID, -1); - if(id == -1) { + if (id == -1) { finish(); return; } @@ -177,7 +177,8 @@ public final class CustomFilterExposer extends BroadcastReceiver implements Astr setResult(RESULT_CANCELED); finish(); } - }); + } + ); } } diff --git a/astrid/plugin-src/com/todoroo/astrid/core/DefaultsPreferences.java b/astrid/plugin-src/com/todoroo/astrid/core/DefaultsPreferences.java index 9748ef508..b64101fc5 100644 --- a/astrid/plugin-src/com/todoroo/astrid/core/DefaultsPreferences.java +++ b/astrid/plugin-src/com/todoroo/astrid/core/DefaultsPreferences.java @@ -21,7 +21,6 @@ import com.todoroo.astrid.gcal.Calendars; * Displays the preference screen for users to edit their preferences * * @author Tim Su - * */ public class DefaultsPreferences extends TodorooPreferenceActivity { @@ -39,7 +38,6 @@ public class DefaultsPreferences extends TodorooPreferenceActivity { } /** - * * @param resource if null, updates all resources */ @Override @@ -47,33 +45,33 @@ public class DefaultsPreferences extends TodorooPreferenceActivity { Resources r = getResources(); // defaults options - if(r.getString(R.string.p_default_urgency_key).equals(preference.getKey())) { + if (r.getString(R.string.p_default_urgency_key).equals(preference.getKey())) { updateTaskListPreference(preference, value, r, R.array.EPr_default_urgency, R.array.EPr_default_urgency_values, R.string.EPr_default_urgency_desc); - } else if(r.getString(R.string.p_default_importance_key).equals(preference.getKey())) { + } else if (r.getString(R.string.p_default_importance_key).equals(preference.getKey())) { updateTaskListPreference(preference, value, r, R.array.EPr_default_importance, R.array.EPr_default_importance_values, R.string.EPr_default_importance_desc); - } else if(r.getString(R.string.p_default_hideUntil_key).equals(preference.getKey())) { + } else if (r.getString(R.string.p_default_hideUntil_key).equals(preference.getKey())) { updateTaskListPreference(preference, value, r, R.array.EPr_default_hideUntil, R.array.EPr_default_hideUntil_values, R.string.EPr_default_hideUntil_desc); - } else if(r.getString(R.string.p_default_reminders_key).equals(preference.getKey())) { + } else if (r.getString(R.string.p_default_reminders_key).equals(preference.getKey())) { updateTaskListPreference(preference, value, r, R.array.EPr_default_reminders, R.array.EPr_default_reminders_values, R.string.EPr_default_reminders_desc); - } else if(r.getString(R.string.p_default_reminders_mode_key).equals(preference.getKey())) { + } else if (r.getString(R.string.p_default_reminders_mode_key).equals(preference.getKey())) { updateTaskListPreference(preference, value, r, R.array.EPr_default_reminders_mode, R.array.EPr_default_reminders_mode_values, R.string.EPr_default_reminders_mode_desc); - } else if(r.getString(R.string.p_rmd_default_random_hours).equals(preference.getKey())) { - int index = AndroidUtilities.indexOf(r.getStringArray(R.array.EPr_reminder_random_hours), (String)value); - if(index <= 0) + } else if (r.getString(R.string.p_rmd_default_random_hours).equals(preference.getKey())) { + int index = AndroidUtilities.indexOf(r.getStringArray(R.array.EPr_reminder_random_hours), (String) value); + if (index <= 0) preference.setSummary(r.getString(R.string.rmd_EPr_defaultRemind_desc_disabled)); else { String setting = r.getStringArray(R.array.EPr_reminder_random)[index]; preference.setSummary(r.getString(R.string.rmd_EPr_defaultRemind_desc, setting)); } - } else if(r.getString(R.string.gcal_p_default).equals(preference.getKey())) { + } else if (r.getString(R.string.gcal_p_default).equals(preference.getKey())) { ListPreference listPreference = (ListPreference) preference; - int index = AndroidUtilities.indexOf(listPreference.getEntryValues(), (String)value); - if(index <= 0) + int index = AndroidUtilities.indexOf(listPreference.getEntryValues(), (String) value); + if (index <= 0) preference.setSummary(r.getString(R.string.EPr_default_addtocalendar_desc_disabled)); else { String setting = listPreference.getEntries()[index].toString(); @@ -81,7 +79,7 @@ public class DefaultsPreferences extends TodorooPreferenceActivity { } } else if (r.getString(R.string.p_voiceInputCreatesTask).equals(preference.getKey())) { preference.setEnabled(Preferences.getBoolean(R.string.p_voiceInputEnabled, false)); - if (value != null && !(Boolean)value) + if (value != null && !(Boolean) value) preference.setSummary(R.string.EPr_voiceInputCreatesTask_desc_disabled); else preference.setSummary(R.string.EPr_voiceInputCreatesTask_desc_enabled); @@ -89,9 +87,9 @@ public class DefaultsPreferences extends TodorooPreferenceActivity { } private void updateTaskListPreference(Preference preference, Object value, - Resources r, int keyArray, int valueArray, int summaryResource) { - int index = AndroidUtilities.indexOf(r.getStringArray(valueArray), (String)value); - if(index == -1) { + Resources r, int keyArray, int valueArray, int summaryResource) { + int index = AndroidUtilities.indexOf(r.getStringArray(valueArray), (String) value); + if (index == -1) { // force the zeroth index index = 0; Editor editor = preference.getEditor(); @@ -104,9 +102,9 @@ public class DefaultsPreferences extends TodorooPreferenceActivity { setting)); // if user changed the value, refresh task defaults - if(!AndroidUtilities.equals(value, Preferences.getStringValue(preference.getKey()))) { + if (!AndroidUtilities.equals(value, Preferences.getStringValue(preference.getKey()))) { Editor editor = Preferences.getPrefs(this).edit(); - editor.putString(preference.getKey(), (String)value); + editor.putString(preference.getKey(), (String) value); editor.commit(); } } diff --git a/astrid/plugin-src/com/todoroo/astrid/core/FilterView.java b/astrid/plugin-src/com/todoroo/astrid/core/FilterView.java index 4c5323ec5..21f60d3eb 100644 --- a/astrid/plugin-src/com/todoroo/astrid/core/FilterView.java +++ b/astrid/plugin-src/com/todoroo/astrid/core/FilterView.java @@ -17,7 +17,6 @@ import android.view.View; * Draws filters * * @author Tim Su - * */ public class FilterView extends View { diff --git a/astrid/plugin-src/com/todoroo/astrid/core/LinkActionExposer.java b/astrid/plugin-src/com/todoroo/astrid/core/LinkActionExposer.java index b95e38245..6f5aa76b9 100644 --- a/astrid/plugin-src/com/todoroo/astrid/core/LinkActionExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/core/LinkActionExposer.java @@ -5,9 +5,6 @@ */ package com.todoroo.astrid.core; -import java.util.HashMap; -import java.util.List; - import android.app.PendingIntent; import android.content.Context; import android.content.Intent; @@ -29,11 +26,13 @@ import com.todoroo.astrid.data.Task; import com.todoroo.astrid.files.FilesAction; import com.todoroo.astrid.notes.NotesAction; +import java.util.HashMap; +import java.util.List; + /** * Exposes {@link TaskDecoration} for phone numbers, emails, urls, etc * * @author Tim Su - * */ public class LinkActionExposer { @@ -44,13 +43,13 @@ public class LinkActionExposer { Linkify.addLinks(titleSpan, Linkify.ALL); URLSpan[] urlSpans = titleSpan.getSpans(0, titleSpan.length(), URLSpan.class); - if(urlSpans.length == 0 && !hasNotes && + if (urlSpans.length == 0 && !hasNotes && !hasAttachments) return null; PackageManager pm = context.getPackageManager(); - for(URLSpan urlSpan : urlSpans) { + for (URLSpan urlSpan : urlSpans) { String url = urlSpan.getURL(); int start = titleSpan.getSpanStart(urlSpan); int end = titleSpan.getSpanEnd(urlSpan); @@ -85,12 +84,12 @@ public class LinkActionExposer { Intent actionIntent; // if options > 1, display open with... - if(resolveInfoList.size() > 1) { + if (resolveInfoList.size() > 1) { actionIntent = Intent.createChooser(itemIntent, text); } // else show app that gets opened - else if(resolveInfoList.size() == 1) { + else if (resolveInfoList.size() == 1) { actionIntent = itemIntent; } @@ -108,11 +107,11 @@ public class LinkActionExposer { icon = getBitmapDrawable(R.drawable.action_web, r); } - if(text.length() > 15) + if (text.length() > 15) text = text.substring(0, 12) + "..."; //$NON-NLS-1$ TaskAction action = new TaskAction(text, - PendingIntent.getActivity(context, (int)id, actionIntent, 0), (BitmapDrawable)icon); + PendingIntent.getActivity(context, (int) id, actionIntent, 0), (BitmapDrawable) icon); return action; } diff --git a/astrid/plugin-src/com/todoroo/astrid/core/OldTaskPreferences.java b/astrid/plugin-src/com/todoroo/astrid/core/OldTaskPreferences.java index 32f1d18e2..dc1dadb4a 100644 --- a/astrid/plugin-src/com/todoroo/astrid/core/OldTaskPreferences.java +++ b/astrid/plugin-src/com/todoroo/astrid/core/OldTaskPreferences.java @@ -39,15 +39,18 @@ import com.todoroo.astrid.utility.AstridPreferences; * Displays the preference screen for users to manage their old tasks and events * * @author Tim Su - * */ public class OldTaskPreferences extends TodorooPreferenceActivity { - @Autowired TaskService taskService; - @Autowired MetadataService metadataService; - @Autowired Database database; + @Autowired + TaskService taskService; + @Autowired + MetadataService metadataService; + @Autowired + Database database; - @Autowired ActFmSyncService actFmSyncService; + @Autowired + ActFmSyncService actFmSyncService; ProgressDialog pd; @@ -104,7 +107,7 @@ public class OldTaskPreferences extends TodorooPreferenceActivity { } }); - preference= screen.findPreference(getString(R.string.EPr_manage_clear_all)); + preference = screen.findPreference(getString(R.string.EPr_manage_clear_all)); preference.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference p) { showClearDataDialog(); @@ -118,7 +121,7 @@ public class OldTaskPreferences extends TodorooPreferenceActivity { this, getResources().getString( R.string.EPr_manage_clear_all_message), - new OnClickListener() { + new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Editor editor = Preferences.getPrefs(OldTaskPreferences.this).edit(); @@ -150,7 +153,9 @@ public class OldTaskPreferences extends TodorooPreferenceActivity { super.onPause(); } - /** Show the dialog to delete completed tasks */ + /** + * Show the dialog to delete completed tasks + */ private void showDeleteCompletedDialog() { DialogUtilities.okCancelDialog( this, @@ -167,7 +172,7 @@ public class OldTaskPreferences extends TodorooPreferenceActivity { try { Task task = new Task(); int length = cursor.getCount(); - for(int i = 0; i < length; i++) { + for (int i = 0; i < length; i++) { cursor.moveToNext(); task.readFromCursor(cursor); GCalHelper.deleteTaskEvent(task); @@ -189,7 +194,9 @@ public class OldTaskPreferences extends TodorooPreferenceActivity { }, null); } - /** Show the dialog to purge deleted tasks */ + /** + * Show the dialog to purge deleted tasks + */ private void showPurgeDeletedDialog() { DialogUtilities.okCancelDialog( this, @@ -206,7 +213,7 @@ public class OldTaskPreferences extends TodorooPreferenceActivity { try { Task task = new Task(); int length = cursor.getCount(); - for(int i = 0; i < length; i++) { + for (int i = 0; i < length; i++) { cursor.moveToNext(); task.readFromCursor(cursor); GCalHelper.deleteTaskEvent(task); @@ -225,7 +232,9 @@ public class OldTaskPreferences extends TodorooPreferenceActivity { }, null); } - /** Show the dialog to delete completed events */ + /** + * Show the dialog to delete completed events + */ private void showDeleteCompletedEventsDialog() { DialogUtilities.okCancelDialog( this, @@ -243,7 +252,7 @@ public class OldTaskPreferences extends TodorooPreferenceActivity { try { Task task = new Task(); int length = cursor.getCount(); - for(int i = 0; i < length; i++) { + for (int i = 0; i < length; i++) { cursor.moveToNext(); task.readFromCursor(cursor); if (GCalHelper.deleteTaskEvent(task)) @@ -266,7 +275,9 @@ public class OldTaskPreferences extends TodorooPreferenceActivity { }, null); } - /** Show the dialog to delete all events */ + /** + * Show the dialog to delete all events + */ private void showDeleteAllEventsDialog() { DialogUtilities.okCancelDialog( this, @@ -284,7 +295,7 @@ public class OldTaskPreferences extends TodorooPreferenceActivity { try { Task task = new Task(); int length = cursor.getCount(); - for(int i = 0; i < length; i++) { + for (int i = 0; i < length; i++) { cursor.moveToNext(); task.readFromCursor(cursor); if (GCalHelper.deleteTaskEvent(task)) diff --git a/astrid/plugin-src/com/todoroo/astrid/core/PluginServices.java b/astrid/plugin-src/com/todoroo/astrid/core/PluginServices.java index 59f612b49..531b60bcb 100644 --- a/astrid/plugin-src/com/todoroo/astrid/core/PluginServices.java +++ b/astrid/plugin-src/com/todoroo/astrid/core/PluginServices.java @@ -41,7 +41,6 @@ import com.todoroo.astrid.service.TaskService; * Utility class for getting dependency-injected services from plugins * * @author Tim Su - * */ public final class PluginServices { @@ -128,7 +127,7 @@ public final class PluginServices { } private static PluginServices getInstance() { - if(instance == null) { + if (instance == null) { synchronized (PluginServices.class) { if (instance == null) instance = new PluginServices(); @@ -244,8 +243,8 @@ public final class PluginServices { public static Metadata getMetadataByTaskAndWithKey(long taskId, String metadataKey) { TodorooCursor cursor = PluginServices.getMetadataService().query(Query.select( Metadata.PROPERTIES).where(MetadataCriteria.byTaskAndwithKey(taskId, metadataKey))); - try { - if(cursor.getCount() > 0) { + try { + if (cursor.getCount() > 0) { cursor.moveToNext(); return new Metadata(cursor); } else diff --git a/astrid/plugin-src/com/todoroo/astrid/core/SavedFilter.java b/astrid/plugin-src/com/todoroo/astrid/core/SavedFilter.java index 057461a23..52edea76e 100644 --- a/astrid/plugin-src/com/todoroo/astrid/core/SavedFilter.java +++ b/astrid/plugin-src/com/todoroo/astrid/core/SavedFilter.java @@ -21,26 +21,35 @@ import com.todoroo.astrid.data.StoreObject; * {@link StoreObject} entries for a saved custom filter * * @author Tim Su - * */ public class SavedFilter { - /** type */ + /** + * type + */ public static final String TYPE = "filter"; //$NON-NLS-1$ - /** saved filter name */ + /** + * saved filter name + */ public static final StringProperty NAME = new StringProperty(StoreObject.TABLE, StoreObject.ITEM.name); - /** perma-sql */ + /** + * perma-sql + */ public static final StringProperty SQL = new StringProperty(StoreObject.TABLE, StoreObject.VALUE1.name); - /** serialized new task content values */ + /** + * serialized new task content values + */ public static final StringProperty VALUES = new StringProperty(StoreObject.TABLE, StoreObject.VALUE2.name); - /** serialized list of filters applied */ + /** + * serialized list of filters applied + */ public static final StringProperty FILTERS = new StringProperty(StoreObject.TABLE, StoreObject.VALUE3.name); @@ -55,9 +64,9 @@ public class SavedFilter { * @param values2 */ public static void persist(CustomFilterAdapter adapter, String title, - String sql, ContentValues values) { + String sql, ContentValues values) { - if(title == null || title.length() == 0) + if (title == null || title.length() == 0) return; // if filter of this name exists, edit it @@ -65,7 +74,7 @@ public class SavedFilter { StoreObject storeObject = new StoreObject(); TodorooCursor cursor = dao.query(Query.select(StoreObject.ID).where(NAME.eq(title))); try { - if(!cursor.isAfterLast()) { + if (!cursor.isAfterLast()) { cursor.moveToNext(); storeObject.readFromCursor(cursor); } @@ -78,7 +87,7 @@ public class SavedFilter { storeObject.setValue(NAME, title); storeObject.setValue(SQL, sql); - if(values == null) + if (values == null) storeObject.setValue(VALUES, ""); //$NON-NLS-1$ else storeObject.setValue(VALUES, AndroidUtilities.contentValuesToSerializedString(values)); @@ -91,12 +100,13 @@ public class SavedFilter { /** * Turn a series of CriterionInstance objects into a string + * * @param adapter * @return */ private static String serializeFilters(CustomFilterAdapter adapter) { StringBuilder values = new StringBuilder(); - for(int i = 0; i < adapter.getCount(); i++) { + for (int i = 0; i < adapter.getCount(); i++) { CriterionInstance item = adapter.getItem(i); // criterion|entry|text|type|sql @@ -104,7 +114,7 @@ public class SavedFilter { values.append(escape(item.getValueFromCriterion())).append(AndroidUtilities.SERIALIZATION_SEPARATOR); values.append(escape(item.criterion.text)).append(AndroidUtilities.SERIALIZATION_SEPARATOR); values.append(item.type).append(AndroidUtilities.SERIALIZATION_SEPARATOR); - if(item.criterion.sql != null) + if (item.criterion.sql != null) values.append(item.criterion.sql); values.append('\n'); } @@ -113,7 +123,7 @@ public class SavedFilter { } private static String escape(String item) { - if(item == null) + if (item == null) return ""; //$NON-NLS-1$ return item.replace(AndroidUtilities.SERIALIZATION_SEPARATOR, AndroidUtilities.SEPARATOR_ESCAPE); @@ -121,6 +131,7 @@ public class SavedFilter { /** * Read filter from store + * * @param savedFilter * @return */ @@ -130,7 +141,7 @@ public class SavedFilter { String values = savedFilter.getValue(VALUES); ContentValues contentValues = null; - if(!TextUtils.isEmpty(values)) + if (!TextUtils.isEmpty(values)) contentValues = AndroidUtilities.contentValuesFromSerializedString(values); return new Filter(title, title, sql, contentValues); diff --git a/astrid/plugin-src/com/todoroo/astrid/files/AACRecordingActivity.java b/astrid/plugin-src/com/todoroo/astrid/files/AACRecordingActivity.java index c4852466e..071d557f4 100644 --- a/astrid/plugin-src/com/todoroo/astrid/files/AACRecordingActivity.java +++ b/astrid/plugin-src/com/todoroo/astrid/files/AACRecordingActivity.java @@ -5,9 +5,6 @@ */ package com.todoroo.astrid.files; -import java.io.IOException; -import java.util.concurrent.atomic.AtomicReference; - import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; @@ -23,6 +20,9 @@ import com.todoroo.aacenc.AACRecorder.AACRecorderCallbacks; import com.todoroo.aacenc.AACToM4A; import com.todoroo.andlib.utility.DialogUtilities; +import java.io.IOException; +import java.util.concurrent.atomic.AtomicReference; + public class AACRecordingActivity extends Activity implements AACRecorderCallbacks { public static final String EXTRA_TEMP_FILE = "tempFile"; //$NON-NLS-1$ diff --git a/astrid/plugin-src/com/todoroo/astrid/files/FileExplore.java b/astrid/plugin-src/com/todoroo/astrid/files/FileExplore.java index 293dd4b9a..9d493344d 100644 --- a/astrid/plugin-src/com/todoroo/astrid/files/FileExplore.java +++ b/astrid/plugin-src/com/todoroo/astrid/files/FileExplore.java @@ -5,10 +5,6 @@ */ package com.todoroo.astrid.files; -import java.io.File; -import java.io.FilenameFilter; -import java.util.ArrayList; - import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; @@ -28,214 +24,217 @@ import android.widget.TextView; import com.timsu.astrid.R; import com.todoroo.andlib.utility.DialogUtilities; +import java.io.File; +import java.io.FilenameFilter; +import java.util.ArrayList; + /** * Based on the Android-File-Explore project by Manish Burman * https://github.com/mburman/Android-File-Explore - * */ public class FileExplore extends Activity { - // Stores names of traversed directories - ArrayList str = new ArrayList(); + // Stores names of traversed directories + ArrayList str = new ArrayList(); - // Check if the first level of the directory structure is the one showing - private Boolean firstLvl = true; + // Check if the first level of the directory structure is the one showing + private Boolean firstLvl = true; - private static final String TAG = "F_PATH"; //$NON-NLS-1$ + private static final String TAG = "F_PATH"; //$NON-NLS-1$ - public static final String RESULT_FILE_SELECTED = "fileSelected"; //$NON-NLS-1$ + public static final String RESULT_FILE_SELECTED = "fileSelected"; //$NON-NLS-1$ - public static final String RESULT_DIR_SELECTED = "dirSelected"; //$NON-NLS-1$ + public static final String RESULT_DIR_SELECTED = "dirSelected"; //$NON-NLS-1$ - public static final String EXTRA_DIRECTORIES_SELECTABLE = "directoriesSelectable"; //$NON-NLS-1$ + public static final String EXTRA_DIRECTORIES_SELECTABLE = "directoriesSelectable"; //$NON-NLS-1$ - private Item[] fileList; - private File path; - private String chosenFile; - private static final int DIALOG_LOAD_FILE = 1000; - private String upString; + private Item[] fileList; + private File path; + private String chosenFile; + private static final int DIALOG_LOAD_FILE = 1000; + private String upString; - private boolean directoryMode; + private boolean directoryMode; - private ListAdapter adapter; + private ListAdapter adapter; - @Override - public void onCreate(Bundle savedInstanceState) { + @Override + public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + super.onCreate(savedInstanceState); - if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) - path = new File(Environment.getExternalStorageDirectory().toString()); - else - path = Environment.getRootDirectory(); + if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) + path = new File(Environment.getExternalStorageDirectory().toString()); + else + path = Environment.getRootDirectory(); - loadFileList(); + loadFileList(); - directoryMode = getIntent().getBooleanExtra(EXTRA_DIRECTORIES_SELECTABLE, false); + directoryMode = getIntent().getBooleanExtra(EXTRA_DIRECTORIES_SELECTABLE, false); - showDialog(DIALOG_LOAD_FILE); - upString = getString(R.string.file_browser_up); - Log.d(TAG, path.getAbsolutePath()); + showDialog(DIALOG_LOAD_FILE); + upString = getString(R.string.file_browser_up); + Log.d(TAG, path.getAbsolutePath()); - } + } - private void loadFileList() { - try { - path.mkdirs(); - } catch (SecurityException e) { - DialogUtilities.okDialog(this, getString(R.string.file_browser_err_permissions), new DialogInterface.OnClickListener() { + private void loadFileList() { + try { + path.mkdirs(); + } catch (SecurityException e) { + DialogUtilities.okDialog(this, getString(R.string.file_browser_err_permissions), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); - } - - // Checks whether path exists - if (path.exists()) { - FilenameFilter filter = new FilenameFilter() { - @Override - public boolean accept(File dir, String filename) { - File sel = new File(dir, filename); - // Filters based on whether the file is hidden or not - return (sel.isFile() || sel.isDirectory()) - && !sel.isHidden(); - - } - }; - - String[] fList = path.list(filter); - fileList = new Item[fList.length]; - for (int i = 0; i < fList.length; i++) { - fileList[i] = new Item(fList[i], R.drawable.file_icon); - - // Convert into file path - File sel = new File(path, fList[i]); - - // Set drawables - if (sel.isDirectory()) { - fileList[i].icon = R.drawable.directory_icon; - } - } - - if (!firstLvl) { - Item temp[] = new Item[fileList.length + 1]; - for (int i = 0; i < fileList.length; i++) { - temp[i + 1] = fileList[i]; - } - temp[0] = new Item(upString, R.drawable.directory_up); - fileList = temp; - } - } else { - Log.e(TAG, "path does not exist"); //$NON-NLS-1$ - } - - adapter = new ArrayAdapter(this, - android.R.layout.select_dialog_item, android.R.id.text1, - fileList) { - @Override - public View getView(int position, View convertView, ViewGroup parent) { - // creates view - View view = super.getView(position, convertView, parent); - TextView textView = (TextView) view - .findViewById(android.R.id.text1); - - // put the image on the text view - textView.setCompoundDrawablesWithIntrinsicBounds( - fileList[position].icon, 0, 0, 0); - - // add margin between image and text (support various screen - // densities) - int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f); - textView.setCompoundDrawablePadding(dp5); - - return view; - } - }; - - } - - private class Item { - public String file; - public int icon; - - public Item(String file, Integer icon) { - this.file = file; - this.icon = icon; - } - - @Override - public String toString() { - return file; - } - } - - @Override - protected Dialog onCreateDialog(int id) { - Dialog dialog = null; - AlertDialog.Builder builder = new Builder(this); - - if (fileList == null) { - dialog = builder.create(); - return dialog; - } - - switch (id) { - case DIALOG_LOAD_FILE: - builder.setTitle(getString(directoryMode ? R.string.dir_browser_title : R.string.file_browser_title)); - builder.setAdapter(adapter, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface d, int which) { - chosenFile = fileList[which].file; - File sel = new File(path + File.separator + chosenFile); - if (sel.isDirectory()) { - firstLvl = false; - - // Adds chosen directory to list - str.add(chosenFile); - fileList = null; - path = new File(sel.toString()); - - loadFileList(); - - removeDialog(DIALOG_LOAD_FILE); - showDialog(DIALOG_LOAD_FILE); - } else if (chosenFile.equals(upString) && !sel.exists()) { // Checks if 'up' was clicked - // present directory removed from list - String s = str.remove(str.size() - 1); - - // path modified to exclude present directory - path = new File(path.toString().substring(0, - path.toString().lastIndexOf(s))); - fileList = null; - - // if there are no more directories in the list, then - // its the first level - if (str.isEmpty()) { - firstLvl = true; - } - loadFileList(); - - removeDialog(DIALOG_LOAD_FILE); - showDialog(DIALOG_LOAD_FILE); - } else { - Intent result = new Intent(); - if (directoryMode) { - result.putExtra(RESULT_DIR_SELECTED, path.getAbsolutePath()); - } else { - result.putExtra(RESULT_FILE_SELECTED, sel.getAbsolutePath()); - } - setResult(RESULT_OK, result); - removeDialog(DIALOG_LOAD_FILE); - finish(); - } - - } - }); - break; - } - if (directoryMode) { - builder.setPositiveButton(R.string.file_dir_dialog_ok, new DialogInterface.OnClickListener() { + } + + // Checks whether path exists + if (path.exists()) { + FilenameFilter filter = new FilenameFilter() { + @Override + public boolean accept(File dir, String filename) { + File sel = new File(dir, filename); + // Filters based on whether the file is hidden or not + return (sel.isFile() || sel.isDirectory()) + && !sel.isHidden(); + + } + }; + + String[] fList = path.list(filter); + fileList = new Item[fList.length]; + for (int i = 0; i < fList.length; i++) { + fileList[i] = new Item(fList[i], R.drawable.file_icon); + + // Convert into file path + File sel = new File(path, fList[i]); + + // Set drawables + if (sel.isDirectory()) { + fileList[i].icon = R.drawable.directory_icon; + } + } + + if (!firstLvl) { + Item temp[] = new Item[fileList.length + 1]; + for (int i = 0; i < fileList.length; i++) { + temp[i + 1] = fileList[i]; + } + temp[0] = new Item(upString, R.drawable.directory_up); + fileList = temp; + } + } else { + Log.e(TAG, "path does not exist"); //$NON-NLS-1$ + } + + adapter = new ArrayAdapter(this, + android.R.layout.select_dialog_item, android.R.id.text1, + fileList) { + @Override + public View getView(int position, View convertView, ViewGroup parent) { + // creates view + View view = super.getView(position, convertView, parent); + TextView textView = (TextView) view + .findViewById(android.R.id.text1); + + // put the image on the text view + textView.setCompoundDrawablesWithIntrinsicBounds( + fileList[position].icon, 0, 0, 0); + + // add margin between image and text (support various screen + // densities) + int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f); + textView.setCompoundDrawablePadding(dp5); + + return view; + } + }; + + } + + private class Item { + public String file; + public int icon; + + public Item(String file, Integer icon) { + this.file = file; + this.icon = icon; + } + + @Override + public String toString() { + return file; + } + } + + @Override + protected Dialog onCreateDialog(int id) { + Dialog dialog = null; + AlertDialog.Builder builder = new Builder(this); + + if (fileList == null) { + dialog = builder.create(); + return dialog; + } + + switch (id) { + case DIALOG_LOAD_FILE: + builder.setTitle(getString(directoryMode ? R.string.dir_browser_title : R.string.file_browser_title)); + builder.setAdapter(adapter, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface d, int which) { + chosenFile = fileList[which].file; + File sel = new File(path + File.separator + chosenFile); + if (sel.isDirectory()) { + firstLvl = false; + + // Adds chosen directory to list + str.add(chosenFile); + fileList = null; + path = new File(sel.toString()); + + loadFileList(); + + removeDialog(DIALOG_LOAD_FILE); + showDialog(DIALOG_LOAD_FILE); + } else if (chosenFile.equals(upString) && !sel.exists()) { // Checks if 'up' was clicked + // present directory removed from list + String s = str.remove(str.size() - 1); + + // path modified to exclude present directory + path = new File(path.toString().substring(0, + path.toString().lastIndexOf(s))); + fileList = null; + + // if there are no more directories in the list, then + // its the first level + if (str.isEmpty()) { + firstLvl = true; + } + loadFileList(); + + removeDialog(DIALOG_LOAD_FILE); + showDialog(DIALOG_LOAD_FILE); + } else { + Intent result = new Intent(); + if (directoryMode) { + result.putExtra(RESULT_DIR_SELECTED, path.getAbsolutePath()); + } else { + result.putExtra(RESULT_FILE_SELECTED, sel.getAbsolutePath()); + } + setResult(RESULT_OK, result); + removeDialog(DIALOG_LOAD_FILE); + finish(); + } + + } + }); + break; + } + if (directoryMode) { + builder.setPositiveButton(R.string.file_dir_dialog_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface d, int which) { Intent result = new Intent(); @@ -245,7 +244,7 @@ public class FileExplore extends Activity { finish(); } }); - builder.setNegativeButton(R.string.file_dir_dialog_default, new DialogInterface.OnClickListener() { + builder.setNegativeButton(R.string.file_dir_dialog_default, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface d, int which) { Intent result = new Intent(); @@ -255,17 +254,17 @@ public class FileExplore extends Activity { finish(); } }); - } + } - dialog = builder.show(); - dialog.setCancelable(true); - dialog.setOnCancelListener(new OnCancelListener() { + dialog = builder.show(); + dialog.setCancelable(true); + dialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface d) { finish(); } }); - return dialog; - } + return dialog; + } } \ No newline at end of file diff --git a/astrid/plugin-src/com/todoroo/astrid/files/FileMetadata.java b/astrid/plugin-src/com/todoroo/astrid/files/FileMetadata.java index b51bc6c1c..586ea92bb 100644 --- a/astrid/plugin-src/com/todoroo/astrid/files/FileMetadata.java +++ b/astrid/plugin-src/com/todoroo/astrid/files/FileMetadata.java @@ -11,13 +11,15 @@ import com.todoroo.astrid.data.Metadata; /** * This class was deprecated with SyncV2. Use TaskAttachment instead. - * @author Sam * + * @author Sam */ @Deprecated public class FileMetadata { - /** metadata key */ + /** + * metadata key + */ public static final String METADATA_KEY = "file"; //$NON-NLS-1$ public static final StringProperty FILE_PATH = new StringProperty(Metadata.TABLE, diff --git a/astrid/plugin-src/com/todoroo/astrid/files/FileUtilities.java b/astrid/plugin-src/com/todoroo/astrid/files/FileUtilities.java index 7743608b8..58f1a7e16 100644 --- a/astrid/plugin-src/com/todoroo/astrid/files/FileUtilities.java +++ b/astrid/plugin-src/com/todoroo/astrid/files/FileUtilities.java @@ -5,11 +5,6 @@ */ package com.todoroo.astrid.files; -import java.io.File; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.concurrent.atomic.AtomicReference; - import android.content.Context; import android.text.TextUtils; @@ -18,6 +13,11 @@ import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.andlib.utility.Preferences; import com.todoroo.astrid.data.TaskAttachment; +import java.io.File; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.concurrent.atomic.AtomicReference; + public class FileUtilities { /** @@ -32,8 +32,7 @@ public class FileUtilities { String value; if (DateUtilities.is24HourFormat(context)) { value = "HH.mm"; - } - else { + } else { value = "hh.mma"; } return new SimpleDateFormat(value).format(date); diff --git a/astrid/plugin-src/com/todoroo/astrid/files/FilesControlSet.java b/astrid/plugin-src/com/todoroo/astrid/files/FilesControlSet.java index f8c2c4ee6..0d947322f 100644 --- a/astrid/plugin-src/com/todoroo/astrid/files/FilesControlSet.java +++ b/astrid/plugin-src/com/todoroo/astrid/files/FilesControlSet.java @@ -5,13 +5,6 @@ */ package com.todoroo.astrid.files; -import java.io.File; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.ArrayList; - import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; @@ -52,6 +45,13 @@ import com.todoroo.astrid.service.ThemeService; import com.todoroo.astrid.ui.PopupControlSet; import com.todoroo.astrid.utility.Constants; +import java.io.File; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.ArrayList; + public class FilesControlSet extends PopupControlSet { @Autowired @@ -99,8 +99,8 @@ public class FilesControlSet extends PopupControlSet { if (model != null) { TodorooCursor cursor = taskAttachmentDao.query( Query.select(TaskAttachment.PROPERTIES) - .where(Criterion.and(TaskAttachment.TASK_UUID.eq(model.getUuid()), - TaskAttachment.DELETED_AT.eq(0)))); + .where(Criterion.and(TaskAttachment.TASK_UUID.eq(model.getUuid()), + TaskAttachment.DELETED_AT.eq(0)))); try { files.clear(); for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { @@ -170,24 +170,24 @@ public class FilesControlSet extends PopupControlSet { public void onClick(View v) { DialogUtilities.okCancelDialog(activity, activity.getString(R.string.premium_remove_file_confirm), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface d, int which) { - if (RemoteModel.isValidUuid(m.getValue(TaskAttachment.UUID))) { - m.setValue(TaskAttachment.DELETED_AT, DateUtilities.now()); - taskAttachmentDao.saveExisting(m); - } else { - taskAttachmentDao.delete(m.getId()); - } - - if (m.containsNonNullValue(TaskAttachment.FILE_PATH)) { - File f = new File(m.getValue(TaskAttachment.FILE_PATH)); - f.delete(); - } - files.remove(m); - refreshDisplayView(); - finalList.removeView(fileRow); - } - }, null); + @Override + public void onClick(DialogInterface d, int which) { + if (RemoteModel.isValidUuid(m.getValue(TaskAttachment.UUID))) { + m.setValue(TaskAttachment.DELETED_AT, DateUtilities.now()); + taskAttachmentDao.saveExisting(m); + } else { + taskAttachmentDao.delete(m.getId()); + } + + if (m.containsNonNullValue(TaskAttachment.FILE_PATH)) { + File f = new File(m.getValue(TaskAttachment.FILE_PATH)); + f.delete(); + } + files.remove(m); + refreshDisplayView(); + finalList.removeView(fileRow); + } + }, null); } }); } @@ -335,8 +335,8 @@ public class FilesControlSet extends PopupControlSet { } filePathBuilder.append(directory.toString()) - .append(File.separator) - .append(name); + .append(File.separator) + .append(name); File file = new File(filePathBuilder.toString()); if (file.exists()) { @@ -373,7 +373,7 @@ public class FilesControlSet extends PopupControlSet { fileOutput.write(buffer, 0, bufferLength); downloadedSize += bufferLength; - int progress = (int) (downloadedSize*100/totalSize); + int progress = (int) (downloadedSize * 100 / totalSize); pd.setProgress(progress); } diff --git a/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarAlarmListCreator.java b/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarAlarmListCreator.java index b6d9cbe69..60dbf3925 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarAlarmListCreator.java +++ b/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarAlarmListCreator.java @@ -1,12 +1,5 @@ package com.todoroo.astrid.gcal; -import java.util.ArrayList; -import java.util.HashMap; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - import android.app.Activity; import android.content.Intent; import android.os.Bundle; @@ -32,6 +25,13 @@ import com.todoroo.astrid.data.User; import com.todoroo.astrid.service.TagDataService; import com.todoroo.astrid.service.ThemeService; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.HashMap; + public class CalendarAlarmListCreator extends Activity { public static final String TOKEN_LIST_NAME = "listName"; //$NON-NLS-1$ @@ -120,9 +120,9 @@ public class CalendarAlarmListCreator extends Activity { String title; if (!TextUtils.isEmpty(attendeesString)) { builder.append(" ") //$NON-NLS-1$ - .append(attendeesString) - .append(" ") //$NON-NLS-1$ - .append(getString(R.string.CRA_invitation_prompt)); + .append(attendeesString) + .append(" ") //$NON-NLS-1$ + .append(getString(R.string.CRA_invitation_prompt)); inviteAll.setBackgroundColor(getResources().getColor(color)); title = getString(R.string.CRA_share_list_title); } else { @@ -134,7 +134,7 @@ public class CalendarAlarmListCreator extends Activity { } ((TextView) findViewById(R.id.reminder_title)) - .setText(title); + .setText(title); dialogView.setText(builder.toString()); } diff --git a/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarAlarmReceiver.java b/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarAlarmReceiver.java index 51498cd30..371ea4403 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarAlarmReceiver.java +++ b/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarAlarmReceiver.java @@ -1,9 +1,5 @@ package com.todoroo.astrid.gcal; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Set; - import android.accounts.Account; import android.accounts.AccountManager; import android.content.BroadcastReceiver; @@ -22,6 +18,10 @@ import com.todoroo.andlib.utility.Preferences; import com.todoroo.astrid.actfm.sync.ActFmPreferenceService; import com.todoroo.astrid.utility.Constants; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; + @SuppressWarnings("nls") public class CalendarAlarmReceiver extends BroadcastReceiver { @@ -29,14 +29,14 @@ public class CalendarAlarmReceiver extends BroadcastReceiver { public static final String BROADCAST_CALENDAR_REMINDER = Constants.PACKAGE + ".CALENDAR_EVENT"; private static final String[] EVENTS_PROJECTION = { - Calendars.EVENTS_DTSTART_COL, - Calendars.EVENTS_DTEND_COL, - Calendars.EVENTS_NAME_COL, + Calendars.EVENTS_DTSTART_COL, + Calendars.EVENTS_DTEND_COL, + Calendars.EVENTS_NAME_COL, }; private static final String[] ATTENDEES_PROJECTION = { - Calendars.ATTENDEES_NAME_COL, - Calendars.ATTENDEES_EMAIL_COL, + Calendars.ATTENDEES_NAME_COL, + Calendars.ATTENDEES_EMAIL_COL, }; @Override @@ -64,14 +64,14 @@ public class CalendarAlarmReceiver extends BroadcastReceiver { } private void showCalReminder(Context context, - long eventId, boolean fromPostpone) { + long eventId, boolean fromPostpone) { ContentResolver cr = context.getContentResolver(); Uri eventUri = Calendars.getCalendarContentUri(Calendars.CALENDAR_CONTENT_EVENTS); if (AndroidUtilities.getSdkVersion() <= 7) return; - String[] eventArg = new String[] { Long.toString(eventId) }; + String[] eventArg = new String[]{Long.toString(eventId)}; Cursor event = cr.query(eventUri, EVENTS_PROJECTION, Calendars.ID_COLUMN_NAME + " = ?", diff --git a/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarAlarmScheduler.java b/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarAlarmScheduler.java index 86eb3fe3e..4ff675d6d 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarAlarmScheduler.java +++ b/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarAlarmScheduler.java @@ -1,7 +1,5 @@ package com.todoroo.astrid.gcal; -import java.util.Date; - import android.app.AlarmManager; import android.app.PendingIntent; import android.content.ContentResolver; @@ -16,6 +14,8 @@ import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.andlib.utility.Preferences; import com.todoroo.astrid.utility.Constants; +import java.util.Date; + @SuppressWarnings("nls") public class CalendarAlarmScheduler { @@ -32,11 +32,11 @@ public class CalendarAlarmScheduler { long now = DateUtilities.now(); - AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); + AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Cursor events = cr.query(Calendars.getCalendarContentUri(Calendars.CALENDAR_CONTENT_EVENTS), - new String[] { Calendars.ID_COLUMN_NAME, Calendars.EVENTS_DTSTART_COL }, + new String[]{Calendars.ID_COLUMN_NAME, Calendars.EVENTS_DTSTART_COL}, Calendars.EVENTS_DTSTART_COL + " > ? AND " + Calendars.EVENTS_DTSTART_COL + " < ?", - new String[] { Long.toString(now + DateUtilities.ONE_MINUTE * 15), Long.toString(now + DateUtilities.ONE_DAY) }, + new String[]{Long.toString(now + DateUtilities.ONE_MINUTE * 15), Long.toString(now + DateUtilities.ONE_DAY)}, null); try { if (events != null && events.getCount() > 0) { diff --git a/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarReminderActivity.java b/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarReminderActivity.java index a3c23391e..78c993917 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarReminderActivity.java +++ b/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarReminderActivity.java @@ -1,7 +1,5 @@ package com.todoroo.astrid.gcal; -import java.util.Date; - import android.app.Activity; import android.app.AlarmManager; import android.app.PendingIntent; @@ -33,6 +31,8 @@ import com.todoroo.astrid.service.ThemeService; import com.todoroo.astrid.tags.TagFilterExposer; import com.todoroo.astrid.utility.Constants; +import java.util.Date; + @SuppressWarnings("nls") public class CalendarReminderActivity extends Activity { @@ -99,7 +99,8 @@ public class CalendarReminderActivity extends Activity { public void onClick(DialogInterface dialog, int which) { dismissListener.onClick(v); } - }); + } + ); } else { dismissListener.onClick(v); } @@ -136,7 +137,7 @@ public class CalendarReminderActivity extends Activity { private void setupUi() { ((TextView) findViewById(R.id.reminder_title)) - .setText(getString(R.string.CRA_title)); + .setText(getString(R.string.CRA_title)); TextView dialogView = (TextView) findViewById(R.id.reminder_message); String speechText; @@ -190,31 +191,32 @@ public class CalendarReminderActivity extends Activity { private void listExists(final TagData tag) { DialogUtilities.okCancelCustomDialog(this, - getString(R.string.CRA_list_exists_title), - getString(R.string.CRA_list_exists_body, tag.getValue(TagData.NAME)), - R.string.CRA_create_new, - R.string.CRA_use_existing, - 0, - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - createNewList(tag.getValue(TagData.NAME) + " " - + DateUtilities.getDateStringHideYear(CalendarReminderActivity.this, new Date(startTime))); + getString(R.string.CRA_list_exists_title), + getString(R.string.CRA_list_exists_body, tag.getValue(TagData.NAME)), + R.string.CRA_create_new, + R.string.CRA_use_existing, + 0, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + createNewList(tag.getValue(TagData.NAME) + " " + + DateUtilities.getDateStringHideYear(CalendarReminderActivity.this, new Date(startTime))); + } + }, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + FilterWithCustomIntent filter = TagFilterExposer.filterFromTagData(CalendarReminderActivity.this, tag); + + Intent listIntent = new Intent(CalendarReminderActivity.this, TaskListActivity.class); + listIntent.putExtra(TaskListFragment.TOKEN_FILTER, filter); + listIntent.putExtras(filter.customExtras); + + startActivity(listIntent); + dismissButton.performClick(); + } } - }, - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - FilterWithCustomIntent filter = TagFilterExposer.filterFromTagData(CalendarReminderActivity.this, tag); - - Intent listIntent = new Intent(CalendarReminderActivity.this, TaskListActivity.class); - listIntent.putExtra(TaskListFragment.TOKEN_FILTER, filter); - listIntent.putExtras(filter.customExtras); - - startActivity(listIntent); - dismissButton.performClick(); - } - }); + ); } private void createNewList(String name) { diff --git a/astrid/plugin-src/com/todoroo/astrid/gcal/Calendars.java b/astrid/plugin-src/com/todoroo/astrid/gcal/Calendars.java index 57fb28eca..9357fecd0 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gcal/Calendars.java +++ b/astrid/plugin-src/com/todoroo/astrid/gcal/Calendars.java @@ -5,9 +5,6 @@ */ package com.todoroo.astrid.gcal; -import java.util.ArrayList; -import java.util.Arrays; - import android.content.ContentResolver; import android.content.Context; import android.content.res.Resources; @@ -22,6 +19,9 @@ import com.todoroo.andlib.service.ContextManager; import com.todoroo.andlib.utility.AndroidUtilities; import com.todoroo.andlib.utility.Preferences; +import java.util.ArrayList; +import java.util.Arrays; + @SuppressWarnings("nls") public class Calendars { @@ -29,156 +29,162 @@ public class Calendars { public static final String CALENDAR_CONTENT_EVENTS = "events"; public static final String CALENDAR_CONTENT_ATTENDEES = "attendees"; - private static final boolean USE_ICS_NAMES = AndroidUtilities.getSdkVersion() >= 14; + private static final boolean USE_ICS_NAMES = AndroidUtilities.getSdkVersion() >= 14; - public static final String ID_COLUMN_NAME = "_id"; - public static final String CALENDARS_DISPLAY_COL = (USE_ICS_NAMES ? CalendarContract.Calendars.CALENDAR_DISPLAY_NAME : "displayName"); - public static final String CALENDARS_ACCESS_LEVEL_COL = (USE_ICS_NAMES ? CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL : "access_level"); - public static final String EVENTS_DTSTART_COL = (USE_ICS_NAMES ? CalendarContract.Events.DTSTART : "dtstart"); - public static final String EVENTS_DTEND_COL = (USE_ICS_NAMES ? CalendarContract.Events.DTEND : "dtend"); - public static final String EVENTS_NAME_COL = (USE_ICS_NAMES ? CalendarContract.Events.TITLE : "title"); - public static final String ATTENDEES_EVENT_ID_COL = (USE_ICS_NAMES ? CalendarContract.Attendees.EVENT_ID : "event_id"); + public static final String ID_COLUMN_NAME = "_id"; + public static final String CALENDARS_DISPLAY_COL = (USE_ICS_NAMES ? CalendarContract.Calendars.CALENDAR_DISPLAY_NAME : "displayName"); + public static final String CALENDARS_ACCESS_LEVEL_COL = (USE_ICS_NAMES ? CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL : "access_level"); + public static final String EVENTS_DTSTART_COL = (USE_ICS_NAMES ? CalendarContract.Events.DTSTART : "dtstart"); + public static final String EVENTS_DTEND_COL = (USE_ICS_NAMES ? CalendarContract.Events.DTEND : "dtend"); + public static final String EVENTS_NAME_COL = (USE_ICS_NAMES ? CalendarContract.Events.TITLE : "title"); + public static final String ATTENDEES_EVENT_ID_COL = (USE_ICS_NAMES ? CalendarContract.Attendees.EVENT_ID : "event_id"); public static final String ATTENDEES_NAME_COL = (USE_ICS_NAMES ? CalendarContract.Attendees.ATTENDEE_NAME : "attendeeName"); - public static final String ATTENDEES_EMAIL_COL = (USE_ICS_NAMES ? CalendarContract.Attendees.ATTENDEE_EMAIL: "attendeeEmail"); - - - private static final String[] CALENDARS_PROJECTION = new String[] { - ID_COLUMN_NAME, - CALENDARS_DISPLAY_COL, - }; - - // Only show calendars that the user can modify. Access level 500 - // corresponds to Calendars.CONTRIBUTOR_ACCESS - private static final String CALENDARS_WHERE = CALENDARS_ACCESS_LEVEL_COL + ">= 500"; - - private static final String CALENDARS_SORT = CALENDARS_DISPLAY_COL + " ASC"; - - // --- api access - - /** Return content uri for calendars - * @param table provider table, something like calendars, events - */ - public static Uri getCalendarContentUri(String table) { - if (AndroidUtilities.getSdkVersion() >= 14) { - return getIcsUri(table); - } - - if(AndroidUtilities.getSdkVersion() >= 8) - return Uri.parse("content://com.android.calendar/" + table); - else - return Uri.parse("content://calendar/" + table); - } - - private static Uri getIcsUri(String table) { - if (CALENDAR_CONTENT_CALENDARS.equals(table)) - return CalendarContract.Calendars.CONTENT_URI; - else if (CALENDAR_CONTENT_EVENTS.equals(table)) - return CalendarContract.Events.CONTENT_URI; - else if (CALENDAR_CONTENT_ATTENDEES.equals(table)) - return CalendarContract.Attendees.CONTENT_URI; - return null; - } - - /** Return calendar package name */ - public static String getCalendarPackage() { - if(AndroidUtilities.getSdkVersion() >= 8) - return "com.google.android.calendar"; - else - return "com.android.calendar"; - } - - // --- helper data structure - - /** - * Helper class for working with the results of getCalendars - */ - public static class CalendarResult { - /** calendar names */ - public String[] calendars; - - /** calendar ids. null entry -> use default */ - public String[] calendarIds; - - /** default selection index */ - public int defaultIndex = -1; - } - - /** - * Appends all user-modifiable calendars to listPreference. - * - * @param context - * context - * @param listPreference - * preference to init - */ - public static CalendarResult getCalendars() { - Context context = ContextManager.getContext(); - ContentResolver cr = context.getContentResolver(); - Resources r = context.getResources(); - - Cursor c = cr.query(getCalendarContentUri(CALENDAR_CONTENT_CALENDARS), CALENDARS_PROJECTION, - CALENDARS_WHERE, null, CALENDARS_SORT); - try { - // Fetch the current setting. Invalid calendar id will - // be changed to default value. - String defaultSetting = Preferences.getStringValue(R.string.gcal_p_default); - - CalendarResult result = new CalendarResult(); - - if (c == null || c.getCount() == 0) { - // Something went wrong when querying calendars. Only offer them - // the system default choice - result.calendars = new String[] { - r.getString(R.string.gcal_GCP_default) }; - result.calendarIds = new String[] { null }; - result.defaultIndex = 0; - return result; - } - - int calendarCount = c.getCount(); - - result.calendars = new String[calendarCount]; - result.calendarIds = new String[calendarCount]; - - // Iterate calendars one by one, and fill up the list preference - int row = 0; - int idColumn = c.getColumnIndex(ID_COLUMN_NAME); - int nameColumn = c.getColumnIndex(CALENDARS_DISPLAY_COL); - while (c.moveToNext()) { - String id = c.getString(idColumn); - String name = c.getString(nameColumn); - result.calendars[row] = name; - result.calendarIds[row] = id; - - // We found currently selected calendar - if (defaultSetting != null && defaultSetting.equals(id)) { - result.defaultIndex = row; - } - - row++; - } - - if (result.defaultIndex >= calendarCount) { - result.defaultIndex = 0; - } - - return result; - } finally { - if(c != null) - c.close(); - } - } + public static final String ATTENDEES_EMAIL_COL = (USE_ICS_NAMES ? CalendarContract.Attendees.ATTENDEE_EMAIL : "attendeeEmail"); + + + private static final String[] CALENDARS_PROJECTION = new String[]{ + ID_COLUMN_NAME, + CALENDARS_DISPLAY_COL, + }; + + // Only show calendars that the user can modify. Access level 500 + // corresponds to Calendars.CONTRIBUTOR_ACCESS + private static final String CALENDARS_WHERE = CALENDARS_ACCESS_LEVEL_COL + ">= 500"; + + private static final String CALENDARS_SORT = CALENDARS_DISPLAY_COL + " ASC"; + + // --- api access + + /** + * Return content uri for calendars + * + * @param table provider table, something like calendars, events + */ + public static Uri getCalendarContentUri(String table) { + if (AndroidUtilities.getSdkVersion() >= 14) { + return getIcsUri(table); + } + + if (AndroidUtilities.getSdkVersion() >= 8) + return Uri.parse("content://com.android.calendar/" + table); + else + return Uri.parse("content://calendar/" + table); + } + + private static Uri getIcsUri(String table) { + if (CALENDAR_CONTENT_CALENDARS.equals(table)) + return CalendarContract.Calendars.CONTENT_URI; + else if (CALENDAR_CONTENT_EVENTS.equals(table)) + return CalendarContract.Events.CONTENT_URI; + else if (CALENDAR_CONTENT_ATTENDEES.equals(table)) + return CalendarContract.Attendees.CONTENT_URI; + return null; + } + + /** + * Return calendar package name + */ + public static String getCalendarPackage() { + if (AndroidUtilities.getSdkVersion() >= 8) + return "com.google.android.calendar"; + else + return "com.android.calendar"; + } + + // --- helper data structure + + /** + * Helper class for working with the results of getCalendars + */ + public static class CalendarResult { + /** + * calendar names + */ + public String[] calendars; + + /** + * calendar ids. null entry -> use default + */ + public String[] calendarIds; + + /** + * default selection index + */ + public int defaultIndex = -1; + } /** * Appends all user-modifiable calendars to listPreference. * - * @param context - * context - * @param listPreference - * preference to init + * @param context context + * @param listPreference preference to init + */ + public static CalendarResult getCalendars() { + Context context = ContextManager.getContext(); + ContentResolver cr = context.getContentResolver(); + Resources r = context.getResources(); + + Cursor c = cr.query(getCalendarContentUri(CALENDAR_CONTENT_CALENDARS), CALENDARS_PROJECTION, + CALENDARS_WHERE, null, CALENDARS_SORT); + try { + // Fetch the current setting. Invalid calendar id will + // be changed to default value. + String defaultSetting = Preferences.getStringValue(R.string.gcal_p_default); + + CalendarResult result = new CalendarResult(); + + if (c == null || c.getCount() == 0) { + // Something went wrong when querying calendars. Only offer them + // the system default choice + result.calendars = new String[]{ + r.getString(R.string.gcal_GCP_default)}; + result.calendarIds = new String[]{null}; + result.defaultIndex = 0; + return result; + } + + int calendarCount = c.getCount(); + + result.calendars = new String[calendarCount]; + result.calendarIds = new String[calendarCount]; + + // Iterate calendars one by one, and fill up the list preference + int row = 0; + int idColumn = c.getColumnIndex(ID_COLUMN_NAME); + int nameColumn = c.getColumnIndex(CALENDARS_DISPLAY_COL); + while (c.moveToNext()) { + String id = c.getString(idColumn); + String name = c.getString(nameColumn); + result.calendars[row] = name; + result.calendarIds[row] = id; + + // We found currently selected calendar + if (defaultSetting != null && defaultSetting.equals(id)) { + result.defaultIndex = row; + } + + row++; + } + + if (result.defaultIndex >= calendarCount) { + result.defaultIndex = 0; + } + + return result; + } finally { + if (c != null) + c.close(); + } + } + + /** + * Appends all user-modifiable calendars to listPreference. + * + * @param context context + * @param listPreference preference to init */ public static void initCalendarsPreference(Context context, - ListPreference listPreference) { + ListPreference listPreference) { Resources r = context.getResources(); CalendarResult calendars = getCalendars(); @@ -211,16 +217,16 @@ public class Calendars { // Iterate calendars one by one, and fill up the list preference if (currentSetting != null) { - for (int i=0; i calendars.calendarIds.length+1) { + if (currentSettingIndex == -1 || currentSettingIndex > calendars.calendarIds.length + 1) { // Should not happen! // Leave the preference at disabled. Log.d("astrid", "initCalendarsPreference: Unknown calendar."); @@ -231,20 +237,22 @@ public class Calendars { listPreference.setEnabled(true); } - /** - * sets the default calendar for future use - * @param defaultCalendar default calendar id - */ - public static void setDefaultCalendar(String defaultCalendar) { + /** + * sets the default calendar for future use + * + * @param defaultCalendar default calendar id + */ + public static void setDefaultCalendar(String defaultCalendar) { Preferences.setString(R.string.gcal_p_default, defaultCalendar); - } - - /** - * gets the default calendar for future use - * @return the calendar id for use with the contentresolver - */ - public static String getDefaultCalendar() { - return Preferences.getStringValue(R.string.gcal_p_default); - } + } + + /** + * gets the default calendar for future use + * + * @return the calendar id for use with the contentresolver + */ + public static String getDefaultCalendar() { + return Preferences.getStringValue(R.string.gcal_p_default); + } } diff --git a/astrid/plugin-src/com/todoroo/astrid/gcal/GCalControlSet.java b/astrid/plugin-src/com/todoroo/astrid/gcal/GCalControlSet.java index a1d1d704d..bdd21f51a 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gcal/GCalControlSet.java +++ b/astrid/plugin-src/com/todoroo/astrid/gcal/GCalControlSet.java @@ -5,9 +5,6 @@ */ package com.todoroo.astrid.gcal; -import java.util.ArrayList; -import java.util.Collections; - import android.app.Activity; import android.content.ContentResolver; import android.content.ContentValues; @@ -39,11 +36,13 @@ import com.todoroo.astrid.service.StatisticsService; import com.todoroo.astrid.service.ThemeService; import com.todoroo.astrid.ui.PopupControlSet; +import java.util.ArrayList; +import java.util.Collections; + /** * Control Set for managing repeats * * @author Tim Su - * */ public class GCalControlSet extends PopupControlSet { @@ -88,7 +87,7 @@ public class GCalControlSet extends PopupControlSet { calendarSelector.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView arg0, View arg1, - int arg2, long arg3) { + int arg2, long arg3) { refreshDisplayView(); } @@ -102,17 +101,17 @@ public class GCalControlSet extends PopupControlSet { @Override protected void readFromTaskOnInitialize() { String uri = GCalHelper.getTaskEventUri(model); - if(!TextUtils.isEmpty(uri)) { + if (!TextUtils.isEmpty(uri)) { try { calendarUri = Uri.parse(uri); // try to load calendar ContentResolver cr = activity.getContentResolver(); - Cursor cursor = cr.query(calendarUri, new String[] { "dtstart" }, null, null, null); //$NON-NLS-1$ + Cursor cursor = cr.query(calendarUri, new String[]{"dtstart"}, null, null, null); //$NON-NLS-1$ try { boolean deleted = cursor.getCount() == 0; - if(deleted) { + if (deleted) { calendarUri = null; return; } @@ -144,12 +143,12 @@ public class GCalControlSet extends PopupControlSet { return null; boolean gcalCreateEventEnabled = Preferences.getStringValue(R.string.gcal_p_default) != null && - !Preferences.getStringValue(R.string.gcal_p_default).equals("-1"); + !Preferences.getStringValue(R.string.gcal_p_default).equals("-1"); if ((gcalCreateEventEnabled || calendarSelector.getSelectedItemPosition() != 0) && calendarUri == null) { StatisticsService.reportEvent(StatisticsConstants.CREATE_CALENDAR_EVENT); - try{ + try { ContentResolver cr = activity.getContentResolver(); ContentValues values = new ContentValues(); @@ -157,7 +156,7 @@ public class GCalControlSet extends PopupControlSet { values.put("calendar_id", calendarId); calendarUri = GCalHelper.createTaskEvent(task, cr, values); - if(calendarUri != null) { + if (calendarUri != null) { task.setValue(Task.CALENDAR_URI, calendarUri.toString()); if (calendarSelector.getSelectedItemPosition() != 0 && !hasEvent) { @@ -173,21 +172,21 @@ public class GCalControlSet extends PopupControlSet { exceptionService.displayAndReportError(activity, activity.getString(R.string.gcal_TEA_error), e); } - } else if(calendarUri != null) { + } else if (calendarUri != null) { try { ContentValues updateValues = new ContentValues(); // check if we need to update the item ContentValues setValues = task.getSetValues(); - if(setValues.containsKey(Task.TITLE.name)) + if (setValues.containsKey(Task.TITLE.name)) updateValues.put("title", task.getValue(Task.TITLE)); - if(setValues.containsKey(Task.NOTES.name)) + if (setValues.containsKey(Task.NOTES.name)) updateValues.put("description", task.getValue(Task.NOTES)); - if(setValues.containsKey(Task.DUE_DATE.name) || setValues.containsKey(Task.ESTIMATED_SECONDS.name)) + if (setValues.containsKey(Task.DUE_DATE.name) || setValues.containsKey(Task.ESTIMATED_SECONDS.name)) GCalHelper.createStartAndEndDate(task, updateValues); ContentResolver cr = activity.getContentResolver(); - if(cr.update(calendarUri, updateValues, null, null) > 0) + if (cr.update(calendarUri, updateValues, null, null) > 0) return activity.getString(R.string.gcal_TEA_calendar_updated); } catch (Exception e) { exceptionService.reportError("unable-to-update-calendar: " + //$NON-NLS-1$ @@ -200,15 +199,15 @@ public class GCalControlSet extends PopupControlSet { @SuppressWarnings("nls") private void viewCalendarEvent() { - if(calendarUri == null) + if (calendarUri == null) return; ContentResolver cr = activity.getContentResolver(); Intent intent = new Intent(Intent.ACTION_EDIT, calendarUri); - Cursor cursor = cr.query(calendarUri, new String[] { "dtstart", "dtend" }, + Cursor cursor = cr.query(calendarUri, new String[]{"dtstart", "dtend"}, null, null, null); try { - if(cursor.getCount() == 0) { + if (cursor.getCount() == 0) { // event no longer exists, recreate it calendarUri = null; writeToModel(model); @@ -237,7 +236,7 @@ public class GCalControlSet extends PopupControlSet { if (hasEvent) { calendar.setText(R.string.gcal_TEA_has_event); } else if (calendarSelector.getSelectedItemPosition() != 0) { - calendar.setText((String)calendarSelector.getSelectedItem()); + calendar.setText((String) calendarSelector.getSelectedItem()); } else { calendar.setTextColor(unsetColor); image.setImageResource(R.drawable.tea_icn_addcal_gray); diff --git a/astrid/plugin-src/com/todoroo/astrid/gcal/GCalHelper.java b/astrid/plugin-src/com/todoroo/astrid/gcal/GCalHelper.java index 4912e44c7..19627caa2 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gcal/GCalHelper.java +++ b/astrid/plugin-src/com/todoroo/astrid/gcal/GCalHelper.java @@ -5,8 +5,6 @@ */ package com.todoroo.astrid.gcal; -import java.util.TimeZone; - import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; @@ -24,8 +22,12 @@ import com.todoroo.andlib.utility.Preferences; import com.todoroo.astrid.core.PluginServices; import com.todoroo.astrid.data.Task; +import java.util.TimeZone; + public class GCalHelper { - /** If task has no estimated time, how early to set a task in calendar (seconds)*/ + /** + * If task has no estimated time, how early to set a task in calendar (seconds) + */ private static final long DEFAULT_CAL_TIME = DateUtilities.ONE_HOUR; public static final String CALENDAR_ID_COLUMN = "calendar_id"; //$NON-NLS-1$ @@ -36,7 +38,7 @@ public class GCalHelper { uri = task.getValue(Task.CALENDAR_URI); else { task = PluginServices.getTaskService().fetchById(task.getId(), Task.CALENDAR_URI); - if(task == null) + if (task == null) return null; uri = task.getValue(Task.CALENDAR_URI); } @@ -52,7 +54,7 @@ public class GCalHelper { private static void createTaskEventIfEnabled(Task t, boolean deleteEventIfExists) { boolean gcalCreateEventEnabled = Preferences.getStringValue(R.string.gcal_p_default) != null - && !Preferences.getStringValue(R.string.gcal_p_default).equals("-1"); //$NON-NLS-1$ + && !Preferences.getStringValue(R.string.gcal_p_default).equals("-1"); //$NON-NLS-1$ if (gcalCreateEventEnabled) { ContentResolver cr = ContextManager.getContext().getContentResolver(); Uri calendarUri = GCalHelper.createTaskEvent(t, cr, new ContentValues(), deleteEventIfExists); @@ -69,11 +71,11 @@ public class GCalHelper { public static Uri createTaskEvent(Task task, ContentResolver cr, ContentValues values, boolean deleteEventIfExists) { String eventuri = getTaskEventUri(task); - if(!TextUtils.isEmpty(eventuri) && deleteEventIfExists) { + if (!TextUtils.isEmpty(eventuri) && deleteEventIfExists) { deleteTaskEvent(task); } - try{ + try { Uri uri = Calendars.getCalendarContentUri(Calendars.CALENDAR_CONTENT_EVENTS); values.put("title", task.getValue(Task.TITLE)); values.put("description", task.getValue(Task.NOTES)); @@ -126,13 +128,13 @@ public class GCalHelper { } private static String getCalendarId(Uri uri, ContentResolver cr) { - Cursor calendar = cr.query(uri, new String[] { CALENDAR_ID_COLUMN }, null, null, null); + Cursor calendar = cr.query(uri, new String[]{CALENDAR_ID_COLUMN}, null, null, null); try { calendar.moveToFirst(); return calendar.getString(0); } catch (CursorIndexOutOfBoundsException e) { return null; - } finally { + } finally { calendar.close(); } } @@ -141,22 +143,22 @@ public class GCalHelper { public static boolean deleteTaskEvent(Task task) { boolean eventDeleted = false; String uri; - if(task.containsNonNullValue(Task.CALENDAR_URI)) + if (task.containsNonNullValue(Task.CALENDAR_URI)) uri = task.getValue(Task.CALENDAR_URI); else { task = PluginServices.getTaskService().fetchById(task.getId(), Task.CALENDAR_URI); - if(task == null) + if (task == null) return false; uri = task.getValue(Task.CALENDAR_URI); } - if(!TextUtils.isEmpty(uri)) { + if (!TextUtils.isEmpty(uri)) { try { Uri calendarUri = Uri.parse(uri); // try to load calendar ContentResolver cr = ContextManager.getContext().getContentResolver(); - Cursor cursor = cr.query(calendarUri, new String[] { "dtstart" }, null, null, null); //$NON-NLS-1$ + Cursor cursor = cr.query(calendarUri, new String[]{"dtstart"}, null, null, null); //$NON-NLS-1$ try { boolean alreadydeleted = cursor.getCount() == 0; @@ -168,7 +170,7 @@ public class GCalHelper { cursor.close(); } - task.setValue(Task.CALENDAR_URI,""); + task.setValue(Task.CALENDAR_URI, ""); } catch (Exception e) { Log.e("astrid-gcal", "error-deleting-calendar-event", e); //$NON-NLS-1$ //$NON-NLS-2$ } @@ -183,15 +185,15 @@ public class GCalHelper { long tzCorrectedDueDate = dueDate + TimeZone.getDefault().getOffset(dueDate); long tzCorrectedDueDateNow = DateUtilities.now() + TimeZone.getDefault().getOffset(DateUtilities.now()); // FIXME: doesnt respect timezones, see story 17443653 - if(task.hasDueDate()) { - if(task.hasDueTime()) { - long estimatedTime = task.getValue(Task.ESTIMATED_SECONDS) * 1000; - if(estimatedTime <= 0) + if (task.hasDueDate()) { + if (task.hasDueTime()) { + long estimatedTime = task.getValue(Task.ESTIMATED_SECONDS) * 1000; + if (estimatedTime <= 0) estimatedTime = DEFAULT_CAL_TIME; if (Preferences.getBoolean(R.string.p_end_at_deadline, true)) { values.put("dtstart", dueDate); values.put("dtend", dueDate + estimatedTime); - }else{ + } else { values.put("dtstart", dueDate - estimatedTime); values.put("dtend", dueDate); } diff --git a/astrid/plugin-src/com/todoroo/astrid/gcal/GCalTaskCompleteListener.java b/astrid/plugin-src/com/todoroo/astrid/gcal/GCalTaskCompleteListener.java index b3337bdf1..2989fe322 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gcal/GCalTaskCompleteListener.java +++ b/astrid/plugin-src/com/todoroo/astrid/gcal/GCalTaskCompleteListener.java @@ -27,15 +27,15 @@ public class GCalTaskCompleteListener extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { ContextManager.setContext(context); long taskId = intent.getLongExtra(AstridApiConstants.EXTRAS_TASK_ID, -1); - if(taskId == -1) + if (taskId == -1) return; Task task = PluginServices.getTaskService().fetchById(taskId, Task.ID, Task.TITLE, Task.CALENDAR_URI); - if(task == null) + if (task == null) return; String calendarUri = task.getValue(Task.CALENDAR_URI); - if(!TextUtils.isEmpty(calendarUri)) { + if (!TextUtils.isEmpty(calendarUri)) { try { // change title of calendar event ContentResolver cr = context.getContentResolver(); diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksBackgroundService.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksBackgroundService.java index 9823ef892..2e8cfcaed 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksBackgroundService.java +++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksBackgroundService.java @@ -15,7 +15,8 @@ import com.todoroo.astrid.sync.SyncV2Provider; public class GtasksBackgroundService extends SyncV2BackgroundService { - @Autowired private GtasksPreferenceService gtasksPreferenceService; + @Autowired + private GtasksPreferenceService gtasksPreferenceService; @Override protected SyncV2Provider getSyncProvider() { @@ -24,7 +25,7 @@ public class GtasksBackgroundService extends SyncV2BackgroundService { @Override protected SyncProviderUtilities getSyncUtilities() { - if(gtasksPreferenceService == null) + if (gtasksPreferenceService == null) DependencyInjectionService.getInstance().inject(this); return gtasksPreferenceService; } diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksCustomFilterCriteriaExposer.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksCustomFilterCriteriaExposer.java index 5247e49cf..06e381dea 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksCustomFilterCriteriaExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksCustomFilterCriteriaExposer.java @@ -31,8 +31,10 @@ import com.todoroo.astrid.data.Task; import com.todoroo.astrid.service.AstridDependencyInjector; public class GtasksCustomFilterCriteriaExposer extends BroadcastReceiver { - @Autowired private GtasksPreferenceService gtasksPreferenceService; - @Autowired private GtasksListService gtasksListService; + @Autowired + private GtasksPreferenceService gtasksPreferenceService; + @Autowired + private GtasksListService gtasksListService; private static final String IDENTIFIER = "gtaskslist"; //$NON-NLS-1$ @@ -47,7 +49,7 @@ public class GtasksCustomFilterCriteriaExposer extends BroadcastReceiver { DependencyInjectionService.getInstance().inject(this); // if we aren't logged in, don't expose sync action - if(!gtasksPreferenceService.isLoggedIn()) + if (!gtasksPreferenceService.isLoggedIn()) return; Resources r = context.getResources(); @@ -81,7 +83,7 @@ public class GtasksCustomFilterCriteriaExposer extends BroadcastReceiver { values, listNames, listIds, - ((BitmapDrawable)r.getDrawable(R.drawable.gtasks_icon)).getBitmap(), + ((BitmapDrawable) r.getDrawable(R.drawable.gtasks_icon)).getBitmap(), context.getString(R.string.CFC_gtasks_list_name)); result[0] = criterion; diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksDetailExposer.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksDetailExposer.java index 22a52d246..60ff0310a 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksDetailExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksDetailExposer.java @@ -22,15 +22,17 @@ import com.todoroo.astrid.service.AstridDependencyInjector; * - list * * @author Tim Su - * */ public class GtasksDetailExposer extends BroadcastReceiver { public static final String DETAIL_SEPARATOR = " | "; //$NON-NLS-1$ - @Autowired private GtasksMetadataService gtasksMetadataService; - @Autowired private GtasksListService gtasksListService; - @Autowired private GtasksPreferenceService gtasksPreferenceService; + @Autowired + private GtasksMetadataService gtasksMetadataService; + @Autowired + private GtasksListService gtasksListService; + @Autowired + private GtasksPreferenceService gtasksPreferenceService; static { AstridDependencyInjector.initialize(); @@ -45,15 +47,15 @@ public class GtasksDetailExposer extends BroadcastReceiver { ContextManager.setContext(context); // if we aren't logged in, don't expose features - if(!gtasksPreferenceService.isLoggedIn()) + if (!gtasksPreferenceService.isLoggedIn()) return; long taskId = intent.getLongExtra(AstridApiConstants.EXTRAS_TASK_ID, -1); - if(taskId == -1) + if (taskId == -1) return; String taskDetail = getTaskDetails(taskId); - if(taskDetail == null) + if (taskDetail == null) return; Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_SEND_DETAILS); @@ -65,16 +67,16 @@ public class GtasksDetailExposer extends BroadcastReceiver { public String getTaskDetails(long id) { Metadata metadata = gtasksMetadataService.getTaskMetadata(id); - if(metadata == null) + if (metadata == null) return null; StringBuilder builder = new StringBuilder(); String listId = metadata.getValue(GtasksMetadata.LIST_ID); - if(listId == null || listId.equals(Preferences.getStringValue(GtasksPreferenceService.PREF_DEFAULT_LIST))) + if (listId == null || listId.equals(Preferences.getStringValue(GtasksPreferenceService.PREF_DEFAULT_LIST))) return null; String listName = gtasksListService.getListName(listId); - if(listName == GtasksListService.LIST_NOT_FOUND) + if (listName == GtasksListService.LIST_NOT_FOUND) return null; builder.append(" ").append(listName); //$NON-NLS-1$ diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksFilterExposer.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksFilterExposer.java index 6b58105c2..568c4a2c4 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksFilterExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksFilterExposer.java @@ -43,13 +43,15 @@ import com.todoroo.astrid.service.AstridDependencyInjector; * Exposes filters based on lists * * @author Tim Su - * */ public class GtasksFilterExposer extends BroadcastReceiver implements AstridFilterExposer { - @Autowired private GtasksListService gtasksListService; - @Autowired private GtasksPreferenceService gtasksPreferenceService; - @Autowired private ActFmPreferenceService actFmPreferenceService; + @Autowired + private GtasksListService gtasksListService; + @Autowired + private GtasksPreferenceService gtasksPreferenceService; + @Autowired + private ActFmPreferenceService actFmPreferenceService; static { AstridDependencyInjector.initialize(); @@ -67,12 +69,12 @@ public class GtasksFilterExposer extends BroadcastReceiver implements AstridFilt FilterWithCustomIntent filter = new FilterWithCustomIntent(listName, ContextManager.getString(R.string.gtasks_FEx_title, listName), new QueryTemplate().join( Join.left(Metadata.TABLE, Task.ID.eq(Metadata.TASK))).where(Criterion.and( - MetadataCriteria.withKey(GtasksMetadata.METADATA_KEY), - TaskCriteria.notDeleted(), - GtasksMetadata.LIST_ID.eq(list.getValue(GtasksList.REMOTE_ID)))).orderBy( - Order.asc(Functions.cast(GtasksMetadata.ORDER, "LONG"))), //$NON-NLS-1$ + MetadataCriteria.withKey(GtasksMetadata.METADATA_KEY), + TaskCriteria.notDeleted(), + GtasksMetadata.LIST_ID.eq(list.getValue(GtasksList.REMOTE_ID)))).orderBy( + Order.asc(Functions.cast(GtasksMetadata.ORDER, "LONG"))), //$NON-NLS-1$ values); - filter.listingIcon = ((BitmapDrawable)context.getResources().getDrawable(R.drawable.gtasks_icon)).getBitmap(); + filter.listingIcon = ((BitmapDrawable) context.getResources().getDrawable(R.drawable.gtasks_icon)).getBitmap(); filter.customTaskList = new ComponentName(ContextManager.getContext(), GtasksListFragment.class); Bundle extras = new Bundle(); extras.putLong(GtasksListFragment.TOKEN_STORE_ID, list.getId()); @@ -95,17 +97,17 @@ public class GtasksFilterExposer extends BroadcastReceiver implements AstridFilt DependencyInjectionService.getInstance().inject(this); // if we aren't logged in (or we are logged in to astrid.com), don't expose features - if(!gtasksPreferenceService.isLoggedIn() || actFmPreferenceService.isLoggedIn()) + if (!gtasksPreferenceService.isLoggedIn() || actFmPreferenceService.isLoggedIn()) return null; lists = gtasksListService.getLists(); // If user does not have any lists, don't show this section at all - if(noListsToShow()) + if (noListsToShow()) return null; Filter[] listFilters = new Filter[lists.length]; - for(int i = 0; i < lists.length; i++) + for (int i = 0; i < lists.length; i++) listFilters[i] = filterFromList(context, lists[i]); FilterCategoryWithNewButton listsCategory = new FilterCategoryWithNewButton(context.getString(R.string.gtasks_FEx_header), diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksList.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksList.java index 56992e71f..6e0d86a56 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksList.java +++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksList.java @@ -14,22 +14,29 @@ import com.todoroo.astrid.data.StoreObject; * {@link StoreObject} entries for a GTasks List * * @author Tim Su - * */ public class GtasksList { - /** type*/ + /** + * type + */ public static final String TYPE = "gtasks-list"; //$NON-NLS-1$ - /** list id in g-tasks */ + /** + * list id in g-tasks + */ public static final StringProperty REMOTE_ID = new StringProperty(StoreObject.TABLE, StoreObject.ITEM.name); - /** list name */ + /** + * list name + */ public static final StringProperty NAME = new StringProperty(StoreObject.TABLE, StoreObject.VALUE1.name); - /** list order */ + /** + * list order + */ public static final IntegerProperty ORDER = new IntegerProperty(StoreObject.TABLE, StoreObject.VALUE2.name); diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksListAdder.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksListAdder.java index 12a9e27c8..2b87821cc 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksListAdder.java +++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksListAdder.java @@ -5,8 +5,6 @@ */ package com.todoroo.astrid.gtasks; -import java.io.IOException; - import android.app.Activity; import android.app.ProgressDialog; import android.content.DialogInterface; @@ -24,10 +22,14 @@ import com.todoroo.astrid.data.StoreObject; import com.todoroo.astrid.gtasks.api.GtasksInvoker; import com.todoroo.astrid.gtasks.auth.GtasksTokenValidator; +import java.io.IOException; + public class GtasksListAdder extends Activity { - @Autowired GtasksPreferenceService gtasksPreferenceService; - @Autowired GtasksListService gtasksListService; + @Autowired + GtasksPreferenceService gtasksPreferenceService; + @Autowired + GtasksListService gtasksListService; @Override protected void onCreate(Bundle savedInstanceState) { @@ -46,7 +48,7 @@ public class GtasksListAdder extends Activity { DialogInterface.OnClickListener onClick = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { - if (gtasksPreferenceService.isLoggedIn() && ! gtasksPreferenceService.isOngoing()) { + if (gtasksPreferenceService.isLoggedIn() && !gtasksPreferenceService.isOngoing()) { final ProgressDialog pd = DialogUtilities.progressDialog(GtasksListAdder.this, GtasksListAdder.this.getString(R.string.gtasks_FEx_creating_list)); pd.show(); diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksListFragment.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksListFragment.java index 62bf9b182..d3e4a085f 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksListFragment.java +++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksListFragment.java @@ -38,25 +38,30 @@ public class GtasksListFragment extends SubtasksListFragment { protected static final int MENU_REFRESH_ID = MENU_SUPPORT_ID + 1; - @Autowired private StoreObjectDao storeObjectDao; + @Autowired + private StoreObjectDao storeObjectDao; - @Autowired private GtasksTaskListUpdater gtasksTaskListUpdater; + @Autowired + private GtasksTaskListUpdater gtasksTaskListUpdater; - @Autowired private GtasksMetadataService gtasksMetadataService; + @Autowired + private GtasksMetadataService gtasksMetadataService; - @Autowired private GtasksPreferenceService gtasksPreferenceService; + @Autowired + private GtasksPreferenceService gtasksPreferenceService; - @Autowired private SyncV2Service syncService; + @Autowired + private SyncV2Service syncService; private StoreObject list; - private static final Property[] LIST_PROPERTIES = new Property[] { - StoreObject.ID, - StoreObject.TYPE, - GtasksList.REMOTE_ID, - GtasksList.ORDER, - GtasksList.NAME, - GtasksList.LAST_SYNC + private static final Property[] LIST_PROPERTIES = new Property[]{ + StoreObject.ID, + StoreObject.TYPE, + GtasksList.REMOTE_ID, + GtasksList.ORDER, + GtasksList.NAME, + GtasksList.LAST_SYNC }; @Override @@ -75,7 +80,7 @@ public class GtasksListFragment extends SubtasksListFragment { long storeObjectId = extras.getLong(TOKEN_STORE_ID, 0); list = storeObjectDao.fetch(storeObjectId, LIST_PROPERTIES); - ((OrderedMetadataListFragmentHelper)helper).setList(list); + ((OrderedMetadataListFragmentHelper) helper).setList(list); } @Override @@ -88,7 +93,7 @@ public class GtasksListFragment extends SubtasksListFragment { } private void refreshData(final boolean manual) { - ((TextView)getView().findViewById(android.R.id.empty)).setText(R.string.DLG_loading); + ((TextView) getView().findViewById(android.R.id.empty)).setText(R.string.DLG_loading); syncService.synchronizeList(list, manual, new ProgressBarSyncResultCallback(getActivity(), this, R.id.progressBar, new Runnable() { @@ -98,7 +103,7 @@ public class GtasksListFragment extends SubtasksListFragment { ContextManager.getContext().sendBroadcast(new Intent(AstridApiConstants.BROADCAST_EVENT_REFRESH)); else refresh(); - ((TextView)getView().findViewById(android.R.id.empty)).setText(R.string.TLA_no_items); + ((TextView) getView().findViewById(android.R.id.empty)).setText(R.string.TLA_no_items); } })); } @@ -116,14 +121,14 @@ public class GtasksListFragment extends SubtasksListFragment { @Override public boolean handleOptionsMenuItemSelected(int id, Intent intent) { - // handle my own menus + // handle my own menus switch (id) { - case MENU_REFRESH_ID: - refreshData(true); - return true; - case MENU_CLEAR_COMPLETED_ID: - clearCompletedTasks(); - return true; + case MENU_REFRESH_ID: + refreshData(true); + return true; + case MENU_CLEAR_COMPLETED_ID: + clearCompletedTasks(); + return true; } return super.handleOptionsMenuItemSelected(id, intent); @@ -178,7 +183,7 @@ public class GtasksListFragment extends SubtasksListFragment { @Override protected void addSyncRefreshMenuItem(Menu menu, int themeFlags) { - if(gtasksPreferenceService.isLoggedIn()) { + if (gtasksPreferenceService.isLoggedIn()) { addMenuItem(menu, R.string.actfm_TVA_menu_refresh, ThemeService.getDrawable(R.drawable.icn_menu_refresh, themeFlags), MENU_REFRESH_ID, true); } else { diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksListService.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksListService.java index 81fb44834..e4cbe3113 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksListService.java +++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksListService.java @@ -5,9 +5,6 @@ */ package com.todoroo.astrid.gtasks; -import java.util.HashSet; -import java.util.List; - import com.google.api.services.tasks.model.TaskList; import com.google.api.services.tasks.model.TaskLists; import com.todoroo.andlib.data.TodorooCursor; @@ -18,6 +15,9 @@ import com.todoroo.astrid.dao.StoreObjectDao; import com.todoroo.astrid.dao.StoreObjectDao.StoreObjectCriteria; import com.todoroo.astrid.data.StoreObject; +import java.util.HashSet; +import java.util.List; + public class GtasksListService { public static final String LIST_NOT_FOUND = null; @@ -33,7 +33,7 @@ public class GtasksListService { } private void readLists() { - if(lists != null) { + if (lists != null) { return; } @@ -41,7 +41,7 @@ public class GtasksListService { where(StoreObjectCriteria.byType(GtasksList.TYPE))); try { lists = new StoreObject[cursor.getCount()]; - for(int i = 0; i < lists.length; i++) { + for (int i = 0; i < lists.length; i++) { cursor.moveToNext(); StoreObject dashboard = new StoreObject(cursor); lists[i] = dashboard; @@ -58,17 +58,18 @@ public class GtasksListService { /** * Get list name + * * @param listId * @return NOT_FOUND if no list by this id exists, otherwise list name */ public String getListName(String listId) { StoreObject list = getList(listId); - if(list != LIST_NOT_FOUND_OBJECT) + if (list != LIST_NOT_FOUND_OBJECT) return list.getValue(GtasksList.NAME); return LIST_NOT_FOUND; } - public void migrateListIds (TaskLists remoteLists) { + public void migrateListIds(TaskLists remoteLists) { readLists(); List items = remoteLists.getItems(); @@ -93,24 +94,24 @@ public class GtasksListService { readLists(); HashSet previousLists = new HashSet(lists.length); - for(StoreObject list : lists) + for (StoreObject list : lists) previousLists.add(list.getId()); List items = remoteLists.getItems(); StoreObject[] newLists = new StoreObject[items.size()]; - for(int i = 0; i < items.size(); i++) { + for (int i = 0; i < items.size(); i++) { com.google.api.services.tasks.model.TaskList remote = items.get(i); String id = remote.getId(); StoreObject local = null; - for(StoreObject list : lists) { - if(list.getValue(GtasksList.REMOTE_ID).equals(id)) { + for (StoreObject list : lists) { + if (list.getValue(GtasksList.REMOTE_ID).equals(id)) { local = list; break; } } - if(local == null) + if (local == null) local = new StoreObject(); local.setValue(StoreObject.TYPE, GtasksList.TYPE); @@ -124,7 +125,7 @@ public class GtasksListService { lists = newLists; // check for lists that aren't on remote server - for(Long listId : previousLists) { + for (Long listId : previousLists) { storeObjectDao.delete(listId); } } @@ -159,8 +160,8 @@ public class GtasksListService { public StoreObject getList(String listId) { readLists(); - for(StoreObject list : lists) - if(list != null && list.getValue(GtasksList.REMOTE_ID).equals(listId)) + for (StoreObject list : lists) + if (list != null && list.getValue(GtasksList.REMOTE_ID).equals(listId)) return list; return LIST_NOT_FOUND_OBJECT; } diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksMetadata.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksMetadata.java index 5c8578597..ffc5cab2d 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksMetadata.java +++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksMetadata.java @@ -15,24 +15,30 @@ import com.todoroo.astrid.data.Metadata; /** * Metadata entries for a GTasks Task - * @author Tim Su * + * @author Tim Su */ public class GtasksMetadata { static final int VALUE_UNSET = -1; - /** metadata key */ + /** + * metadata key + */ public static final String METADATA_KEY = "gtasks"; //$NON-NLS-1$ - /** task id in google */ + /** + * task id in google + */ public static final StringProperty ID = new StringProperty(Metadata.TABLE, Metadata.VALUE1.name); public static final StringProperty LIST_ID = new StringProperty(Metadata.TABLE, Metadata.VALUE2.name); - /** parent task id, or 0 if top level task */ + /** + * parent task id, or 0 if top level task + */ public static final LongProperty PARENT_TASK = new LongProperty(Metadata.TABLE, Metadata.VALUE3.name); @@ -50,6 +56,7 @@ public class GtasksMetadata { /** * Creates default GTasks metadata item + * * @param taskId if > 0, will set metadata task field * @return */ @@ -59,14 +66,14 @@ public class GtasksMetadata { metadata.setValue(ID, ""); //$NON-NLS-1$ String defaultList = Preferences.getStringValue(GtasksPreferenceService.PREF_DEFAULT_LIST); - if(defaultList == null) + if (defaultList == null) defaultList = "@default"; //$NON-NLS-1$ metadata.setValue(LIST_ID, defaultList); metadata.setValue(PARENT_TASK, AbstractModel.NO_ID); metadata.setValue(INDENT, 0); metadata.setValue(ORDER, DateUtilities.now()); - if(taskId > AbstractModel.NO_ID) + if (taskId > AbstractModel.NO_ID) metadata.setValue(Metadata.TASK, taskId); return metadata; } diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksMetadataService.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksMetadataService.java index 9e9d0ca5d..0d308d60e 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksMetadataService.java +++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksMetadataService.java @@ -5,12 +5,6 @@ */ package com.todoroo.astrid.gtasks; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicReference; - import android.text.TextUtils; import com.todoroo.andlib.data.AbstractModel; @@ -33,15 +27,21 @@ import com.todoroo.astrid.subtasks.OrderedMetadataListUpdater.OrderedListIterato import com.todoroo.astrid.sync.SyncProviderUtilities; import com.todoroo.astrid.utility.SyncMetadataService; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; + /** * Service for working with GTasks metadata * * @author Tim Su - * */ public final class GtasksMetadataService extends SyncMetadataService { - @Autowired private GtasksPreferenceService gtasksPreferenceService; + @Autowired + private GtasksPreferenceService gtasksPreferenceService; public GtasksMetadataService() { super(ContextManager.getContext()); @@ -50,7 +50,7 @@ public final class GtasksMetadataService extends SyncMetadataService metadata) { + ArrayList metadata) { return new GtasksTaskContainer(task, metadata); } @@ -81,13 +81,13 @@ public final class GtasksMetadataService extends SyncMetadataService cursor = metadataDao.query(Query.select(Metadata.PROPERTIES). where(Criterion.and(MetadataCriteria.withKey(getMetadataKey()), getLocalMatchCriteria(remoteTask)))); try { - if(cursor.getCount() == 0) + if (cursor.getCount() == 0) return; cursor.moveToFirst(); remoteTask.task.setId(cursor.get(Metadata.TASK)); @@ -116,13 +116,13 @@ public final class GtasksMetadataService extends SyncMetadataService filterLocallyUpdated(TodorooCursor tasks, long lastSyncDate) { HashSet taskIds = new HashSet(); - for(tasks.moveToFirst(); !tasks.isAfterLast(); tasks.moveToNext()) + for (tasks.moveToFirst(); !tasks.isAfterLast(); tasks.moveToNext()) taskIds.add(tasks.get(Task.ID)); TodorooCursor metadata = metadataDao.query(Query.select(Metadata.TASK).where( Criterion.and(MetadataCriteria.withKey(GtasksMetadata.METADATA_KEY), - GtasksMetadata.LAST_SYNC.gt(lastSyncDate)))); - for(metadata.moveToFirst(); !metadata.isAfterLast(); metadata.moveToNext()) + GtasksMetadata.LAST_SYNC.gt(lastSyncDate)))); + for (metadata.moveToFirst(); !metadata.isAfterLast(); metadata.moveToNext()) taskIds.remove(metadata.get(Metadata.TASK)); return taskDao.query(Query.select(Task.ID).where( @@ -141,20 +141,20 @@ public final class GtasksMetadataService extends SyncMetadataService cursor = PluginServices.getMetadataService().query(query); try { - for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { + for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { long taskId = cursor.get(Metadata.TASK); Metadata metadata = getTaskMetadata(taskId); - if(metadata == null) + if (metadata == null) continue; iterator.processTask(taskId, metadata); } @@ -166,6 +166,7 @@ public final class GtasksMetadataService extends SyncMetadataService - * */ public class GtasksPreferences extends SyncProviderPreferences { - @Autowired private GtasksPreferenceService gtasksPreferenceService; - @Autowired private ActFmPreferenceService actFmPreferenceService; - @Autowired private TagService tagService; + @Autowired + private GtasksPreferenceService gtasksPreferenceService; + @Autowired + private ActFmPreferenceService actFmPreferenceService; + @Autowired + private TagService tagService; public GtasksPreferences() { super(); @@ -88,7 +90,8 @@ public class GtasksPreferences extends SyncProviderPreferences { final ProgressDialog pd = DialogUtilities.progressDialog(this, getString(R.string.gtasks_import_progress)); pd.setCancelable(false); - GtasksImportCallback callback = new GtasksImportCallback(new SyncResultCallbackAdapter() {/**/}) { + GtasksImportCallback callback = new GtasksImportCallback(new SyncResultCallbackAdapter() {/**/ + }) { @Override public void finished() { super.finished(); diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksSyncActionExposer.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksSyncActionExposer.java index 5635196be..ea343acf4 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksSyncActionExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksSyncActionExposer.java @@ -20,11 +20,11 @@ import com.todoroo.astrid.service.AstridDependencyInjector; /** * Exposes sync action - * */ public class GtasksSyncActionExposer extends BroadcastReceiver { - @Autowired private GtasksPreferenceService gtasksPreferenceService; + @Autowired + private GtasksPreferenceService gtasksPreferenceService; static { AstridDependencyInjector.initialize(); @@ -36,7 +36,7 @@ public class GtasksSyncActionExposer extends BroadcastReceiver { DependencyInjectionService.getInstance().inject(this); // if we aren't logged in, don't expose sync action - if(!gtasksPreferenceService.isLoggedIn()) + if (!gtasksPreferenceService.isLoggedIn()) return; Intent syncIntent = new Intent(null, null, diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksTaskListUpdater.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksTaskListUpdater.java index 255e3d51d..6b1d616e6 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksTaskListUpdater.java +++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksTaskListUpdater.java @@ -5,11 +5,6 @@ */ package com.todoroo.astrid.gtasks; -import java.util.HashMap; -import java.util.HashSet; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; - import android.text.TextUtils; import android.util.Log; @@ -29,23 +24,35 @@ import com.todoroo.astrid.data.StoreObject; import com.todoroo.astrid.data.Task; import com.todoroo.astrid.gtasks.sync.GtasksSyncService; import com.todoroo.astrid.subtasks.OrderedMetadataListUpdater; -import com.todoroo.astrid.subtasks.OrderedMetadataListUpdater.OrderedListIterator; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; public class GtasksTaskListUpdater extends OrderedMetadataListUpdater { - /** map of task -> parent task */ + /** + * map of task -> parent task + */ final HashMap parents = new HashMap(); - /** map of task -> prior sibling */ + /** + * map of task -> prior sibling + */ final HashMap siblings = new HashMap(); final HashMap localToRemoteIdMap = - new HashMap(); + new HashMap(); - @Autowired private GtasksListService gtasksListService; - @Autowired private GtasksMetadataService gtasksMetadataService; - @Autowired private GtasksSyncService gtasksSyncService; - @Autowired private MetadataDao metadataDao; + @Autowired + private GtasksListService gtasksListService; + @Autowired + private GtasksMetadataService gtasksMetadataService; + @Autowired + private GtasksSyncService gtasksSyncService; + @Autowired + private MetadataDao metadataDao; public GtasksTaskListUpdater() { super(); @@ -72,6 +79,7 @@ public class GtasksTaskListUpdater extends OrderedMetadataListUpdater previousIndent.get() + 1) + if (indent > previousIndent.get() + 1) indent = previousIndent.get() + 1; metadata.setValue(GtasksMetadata.INDENT, indent); Long parent = parents.get(taskId); - if(parent == null || parent < 0) + if (parent == null || parent < 0) parent = Task.NO_ID; metadata.setValue(GtasksMetadata.PARENT_TASK, parent); @@ -145,7 +154,7 @@ public class GtasksTaskListUpdater extends OrderedMetadataListUpdater alreadyChecked) { + HashSet alreadyChecked) { TodorooCursor metadata = metadataDao.query(Query.select(Metadata.PROPERTIES) .where(Criterion.and(Metadata.KEY.eq(GtasksMetadata.METADATA_KEY), GtasksMetadata.LIST_ID.eq(listId), GtasksMetadata.PARENT_TASK.eq(parent))) @@ -155,7 +164,7 @@ public class GtasksTaskListUpdater extends OrderedMetadataListUpdater previousIndent.get()) { + if (indent > previousIndent.get()) { parent = previousTask.get(); sibling = Task.NO_ID; - } else if(indent == previousIndent.get()) { + } else if (indent == previousIndent.get()) { sibling = previousTask.get(); parent = parents.get(sibling); } else { // move up once for each indent sibling = previousTask.get(); - for(int i = indent; i < previousIndent.get(); i++) + for (int i = indent; i < previousIndent.get(); i++) sibling = parents.get(sibling); - if(parents.containsKey(sibling)) + if (parents.containsKey(sibling)) parent = parents.get(sibling); else parent = Task.NO_ID; @@ -206,7 +215,7 @@ public class GtasksTaskListUpdater extends OrderedMetadataListUpdater future = accountManager.manager.getAuthToken(a, GtasksInvoker.AUTH_TOKEN_TYPE, false, null, null); token = getTokenFromFuture(c, future); - if(TOKEN_INTENT_RECEIVED.equals(token)) + if (TOKEN_INTENT_RECEIVED.equals(token)) return null; - else if(token != null && testToken(token)) + else if (token != null && testToken(token)) return token; } @@ -80,7 +82,7 @@ public class GtasksTokenValidator { Bundle result; try { result = future.getResult(); - if(result == null) + if (result == null) throw new NullPointerException("Future result was null."); //$NON-NLS-1$ } catch (Exception e) { throw new GoogleTasksException(e.getLocalizedMessage(), "future-error"); diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/auth/ModernAuthManager.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/auth/ModernAuthManager.java index 34567788b..108cbb1d5 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gtasks/auth/ModernAuthManager.java +++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/auth/ModernAuthManager.java @@ -15,9 +15,6 @@ */ package com.todoroo.astrid.gtasks.auth; -import java.io.IOException; -import java.util.ArrayList; - import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AccountManagerCallback; @@ -31,6 +28,9 @@ import android.util.Log; import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager; +import java.io.IOException; +import java.util.ArrayList; + /** * AuthManager keeps track of the current auth token for a user. The advantage * over just passing around a String is that this class can renew the auth @@ -38,178 +38,184 @@ import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountMa * AuthManager. */ public class ModernAuthManager implements AuthManager { - protected static final int GET_LOGIN_REQUEST = 1; - -/** The activity that will handle auth result callbacks. */ - private final Activity activity; - - /** The name of the service to authorize for. */ - private final String service; - - /** The most recently fetched auth token or null if none is available. */ - private String authToken; - - private final AccountManager accountManager; - - private Runnable whenFinished; - - /** - * AuthManager requires many of the same parameters as - * {@link com.google.android.googlelogindist.GoogleLoginServiceHelper - * #getCredentials(Activity, int, Bundle, boolean, String, boolean)}. - * The activity must have a handler in {@link Activity#onActivityResult} that - * calls {@link #authResult(int, Intent)} if the request code is the code - * given here. - * - * @param activity An activity with a handler in - * {@link Activity#onActivityResult} that calls - * {@link #authResult(int, Intent)} when {@literal code} is the request - * code - * @param code The request code to pass to - * {@link Activity#onActivityResult} when - * {@link #authResult(int, Intent)} should be called - * @param extras A {@link Bundle} of extras for - * {@link com.google.android.googlelogindist.GoogleLoginServiceHelper} - * @param requireGoogle True if the account must be a Google account - * @param service The name of the service to authenticate as - */ - public ModernAuthManager(Activity activity, int code, Bundle extras, - boolean requireGoogle, String service) { - this.activity = activity; - this.service = service; - this.accountManager = AccountManager.get(activity); - } - - /** - * Call this to do the initial login. The user will be asked to login if - * they haven't already. The {@link Runnable} provided will be executed - * when the auth token is successfully fetched. - * - * @param runnable A {@link Runnable} to execute when the auth token - * has been successfully fetched and is available via - * {@link #getAuthToken()} - */ - @SuppressWarnings("nls") - public void doLogin(final Runnable runnable, Object o) { - this.whenFinished = runnable; - if (!(o instanceof Account)) { - throw new IllegalArgumentException("FroyoAuthManager requires an account."); + protected static final int GET_LOGIN_REQUEST = 1; + + /** + * The activity that will handle auth result callbacks. + */ + private final Activity activity; + + /** + * The name of the service to authorize for. + */ + private final String service; + + /** + * The most recently fetched auth token or null if none is available. + */ + private String authToken; + + private final AccountManager accountManager; + + private Runnable whenFinished; + + /** + * AuthManager requires many of the same parameters as + * {@link com.google.android.googlelogindist.GoogleLoginServiceHelper + * #getCredentials(Activity, int, Bundle, boolean, String, boolean)}. + * The activity must have a handler in {@link Activity#onActivityResult} that + * calls {@link #authResult(int, Intent)} if the request code is the code + * given here. + * + * @param activity An activity with a handler in + * {@link Activity#onActivityResult} that calls + * {@link #authResult(int, Intent)} when {@literal code} is the request + * code + * @param code The request code to pass to + * {@link Activity#onActivityResult} when + * {@link #authResult(int, Intent)} should be called + * @param extras A {@link Bundle} of extras for + * {@link com.google.android.googlelogindist.GoogleLoginServiceHelper} + * @param requireGoogle True if the account must be a Google account + * @param service The name of the service to authenticate as + */ + public ModernAuthManager(Activity activity, int code, Bundle extras, + boolean requireGoogle, String service) { + this.activity = activity; + this.service = service; + this.accountManager = AccountManager.get(activity); + } + + /** + * Call this to do the initial login. The user will be asked to login if + * they haven't already. The {@link Runnable} provided will be executed + * when the auth token is successfully fetched. + * + * @param runnable A {@link Runnable} to execute when the auth token + * has been successfully fetched and is available via + * {@link #getAuthToken()} + */ + @SuppressWarnings("nls") + public void doLogin(final Runnable runnable, Object o) { + this.whenFinished = runnable; + if (!(o instanceof Account)) { + throw new IllegalArgumentException("FroyoAuthManager requires an account."); + } + Account account = (Account) o; + accountManager.getAuthToken(account, service, true, + new AccountManagerCallback() { + public void run(AccountManagerFuture future) { + try { + Bundle result = future.getResult(); + + // AccountManager needs user to grant permission + if (result.containsKey(AccountManager.KEY_INTENT)) { + Intent intent = (Intent) result.get(AccountManager.KEY_INTENT); + clearNewTaskFlag(intent); + activity.startActivityForResult(intent, GET_LOGIN_REQUEST); + return; + } + + authToken = result.getString( + AccountManager.KEY_AUTHTOKEN); + Log.e("gtasks-auth", "Got auth token."); + runWhenFinished(); + } catch (OperationCanceledException e) { + Log.e("gtasks-auth", "Operation Canceled", e); + } catch (IOException e) { + Log.e("gtasks-auth", "IOException", e); + } catch (AuthenticatorException e) { + Log.e("gtasks-auth", "Authentication Failed", e); + } + } + }, null /* handler */); + } + + private static void clearNewTaskFlag(Intent intent) { + int flags = intent.getFlags(); + flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK; + intent.setFlags(flags); } - Account account = (Account) o; - accountManager.getAuthToken(account, service, true, - new AccountManagerCallback() { - public void run(AccountManagerFuture future) { - try { - Bundle result = future.getResult(); - - // AccountManager needs user to grant permission - if (result.containsKey(AccountManager.KEY_INTENT)) { - Intent intent = (Intent) result.get(AccountManager.KEY_INTENT); - clearNewTaskFlag(intent); - activity.startActivityForResult(intent, GET_LOGIN_REQUEST); - return; - } - authToken = result.getString( - AccountManager.KEY_AUTHTOKEN); - Log.e("gtasks-auth", "Got auth token."); - runWhenFinished(); - } catch (OperationCanceledException e) { - Log.e("gtasks-auth", "Operation Canceled", e); - } catch (IOException e) { - Log.e("gtasks-auth", "IOException", e); - } catch (AuthenticatorException e) { - Log.e("gtasks-auth", "Authentication Failed", e); - } + /** + * The {@link Activity} passed into the constructor should call this + * function when it gets {@link Activity#onActivityResult} with the request + * code passed into the constructor. The resultCode and results should + * come directly from the {@link Activity#onActivityResult} function. This + * function will return true if an auth token was successfully fetched or + * the process is not finished. + * + * @param resultCode The result code passed in to the {@link Activity}'s + * {@link Activity#onActivityResult} function + * @param results The data passed in to the {@link Activity}'s + * {@link Activity#onActivityResult} function + * @return True if the auth token was fetched or we aren't done fetching + * the auth token, or False if there was an error or the request was + * canceled + */ + @SuppressWarnings("nls") + public boolean authResult(int resultCode, Intent results) { + if (results != null) { + authToken = results.getStringExtra( + AccountManager.KEY_AUTHTOKEN); + Log.w("google-auth", "authResult: " + authToken); + } else { + Log.e("google-auth", "No auth result results!!"); } - }, null /* handler */); - } - - private static void clearNewTaskFlag(Intent intent) { - int flags = intent.getFlags(); - flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK; - intent.setFlags(flags); - } - - /** - * The {@link Activity} passed into the constructor should call this - * function when it gets {@link Activity#onActivityResult} with the request - * code passed into the constructor. The resultCode and results should - * come directly from the {@link Activity#onActivityResult} function. This - * function will return true if an auth token was successfully fetched or - * the process is not finished. - * - * @param resultCode The result code passed in to the {@link Activity}'s - * {@link Activity#onActivityResult} function - * @param results The data passed in to the {@link Activity}'s - * {@link Activity#onActivityResult} function - * @return True if the auth token was fetched or we aren't done fetching - * the auth token, or False if there was an error or the request was - * canceled - */ - @SuppressWarnings("nls") - public boolean authResult(int resultCode, Intent results) { - if (results != null) { - authToken = results.getStringExtra( - AccountManager.KEY_AUTHTOKEN); - Log.w("google-auth", "authResult: " + authToken); - } else { - Log.e("google-auth", "No auth result results!!"); + runWhenFinished(); + return authToken != null; + } + + /** + * Returns the current auth token. Response may be null if no valid auth + * token has been fetched. + * + * @return The current auth token or null if no auth token has been + * fetched + */ + public String getAuthToken() { + return authToken; } - runWhenFinished(); - return authToken != null; - } - - /** - * Returns the current auth token. Response may be null if no valid auth - * token has been fetched. - * - * @return The current auth token or null if no auth token has been - * fetched - */ - public String getAuthToken() { - return authToken; - } - - /** - * Invalidates the existing auth token and request a new one. The - * {@link Runnable} provided will be executed when the new auth token is - * successfully fetched. - * - * @param runnable A {@link Runnable} to execute when a new auth token - * is successfully fetched - */ - public void invalidateAndRefresh(final Runnable runnable) { - this.whenFinished = runnable; - - activity.runOnUiThread(new Runnable() { - public void run() { - accountManager.invalidateAuthToken("com.google", authToken); //$NON-NLS-1$ - new AccountChooser().chooseAccount(activity, - new AccountChooser.AccountHandler() { - @Override - public void handleAccountSelected(Account account) { - if (account != null) { - doLogin(whenFinished, account); - } else { - runWhenFinished(); + + /** + * Invalidates the existing auth token and request a new one. The + * {@link Runnable} provided will be executed when the new auth token is + * successfully fetched. + * + * @param runnable A {@link Runnable} to execute when a new auth token + * is successfully fetched + */ + public void invalidateAndRefresh(final Runnable runnable) { + this.whenFinished = runnable; + + activity.runOnUiThread(new Runnable() { + public void run() { + accountManager.invalidateAuthToken("com.google", authToken); //$NON-NLS-1$ + new AccountChooser().chooseAccount(activity, + new AccountChooser.AccountHandler() { + @Override + public void handleAccountSelected(Account account) { + if (account != null) { + doLogin(whenFinished, account); + } else { + runWhenFinished(); + } + } + }); + } + }); + } + + private void runWhenFinished() { + if (whenFinished != null) { + (new Thread() { + @Override + public void run() { + whenFinished.run(); } - } - }); - } - }); - } - - private void runWhenFinished() { - if (whenFinished != null) { - (new Thread() { - @Override - public void run() { - whenFinished.run(); + }).start(); } - }).start(); } - } public static String[] getAccounts(Activity activity) { try { @@ -221,7 +227,7 @@ public class ModernAuthManager implements AuthManager { } return accountNames.toArray(new String[accountNames.size()]); } catch (Exception e) { - return new String[] {}; // Empty array on failure + return new String[]{}; // Empty array on failure } } } diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/sync/GtasksLegacyMigrator.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/sync/GtasksLegacyMigrator.java index 9df1ee477..9d24c0df5 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gtasks/sync/GtasksLegacyMigrator.java +++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/sync/GtasksLegacyMigrator.java @@ -5,10 +5,6 @@ */ package com.todoroo.astrid.gtasks.sync; -import java.io.IOException; -import java.util.HashMap; -import java.util.List; - import com.google.api.services.tasks.model.TaskList; import com.google.api.services.tasks.model.TaskLists; import com.google.api.services.tasks.model.Tasks; @@ -28,19 +24,28 @@ import com.todoroo.astrid.service.AstridDependencyInjector; import com.todoroo.astrid.service.MetadataService; import com.todoroo.astrid.service.TaskService; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; + /** * Class to handle migration of legacy metadata (old remote ids) to new * metadata based on the official remote ids returned by the api. - * @author Sam Bosley * + * @author Sam Bosley */ public class GtasksLegacyMigrator { - @Autowired GtasksMetadataService gtasksMetadataService; - @Autowired TaskService taskService; - @Autowired MetadataService metadataService; - @Autowired GtasksListService gtasksListService; - @Autowired GtasksPreferenceService gtasksPreferenceService; + @Autowired + GtasksMetadataService gtasksMetadataService; + @Autowired + TaskService taskService; + @Autowired + MetadataService metadataService; + @Autowired + GtasksListService gtasksListService; + @Autowired + GtasksPreferenceService gtasksPreferenceService; private final GtasksInvoker gtasksService; private final GtasksListService listService; @@ -50,7 +55,7 @@ public class GtasksLegacyMigrator { AstridDependencyInjector.initialize(); } - public GtasksLegacyMigrator(GtasksInvoker service,GtasksListService listService, TaskLists allLists) { + public GtasksLegacyMigrator(GtasksInvoker service, GtasksListService listService, TaskLists allLists) { DependencyInjectionService.getInstance().inject(this); this.gtasksService = service; this.listService = listService; @@ -67,7 +72,7 @@ public class GtasksLegacyMigrator { TodorooCursor allTasksWithGtaskData = taskService.query(Query.select(Task.PROPERTIES). where(Task.ID.in( Query.select(Metadata.TASK).from(Metadata.TABLE). - where(Metadata.KEY.eq(GtasksMetadata.METADATA_KEY))))); + where(Metadata.KEY.eq(GtasksMetadata.METADATA_KEY))))); try { if (allTasksWithGtaskData.getCount() > 0) { diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/sync/GtasksSyncService.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/sync/GtasksSyncService.java index 09ec72718..4c337f1a8 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gtasks/sync/GtasksSyncService.java +++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/sync/GtasksSyncService.java @@ -5,10 +5,6 @@ */ package com.todoroo.astrid.gtasks.sync; -import java.io.IOException; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.Semaphore; - import android.content.ContentValues; import android.text.TextUtils; import android.util.Log; @@ -36,15 +32,25 @@ import com.todoroo.astrid.gtasks.api.MoveRequest; import com.todoroo.astrid.service.MetadataService; import com.todoroo.astrid.service.TaskService; +import java.io.IOException; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.Semaphore; + public final class GtasksSyncService { private static final String DEFAULT_LIST = "@default"; //$NON-NLS-1$ - @Autowired MetadataService metadataService; - @Autowired MetadataDao metadataDao; - @Autowired GtasksMetadataService gtasksMetadataService; - @Autowired TaskDao taskDao; - @Autowired GtasksPreferenceService gtasksPreferenceService; - @Autowired ActFmPreferenceService actFmPreferenceService; + @Autowired + MetadataService metadataService; + @Autowired + MetadataDao metadataDao; + @Autowired + GtasksMetadataService gtasksMetadataService; + @Autowired + TaskDao taskDao; + @Autowired + GtasksPreferenceService gtasksPreferenceService; + @Autowired + ActFmPreferenceService actFmPreferenceService; public GtasksSyncService() { DependencyInjectionService.getInstance().inject(this); @@ -66,7 +72,7 @@ public final class GtasksSyncService { @Override public void op(GtasksInvoker invoker) throws IOException { - if(DateUtilities.now() - creationDate < 1000) + if (DateUtilities.now() - creationDate < 1000) AndroidUtilities.sleepDeep(1000 - (DateUtilities.now() - creationDate)); pushTaskOnSave(model, model.getMergedValues(), invoker, false); } @@ -104,14 +110,14 @@ public final class GtasksSyncService { taskDao.addListener(new ModelUpdateListener() { public void onModelUpdated(final Task model, boolean outstandingEntries) { - if(model.checkAndClearTransitory(SyncFlags.GTASKS_SUPPRESS_SYNC)) + if (model.checkAndClearTransitory(SyncFlags.GTASKS_SUPPRESS_SYNC)) return; if (actFmPreferenceService.isLoggedIn()) return; if (gtasksPreferenceService.isOngoing() && !model.checkTransitory(TaskService.TRANS_REPEAT_COMPLETE)) //Don't try and sync changes that occur during a normal sync return; final ContentValues setValues = model.getSetValues(); - if(setValues == null || !checkForToken()) + if (setValues == null || !checkForToken()) return; if (!checkValuesForProperties(setValues, TASK_PROPERTIES)) //None of the properties we sync were updated return; @@ -159,11 +165,12 @@ public final class GtasksSyncService { } } - private static final Property[] TASK_PROPERTIES = { Task.ID, Task.TITLE, - Task.NOTES, Task.DUE_DATE, Task.COMPLETION_DATE, Task.DELETION_DATE, Task.USER_ID }; + private static final Property[] TASK_PROPERTIES = {Task.ID, Task.TITLE, + Task.NOTES, Task.DUE_DATE, Task.COMPLETION_DATE, Task.DELETION_DATE, Task.USER_ID}; /** * Checks to see if any of the values changed are among the properties we sync + * * @param values * @param properties * @return false if none of the properties we sync were changed, true otherwise diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/sync/GtasksSyncV2Provider.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/sync/GtasksSyncV2Provider.java index 9cd74558b..b55924e97 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gtasks/sync/GtasksSyncV2Provider.java +++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/sync/GtasksSyncV2Provider.java @@ -5,15 +5,6 @@ */ package com.todoroo.astrid.gtasks.sync; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; - -import org.json.JSONException; - import android.app.Activity; import android.text.TextUtils; @@ -62,21 +53,43 @@ import com.todoroo.astrid.sync.SyncResultCallback; import com.todoroo.astrid.sync.SyncV2Provider; import com.todoroo.astrid.tags.TagService; +import org.json.JSONException; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + public class GtasksSyncV2Provider extends SyncV2Provider { - @Autowired TaskService taskService; - @Autowired MetadataService metadataService; - @Autowired MetadataDao metadataDao; - @Autowired StoreObjectDao storeObjectDao; - @Autowired ActFmPreferenceService actFmPreferenceService; - @Autowired GtasksPreferenceService gtasksPreferenceService; - @Autowired GtasksSyncService gtasksSyncService; - @Autowired GtasksListService gtasksListService; - @Autowired GtasksMetadataService gtasksMetadataService; - @Autowired GtasksTaskListUpdater gtasksTaskListUpdater; - @Autowired TagService tagService; - @Autowired TagDataDao tagDataDao; - @Autowired TagMetadataDao tagMetadataDao; + @Autowired + TaskService taskService; + @Autowired + MetadataService metadataService; + @Autowired + MetadataDao metadataDao; + @Autowired + StoreObjectDao storeObjectDao; + @Autowired + ActFmPreferenceService actFmPreferenceService; + @Autowired + GtasksPreferenceService gtasksPreferenceService; + @Autowired + GtasksSyncService gtasksSyncService; + @Autowired + GtasksListService gtasksListService; + @Autowired + GtasksMetadataService gtasksMetadataService; + @Autowired + GtasksTaskListUpdater gtasksTaskListUpdater; + @Autowired + TagService tagService; + @Autowired + TagDataDao tagDataDao; + @Autowired + TagMetadataDao tagMetadataDao; static { AstridDependencyInjector.initialize(); @@ -89,7 +102,7 @@ public class GtasksSyncV2Provider extends SyncV2Provider { } public synchronized static GtasksSyncV2Provider getInstance() { - if(instance == null) + if (instance == null) instance = new GtasksSyncV2Provider(); return instance; } @@ -197,9 +210,9 @@ public class GtasksSyncV2Provider extends SyncV2Provider { private synchronized void pushUpdated(GtasksInvoker invoker, SyncResultCallback callback) { TodorooCursor queued = taskService.query(Query.select(Task.PROPERTIES). join(Join.left(Metadata.TABLE, Criterion.and(MetadataCriteria.withKey(GtasksMetadata.METADATA_KEY), Task.ID.eq(Metadata.TASK)))).where( - Criterion.or(Task.MODIFICATION_DATE.gt(GtasksMetadata.LAST_SYNC), - Criterion.and(Task.USER_ID.neq(Task.USER_ID_SELF), GtasksMetadata.ID.isNotNull()), - Metadata.KEY.isNull()))); + Criterion.or(Task.MODIFICATION_DATE.gt(GtasksMetadata.LAST_SYNC), + Criterion.and(Task.USER_ID.neq(Task.USER_ID_SELF), GtasksMetadata.ID.isNotNull()), + Metadata.KEY.isNull()))); callback.incrementMax(queued.getCount() * 10); try { Task task = new Task(); @@ -266,7 +279,7 @@ public class GtasksSyncV2Provider extends SyncV2Provider { private synchronized void synchronizeListHelper(StoreObject list, GtasksInvoker invoker, - boolean manual, SyncExceptionHandler errorHandler, SyncResultCallback callback, boolean isImport) { + boolean manual, SyncExceptionHandler errorHandler, SyncResultCallback callback, boolean isImport) { String listId = list.getValue(GtasksList.REMOTE_ID); long lastSyncDate; if (!manual && list.containsNonNullValue(GtasksList.LAST_SYNC)) { @@ -298,7 +311,7 @@ public class GtasksSyncV2Provider extends SyncV2Provider { list.setValue(GtasksList.LAST_SYNC, DateUtilities.now()); storeObjectDao.persist(list); - if(lastSyncDate == 0 && !isImport) { + if (lastSyncDate == 0 && !isImport) { Long[] localIdArray = localIds.toArray(new Long[localIds.size()]); Criterion delete = Criterion.and(Metadata.KEY.eq(GtasksMetadata.METADATA_KEY), GtasksMetadata.LIST_ID.eq(listId), @@ -320,8 +333,11 @@ public class GtasksSyncV2Provider extends SyncV2Provider { } } - /** Create a task container for the given remote task - * @throws JSONException */ + /** + * Create a task container for the given remote task + * + * @throws JSONException + */ private GtasksTaskContainer parseRemoteTask(com.google.api.services.tasks.model.Task remoteTask, String listId) { Task task = new Task(); @@ -356,14 +372,14 @@ public class GtasksSyncV2Provider extends SyncV2Provider { if (!task.task.isSaved() && actFmPreferenceService.isLoggedIn()) titleMatchWithActFm(task.task); - if(task.task.isSaved()) { + if (task.task.isSaved()) { Task local = PluginServices.getTaskService().fetchById(task.task.getId(), Task.DUE_DATE, Task.COMPLETION_DATE); if (local == null) { task.task.clearValue(Task.ID); task.task.clearValue(Task.UUID); } else { mergeDates(task.task, local); - if(task.task.isCompleted() && !local.isCompleted()) + if (task.task.isCompleted() && !local.isCompleted()) StatisticsService.reportEvent(StatisticsConstants.GTASKS_TASK_COMPLETED); } } else { // Set default importance and reminders for remotely created tasks @@ -394,7 +410,7 @@ public class GtasksSyncV2Provider extends SyncV2Provider { } private void mergeDates(Task remote, Task local) { - if(remote.hasDueDate() && local.hasDueTime()) { + if (remote.hasDueDate() && local.hasDueTime()) { Date newDate = new Date(remote.getValue(Task.DUE_DATE)); Date oldDate = new Date(local.getValue(Task.DUE_DATE)); newDate.setHours(oldDate.getHours()); diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/sync/GtasksTaskContainer.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/sync/GtasksTaskContainer.java index 8e6731aae..8a1bfcfd0 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gtasks/sync/GtasksTaskContainer.java +++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/sync/GtasksTaskContainer.java @@ -5,19 +5,18 @@ */ package com.todoroo.astrid.gtasks.sync; -import java.util.ArrayList; -import java.util.Iterator; - import com.todoroo.astrid.data.Metadata; import com.todoroo.astrid.data.Task; import com.todoroo.astrid.gtasks.GtasksMetadata; import com.todoroo.astrid.sync.SyncContainer; +import java.util.ArrayList; +import java.util.Iterator; + /** * RTM Task Container * * @author Tim Su - * */ public class GtasksTaskContainer extends SyncContainer { @@ -31,7 +30,7 @@ public class GtasksTaskContainer extends SyncContainer { this.task = task; this.metadata = metadata; this.gtaskMetadata = gtaskMetadata; - if(this.gtaskMetadata == null) { + if (this.gtaskMetadata == null) { this.gtaskMetadata = GtasksMetadata.createEmptyMetadata(task.getId()); } } @@ -40,15 +39,15 @@ public class GtasksTaskContainer extends SyncContainer { this.task = task; this.metadata = metadata; - for(Iterator iterator = metadata.iterator(); iterator.hasNext(); ) { + for (Iterator iterator = metadata.iterator(); iterator.hasNext(); ) { Metadata item = iterator.next(); - if(GtasksMetadata.METADATA_KEY.equals(item.getValue(Metadata.KEY))) { + if (GtasksMetadata.METADATA_KEY.equals(item.getValue(Metadata.KEY))) { gtaskMetadata = item; iterator.remove(); // don't break, could be multiple } } - if(this.gtaskMetadata == null) { + if (this.gtaskMetadata == null) { this.gtaskMetadata = GtasksMetadata.createEmptyMetadata(task.getId()); } } diff --git a/astrid/plugin-src/com/todoroo/astrid/locale/LocaleEditAlerts.java b/astrid/plugin-src/com/todoroo/astrid/locale/LocaleEditAlerts.java index 29b2129b6..d1fd26b6e 100644 --- a/astrid/plugin-src/com/todoroo/astrid/locale/LocaleEditAlerts.java +++ b/astrid/plugin-src/com/todoroo/astrid/locale/LocaleEditAlerts.java @@ -35,25 +35,32 @@ import com.twofortyfouram.SharedResources; * Activity to edit alerts from Locale * * @author Tim Su - * */ public final class LocaleEditAlerts extends ListActivity { // --- locale constants - /** key name for filter title in bundle */ + /** + * key name for filter title in bundle + */ @SuppressWarnings("nls") public static final String KEY_FILTER_TITLE = "title"; - /** key name for filter SQL in bundle */ + /** + * key name for filter SQL in bundle + */ @SuppressWarnings("nls") public static final String KEY_SQL = "sql"; - /** key name for filter content-values in bundle */ + /** + * key name for filter content-values in bundle + */ @SuppressWarnings("nls") public static final String KEY_VALUES = "val"; - /** key name for interval (integer, # of seconds) */ + /** + * key name for interval (integer, # of seconds) + */ @SuppressWarnings("nls") public static final String KEY_INTERVAL = "interval"; @@ -72,8 +79,8 @@ public final class LocaleEditAlerts extends ListActivity { /** * Intervals in seconds */ - public static final int[] INTERVALS = new int[] { - 3600, 6 * 3600, 12 * 3600, 24 * 3600, 3 * 24 * 3600, 7 * 24 * 3600 + public static final int[] INTERVALS = new int[]{ + 3600, 6 * 3600, 12 * 3600, 24 * 3600, 3 * 24 * 3600, 7 * 24 * 3600 }; /** @@ -94,13 +101,15 @@ public final class LocaleEditAlerts extends ListActivity { /** * Flag boolean that can only be set to true via the "Don't Save" menu item in {@link #onMenuItemSelected(int, MenuItem)}. If * true, then this {@code Activity} should return {@link Activity#RESULT_CANCELED} in {@link #finish()}. - *

    + *

    * There is no need to save/restore this field's state when the {@code Activity} is paused. */ private boolean isCancelled = false; private boolean isRemoved = false; - /** Called when the activity is first created. */ + /** + * Called when the activity is first created. + */ @Override public void onCreate(Bundle savedInstanceState) { setTheme(R.style.Theme); @@ -135,18 +144,16 @@ public final class LocaleEditAlerts extends ListActivity { * if savedInstanceState == null, then we are entering the Activity directly from Locale and we need to check whether the * Intent has forwarded a Bundle extra (e.g. whether we editing an old setting or creating a new one) */ - if (savedInstanceState == null) - { + if (savedInstanceState == null) { final Bundle forwardedBundle = getIntent().getBundleExtra(com.twofortyfouram.Intent.EXTRA_BUNDLE); /* * the forwardedBundle would be null if this was a new setting */ - if (forwardedBundle != null) - { + if (forwardedBundle != null) { final int intervalValue = forwardedBundle.getInt(KEY_INTERVAL, INTERVALS[interval.getSelectedItemPosition()]); - for(int i = 0; i < INTERVALS.length; i++) { - if(intervalValue == INTERVALS[i]) { + for (int i = 0; i < INTERVALS.length; i++) { + if (intervalValue == INTERVALS[i]) { interval.setSelection(i); break; } @@ -164,17 +171,17 @@ public final class LocaleEditAlerts extends ListActivity { adapter = new FilterAdapter(this, getListView(), R.layout.filter_adapter_row, true) { @Override public void onReceiveFilter(FilterListItem item) { - if(adapter.getSelection() != null || finalSelection == null) + if (adapter.getSelection() != null || finalSelection == null) return; - if(item instanceof Filter) { - if(finalSelection.equals(((Filter)item).getSqlQuery())) + if (item instanceof Filter) { + if (finalSelection.equals(((Filter) item).getSqlQuery())) adapter.setSelection(item); - } else if(item instanceof FilterCategory) { - Filter[] filters = ((FilterCategory)item).children; - if(filters == null) + } else if (item instanceof FilterCategory) { + Filter[] filters = ((FilterCategory) item).children; + if (filters == null) return; - for(Filter filter : filters) - if(finalSelection.equals(filter.getSqlQuery())) { + for (Filter filter : filters) + if (finalSelection.equals(filter.getSqlQuery())) { adapter.setSelection(filter); break; } @@ -186,15 +193,15 @@ public final class LocaleEditAlerts extends ListActivity { setListAdapter(adapter); // check for plugin - if(!PluginServices.getAddOnService().hasLocalePlugin()) { + if (!PluginServices.getAddOnService().hasLocalePlugin()) { isRemoved = true; new AlertDialog.Builder(this) - .setTitle(R.string.DLG_information_title) - .setMessage(R.string.locale_plugin_required) - .setCancelable(false) - .setPositiveButton(android.R.string.ok, - AddOnActivity.createAddOnClicker(LocaleEditAlerts.this, true)) - .show(); + .setTitle(R.string.DLG_information_title) + .setMessage(R.string.locale_plugin_required) + .setCancelable(false) + .setPositiveButton(android.R.string.ok, + AddOnActivity.createAddOnClicker(LocaleEditAlerts.this, true)) + .show(); StatisticsService.reportEvent(StatisticsConstants.LOCALE_EDIT_ALERTS_NO_PLUGIN); } else { StatisticsService.reportEvent(StatisticsConstants.LOCALE_EDIT_ALERTS); @@ -212,26 +219,21 @@ public final class LocaleEditAlerts extends ListActivity { * sort of result should be returned to Locale. */ @Override - public void finish() - { - if(isRemoved) + public void finish() { + if (isRemoved) setResult(com.twofortyfouram.Intent.RESULT_REMOVE); else if (isCancelled) setResult(RESULT_CANCELED); - else - { + else { final FilterListItem selected = adapter.getSelection(); final int intervalIndex = interval.getSelectedItemPosition(); - if (selected == null) - { + if (selected == null) { /* * If nothing is selected, return as if user had canceled */ setResult(RESULT_CANCELED); - } - else - { + } else { /* * This is the return Intent, into which we'll put all the required extras */ @@ -248,7 +250,7 @@ public final class LocaleEditAlerts extends ListActivity { Filter filterItem = (Filter) selected; storeAndForwardExtras.putString(KEY_FILTER_TITLE, filterItem.title); storeAndForwardExtras.putString(KEY_SQL, filterItem.getSqlQuery()); - if(filterItem.valuesForNewTasks != null) + if (filterItem.valuesForNewTasks != null) storeAndForwardExtras.putString(KEY_VALUES, AndroidUtilities.contentValuesToSerializedString(filterItem.valuesForNewTasks)); storeAndForwardExtras.putInt(KEY_INTERVAL, INTERVALS[intervalIndex]); @@ -300,8 +302,7 @@ public final class LocaleEditAlerts extends ListActivity { * {@inheritDoc} */ @Override - public boolean onCreateOptionsMenu(final Menu menu) - { + public boolean onCreateOptionsMenu(final Menu menu) { super.onCreateOptionsMenu(menu); final PackageManager manager = getPackageManager(); @@ -310,10 +311,10 @@ public final class LocaleEditAlerts extends ListActivity { * We are dynamically loading resources from Locale's APK. This will only work if Locale is actually installed */ menu.add(0, MENU_DONT_SAVE, 0, SharedResources.getTextResource(manager, SharedResources.STRING_MENU_DONTSAVE)) - .setIcon(SharedResources.getDrawableResource(manager, SharedResources.DRAWABLE_MENU_DONTSAVE)).getItemId(); + .setIcon(SharedResources.getDrawableResource(manager, SharedResources.DRAWABLE_MENU_DONTSAVE)).getItemId(); menu.add(0, MENU_SAVE, 0, SharedResources.getTextResource(manager, SharedResources.STRING_MENU_SAVE)) - .setIcon(SharedResources.getDrawableResource(manager, SharedResources.DRAWABLE_MENU_SAVE)).getItemId(); + .setIcon(SharedResources.getDrawableResource(manager, SharedResources.DRAWABLE_MENU_SAVE)).getItemId(); return true; } @@ -322,17 +323,13 @@ public final class LocaleEditAlerts extends ListActivity { * {@inheritDoc} */ @Override - public boolean onMenuItemSelected(final int featureId, final MenuItem item) - { - switch (item.getItemId()) - { - case MENU_SAVE: - { + public boolean onMenuItemSelected(final int featureId, final MenuItem item) { + switch (item.getItemId()) { + case MENU_SAVE: { finish(); return true; } - case MENU_DONT_SAVE: - { + case MENU_DONT_SAVE: { isCancelled = true; finish(); return true; diff --git a/astrid/plugin-src/com/todoroo/astrid/locale/LocaleReceiver.java b/astrid/plugin-src/com/todoroo/astrid/locale/LocaleReceiver.java index 8a2367a56..95be919df 100644 --- a/astrid/plugin-src/com/todoroo/astrid/locale/LocaleReceiver.java +++ b/astrid/plugin-src/com/todoroo/astrid/locale/LocaleReceiver.java @@ -31,12 +31,12 @@ import com.todoroo.astrid.utility.Constants; * Receiver is activated when Locale conditions are triggered * * @author timsu - * */ public class LocaleReceiver extends BroadcastReceiver { /** * Create a preference key for storing / retrieving last interval time + * * @param filterTitle * @param interval * @return @@ -53,7 +53,7 @@ public class LocaleReceiver extends BroadcastReceiver { try { if (com.twofortyfouram.Intent.ACTION_FIRE_SETTING.equals(intent.getAction())) { - if(!PluginServices.getAddOnService().hasLocalePlugin()) + if (!PluginServices.getAddOnService().hasLocalePlugin()) return; final Bundle forwardedBundle = intent.getBundleExtra(com.twofortyfouram.Intent.EXTRA_BUNDLE); @@ -61,18 +61,18 @@ public class LocaleReceiver extends BroadcastReceiver { final String title = forwardedBundle.getString(LocaleEditAlerts.KEY_FILTER_TITLE); final String sql = forwardedBundle.getString(LocaleEditAlerts.KEY_SQL); final String values = forwardedBundle.getString(LocaleEditAlerts.KEY_VALUES); - final int interval = forwardedBundle.getInt(LocaleEditAlerts.KEY_INTERVAL, 24*3600); + final int interval = forwardedBundle.getInt(LocaleEditAlerts.KEY_INTERVAL, 24 * 3600); - if(TextUtils.isEmpty(title) || TextUtils.isEmpty(sql) || + if (TextUtils.isEmpty(title) || TextUtils.isEmpty(sql) || sql.contains("--") || sql.contains(";") || interval == 0) return; // check if we've already made a notification recently String preferenceKey = makePreferenceKey(title, interval); long lastNotifyTime = Preferences.getLong(preferenceKey, 0); - if(DateUtilities.now() - lastNotifyTime < interval * 1000L) { + if (DateUtilities.now() - lastNotifyTime < interval * 1000L) { Log.i("astrid-locale-rx", title + ": Too soon, need " + (interval - - (DateUtilities.now() - lastNotifyTime)/1000) + " more seconds"); + - (DateUtilities.now() - lastNotifyTime) / 1000) + " more seconds"); return; } @@ -82,10 +82,10 @@ public class LocaleReceiver extends BroadcastReceiver { TodorooCursor cursor = PluginServices.getTaskService().fetchFiltered( sql, null, Task.ID); try { - if(cursor.getCount() == 0) + if (cursor.getCount() == 0) return; - if(values != null) + if (values != null) filter.valuesForNewTasks = AndroidUtilities.contentValuesFromSerializedString(values); Resources r = context.getResources(); diff --git a/astrid/plugin-src/com/todoroo/astrid/notes/EditNoteActivity.java b/astrid/plugin-src/com/todoroo/astrid/notes/EditNoteActivity.java index d7723a474..dcbcb2507 100644 --- a/astrid/plugin-src/com/todoroo/astrid/notes/EditNoteActivity.java +++ b/astrid/plugin-src/com/todoroo/astrid/notes/EditNoteActivity.java @@ -5,16 +5,6 @@ */ package com.todoroo.astrid.notes; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.LinkedList; -import java.util.List; - -import org.json.JSONArray; -import org.json.JSONObject; - import android.app.Activity; import android.content.Intent; import android.content.res.Resources; @@ -84,6 +74,16 @@ import com.todoroo.astrid.service.TaskService; import com.todoroo.astrid.timers.TimerActionControlSet.TimerActionListener; import com.todoroo.astrid.utility.ResourceDrawableCache; +import org.json.JSONArray; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.LinkedList; +import java.util.List; + import edu.mit.mobile.android.imagecache.ImageCache; public class EditNoteActivity extends LinearLayout implements TimerActionListener { @@ -92,12 +92,18 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene private Task task; - @Autowired ActFmSyncService actFmSyncService; - @Autowired ActFmPreferenceService actFmPreferenceService; - @Autowired MetadataService metadataService; - @Autowired UserActivityDao userActivityDao; - @Autowired TaskService taskService; - @Autowired TaskDao taskDao; + @Autowired + ActFmSyncService actFmSyncService; + @Autowired + ActFmPreferenceService actFmPreferenceService; + @Autowired + MetadataService metadataService; + @Autowired + UserActivityDao userActivityDao; + @Autowired + TaskService taskService; + @Autowired + TaskDao taskDao; private final ArrayList items = new ArrayList(); private EditText commentField; @@ -125,7 +131,7 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene private final SyncMessageCallback callback = new SyncMessageCallback() { @Override public void runOnSuccess() { - synchronized(this) { + synchronized (this) { if (activity != null) { activity.runOnUiThread(new Runnable() { @Override @@ -143,6 +149,7 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene } } } + @Override public void runOnErrors(List errors) {/**/} }; @@ -153,6 +160,7 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene public interface UpdatesChangedListener { public void updatesChanged(); + public void commentAdded(); } @@ -193,32 +201,31 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene task = PluginServices.getTaskService().fetchById(id, Task.NOTES, Task.ID, Task.UUID, Task.TITLE, Task.HISTORY_FETCH_DATE, Task.HISTORY_HAS_MORE, Task.USER_ACTIVITIES_PUSHED_AT, Task.ATTACHMENTS_PUSHED_AT); } - public void loadViewForTaskID(long t){ + public void loadViewForTaskID(long t) { try { fetchTask(t); } catch (SQLiteException e) { StartupService.handleSQLiteError(ContextManager.getContext(), e); } - if(task == null) { + if (task == null) { return; } setUpInterface(); setUpListAdapter(); - if(actFmPreferenceService.isLoggedIn()) { + if (actFmPreferenceService.isLoggedIn()) { long pushedAt = task.getValue(Task.USER_ACTIVITIES_PUSHED_AT); - if(DateUtilities.now() - pushedAt > DateUtilities.ONE_HOUR / 2) { + if (DateUtilities.now() - pushedAt > DateUtilities.ONE_HOUR / 2) { refreshData(); } else { loadingText.setText(R.string.ENA_no_comments); - if(items.size() == 0) + if (items.size() == 0) loadingText.setVisibility(View.VISIBLE); } } } - // --- UI preparation private void setUpInterface() { @@ -235,8 +242,7 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene if (hasFocus) { timerView.setVisibility(View.GONE); commentButton.setVisibility(View.VISIBLE); - } - else { + } else { timerView.setVisibility(View.VISIBLE); commentButton.setVisibility(View.GONE); } @@ -260,6 +266,7 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene public void beforeTextChanged(CharSequence s, int start, int count, int after) { // } + @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // @@ -269,7 +276,7 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene commentField.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView view, int actionId, KeyEvent event) { - if(actionId == EditorInfo.IME_NULL && commentField.getText().length() > 0) { + if (actionId == EditorInfo.IME_NULL && commentField.getText().length() > 0) { addComment(); return true; } @@ -301,7 +308,7 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene respondToPicture = true; } }); - if(!TextUtils.isEmpty(task.getValue(Task.NOTES))) { + if (!TextUtils.isEmpty(task.getValue(Task.NOTES))) { TextView notes = new TextView(getContext()); notes.setLinkTextColor(Color.rgb(100, 160, 255)); notes.setTextSize(18); @@ -333,7 +340,7 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene NoteMetadata.METADATA_KEY))); try { Metadata metadata = new Metadata(); - for(notes.moveToFirst(); !notes.isAfterLast(); notes.moveToNext()) { + for (notes.moveToFirst(); !notes.isAfterLast(); notes.moveToNext()) { metadata.readFromCursor(notes); items.add(NoteOrUpdate.fromMetadata(metadata)); } @@ -348,7 +355,7 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene UserActivity update = new UserActivity(); History history = new History(); User user = new User(); - for(updates.moveToFirst(); !updates.isAfterLast(); updates.moveToNext()) { + for (updates.moveToFirst(); !updates.isAfterLast(); updates.moveToNext()) { update.clear(); user.clear(); @@ -367,7 +374,7 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene noa = NoteOrUpdate.fromUpdateOrHistory(activity, null, history, user, linkColor); historyCount++; } - if(noa != null) + if (noa != null) items.add(noa); } } finally { @@ -377,7 +384,7 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene Collections.sort(items, new Comparator() { @Override public int compare(NoteOrUpdate a, NoteOrUpdate b) { - if(a.createdAt < b.createdAt) + if (a.createdAt < b.createdAt) return 1; else if (a.createdAt == b.createdAt) return 0; @@ -407,8 +414,7 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene } }); this.addView(loadMore); - } - else if (items.size() == 0) { + } else if (items.size() == 0) { TextView noUpdates = new TextView(getContext()); noUpdates.setText(R.string.TEA_no_activity); noUpdates.setTextColor(activity.getResources().getColor(R.color.task_edit_deadline_gray)); @@ -426,26 +432,29 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene } - public View getUpdateNotes(NoteOrUpdate note, ViewGroup parent) { - View convertView = ((Activity)getContext()).getLayoutInflater().inflate( + View convertView = ((Activity) getContext()).getLayoutInflater().inflate( R.layout.update_adapter_row, parent, false); bindView(convertView, note); return convertView; } - /** Helper method to set the contents and visibility of each field */ + /** + * Helper method to set the contents and visibility of each field + */ public synchronized void bindView(View view, NoteOrUpdate item) { // picture - final AsyncImageView pictureView = (AsyncImageView)view.findViewById(R.id.picture); { + final AsyncImageView pictureView = (AsyncImageView) view.findViewById(R.id.picture); + { pictureView.setDefaultImageDrawable(ResourceDrawableCache.getImageDrawableFromId(resources, R.drawable.icn_default_person_image)); pictureView.setUrl(item.picture); } // name - final TextView nameView = (TextView)view.findViewById(R.id.title); { + final TextView nameView = (TextView) view.findViewById(R.id.title); + { nameView.setText(item.title); if (NameMaps.TABLE_ID_HISTORY.equals(item.type)) nameView.setTextColor(grayColor); @@ -455,7 +464,8 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene } // date - final TextView date = (TextView)view.findViewById(R.id.date); { + final TextView date = (TextView) view.findViewById(R.id.date); + { CharSequence dateString = DateUtils.getRelativeTimeSpanString(item.createdAt, DateUtilities.now(), DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_RELATIVE); @@ -463,13 +473,14 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene } // picture - final AsyncImageView commentPictureView = (AsyncImageView)view.findViewById(R.id.comment_picture); { + final AsyncImageView commentPictureView = (AsyncImageView) view.findViewById(R.id.comment_picture); + { UpdateAdapter.setupImagePopupForCommentView(view, commentPictureView, item.pictureThumb, item.pictureFull, item.commentBitmap, item.title.toString(), fragment, imageCache); } } public void refreshData() { - if(!task.containsNonNullValue(Task.UUID)) { + if (!task.containsNonNullValue(Task.UUID)) { return; } @@ -565,9 +576,9 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene } public static NoteOrUpdate fromMetadata(Metadata m) { - if(!m.containsNonNullValue(NoteMetadata.THUMBNAIL)) + if (!m.containsNonNullValue(NoteMetadata.THUMBNAIL)) m.setValue(NoteMetadata.THUMBNAIL, ""); //$NON-NLS-1$ - if(!m.containsNonNullValue(NoteMetadata.COMMENT_PICTURE)) + if (!m.containsNonNullValue(NoteMetadata.COMMENT_PICTURE)) m.setValue(NoteMetadata.COMMENT_PICTURE, ""); //$NON-NLS-1$ Spanned title = Html.fromHtml(String.format("%s\n%s", m.getValue(NoteMetadata.TITLE), m.getValue(NoteMetadata.BODY))); //$NON-NLS-1$ return new NoteOrUpdate(m.getValue(NoteMetadata.THUMBNAIL), @@ -669,7 +680,7 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene } }; - return (ActFmCameraModule.activityResult((Activity)getContext(), + return (ActFmCameraModule.activityResult((Activity) getContext(), requestCode, resultCode, data, callback)); } else { return false; diff --git a/astrid/plugin-src/com/todoroo/astrid/notes/NoteMetadata.java b/astrid/plugin-src/com/todoroo/astrid/notes/NoteMetadata.java index 154121d66..66f262761 100644 --- a/astrid/plugin-src/com/todoroo/astrid/notes/NoteMetadata.java +++ b/astrid/plugin-src/com/todoroo/astrid/notes/NoteMetadata.java @@ -12,29 +12,42 @@ import com.todoroo.astrid.data.Metadata; * Metadata entry for a note displayed by the Notes plugin. * * @author Tim Su - * */ public class NoteMetadata { - /** metadata key */ + /** + * metadata key + */ public static final String METADATA_KEY = "note"; //$NON-NLS-1$ - /** note body */ + /** + * note body + */ public static final StringProperty BODY = Metadata.VALUE1; - /** note description (title, date, from, etc) */ + /** + * note description (title, date, from, etc) + */ public static final StringProperty TITLE = Metadata.VALUE2; - /** note thumbnail URL */ + /** + * note thumbnail URL + */ public static final StringProperty THUMBNAIL = Metadata.VALUE3; - /** note external id (use for your own purposes) */ + /** + * note external id (use for your own purposes) + */ public static final StringProperty COMMENT_PICTURE = Metadata.VALUE6; - /** note external provider (use for your own purposes) */ + /** + * note external provider (use for your own purposes) + */ public static final StringProperty EXT_PROVIDER = Metadata.VALUE4; - /** note external id (use for your own purposes) */ + /** + * note external id (use for your own purposes) + */ public static final StringProperty EXT_ID = Metadata.VALUE5; diff --git a/astrid/plugin-src/com/todoroo/astrid/notes/NotesDecorationExposer.java b/astrid/plugin-src/com/todoroo/astrid/notes/NotesDecorationExposer.java index 50df6d27b..c7ff000b1 100644 --- a/astrid/plugin-src/com/todoroo/astrid/notes/NotesDecorationExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/notes/NotesDecorationExposer.java @@ -20,22 +20,21 @@ import com.todoroo.astrid.data.Task; * Exposes {@link TaskDecoration} for timers * * @author Tim Su - * */ public class NotesDecorationExposer implements TaskDecorationExposer { @Override public TaskDecoration expose(Task task) { - if(Preferences.getBoolean(R.string.p_showNotes, false)) + if (Preferences.getBoolean(R.string.p_showNotes, false)) return null; - if(task == null || !NotesPlugin.hasNotes(task)) + if (task == null || !NotesPlugin.hasNotes(task)) return null; Intent intent = new Intent(ContextManager.getContext(), EditNoteActivity.class); intent.setAction(EditNoteActivity.class.getName()); intent.putExtra(EditNoteActivity.EXTRA_TASK_ID, task.getId()); - PendingIntent pi = PendingIntent.getActivity(ContextManager.getContext(), - (int)task.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT); + PendingIntent pi = PendingIntent.getActivity(ContextManager.getContext(), + (int) task.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT); TaskDecoration decoration; RemoteViews remoteViews = new RemoteViews(ContextManager.getContext().getPackageName(), diff --git a/astrid/plugin-src/com/todoroo/astrid/notes/NotesDetailExposer.java b/astrid/plugin-src/com/todoroo/astrid/notes/NotesDetailExposer.java index 80a1dc559..38eecae57 100644 --- a/astrid/plugin-src/com/todoroo/astrid/notes/NotesDetailExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/notes/NotesDetailExposer.java @@ -26,7 +26,6 @@ import com.todoroo.astrid.data.Task; * Exposes Task Detail for notes * * @author Tim Su - * */ public class NotesDetailExposer extends BroadcastReceiver { @@ -36,11 +35,11 @@ public class NotesDetailExposer extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { // get tags associated with this task long taskId = intent.getLongExtra(AstridApiConstants.EXTRAS_TASK_ID, -1); - if(taskId == -1) + if (taskId == -1) return; String taskDetail = getTaskDetails(taskId); - if(taskDetail == null) + if (taskDetail == null) return; // transmit @@ -53,18 +52,18 @@ public class NotesDetailExposer extends BroadcastReceiver { @SuppressWarnings("nls") public String getTaskDetails(long id) { - if(!Preferences.getBoolean(R.string.p_showNotes, false)) + if (!Preferences.getBoolean(R.string.p_showNotes, false)) return null; Task task = PluginServices.getTaskService().fetchById(id, Task.ID, Task.NOTES); - if(task == null) + if (task == null) return null; StringBuilder notesBuilder = new StringBuilder(); String notes = task.getValue(Task.NOTES); - if(!TextUtils.isEmpty(notes)) { - if(notes.length() > NOTE_MAX) { + if (!TextUtils.isEmpty(notes)) { + if (notes.length() > NOTE_MAX) { int lastSpace = notes.lastIndexOf(' ', NOTE_MAX); notes = notes.substring(0, Math.max(lastSpace, NOTE_MAX - 20)) + "..."; } @@ -77,10 +76,10 @@ public class NotesDetailExposer extends BroadcastReceiver { NoteMetadata.METADATA_KEY)).orderBy(Order.asc(Metadata.CREATION_DATE))); Metadata metadata = new Metadata(); try { - for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { + for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { metadata.readFromCursor(cursor); - if(notesBuilder.length() > 0) + if (notesBuilder.length() > 0) notesBuilder.append("\n"); notesBuilder.append("").append(metadata.getValue(NoteMetadata.TITLE)).append("\n"); notesBuilder.append(metadata.getValue(NoteMetadata.BODY)); @@ -89,7 +88,7 @@ public class NotesDetailExposer extends BroadcastReceiver { cursor.close(); } - if(notesBuilder.length() == 0) + if (notesBuilder.length() == 0) return null; return " " + notesBuilder; //$NON-NLS-1$ diff --git a/astrid/plugin-src/com/todoroo/astrid/notes/NotesPlugin.java b/astrid/plugin-src/com/todoroo/astrid/notes/NotesPlugin.java index 313ef996f..52d668d1d 100644 --- a/astrid/plugin-src/com/todoroo/astrid/notes/NotesPlugin.java +++ b/astrid/plugin-src/com/todoroo/astrid/notes/NotesPlugin.java @@ -37,10 +37,10 @@ public class NotesPlugin extends BroadcastReceiver { * @return */ public static boolean hasNotes(Task task) { - if(task.containsNonNullValue(Task.NOTES) && !TextUtils.isEmpty(task.getValue(Task.NOTES))) + if (task.containsNonNullValue(Task.NOTES) && !TextUtils.isEmpty(task.getValue(Task.NOTES))) return true; - if(PluginServices.getMetadataService().hasMetadata(task.getId(), NoteMetadata.METADATA_KEY)) + if (PluginServices.getMetadataService().hasMetadata(task.getId(), NoteMetadata.METADATA_KEY)) return true; return false; diff --git a/astrid/plugin-src/com/todoroo/astrid/opencrx/OpencrxControlSet.java b/astrid/plugin-src/com/todoroo/astrid/opencrx/OpencrxControlSet.java index 975ee6f9a..48a80a3f9 100644 --- a/astrid/plugin-src/com/todoroo/astrid/opencrx/OpencrxControlSet.java +++ b/astrid/plugin-src/com/todoroo/astrid/opencrx/OpencrxControlSet.java @@ -5,8 +5,6 @@ */ package com.todoroo.astrid.opencrx; -import java.util.ArrayList; - import android.app.Activity; import android.util.Log; import android.view.View; @@ -34,28 +32,34 @@ import com.todoroo.astrid.data.Task; import com.todoroo.astrid.service.MetadataService; import com.todoroo.astrid.ui.PopupControlSet; +import java.util.ArrayList; + /** * Control Set for managing contact/creator assignments in OpenCRX * * @author Andrey Marchenko - * */ public class OpencrxControlSet extends PopupControlSet { /** * Class that represents OpenCRX ActivityCreator. Duplicates some functionality of OpenCRX plugin. - * */ @SuppressWarnings("unused") private static class OpencrxActivityCreator { - /** type*/ + /** + * type + */ public static final String TYPE = "opencrx-creator"; //$NON-NLS-1$ - /** hashed creator id in opencrx */ + /** + * hashed creator id in opencrx + */ public static final LongProperty REMOTE_ID = new LongProperty(StoreObject.TABLE, StoreObject.ITEM.name); - /** creator name */ + /** + * creator name + */ public static final StringProperty NAME = new StringProperty(StoreObject.TABLE, StoreObject.VALUE1.name); @@ -71,9 +75,9 @@ public class OpencrxControlSet extends PopupControlSet { private final String crxId; - public OpencrxActivityCreator (StoreObject creatorData) { - this(creatorData.getValue(REMOTE_ID),creatorData.getValue(NAME), - creatorData.containsValue(CRX_ID) ? creatorData.getValue(CRX_ID) : ""); //$NON-NLS-1$ + public OpencrxActivityCreator(StoreObject creatorData) { + this(creatorData.getValue(REMOTE_ID), creatorData.getValue(NAME), + creatorData.containsValue(CRX_ID) ? creatorData.getValue(CRX_ID) : ""); //$NON-NLS-1$ } public OpencrxActivityCreator(long id, String name, String crxId) { @@ -81,6 +85,7 @@ public class OpencrxControlSet extends PopupControlSet { this.name = name; this.crxId = crxId; } + public long getId() { return id; } @@ -101,25 +106,32 @@ public class OpencrxControlSet extends PopupControlSet { /** * Class that represents OpenCRX Contact. Duplicates some functionality of OpenCRX plugin. - * */ @SuppressWarnings("unused") private static class OpencrxContact { public static final String TYPE = "opencrx-contacts"; //$NON-NLS-1$ - /** hash contact id in opencrx */ + /** + * hash contact id in opencrx + */ public static final LongProperty REMOTE_ID = new LongProperty(StoreObject.TABLE, StoreObject.ITEM.name); - /** contact first name */ + /** + * contact first name + */ public static final StringProperty FIRST_NAME = new StringProperty(StoreObject.TABLE, StoreObject.VALUE1.name); - /** contact last name */ + /** + * contact last name + */ public static final StringProperty LAST_NAME = new StringProperty(StoreObject.TABLE, StoreObject.VALUE2.name); - /** id in OpenCRX as string */ + /** + * id in OpenCRX as string + */ public static final StringProperty CRX_ID = new StringProperty(StoreObject.TABLE, StoreObject.VALUE3.name); @@ -134,7 +146,7 @@ public class OpencrxControlSet extends PopupControlSet { private final String crxId; public OpencrxContact(long id, String email, String firstname, - String lastname, String crxId) { + String lastname, String crxId) { this.id = id; this.email = email; this.firstname = firstname; @@ -142,22 +154,26 @@ public class OpencrxControlSet extends PopupControlSet { this.crxId = crxId; } - public OpencrxContact(StoreObject userData){ - this(userData.getValue(REMOTE_ID), "", userData.getValue(FIRST_NAME), userData.getValue(LAST_NAME), userData.getValue(CRX_ID) ); //$NON-NLS-1$ + public OpencrxContact(StoreObject userData) { + this(userData.getValue(REMOTE_ID), "", userData.getValue(FIRST_NAME), userData.getValue(LAST_NAME), userData.getValue(CRX_ID)); //$NON-NLS-1$ } public String getEmail() { return email; } + public String getFirstname() { return firstname; } + public String getLastname() { return lastname; } + public String getCrxId() { return crxId; } + public long getId() { return id; } @@ -210,7 +226,7 @@ public class OpencrxControlSet extends PopupControlSet { @Override protected void afterInflate() { - //View view = LayoutInflater.from(activity).inflate(R.layout.opencrx_control, parent, true); + //View view = LayoutInflater.from(activity).inflate(R.layout.opencrx_control, parent, true); this.assignedToSelector = (Spinner) getView().findViewById(R.id.opencrx_TEA_task_assign); TextView emptyView = new TextView(activity); @@ -228,22 +244,22 @@ public class OpencrxControlSet extends PopupControlSet { Metadata metadata = getTaskMetadata(model.getId()); - if(metadata == null) + if (metadata == null) metadata = OpencrxCoreUtils.INSTANCE.newMetadata(model.getId()); // Fill the dashboard-spinner and set the current dashboard long dashboardId = OpencrxCoreUtils.INSTANCE.getDefaultCreator(); - if(metadata.containsNonNullValue(OpencrxCoreUtils.ACTIVITY_CREATOR_ID)) + if (metadata.containsNonNullValue(OpencrxCoreUtils.ACTIVITY_CREATOR_ID)) dashboardId = metadata.getValue(OpencrxCoreUtils.ACTIVITY_CREATOR_ID); StoreObject[] dashboardsData = readStoreObjects(OpencrxActivityCreator.TYPE); dashboards = new ArrayList(dashboardsData.length); int dashboardSpinnerIndex = -1; - for (int i=0;i creatorAdapterTextInput = new ArrayAdapter(activity, android.R.layout.simple_spinner_item, dashboards); @@ -264,16 +280,16 @@ public class OpencrxControlSet extends PopupControlSet { @Override public void onItemClick(AdapterView adapter, View view, int position, - long id) { + long id) { OpencrxActivityCreator creatorInput = (OpencrxActivityCreator) adapter.getItemAtPosition(position); if (creatorInput == null) return; int selectedIndex = creatorSelector.getSelectedItemPosition(); - for (int i = 0; i < creatorSelector.getAdapter().getCount(); ++i){ + for (int i = 0; i < creatorSelector.getAdapter().getCount(); ++i) { OpencrxActivityCreator current = (OpencrxActivityCreator) creatorSelector.getAdapter().getItem(i); - if (current != null && current.getId() == creatorInput.getId()){ + if (current != null && current.getId() == creatorInput.getId()) { selectedIndex = i; break; } @@ -285,13 +301,13 @@ public class OpencrxControlSet extends PopupControlSet { // Assigned user long responsibleId = OpencrxCoreUtils.INSTANCE.getDefaultAssignedUser(); - if (metadata.containsNonNullValue(OpencrxCoreUtils.ACTIVITY_ASSIGNED_TO_ID)){ + if (metadata.containsNonNullValue(OpencrxCoreUtils.ACTIVITY_ASSIGNED_TO_ID)) { responsibleId = metadata.getValue(OpencrxCoreUtils.ACTIVITY_ASSIGNED_TO_ID); } StoreObject[] usersData = readStoreObjects(OpencrxContact.TYPE); this.users = new ArrayList(); - for (StoreObject user : usersData){ + for (StoreObject user : usersData) { this.users.add(new OpencrxContact(user)); } @@ -302,8 +318,8 @@ public class OpencrxControlSet extends PopupControlSet { int responsibleSpinnerIndex = 0; - for (int i = 0; i < this.users.size() ; i++) { - if (this.users.get(i).getId() == responsibleId ) { + for (int i = 0; i < this.users.size(); i++) { + if (this.users.get(i).getId() == responsibleId) { responsibleSpinnerIndex = i; break; } @@ -318,7 +334,7 @@ public class OpencrxControlSet extends PopupControlSet { @Override public void onItemClick(AdapterView adapter, View view, int position, - long id) { + long id) { OpencrxContact userInput = (OpencrxContact) adapter.getItemAtPosition(position); @@ -326,9 +342,9 @@ public class OpencrxControlSet extends PopupControlSet { int selectedIndex = assignedToSelector.getSelectedItemPosition(); - for (int i = 0; i < assignedToSelector.getAdapter().getCount(); ++i){ + for (int i = 0; i < assignedToSelector.getAdapter().getCount(); ++i) { OpencrxContact current = (OpencrxContact) assignedToSelector.getAdapter().getItem(i); - if (current != null && current.getId() == userInput.getId()){ + if (current != null && current.getId() == userInput.getId()) { selectedIndex = i; break; } @@ -353,12 +369,12 @@ public class OpencrxControlSet extends PopupControlSet { OpencrxContact responsibleUser = (OpencrxContact) assignedToSelector.getSelectedItem(); - if(responsibleUser == null) + if (responsibleUser == null) metadata.setValue(OpencrxCoreUtils.ACTIVITY_ASSIGNED_TO_ID, 0L); else metadata.setValue(OpencrxCoreUtils.ACTIVITY_ASSIGNED_TO_ID, responsibleUser.getId()); - if(metadata.getSetValues().size() > 0) { + if (metadata.getSetValues().size() > 0) { metadataService.save(metadata); task.setValue(Task.MODIFICATION_DATE, DateUtilities.now()); } @@ -370,14 +386,15 @@ public class OpencrxControlSet extends PopupControlSet { /** * Reads metadata out of a task + * * @return null if no metadata found */ private Metadata getTaskMetadata(long taskId) { TodorooCursor cursor = metadataService.query(Query.select(Metadata.PROPERTIES).where( - MetadataCriteria.byTaskAndwithKey(taskId, OpencrxCoreUtils.OPENCRX_ACTIVITY_METADATA_KEY)) - ); + MetadataCriteria.byTaskAndwithKey(taskId, OpencrxCoreUtils.OPENCRX_ACTIVITY_METADATA_KEY)) + ); try { - if(cursor.getCount() == 0) + if (cursor.getCount() == 0) return null; cursor.moveToFirst(); return new Metadata(cursor); @@ -392,7 +409,7 @@ public class OpencrxControlSet extends PopupControlSet { where(StoreObjectCriteria.byType(type))); try { ret = new StoreObject[cursor.getCount()]; - for(int i = 0; i < ret.length; i++) { + for (int i = 0; i < ret.length; i++) { cursor.moveToNext(); StoreObject dashboard = new StoreObject(cursor); ret[i] = dashboard; diff --git a/astrid/plugin-src/com/todoroo/astrid/opencrx/OpencrxCoreUtils.java b/astrid/plugin-src/com/todoroo/astrid/opencrx/OpencrxCoreUtils.java index e674c53fe..caa13d3db 100644 --- a/astrid/plugin-src/com/todoroo/astrid/opencrx/OpencrxCoreUtils.java +++ b/astrid/plugin-src/com/todoroo/astrid/opencrx/OpencrxCoreUtils.java @@ -16,7 +16,7 @@ import com.todoroo.andlib.service.ContextManager; import com.todoroo.astrid.data.Metadata; import com.todoroo.astrid.sync.SyncProviderUtilities; -public class OpencrxCoreUtils extends SyncProviderUtilities{ +public class OpencrxCoreUtils extends SyncProviderUtilities { public static final String OPENCRX_ACTIVITY_METADATA_KEY = "opencrx"; //$NON-NLS-1$ @@ -38,7 +38,7 @@ public class OpencrxCoreUtils extends SyncProviderUtilities{ public static final OpencrxCoreUtils INSTANCE = new OpencrxCoreUtils(); - private OpencrxCoreUtils(){ + private OpencrxCoreUtils() { // prevent instantiation } @@ -58,7 +58,7 @@ public class OpencrxCoreUtils extends SyncProviderUtilities{ public void stopOngoing() { SharedPreferences sharedPreferences = OpencrxCoreUtils.getPrefs(); - if (sharedPreferences != null){ + if (sharedPreferences != null) { Editor editor = sharedPreferences.edit(); editor.putBoolean(getIdentifier() + PREF_ONGOING, false); editor.commit(); @@ -67,18 +67,19 @@ public class OpencrxCoreUtils extends SyncProviderUtilities{ /** * Gets default creator from setting + * * @return CREATOR_NO_SYNC if should not sync, otherwise remote id */ public long getDefaultCreator() { - long defaultCreatorId = CREATOR_NO_SYNC ; + long defaultCreatorId = CREATOR_NO_SYNC; SharedPreferences sharedPreferences = OpencrxCoreUtils.getPrefs(); - if (sharedPreferences != null){ + if (sharedPreferences != null) { String defCreatorString = sharedPreferences.getString(PREF_DEFAULT_CREATOR, String.valueOf(CREATOR_NO_SYNC)); - try{ + try { defaultCreatorId = Long.parseLong(defCreatorString); - }catch(Exception ex){ + } catch (Exception ex) { defaultCreatorId = CREATOR_NO_SYNC; } } @@ -86,12 +87,12 @@ public class OpencrxCoreUtils extends SyncProviderUtilities{ return defaultCreatorId; } - public long getDefaultAssignedUser(){ + public long getDefaultAssignedUser() { SharedPreferences sharedPreferences = OpencrxCoreUtils.getPrefs(); - if (sharedPreferences != null){ + if (sharedPreferences != null) { return sharedPreferences.getLong(PREF_USER_ID, -1); - }else{ + } else { return -1; } } @@ -100,7 +101,7 @@ public class OpencrxCoreUtils extends SyncProviderUtilities{ try { Context crxContext = ContextManager.getContext().createPackageContext(OPENCRX_PACKAGE, 0); SharedPreferences sharedPreferences = crxContext.getSharedPreferences(PREFS_FILE, - Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE); + Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE); return sharedPreferences; } catch (NameNotFoundException e) { return null; @@ -121,6 +122,7 @@ public class OpencrxCoreUtils extends SyncProviderUtilities{ public String getIdentifier() { return IDENTIFIER; } + @Override public int getSyncIntervalKey() { return 0; diff --git a/astrid/plugin-src/com/todoroo/astrid/people/PeopleFilterAdapter.java b/astrid/plugin-src/com/todoroo/astrid/people/PeopleFilterAdapter.java index 46bacbd19..6c9dc4958 100644 --- a/astrid/plugin-src/com/todoroo/astrid/people/PeopleFilterAdapter.java +++ b/astrid/plugin-src/com/todoroo/astrid/people/PeopleFilterAdapter.java @@ -19,7 +19,7 @@ public class PeopleFilterAdapter extends FilterAdapter { public static final String BROADCAST_SEND_PEOPLE_FILTERS = Constants.PACKAGE + ".SEND_PEOPLE_FILTERS"; //$NON-NLS-1$ public PeopleFilterAdapter(Activity activity, ListView listView, - int rowLayout, boolean skipIntentFilters) { + int rowLayout, boolean skipIntentFilters) { super(activity, listView, rowLayout, skipIntentFilters); } diff --git a/astrid/plugin-src/com/todoroo/astrid/people/PeopleFilterExposer.java b/astrid/plugin-src/com/todoroo/astrid/people/PeopleFilterExposer.java index 2e2fc5cda..1050183be 100644 --- a/astrid/plugin-src/com/todoroo/astrid/people/PeopleFilterExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/people/PeopleFilterExposer.java @@ -5,9 +5,6 @@ */ package com.todoroo.astrid.people; -import java.util.ArrayList; -import java.util.List; - import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentValues; @@ -43,6 +40,9 @@ import com.todoroo.astrid.service.ThemeService; import com.todoroo.astrid.tags.TaskToTagMetadata; import com.todoroo.astrid.utility.AstridPreferences; +import java.util.ArrayList; +import java.util.List; + public class PeopleFilterExposer extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { @@ -57,7 +57,7 @@ public class PeopleFilterExposer extends BroadcastReceiver { private FilterListItem[] prepareFilters(Context context) { TodorooCursor users = PluginServices.getUserDao().query(Query.select(User.PROPERTIES) .where(Criterion.not(Criterion.or(User.STATUS.eq(User.STATUS_BLOCKED), - User.STATUS.eq(User.STATUS_IGNORED), User.STATUS.eq(User.STATUS_RENOUNCE), User.STATUS.eq(User.STATUS_IGNORE)))) + User.STATUS.eq(User.STATUS_IGNORED), User.STATUS.eq(User.STATUS_RENOUNCE), User.STATUS.eq(User.STATUS_IGNORE)))) .orderBy(Order.asc(User.FIRST_NAME), Order.asc(User.LAST_NAME), Order.asc(User.NAME))); try { List items = new ArrayList(); @@ -77,7 +77,7 @@ public class PeopleFilterExposer extends BroadcastReceiver { } } - @SuppressWarnings({ "nls", "deprecation" }) + @SuppressWarnings({"nls", "deprecation"}) private static FilterWithCustomIntent filterFromUserData(User user) { String title = user.getDisplayName(); if (TextUtils.isEmpty(title) || "null".equals(title)) @@ -154,7 +154,7 @@ public class PeopleFilterExposer extends BroadcastReceiver { extras.putBoolean(PersonViewFragment.EXTRA_HIDE_QUICK_ADD, true); filter.customExtras = extras; - filter.listingIcon = ((BitmapDrawable)context.getResources().getDrawable( + filter.listingIcon = ((BitmapDrawable) context.getResources().getDrawable( ThemeService.getDrawable(R.drawable.icn_menu_friends, themeFlags))).getBitmap(); return filter; diff --git a/astrid/plugin-src/com/todoroo/astrid/people/PeopleFilterMode.java b/astrid/plugin-src/com/todoroo/astrid/people/PeopleFilterMode.java index 1e3977ab0..92a86ec1f 100644 --- a/astrid/plugin-src/com/todoroo/astrid/people/PeopleFilterMode.java +++ b/astrid/plugin-src/com/todoroo/astrid/people/PeopleFilterMode.java @@ -37,8 +37,8 @@ public class PeopleFilterMode implements FilterModeSpec { } private static final int[] FORBIDDEN_MENU_ITEMS = { - TaskListFragment.MENU_NEW_FILTER_ID, - MainMenuPopover.MAIN_MENU_ITEM_FRIENDS + TaskListFragment.MENU_NEW_FILTER_ID, + MainMenuPopover.MAIN_MENU_ITEM_FRIENDS }; @Override diff --git a/astrid/plugin-src/com/todoroo/astrid/people/PersonViewFragment.java b/astrid/plugin-src/com/todoroo/astrid/people/PersonViewFragment.java index b0d90c4ab..23b61b240 100644 --- a/astrid/plugin-src/com/todoroo/astrid/people/PersonViewFragment.java +++ b/astrid/plugin-src/com/todoroo/astrid/people/PersonViewFragment.java @@ -5,10 +5,6 @@ */ package com.todoroo.astrid.people; -import java.util.List; - -import org.json.JSONArray; - import android.app.Activity; import android.content.ContentValues; import android.content.Intent; @@ -37,6 +33,10 @@ import com.todoroo.astrid.service.SyncV2Service; import com.todoroo.astrid.service.ThemeService; import com.todoroo.astrid.utility.ResourceDrawableCache; +import org.json.JSONArray; + +import java.util.List; + public class PersonViewFragment extends TaskListFragment { public static final String EXTRA_USER_ID_LOCAL = "user_local_id"; //$NON-NLS-1$ @@ -45,13 +45,17 @@ public class PersonViewFragment extends TaskListFragment { protected static final int MENU_REFRESH_ID = MENU_SUPPORT_ID + 1; - @Autowired UserDao userDao; + @Autowired + UserDao userDao; - @Autowired SyncV2Service syncService; + @Autowired + SyncV2Service syncService; - @Autowired ActFmPreferenceService actFmPreferenceService; + @Autowired + ActFmPreferenceService actFmPreferenceService; - @Autowired ActFmSyncService actFmSyncService; + @Autowired + ActFmSyncService actFmSyncService; private AsyncImageView userImage; private TextView userSubtitle; @@ -167,7 +171,7 @@ public class PersonViewFragment extends TaskListFragment { @Override protected void addSyncRefreshMenuItem(Menu menu, int themeFlags) { - if(actFmPreferenceService.isLoggedIn()) { + if (actFmPreferenceService.isLoggedIn()) { addMenuItem(menu, R.string.actfm_TVA_menu_refresh, ThemeService.getDrawable(R.drawable.icn_menu_refresh, themeFlags), MENU_REFRESH_ID, true); } else { @@ -178,9 +182,9 @@ public class PersonViewFragment extends TaskListFragment { @Override public boolean handleOptionsMenuItemSelected(int id, Intent intent) { switch (id) { - case MENU_REFRESH_ID: - refreshData(); - return true; + case MENU_REFRESH_ID: + refreshData(); + return true; } return super.handleOptionsMenuItemSelected(id, intent); } @@ -192,7 +196,7 @@ public class PersonViewFragment extends TaskListFragment { if (user != null) { long lastAutosync = user.getValue(User.LAST_AUTOSYNC); - if(DateUtilities.now() - lastAutosync > AUTOSYNC_INTERVAL) { + if (DateUtilities.now() - lastAutosync > AUTOSYNC_INTERVAL) { refreshData(); user.setValue(User.LAST_AUTOSYNC, DateUtilities.now()); userDao.saveExisting(user); @@ -227,6 +231,7 @@ public class PersonViewFragment extends TaskListFragment { }); } } + @Override public void runOnErrors(List errors) {/**/} }; diff --git a/astrid/plugin-src/com/todoroo/astrid/reminders/NotificationFragment.java b/astrid/plugin-src/com/todoroo/astrid/reminders/NotificationFragment.java index b58c2b8a1..aeccb16bd 100644 --- a/astrid/plugin-src/com/todoroo/astrid/reminders/NotificationFragment.java +++ b/astrid/plugin-src/com/todoroo/astrid/reminders/NotificationFragment.java @@ -5,8 +5,6 @@ */ package com.todoroo.astrid.reminders; -import java.util.Date; - import android.app.Activity; import android.app.AlertDialog; import android.app.TimePickerDialog; @@ -33,18 +31,21 @@ import com.todoroo.astrid.service.StatisticsConstants; import com.todoroo.astrid.service.StatisticsService; import com.todoroo.astrid.ui.NumberPicker; +import java.util.Date; + /** * This activity is launched when a user opens up a notification from the * tray. It launches the appropriate activity based on the passed in parameters. * * @author timsu - * */ public class NotificationFragment extends TaskListFragment { // --- constants - /** task id from notification */ + /** + * task id from notification + */ public static final String TOKEN_ID = "id"; //$NON-NLS-1$ // --- implementation @@ -117,25 +118,25 @@ public class NotificationFragment extends TaskListFragment { public void onClick(DialogInterface dialog, int which) { long time = DateUtilities.now(); int value = snoozeValue.getCurrent(); - switch(snoozeUnits.getSelectedItemPosition()) { - case RepeatControlSet.INTERVAL_DAYS: - time += value * DateUtilities.ONE_DAY; - break; - case RepeatControlSet.INTERVAL_HOURS: - time += value * DateUtilities.ONE_HOUR; - break; - case RepeatControlSet.INTERVAL_MINUTES: - time += value * DateUtilities.ONE_MINUTE; - break; - case RepeatControlSet.INTERVAL_WEEKS: - time += value * 7 * DateUtilities.ONE_DAY; - break; - case RepeatControlSet.INTERVAL_MONTHS: - time = DateUtilities.addCalendarMonthsToUnixtime(time, 1); - break; - case RepeatControlSet.INTERVAL_YEARS: - time = DateUtilities.addCalendarMonthsToUnixtime(time, 12); - break; + switch (snoozeUnits.getSelectedItemPosition()) { + case RepeatControlSet.INTERVAL_DAYS: + time += value * DateUtilities.ONE_DAY; + break; + case RepeatControlSet.INTERVAL_HOURS: + time += value * DateUtilities.ONE_HOUR; + break; + case RepeatControlSet.INTERVAL_MINUTES: + time += value * DateUtilities.ONE_MINUTE; + break; + case RepeatControlSet.INTERVAL_WEEKS: + time += value * 7 * DateUtilities.ONE_DAY; + break; + case RepeatControlSet.INTERVAL_MONTHS: + time = DateUtilities.addCalendarMonthsToUnixtime(time, 1); + break; + case RepeatControlSet.INTERVAL_YEARS: + time = DateUtilities.addCalendarMonthsToUnixtime(time, 12); + break; } snoozeCallback.snoozeForTime(time); @@ -147,7 +148,7 @@ public class NotificationFragment extends TaskListFragment { * Snooze and re-trigger this alarm */ public static void snooze(Activity activity, OnTimeSetListener onTimeSet, SnoozeCallback snoozeCallback) { - if(Preferences.getBoolean(R.string.p_rmd_snooze_dialog, false)) { + if (Preferences.getBoolean(R.string.p_rmd_snooze_dialog, false)) { Date now = new Date(); now.setHours(now.getHours() + 1); int hour = now.getHours(); @@ -159,11 +160,11 @@ public class NotificationFragment extends TaskListFragment { } else { SnoozeDialog sd = new SnoozeDialog(activity, snoozeCallback); new AlertDialog.Builder(activity) - .setTitle(R.string.rmd_NoA_snooze) - .setView(sd) - .setPositiveButton(android.R.string.ok, sd) - .setNegativeButton(android.R.string.cancel, null) - .show().setOwnerActivity(activity); + .setTitle(R.string.rmd_NoA_snooze) + .setView(sd) + .setPositiveButton(android.R.string.ok, sd) + .setNegativeButton(android.R.string.cancel, null) + .show().setOwnerActivity(activity); } } diff --git a/astrid/plugin-src/com/todoroo/astrid/reminders/Notifications.java b/astrid/plugin-src/com/todoroo/astrid/reminders/Notifications.java index 4c7298824..40cac4b50 100644 --- a/astrid/plugin-src/com/todoroo/astrid/reminders/Notifications.java +++ b/astrid/plugin-src/com/todoroo/astrid/reminders/Notifications.java @@ -5,11 +5,6 @@ */ package com.todoroo.astrid.reminders; -import java.util.Date; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - import android.app.Notification; import android.app.PendingIntent; import android.content.BroadcastReceiver; @@ -48,15 +43,24 @@ import com.todoroo.astrid.utility.Constants; import com.todoroo.astrid.utility.Flags; import com.todoroo.astrid.voice.VoiceOutputService; +import java.util.Date; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + public class Notifications extends BroadcastReceiver { // --- constants - /** task id extra */ + /** + * task id extra + */ public static final String ID_KEY = "id"; //$NON-NLS-1$ - /** preference values */ + /** + * preference values + */ public static final int ICON_SET_PINK = 0; public static final int ICON_SET_BORING = 1; public static final int ICON_SET_ASTRID = 2; @@ -68,7 +72,9 @@ public class Notifications extends BroadcastReceiver { public static final String EXTRAS_CUSTOM_INTENT = "intent"; //$NON-NLS-1$ public static final String EXTRAS_NOTIF_ID = "notifId"; //$NON-NLS-1$ - /** notification type extra */ + /** + * notification type extra + */ public static final String EXTRAS_TYPE = "type"; //$NON-NLS-1$ public static final String EXTRAS_TITLE = "title"; //$NON-NLS-1$ public static final String EXTRAS_TEXT = "text"; //$NON-NLS-1$ @@ -106,25 +112,25 @@ public class Notifications extends BroadcastReceiver { Resources r = context.getResources(); String reminder; - if(type == ReminderService.TYPE_ALARM) + if (type == ReminderService.TYPE_ALARM) reminder = getRandomReminder(r.getStringArray(R.array.reminders_alarm)); - else if(Preferences.getBoolean(R.string.p_rmd_nagging, true)) { - if(type == ReminderService.TYPE_DUE || type == ReminderService.TYPE_OVERDUE) + else if (Preferences.getBoolean(R.string.p_rmd_nagging, true)) { + if (type == ReminderService.TYPE_DUE || type == ReminderService.TYPE_OVERDUE) reminder = getRandomReminder(r.getStringArray(R.array.reminders_due)); - else if(type == ReminderService.TYPE_SNOOZE) + else if (type == ReminderService.TYPE_SNOOZE) reminder = getRandomReminder(r.getStringArray(R.array.reminders_snooze)); else reminder = getRandomReminder(r.getStringArray(R.array.reminders)); } else reminder = ""; //$NON-NLS-1$ - synchronized(Notifications.class) { - if(notificationManager == null) + synchronized (Notifications.class) { + if (notificationManager == null) notificationManager = new AndroidNotificationManager(context); } - if(!showTaskNotification(id, type, reminder)) { - notificationManager.cancel((int)id); + if (!showTaskNotification(id, type, reminder)) { + notificationManager.cancel((int) id); } try { @@ -136,7 +142,9 @@ public class Notifications extends BroadcastReceiver { // --- notification creation - /** @return a random reminder string */ + /** + * @return a random reminder string + */ public static String getRandomReminder(String[] reminders) { int next = ReminderService.random.nextInt(reminders.length); String reminder = reminders[next]; @@ -151,8 +159,8 @@ public class Notifications extends BroadcastReceiver { Task task; try { task = taskDao.fetch(id, Task.ID, Task.TITLE, Task.HIDE_UNTIL, Task.COMPLETION_DATE, - Task.DUE_DATE, Task.DELETION_DATE, Task.REMINDER_FLAGS, Task.USER_ID); - if(task == null) + Task.DUE_DATE, Task.DELETION_DATE, Task.REMINDER_FLAGS, Task.USER_ID); + if (task == null) throw new IllegalArgumentException("cound not find item with id"); //$NON-NLS-1$ } catch (Exception e) { @@ -163,21 +171,21 @@ public class Notifications extends BroadcastReceiver { if (!Preferences.getBoolean(R.string.p_rmd_enabled, true)) return false; // you're done, or not yours - don't sound, do delete - if(task.isCompleted() || task.isDeleted() || !Task.USER_ID_SELF.equals(task.getValue(Task.USER_ID))) + if (task.isCompleted() || task.isDeleted() || !Task.USER_ID_SELF.equals(task.getValue(Task.USER_ID))) return false; // new task edit in progress - if(TextUtils.isEmpty(task.getValue(Task.TITLE))) + if (TextUtils.isEmpty(task.getValue(Task.TITLE))) return false; // it's hidden - don't sound, don't delete - if(task.isHidden() && type == ReminderService.TYPE_RANDOM) + if (task.isHidden() && type == ReminderService.TYPE_RANDOM) return true; // task due date was changed, but alarm wasn't rescheduled boolean dueInFuture = task.hasDueTime() && task.getValue(Task.DUE_DATE) > DateUtilities.now() || - !task.hasDueTime() && task.getValue(Task.DUE_DATE) - DateUtilities.now() > DateUtilities.ONE_DAY; - if((type == ReminderService.TYPE_DUE || type == ReminderService.TYPE_OVERDUE) && + !task.hasDueTime() && task.getValue(Task.DUE_DATE) - DateUtilities.now() > DateUtilities.ONE_DAY; + if ((type == ReminderService.TYPE_DUE || type == ReminderService.TYPE_OVERDUE) && (!task.hasDueDate() || dueInFuture)) return true; @@ -214,14 +222,14 @@ public class Notifications extends BroadcastReceiver { notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK); notifyIntent.putExtra(TaskListActivity.TOKEN_SOURCE, Constants.SOURCE_NOTIFICATION); - requestNotification((int)id, notifyIntent, type, title, text, ringTimes); + requestNotification((int) id, notifyIntent, type, title, text, ringTimes); return true; } private static void requestNotification(long taskId, Intent intent, int type, String title, String text, int ringTimes) { Context context = ContextManager.getContext(); Intent inAppNotify = new Intent(BROADCAST_IN_APP_NOTIFY); - inAppNotify.putExtra(EXTRAS_NOTIF_ID, (int)taskId); + inAppNotify.putExtra(EXTRAS_NOTIF_ID, (int) taskId); inAppNotify.putExtra(NotificationFragment.TOKEN_ID, taskId); inAppNotify.putExtra(EXTRAS_CUSTOM_INTENT, intent); inAppNotify.putExtra(EXTRAS_TYPE, type); @@ -229,7 +237,7 @@ public class Notifications extends BroadcastReceiver { inAppNotify.putExtra(EXTRAS_TEXT, text); inAppNotify.putExtra(EXTRAS_RING_TIMES, ringTimes); - if(forceNotificationManager) + if (forceNotificationManager) new ShowNotificationReceiver().onReceive(ContextManager.getContext(), inAppNotify); else context.sendOrderedBroadcast(inAppNotify, AstridApiConstants.PERMISSION_READ); @@ -238,8 +246,8 @@ public class Notifications extends BroadcastReceiver { /** * Receives requests to show an Astrid notification if they were not intercepted and handled * by the in-app reminders in AstridActivity. - * @author Sam * + * @author Sam */ public static class ShowNotificationReceiver extends BroadcastReceiver { @Override @@ -271,17 +279,18 @@ public class Notifications extends BroadcastReceiver { /** * Shows an Astrid notification. Pulls in ring tone and quiet hour settings * from preferences. You can make it say anything you like. + * * @param ringTimes number of times to ring (-1 = nonstop) */ public static void showNotification(int notificationId, Intent intent, int type, String title, - String text, int ringTimes) { + String text, int ringTimes) { Context context = ContextManager.getContext(); - if(notificationManager == null) + if (notificationManager == null) notificationManager = new AndroidNotificationManager(context); // don't ring multiple times if random reminder - if(type == ReminderService.TYPE_RANDOM) + if (type == ReminderService.TYPE_RANDOM) ringTimes = 1; // quiet hours? unless alarm clock @@ -292,16 +301,16 @@ public class Notifications extends BroadcastReceiver { // set up properties (name and icon) for the notification int icon; - switch(Preferences.getIntegerFromString(R.string.p_rmd_icon, + switch (Preferences.getIntegerFromString(R.string.p_rmd_icon, ICON_SET_ASTRID)) { - case ICON_SET_PINK: - icon = R.drawable.notif_pink_alarm; - break; - case ICON_SET_BORING: - icon = R.drawable.notif_boring_alarm; - break; - default: - icon = R.drawable.notif_astrid; + case ICON_SET_PINK: + icon = R.drawable.notif_pink_alarm; + break; + case ICON_SET_BORING: + icon = R.drawable.notif_boring_alarm; + break; + default: + icon = R.drawable.notif_astrid; } // create notification object @@ -312,17 +321,16 @@ public class Notifications extends BroadcastReceiver { text, pendingIntent); notification.flags |= Notification.FLAG_AUTO_CANCEL; - if(Preferences.getBoolean(R.string.p_rmd_persistent, true)) { + if (Preferences.getBoolean(R.string.p_rmd_persistent, true)) { notification.flags |= Notification.FLAG_NO_CLEAR | - Notification.FLAG_SHOW_LIGHTS; + Notification.FLAG_SHOW_LIGHTS; notification.ledOffMS = 5000; notification.ledOnMS = 700; notification.ledARGB = Color.YELLOW; - } - else + } else notification.defaults = Notification.DEFAULT_LIGHTS; - AudioManager audioManager = (AudioManager)context.getSystemService( + AudioManager audioManager = (AudioManager) context.getSystemService( Context.AUDIO_SERVICE); // detect call state @@ -345,7 +353,7 @@ public class Notifications extends BroadcastReceiver { } // insistent rings until notification is disabled - if(ringTimes < 0) { + if (ringTimes < 0) { notification.flags |= Notification.FLAG_INSISTENT; voiceReminder = false; } @@ -357,16 +365,16 @@ public class Notifications extends BroadcastReceiver { boolean soundIntervalOk = checkLastNotificationSound(); // quiet hours = no sound - if(quietHours || callState != TelephonyManager.CALL_STATE_IDLE) { + if (quietHours || callState != TelephonyManager.CALL_STATE_IDLE) { notification.sound = null; voiceReminder = false; } else { String notificationPreference = Preferences.getStringValue(R.string.p_rmd_ringtone); - if(audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) == 0) { + if (audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) == 0) { notification.sound = null; voiceReminder = false; - } else if(notificationPreference != null) { - if(notificationPreference.length() > 0 && soundIntervalOk) { + } else if (notificationPreference != null) { + if (notificationPreference.length() > 0 && soundIntervalOk) { Uri notificationSound = Uri.parse(notificationPreference); notification.sound = notificationSound; } else { @@ -378,20 +386,20 @@ public class Notifications extends BroadcastReceiver { } // quiet hours && ! due date or snooze = no vibrate - if(quietHours && !(type == ReminderService.TYPE_DUE || type == ReminderService.TYPE_SNOOZE)) { + if (quietHours && !(type == ReminderService.TYPE_DUE || type == ReminderService.TYPE_SNOOZE)) { notification.vibrate = null; - } else if(callState != TelephonyManager.CALL_STATE_IDLE) { + } else if (callState != TelephonyManager.CALL_STATE_IDLE) { notification.vibrate = null; } else { if (Preferences.getBoolean(R.string.p_rmd_vibrate, true) && audioManager.shouldVibrate(AudioManager.VIBRATE_TYPE_NOTIFICATION) && soundIntervalOk) { - notification.vibrate = new long[] {0, 1000, 500, 1000, 500, 1000}; + notification.vibrate = new long[]{0, 1000, 500, 1000, 500, 1000}; } else { notification.vibrate = null; } } - if(Constants.DEBUG) + if (Constants.DEBUG) Log.w("Astrid", "Logging notification: " + text); //$NON-NLS-1$ //$NON-NLS-2$ singleThreadVoicePool.submit(new NotificationRunnable(ringTimes, notificationId, notification, voiceReminder, @@ -415,7 +423,7 @@ public class Notifications extends BroadcastReceiver { private final String text; public NotificationRunnable(int ringTimes, int notificationId, Notification notification, boolean voiceReminder, - boolean maxOutVolume, AudioManager audioManager, int previousAlarmVolume, String text) { + boolean maxOutVolume, AudioManager audioManager, int previousAlarmVolume, String text) { this.ringTimes = ringTimes; this.notificationId = notificationId; this.notification = notification; @@ -428,16 +436,16 @@ public class Notifications extends BroadcastReceiver { @Override public void run() { - for(int i = 0; i < Math.max(ringTimes, 1); i++) { + for (int i = 0; i < Math.max(ringTimes, 1); i++) { notificationManager.notify(notificationId, notification); AndroidUtilities.sleepDeep(500); } Flags.set(Flags.REFRESH); // Forces a reload when app launches if ((voiceReminder || maxOutVolumeForMultipleRingReminders)) { AndroidUtilities.sleepDeep(2000); - for(int i = 0; i < 50; i++) { + for (int i = 0; i < 50; i++) { AndroidUtilities.sleepDeep(500); - if(audioManager.getMode() != AudioManager.MODE_RINGTONE) + if (audioManager.getMode() != AudioManager.MODE_RINGTONE) break; } try { @@ -461,13 +469,13 @@ public class Notifications extends BroadcastReceiver { public static boolean isQuietHours() { int quietHoursStart = Preferences.getIntegerFromString(R.string.p_rmd_quietStart, -1); int quietHoursEnd = Preferences.getIntegerFromString(R.string.p_rmd_quietEnd, -1); - if(quietHoursStart != -1 && quietHoursEnd != -1) { + if (quietHoursStart != -1 && quietHoursEnd != -1) { int hour = new Date().getHours(); - if(quietHoursStart <= quietHoursEnd) { - if(hour >= quietHoursStart && hour < quietHoursEnd) + if (quietHoursStart <= quietHoursEnd) { + if (hour >= quietHoursStart && hour < quietHoursEnd) return true; } else { // wrap across 24/hour boundary - if(hour >= quietHoursStart || hour < quietHoursEnd) + if (hour >= quietHoursStart || hour < quietHoursEnd) return true; } } @@ -477,18 +485,17 @@ public class Notifications extends BroadcastReceiver { /** * Schedules alarms for a single task * - * @param shouldPerformPropertyCheck - * whether to check if task has requisite properties + * @param shouldPerformPropertyCheck whether to check if task has requisite properties */ public static void cancelNotifications(long taskId) { - if(notificationManager == null) - synchronized(Notifications.class) { - if(notificationManager == null) + if (notificationManager == null) + synchronized (Notifications.class) { + if (notificationManager == null) notificationManager = new AndroidNotificationManager( ContextManager.getContext()); } - notificationManager.cancel((int)taskId); + notificationManager.cancel((int) taskId); } // --- notification manager diff --git a/astrid/plugin-src/com/todoroo/astrid/reminders/ReengagementReceiver.java b/astrid/plugin-src/com/todoroo/astrid/reminders/ReengagementReceiver.java index 306df88bf..6b8af477f 100644 --- a/astrid/plugin-src/com/todoroo/astrid/reminders/ReengagementReceiver.java +++ b/astrid/plugin-src/com/todoroo/astrid/reminders/ReengagementReceiver.java @@ -5,8 +5,6 @@ */ package com.todoroo.astrid.reminders; -import org.json.JSONObject; - import android.app.Notification; import android.app.PendingIntent; import android.content.BroadcastReceiver; @@ -37,11 +35,15 @@ import com.todoroo.astrid.service.TaskService; import com.todoroo.astrid.utility.Constants; import com.todoroo.astrid.utility.Flags; +import org.json.JSONObject; + public class ReengagementReceiver extends BroadcastReceiver { - @Autowired ActFmPreferenceService actFmPreferenceService; + @Autowired + ActFmPreferenceService actFmPreferenceService; - @Autowired TaskService taskService; + @Autowired + TaskService taskService; private static final int TASK_LIMIT = 3; @@ -112,9 +114,9 @@ public class ReengagementReceiver extends BroadcastReceiver { pendingIntent); notification.flags |= Notification.FLAG_AUTO_CANCEL; - if(Preferences.getBoolean(R.string.p_rmd_persistent, true)) { + if (Preferences.getBoolean(R.string.p_rmd_persistent, true)) { notification.flags |= Notification.FLAG_NO_CLEAR | - Notification.FLAG_SHOW_LIGHTS; + Notification.FLAG_SHOW_LIGHTS; notification.ledOffMS = 5000; notification.ledOnMS = 700; notification.ledARGB = Color.YELLOW; diff --git a/astrid/plugin-src/com/todoroo/astrid/reminders/ReengagementService.java b/astrid/plugin-src/com/todoroo/astrid/reminders/ReengagementService.java index aa4c324fc..09aa86db9 100644 --- a/astrid/plugin-src/com/todoroo/astrid/reminders/ReengagementService.java +++ b/astrid/plugin-src/com/todoroo/astrid/reminders/ReengagementService.java @@ -5,8 +5,6 @@ */ package com.todoroo.astrid.reminders; -import java.util.Date; - import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; @@ -17,6 +15,8 @@ import com.todoroo.andlib.utility.Preferences; import com.todoroo.astrid.utility.AstridPreferences; import com.todoroo.astrid.utility.Constants; +import java.util.Date; + public final class ReengagementService { private static final int REQUEST_CODE = 10; @@ -27,7 +27,7 @@ public final class ReengagementService { public static final String BROADCAST_SHOW_REENGAGEMENT = Constants.PACKAGE + ".SHOW_REENGAGEMENT"; //$NON-NLS-1$ public static void scheduleReengagementAlarm(Context context) { - AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); + AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(BROADCAST_SHOW_REENGAGEMENT); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, intent, 0); am.cancel(pendingIntent); diff --git a/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderDebugContextActions.java b/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderDebugContextActions.java index 63fdce162..3fc4dc933 100644 --- a/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderDebugContextActions.java +++ b/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderDebugContextActions.java @@ -5,8 +5,6 @@ */ package com.todoroo.astrid.reminders; -import java.util.Date; - import android.widget.Toast; import com.todoroo.andlib.service.ContextManager; @@ -15,6 +13,8 @@ import com.todoroo.astrid.data.Task; import com.todoroo.astrid.reminders.ReminderService.AlarmScheduler; import com.todoroo.astrid.utility.Constants; +import java.util.Date; + @SuppressWarnings("nls") public class ReminderDebugContextActions { @@ -32,7 +32,7 @@ public class ReminderDebugContextActions { ReminderService.getInstance().setScheduler(new AlarmScheduler() { @Override public void createAlarm(Task theTask, long time, int type) { - if(time == 0 || time == Long.MAX_VALUE) + if (time == 0 || time == Long.MAX_VALUE) return; Toast.makeText(ContextManager.getContext(), "Scheduled Alarm: " + @@ -41,7 +41,7 @@ public class ReminderDebugContextActions { } }); ReminderService.getInstance().scheduleAlarm(task); - if(ReminderService.getInstance().getScheduler() != null) + if (ReminderService.getInstance().getScheduler() != null) Toast.makeText(ContextManager.getContext(), "No alarms", Toast.LENGTH_LONG).show(); ReminderService.getInstance().setScheduler(original); } @@ -57,7 +57,7 @@ public class ReminderDebugContextActions { public void invoke(Task task) { new Notifications().showTaskNotification(task.getId(), - ReminderService.TYPE_SNOOZE, "test reminder"); + ReminderService.TYPE_SNOOZE, "test reminder"); } } diff --git a/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderDialog.java b/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderDialog.java index b4163b4eb..38b51bbf0 100644 --- a/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderDialog.java +++ b/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderDialog.java @@ -5,16 +5,6 @@ */ package com.todoroo.astrid.reminders; -import java.util.ArrayList; -import java.util.Date; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - import android.app.Activity; import android.app.Dialog; import android.app.TimePickerDialog.OnTimeSetListener; @@ -55,11 +45,20 @@ import com.todoroo.astrid.tags.TagMemberMetadata; import com.todoroo.astrid.tags.TagService; import com.todoroo.astrid.utility.ResourceDrawableCache; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.Date; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; + /** * A dialog that shows your task reminder * * @author sbosley - * */ public class ReminderDialog extends Dialog { @@ -75,7 +74,7 @@ public class ReminderDialog extends Dialog { private UserDao userDao; public ReminderDialog(final AstridActivity activity, final long taskId, - String title) { + String title) { super(activity, R.style.ReminderDialog); DependencyInjectionService.getInstance().inject(this); final SnoozeCallback dialogSnooze = new SnoozeCallback() { @@ -95,7 +94,7 @@ public class ReminderDialog extends Dialog { Date alarmTime = new Date(); alarmTime.setHours(hours); alarmTime.setMinutes(minutes); - if(alarmTime.getTime() < DateUtilities.now()) + if (alarmTime.getTime() < DateUtilities.now()) alarmTime.setDate(alarmTime.getDate() + 1); dialogSnooze.snoozeForTime(alarmTime.getTime()); } @@ -268,8 +267,8 @@ public class ReminderDialog extends Dialog { TodorooCursor users = userDao.query(Query.select(User.PROPERTIES) .where(User.UUID.in( Query.select(TagMemberMetadata.USER_UUID) - .from(TagMetadata.TABLE) - .where(TagMetadata.TAG_UUID.eq(td.getUuid()))))); + .from(TagMetadata.TABLE) + .where(TagMetadata.TAG_UUID.eq(td.getUuid()))))); try { User user = new User(); for (users.moveToFirst(); !users.isAfterLast(); users.moveToNext()) { diff --git a/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderPreferences.java b/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderPreferences.java index 38e0ca01b..d58dd5835 100644 --- a/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderPreferences.java +++ b/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderPreferences.java @@ -17,7 +17,6 @@ import com.todoroo.andlib.utility.TodorooPreferenceActivity; * Displays the preference screen for users to edit their preferences * * @author Tim Su - * */ public class ReminderPreferences extends TodorooPreferenceActivity { @@ -27,17 +26,16 @@ public class ReminderPreferences extends TodorooPreferenceActivity { } /** - * * @param resource if null, updates all resources */ @Override public void updatePreferences(Preference preference, Object value) { Resources r = getResources(); - if(r.getString(R.string.p_rmd_quietStart).equals(preference.getKey())) { - int index = AndroidUtilities.indexOf(r.getStringArray(R.array.EPr_quiet_hours_start_values), (String)value); + if (r.getString(R.string.p_rmd_quietStart).equals(preference.getKey())) { + int index = AndroidUtilities.indexOf(r.getStringArray(R.array.EPr_quiet_hours_start_values), (String) value); Preference endPreference = findPreference(getString(R.string.p_rmd_quietEnd)); - if(index <= 0) { + if (index <= 0) { preference.setSummary(r.getString(R.string.rmd_EPr_quiet_hours_desc_none)); endPreference.setEnabled(false); } else { @@ -45,62 +43,62 @@ public class ReminderPreferences extends TodorooPreferenceActivity { preference.setSummary(r.getString(R.string.rmd_EPr_quiet_hours_start_desc, setting)); endPreference.setEnabled(true); } - } else if(r.getString(R.string.p_rmd_quietEnd).equals(preference.getKey())) { - int index = AndroidUtilities.indexOf(r.getStringArray(R.array.EPr_quiet_hours_end_values), (String)value); + } else if (r.getString(R.string.p_rmd_quietEnd).equals(preference.getKey())) { + int index = AndroidUtilities.indexOf(r.getStringArray(R.array.EPr_quiet_hours_end_values), (String) value); int quietHoursStart = Preferences.getIntegerFromString(R.string.p_rmd_quietStart, -1); - if(index == -1 || quietHoursStart == -1) + if (index == -1 || quietHoursStart == -1) preference.setSummary(r.getString(R.string.rmd_EPr_quiet_hours_desc_none)); else { String setting = r.getStringArray(R.array.EPr_quiet_hours_end)[index]; preference.setSummary(r.getString(R.string.rmd_EPr_quiet_hours_end_desc, setting)); } - } else if(r.getString(R.string.p_rmd_time).equals(preference.getKey())) { - int index = AndroidUtilities.indexOf(r.getStringArray(R.array.EPr_rmd_time_values), (String)value); + } else if (r.getString(R.string.p_rmd_time).equals(preference.getKey())) { + int index = AndroidUtilities.indexOf(r.getStringArray(R.array.EPr_rmd_time_values), (String) value); if (index != -1 && index < r.getStringArray(R.array.EPr_rmd_time).length) { // FIXME this does not fix the underlying cause of the ArrayIndexOutofBoundsException // https://www.crittercism.com/developers/crash-details/e0886dbfcf9e78a21d9f2e2a385c4c13e2f6ad2132ac24a3fa811144 String setting = r.getStringArray(R.array.EPr_rmd_time)[index]; preference.setSummary(r.getString(R.string.rmd_EPr_rmd_time_desc, setting)); } - } else if(r.getString(R.string.p_rmd_ringtone).equals(preference.getKey())) { - if(value == null || "content://settings/system/notification_sound".equals(value)) //$NON-NLS-1$ + } else if (r.getString(R.string.p_rmd_ringtone).equals(preference.getKey())) { + if (value == null || "content://settings/system/notification_sound".equals(value)) //$NON-NLS-1$ preference.setSummary(r.getString(R.string.rmd_EPr_ringtone_desc_default)); - else if("".equals(value)) //$NON-NLS-1$ + else if ("".equals(value)) //$NON-NLS-1$ preference.setSummary(r.getString(R.string.rmd_EPr_ringtone_desc_silent)); else preference.setSummary(r.getString(R.string.rmd_EPr_ringtone_desc_custom)); - } else if(r.getString(R.string.p_rmd_persistent).equals(preference.getKey())) { - if((Boolean)value) + } else if (r.getString(R.string.p_rmd_persistent).equals(preference.getKey())) { + if ((Boolean) value) preference.setSummary(r.getString(R.string.rmd_EPr_persistent_desc_true)); else preference.setSummary(r.getString(R.string.rmd_EPr_persistent_desc_false)); - } else if(r.getString(R.string.p_rmd_maxvolume).equals(preference.getKey())) { - if((Boolean)value) + } else if (r.getString(R.string.p_rmd_maxvolume).equals(preference.getKey())) { + if ((Boolean) value) preference.setSummary(r.getString(R.string.rmd_EPr_multiple_maxvolume_desc_true)); else preference.setSummary(r.getString(R.string.rmd_EPr_multiple_maxvolume_desc_false)); - } else if(r.getString(R.string.p_rmd_vibrate).equals(preference.getKey())) { - if((Boolean)value) + } else if (r.getString(R.string.p_rmd_vibrate).equals(preference.getKey())) { + if ((Boolean) value) preference.setSummary(r.getString(R.string.rmd_EPr_vibrate_desc_true)); else preference.setSummary(r.getString(R.string.rmd_EPr_vibrate_desc_false)); - } else if(r.getString(R.string.p_rmd_nagging).equals(preference.getKey())) { - if((Boolean)value) + } else if (r.getString(R.string.p_rmd_nagging).equals(preference.getKey())) { + if ((Boolean) value) preference.setSummary(r.getString(R.string.rmd_EPr_nagging_desc_true)); else preference.setSummary(r.getString(R.string.rmd_EPr_nagging_desc_false)); - } else if(r.getString(R.string.p_rmd_snooze_dialog).equals(preference.getKey())) { - if(value == null || ((Boolean)value) == true) + } else if (r.getString(R.string.p_rmd_snooze_dialog).equals(preference.getKey())) { + if (value == null || ((Boolean) value) == true) preference.setSummary(r.getString(R.string.rmd_EPr_snooze_dialog_desc_true)); else preference.setSummary(r.getString(R.string.rmd_EPr_snooze_dialog_desc_false)); } else if (r.getString(R.string.p_rmd_enabled).equals(preference.getKey())) { - if((Boolean)value) + if ((Boolean) value) preference.setSummary(R.string.rmd_EPr_enabled_desc_true); else preference.setSummary(R.string.rmd_EPr_enabled_desc_false); } else if (r.getString(R.string.p_rmd_social).equals(preference.getKey())) { - if ((Boolean)value) + if ((Boolean) value) preference.setSummary(R.string.rmd_EPr_social_summary_enabled); else preference.setSummary(R.string.rmd_EPr_social_summary_disabled); diff --git a/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderSchedulingService.java b/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderSchedulingService.java index ee2f4549c..b8a6c717a 100644 --- a/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderSchedulingService.java +++ b/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderSchedulingService.java @@ -18,11 +18,12 @@ import com.todoroo.astrid.alarms.AlarmService; * Schedules reminders in the background to prevent ANR's * * @author Tim Su - * */ public class ReminderSchedulingService extends Service { - /** Receive the alarm - start the synchronize service! */ + /** + * Receive the alarm - start the synchronize service! + */ @Override public int onStartCommand(Intent intent, int flags, int startId) { ContextManager.setContext(ReminderSchedulingService.this); @@ -49,6 +50,7 @@ public class ReminderSchedulingService extends Service { Log.e("reminder-scheduling", "reminder-startup", e); } } + private void delaySchedulingToPreventANRs() { AndroidUtilities.sleepDeep(5000L); } diff --git a/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderService.java b/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderService.java index a778372c2..561cc384f 100644 --- a/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderService.java +++ b/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderService.java @@ -5,9 +5,6 @@ */ package com.todoroo.astrid.reminders; -import java.util.Date; -import java.util.Random; - import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; @@ -32,39 +29,51 @@ import com.todoroo.astrid.dao.TaskDao.TaskCriteria; import com.todoroo.astrid.data.Task; import com.todoroo.astrid.utility.Constants; +import java.util.Date; +import java.util.Random; + /** * Data service for reminders * * @author Tim Su - * */ -public final class ReminderService { +public final class ReminderService { // --- constants - public static final Property[] NOTIFICATION_PROPERTIES = new Property[] { - Task.ID, - Task.CREATION_DATE, - Task.COMPLETION_DATE, - Task.DELETION_DATE, - Task.DUE_DATE, - Task.REMINDER_FLAGS, - Task.REMINDER_PERIOD, - Task.REMINDER_LAST, - Task.REMINDER_SNOOZE, - Task.IMPORTANCE + public static final Property[] NOTIFICATION_PROPERTIES = new Property[]{ + Task.ID, + Task.CREATION_DATE, + Task.COMPLETION_DATE, + Task.DELETION_DATE, + Task.DUE_DATE, + Task.REMINDER_FLAGS, + Task.REMINDER_PERIOD, + Task.REMINDER_LAST, + Task.REMINDER_SNOOZE, + Task.IMPORTANCE }; - /** flag for due date reminder */ + /** + * flag for due date reminder + */ public static final int TYPE_DUE = 0; - /** flag for overdue reminder */ + /** + * flag for overdue reminder + */ public static final int TYPE_OVERDUE = 1; - /** flag for random reminder */ + /** + * flag for random reminder + */ public static final int TYPE_RANDOM = 2; - /** flag for a snoozed reminder */ + /** + * flag for a snoozed reminder + */ public static final int TYPE_SNOOZE = 3; - /** flag for an alarm reminder */ + /** + * flag for an alarm reminder + */ public static final int TYPE_ALARM = 4; static final Random random = new Random(); @@ -88,7 +97,7 @@ public final class ReminderService { private static ReminderService instance = null; public static synchronized ReminderService getInstance() { - if(instance == null) + if (instance == null) instance = new ReminderService(); return instance; } @@ -97,9 +106,11 @@ public final class ReminderService { private static boolean preferencesInitialized = false; - /** Set preference defaults, if unset. called at startup */ + /** + * Set preference defaults, if unset. called at startup + */ public void setPreferenceDefaults() { - if(preferencesInitialized) + if (preferencesInitialized) return; Context context = ContextManager.getContext(); @@ -128,7 +139,7 @@ public final class ReminderService { try { Task task = new Task(); now = DateUtilities.now(); // Before mass scheduling, initialize now variable - for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { + for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { task.readFromCursor(cursor); scheduleAlarm(task, false); } @@ -149,6 +160,7 @@ public final class ReminderService { /** * Schedules alarms for a single task + * * @param task */ public void scheduleAlarm(Task task) { @@ -169,19 +181,18 @@ public final class ReminderService { /** * Schedules alarms for a single task * - * @param shouldPerformPropertyCheck - * whether to check if task has requisite properties + * @param shouldPerformPropertyCheck whether to check if task has requisite properties */ private void scheduleAlarm(Task task, boolean shouldPerformPropertyCheck) { - if(task == null || !task.isSaved()) + if (task == null || !task.isSaved()) return; // read data if necessary - if(shouldPerformPropertyCheck) { - for(Property property : NOTIFICATION_PROPERTIES) { - if(!task.containsValue(property)) { + if (shouldPerformPropertyCheck) { + for (Property property : NOTIFICATION_PROPERTIES) { + if (!task.containsValue(property)) { task = taskDao.fetch(task.getId(), NOTIFICATION_PROPERTIES); - if(task == null) + if (task == null) return; break; } @@ -191,7 +202,7 @@ public final class ReminderService { // Make sure no alarms are scheduled other than the next one. When that one is shown, it // will schedule the next one after it, and so on and so forth. clearAllAlarms(task); - if(task.isCompleted() || task.isDeleted() || !Task.USER_ID_SELF.equals(task.getValue(Task.USER_ID))) { + if (task.isCompleted() || task.isDeleted() || !Task.USER_ID_SELF.equals(task.getValue(Task.USER_ID))) { return; } @@ -216,30 +227,26 @@ public final class ReminderService { } // if random reminders are too close to due date, favor due date - if(whenRandom != NO_ALARM && whenDueDate - whenRandom < DateUtilities.ONE_DAY) + if (whenRandom != NO_ALARM && whenDueDate - whenRandom < DateUtilities.ONE_DAY) whenRandom = NO_ALARM; // snooze trumps all - if(whenSnooze != NO_ALARM) { + if (whenSnooze != NO_ALARM) { scheduler.createAlarm(task, whenSnooze, TYPE_SNOOZE); - } - else if(whenRandom < whenDueDate && whenRandom < whenOverdue) { + } else if (whenRandom < whenDueDate && whenRandom < whenOverdue) { scheduler.createAlarm(task, whenRandom, TYPE_RANDOM); - } - else if(whenDueDate < whenOverdue) { + } else if (whenDueDate < whenOverdue) { scheduler.createAlarm(task, whenDueDate, TYPE_DUE); - } - else if(whenOverdue != NO_ALARM) { + } else if (whenOverdue != NO_ALARM) { scheduler.createAlarm(task, whenOverdue, TYPE_OVERDUE); - } - else { + } else { scheduler.createAlarm(task, 0, 0); } } /** * Calculate the next alarm time for snooze. - *

    + *

    * Pretty simple - if a snooze time is in the future, we use that. If it * has already passed, we do nothing. * @@ -247,14 +254,14 @@ public final class ReminderService { * @return */ private long calculateNextSnoozeReminder(Task task) { - if(task.getValue(Task.REMINDER_SNOOZE) > DateUtilities.now()) + if (task.getValue(Task.REMINDER_SNOOZE) > DateUtilities.now()) return task.getValue(Task.REMINDER_SNOOZE); return NO_ALARM; } /** * Calculate the next alarm time for overdue reminders. - *

    + *

    * We schedule an alarm for after the due date (which could be in the past), * with the exception that if a reminder was recently issued, we move * the alarm time to the near future. @@ -263,8 +270,8 @@ public final class ReminderService { * @return */ private long calculateNextOverdueReminder(Task task) { - // Uses getNowValue() instead of DateUtilities.now() - if(task.hasDueDate() && task.getFlag(Task.REMINDER_FLAGS, Task.NOTIFY_AFTER_DEADLINE)) { + // Uses getNowValue() instead of DateUtilities.now() + if (task.hasDueDate() && task.getFlag(Task.REMINDER_FLAGS, Task.NOTIFY_AFTER_DEADLINE)) { Date due = new Date(task.getValue(Task.DUE_DATE)); if (!task.hasDueTime()) { due.setHours(23); @@ -274,14 +281,14 @@ public final class ReminderService { long dueDateForOverdue = due.getTime(); long lastReminder = task.getValue(Task.REMINDER_LAST); - if(dueDateForOverdue > getNowValue()) - return dueDateForOverdue + (long)((0.5f + 2f * random.nextFloat()) * DateUtilities.ONE_HOUR); + if (dueDateForOverdue > getNowValue()) + return dueDateForOverdue + (long) ((0.5f + 2f * random.nextFloat()) * DateUtilities.ONE_HOUR); - if(lastReminder < dueDateForOverdue) + if (lastReminder < dueDateForOverdue) return getNowValue(); - if(getNowValue() - lastReminder < 6 * DateUtilities.ONE_HOUR) - return getNowValue() + (long)((2.0f + + if (getNowValue() - lastReminder < 6 * DateUtilities.ONE_HOUR) + return getNowValue() + (long) ((2.0f + task.getValue(Task.IMPORTANCE) + 6f * random.nextFloat()) * DateUtilities.ONE_HOUR); @@ -292,11 +299,11 @@ public final class ReminderService { /** * Calculate the next alarm time for due date reminders. - *

    + *

    * This alarm always returns the due date, and is triggered if * the last reminder time occurred before the due date. This means it is * possible to return due dates in the past. - *

    + *

    * If the date was indicated to not have a due time, we read from * preferences and assign a time. * @@ -305,13 +312,13 @@ public final class ReminderService { */ private long calculateNextDueDateReminder(Task task) { // Uses getNowValue() instead of DateUtilities.now() - if(task.hasDueDate() && task.getFlag(Task.REMINDER_FLAGS, Task.NOTIFY_AT_DEADLINE)) { + if (task.hasDueDate() && task.getFlag(Task.REMINDER_FLAGS, Task.NOTIFY_AT_DEADLINE)) { long dueDate = task.getValue(Task.DUE_DATE); long lastReminder = task.getValue(Task.REMINDER_LAST); long dueDateAlarm = NO_ALARM; - if(task.hasDueTime()) + if (task.hasDueTime()) // return due date straight up dueDateAlarm = dueDate; else if (DateUtilities.now() > lastReminder + DateUtilities.ONE_DAY) { @@ -344,10 +351,10 @@ public final class ReminderService { // int periodDivFactor = 4; - if(quietHoursStart != -1 && quietHoursEnd != -1) { + if (quietHoursStart != -1 && quietHoursEnd != -1) { int hour = new Date().getHours(); - if(quietHoursStart <= quietHoursEnd) { - if(hour >= quietHoursStart && hour < quietHoursEnd) { + if (quietHoursStart <= quietHoursEnd) { + if (hour >= quietHoursStart && hour < quietHoursEnd) { // its quiet now, quietHoursEnd is 23 max, // so put the default reminder to the end of the quiethours date.setHours(quietHoursEnd); @@ -358,16 +365,16 @@ public final class ReminderService { long millisAfterQuiet = dueDate - quietHoursEndDate.getTime(); // if there is more time after quiethours today, select quiethours-end for reminder - if (millisAfterQuiet > (millisToQuiet / ((float)(1-(1/periodDivFactor))) )) + if (millisAfterQuiet > (millisToQuiet / ((float) (1 - (1 / periodDivFactor))))) dueDateAlarm = quietHoursEndDate.getTime(); else - dueDateAlarm = getNowValue() + (long)(millisToQuiet / periodDivFactor); + dueDateAlarm = getNowValue() + (long) (millisToQuiet / periodDivFactor); } else { // after quietHours, reuse dueDate for end of day - dueDateAlarm = getNowValue() + (long)(millisToEndOfDay / periodDivFactor); + dueDateAlarm = getNowValue() + (long) (millisToEndOfDay / periodDivFactor); } } else { // wrap across 24/hour boundary - if(hour >= quietHoursStart) { + if (hour >= quietHoursStart) { // do nothing for the end of day, dont let it even vibrate dueDateAlarm = NO_ALARM; } else if (hour < quietHoursEnd) { @@ -376,20 +383,20 @@ public final class ReminderService { } else { // quietHours didnt start yet millisToQuiet = quietHoursStartDate.getTime() - getNowValue(); - dueDateAlarm = getNowValue() + (long)(millisToQuiet / periodDivFactor); + dueDateAlarm = getNowValue() + (long) (millisToQuiet / periodDivFactor); } } } else { // Quiet hours not activated, simply schedule the reminder on 1/periodDivFactor towards the end of day - dueDateAlarm = getNowValue() + (long)(millisToEndOfDay / periodDivFactor); + dueDateAlarm = getNowValue() + (long) (millisToEndOfDay / periodDivFactor); } - if(dueDate > getNowValue() && dueDateAlarm < getNowValue()) + if (dueDate > getNowValue() && dueDateAlarm < getNowValue()) dueDateAlarm = dueDate; } } - if(lastReminder > dueDateAlarm) + if (lastReminder > dueDateAlarm) return NO_ALARM; return dueDateAlarm; @@ -399,7 +406,7 @@ public final class ReminderService { /** * Calculate the next alarm time for random reminders. - *

    + *

    * We take the last reminder time and add approximately the reminder * period. If it's still in the past, we set it to some time in the near * future. @@ -409,16 +416,16 @@ public final class ReminderService { */ private long calculateNextRandomReminder(Task task) { long reminderPeriod = task.getValue(Task.REMINDER_PERIOD); - if((reminderPeriod) > 0) { + if ((reminderPeriod) > 0) { long when = task.getValue(Task.REMINDER_LAST); - if(when == 0) + if (when == 0) when = task.getValue(Task.CREATION_DATE); - when += (long)(reminderPeriod * (0.85f + 0.3f * random.nextFloat())); + when += (long) (reminderPeriod * (0.85f + 0.3f * random.nextFloat())); - if(when < DateUtilities.now()) { - when = DateUtilities.now() + (long)((0.5f + + if (when < DateUtilities.now()) { + when = DateUtilities.now() + (long) ((0.5f + 6 * random.nextFloat()) * DateUtilities.ONE_HOUR); } @@ -455,7 +462,7 @@ public final class ReminderService { */ @SuppressWarnings("nls") public void createAlarm(Task task, long time, int type) { - if(task.getId() == Task.NO_ID) + if (task.getId() == Task.NO_ID) return; Context context = ContextManager.getContext(); Intent intent = new Intent(context, Notifications.class); @@ -473,18 +480,18 @@ public final class ReminderService { } catch (Exception e) { requestCode = type; } - AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); + AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, requestCode, intent, 0); if (time == 0 || time == NO_ALARM) am.cancel(pendingIntent); else { - if(time < DateUtilities.now()) + if (time < DateUtilities.now()) time = DateUtilities.now() + 5000L; - if(Constants.DEBUG) - Log.e("Astrid", "Reminder set for " + new Date(time)+" for (\""+task.getValue(Task.TITLE)+"\" (" + task.getId() + "), " + type +")"); + if (Constants.DEBUG) + Log.e("Astrid", "Reminder set for " + new Date(time) + " for (\"" + task.getValue(Task.TITLE) + "\" (" + task.getId() + "), " + type + ")"); am.set(AlarmManager.RTC_WAKEUP, time, pendingIntent); } } @@ -494,6 +501,7 @@ public final class ReminderService { /** * Gets a listing of all tasks that are active & + * * @param properties * @return todoroo cursor. PLEASE CLOSE THIS CURSOR! */ diff --git a/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderStartupReceiver.java b/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderStartupReceiver.java index 9d8976686..ce8507833 100644 --- a/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderStartupReceiver.java +++ b/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderStartupReceiver.java @@ -16,7 +16,6 @@ import com.todoroo.astrid.service.AstridDependencyInjector; * Service which handles jobs that need to be run when phone boots * * @author Tim Su - * */ public class ReminderStartupReceiver extends BroadcastReceiver { diff --git a/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatControlSet.java b/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatControlSet.java index a6625b9a5..b7ff551dc 100644 --- a/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatControlSet.java +++ b/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatControlSet.java @@ -5,13 +5,6 @@ */ package com.todoroo.astrid.repeats; -import java.text.DateFormatSymbols; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.LinkedList; -import java.util.List; - import android.app.Activity; import android.app.Dialog; import android.content.DialogInterface; @@ -50,11 +43,17 @@ import com.todoroo.astrid.ui.NumberPickerDialog; import com.todoroo.astrid.ui.NumberPickerDialog.OnNumberPickedListener; import com.todoroo.astrid.ui.PopupControlSet; +import java.text.DateFormatSymbols; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.LinkedList; +import java.util.List; + /** * Control Set for managing repeats * * @author Tim Su - * */ public class RepeatControlSet extends PopupControlSet { @@ -103,7 +102,9 @@ public class RepeatControlSet extends PopupControlSet { DependencyInjectionService.getInstance().inject(this); } - /** Set up the repeat value button */ + /** + * Set up the repeat value button + */ private void setRepeatValue(int newValue) { repeatValue = newValue; value.setText(activity.getString(R.string.repeat_every, newValue)); @@ -120,17 +121,17 @@ public class RepeatControlSet extends PopupControlSet { protected void repeatValueClick() { int dialogValue = repeatValue; - if(dialogValue == 0) + if (dialogValue == 0) dialogValue = 1; new NumberPickerDialog(activity, new OnNumberPickedListener() { @Override public void onNumberPicked(NumberPicker view, - int number) { + int number) { setRepeatValue(number); } }, activity.getResources().getString(R.string.repeat_interval_prompt), - dialogValue, 1, 1, 365).show(); + dialogValue, 1, 1, 365).show(); } private void repeatUntilClick() { @@ -165,39 +166,39 @@ public class RepeatControlSet extends PopupControlSet { public void readFromTask(Task task) { super.readFromTask(task); recurrence = model.sanitizedRecurrence(); - if(recurrence == null) + if (recurrence == null) recurrence = ""; repeatUntilValue = model.getValue(Task.REPEAT_UNTIL); - if(recurrence.length() > 0) { + if (recurrence.length() > 0) { try { RRule rrule = new RRule(recurrence); repeatValue = rrule.getInterval(); - switch(rrule.getFreq()) { - case DAILY: - intervalValue = INTERVAL_DAYS; - break; - case WEEKLY: { - intervalValue = INTERVAL_WEEKS; - break; - } - case MONTHLY: - intervalValue = INTERVAL_MONTHS; - break; - case HOURLY: - intervalValue = INTERVAL_HOURS; - break; - case MINUTELY: - intervalValue = INTERVAL_MINUTES; - break; - case YEARLY: - intervalValue = INTERVAL_YEARS; - break; - default: - // an unhandled recurrence - exceptionService.reportError("repeat-unhandled-rule", //$NON-NLS-1$ - new Exception("Unhandled rrule frequency: " + recurrence)); + switch (rrule.getFreq()) { + case DAILY: + intervalValue = INTERVAL_DAYS; + break; + case WEEKLY: { + intervalValue = INTERVAL_WEEKS; + break; + } + case MONTHLY: + intervalValue = INTERVAL_MONTHS; + break; + case HOURLY: + intervalValue = INTERVAL_HOURS; + break; + case MINUTELY: + intervalValue = INTERVAL_MINUTES; + break; + case YEARLY: + intervalValue = INTERVAL_YEARS; + break; + default: + // an unhandled recurrence + exceptionService.reportError("repeat-unhandled-rule", //$NON-NLS-1$ + new Exception("Unhandled rrule frequency: " + recurrence)); } } catch (Exception e) { // invalid RRULE @@ -213,16 +214,16 @@ public class RepeatControlSet extends PopupControlSet { @Override protected void readFromTaskOnInitialize() { Date date; - if(model.getValue(Task.DUE_DATE) != 0) { + if (model.getValue(Task.DUE_DATE) != 0) { date = new Date(model.getValue(Task.DUE_DATE)); int dayOfWeek = date.getDay(); - for(int i = 0; i < 7; i++) + for (int i = 0; i < 7; i++) daysOfWeek[i].setChecked(i == dayOfWeek); } // read recurrence rule - if(recurrence.length() > 0) { + if (recurrence.length() > 0) { try { RRule rrule = new RRule(recurrence); @@ -231,12 +232,12 @@ public class RepeatControlSet extends PopupControlSet { interval.setSelection(intervalValue); // clear all day of week checks, then update them - for(int i = 0; i < 7; i++) + for (int i = 0; i < 7; i++) daysOfWeek[i].setChecked(false); - for(WeekdayNum day : rrule.getByDay()) { - for(int i = 0; i < 7; i++) - if(daysOfWeek[i].getTag().equals(day.wday)) + for (WeekdayNum day : rrule.getByDay()) { + for (int i = 0; i < 7; i++) + if (daysOfWeek[i].getTag().equals(day.wday)) daysOfWeek[i].setChecked(true); } @@ -251,7 +252,7 @@ public class RepeatControlSet extends PopupControlSet { doRepeat = recurrence.length() > 0; // read flag - if(model.repeatAfterCompletion()) + if (model.repeatAfterCompletion()) type.setSelection(TYPE_COMPLETION_DATE); else type.setSelection(TYPE_DUE_DATE); @@ -273,9 +274,9 @@ public class RepeatControlSet extends PopupControlSet { DateFormatSymbols dfs = new DateFormatSymbols(); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek()); - LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1.0f/14); - LinearLayout.LayoutParams textLp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1.0f/14); - for(int i = 0; i < 7; i++) { + LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1.0f / 14); + LinearLayout.LayoutParams textLp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1.0f / 14); + for (int i = 0; i < 7; i++) { CheckBox checkBox = new CheckBox(activity); int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); checkBox.setPadding(0, 0, 0, 0); @@ -327,41 +328,41 @@ public class RepeatControlSet extends PopupControlSet { @Override protected String writeToModelAfterInitialized(Task task) { String result; - if(!doRepeat) + if (!doRepeat) result = ""; //$NON-NLS-1$ else { - if(TextUtils.isEmpty(task.getValue(Task.RECURRENCE))) { + if (TextUtils.isEmpty(task.getValue(Task.RECURRENCE))) { StatisticsService.reportEvent(StatisticsConstants.REPEAT_TASK_CREATE); } RRule rrule = new RRule(); rrule.setInterval(repeatValue); - switch(interval.getSelectedItemPosition()) { - case INTERVAL_DAYS: - rrule.setFreq(Frequency.DAILY); - break; - case INTERVAL_WEEKS: { - rrule.setFreq(Frequency.WEEKLY); - - ArrayList days = new ArrayList(); - for(int i = 0; i < daysOfWeek.length; i++) - if(daysOfWeek[i].isChecked()) - days.add(new WeekdayNum(0, (Weekday)daysOfWeek[i].getTag())); - rrule.setByDay(days); - break; - } - case INTERVAL_MONTHS: - rrule.setFreq(Frequency.MONTHLY); - break; - case INTERVAL_HOURS: - rrule.setFreq(Frequency.HOURLY); - break; - case INTERVAL_MINUTES: - rrule.setFreq(Frequency.MINUTELY); - break; - case INTERVAL_YEARS: - rrule.setFreq(Frequency.YEARLY); - break; + switch (interval.getSelectedItemPosition()) { + case INTERVAL_DAYS: + rrule.setFreq(Frequency.DAILY); + break; + case INTERVAL_WEEKS: { + rrule.setFreq(Frequency.WEEKLY); + + ArrayList days = new ArrayList(); + for (int i = 0; i < daysOfWeek.length; i++) + if (daysOfWeek[i].isChecked()) + days.add(new WeekdayNum(0, (Weekday) daysOfWeek[i].getTag())); + rrule.setByDay(days); + break; + } + case INTERVAL_MONTHS: + rrule.setFreq(Frequency.MONTHLY); + break; + case INTERVAL_HOURS: + rrule.setFreq(Frequency.HOURLY); + break; + case INTERVAL_MINUTES: + rrule.setFreq(Frequency.MINUTELY); + break; + case INTERVAL_YEARS: + rrule.setFreq(Frequency.YEARLY); + break; } result = rrule.toIcal(); @@ -376,7 +377,7 @@ public class RepeatControlSet extends PopupControlSet { task.setValue(Task.RECURRENCE, result); task.setValue(Task.REPEAT_UNTIL, repeatUntilValue); - if(task.repeatAfterCompletion()) + if (task.repeatAfterCompletion()) type.setSelection(1); return null; @@ -421,7 +422,7 @@ public class RepeatControlSet extends PopupControlSet { arrayResource = R.array.repeat_interval; String[] dates = activity.getResources().getStringArray( - arrayResource); + arrayResource); String date = String.format("%s %s", repeatValue, dates[intervalValue]); //$NON-NLS-1$ if (repeatUntilValue > 0) return activity.getString(R.string.repeat_detail_duedate_until, date, DateAndTimePicker.getDisplayString(activity, repeatUntilValue, false, useAbbrev, useAbbrev)); diff --git a/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatDetailExposer.java b/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatDetailExposer.java index e60771365..21bf31b53 100644 --- a/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatDetailExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatDetailExposer.java @@ -5,10 +5,6 @@ */ package com.todoroo.astrid.repeats; -import java.text.DateFormatSymbols; -import java.text.ParseException; -import java.util.List; - import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; @@ -22,11 +18,14 @@ import com.todoroo.astrid.api.AstridApiConstants; import com.todoroo.astrid.core.PluginServices; import com.todoroo.astrid.data.Task; +import java.text.DateFormatSymbols; +import java.text.ParseException; +import java.util.List; + /** * Exposes Task Detail for repeats, i.e. "Repeats every 2 days" * * @author Tim Su - * */ public class RepeatDetailExposer extends BroadcastReceiver { @@ -34,11 +33,11 @@ public class RepeatDetailExposer extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { // get tags associated with this task long taskId = intent.getLongExtra(AstridApiConstants.EXTRAS_TASK_ID, -1); - if(taskId == -1) + if (taskId == -1) return; String taskDetail = getTaskDetails(context, taskId); - if(taskDetail == null) + if (taskDetail == null) return; // transmit @@ -51,13 +50,13 @@ public class RepeatDetailExposer extends BroadcastReceiver { public String getTaskDetails(Context context, long id) { Task task = PluginServices.getTaskService().fetchById(id, Task.RECURRENCE); - if(task == null) + if (task == null) return null; Resources r = context.getResources(); String recurrence = task.sanitizedRecurrence(); - if(recurrence != null && recurrence.length() > 0) { + if (recurrence != null && recurrence.length() > 0) { RRule rrule; try { rrule = new RRule(recurrence); @@ -70,15 +69,15 @@ public class RepeatDetailExposer extends BroadcastReceiver { interval = "" + interval + ""; //$NON-NLS-1$//$NON-NLS-2$ List byDay = rrule.getByDay(); - if(rrule.getFreq() == Frequency.WEEKLY || byDay.size() != 7) { - if(byDay.size() > 0) { + if (rrule.getFreq() == Frequency.WEEKLY || byDay.size() != 7) { + if (byDay.size() > 0) { StringBuilder byDayString = new StringBuilder(); DateFormatSymbols dfs = new DateFormatSymbols(); String[] weekdays = dfs.getShortWeekdays(); - for(int i = 0; i < byDay.size(); i++) { + for (int i = 0; i < byDay.size(); i++) { byDayString.append(weekdays[byDay.get(i).wday.javaDayNum]); - if(i < byDay.size() - 1) - byDayString.append(", "); //$NON-NLS-1$ + if (i < byDay.size() - 1) + byDayString.append(", "); //$NON-NLS-1$ } interval = r.getString(R.string.repeat_detail_byday).replace("$I", //$NON-NLS-1$ interval).replace("$D", byDayString); //$NON-NLS-1$ @@ -86,7 +85,7 @@ public class RepeatDetailExposer extends BroadcastReceiver { } String detail; - if(task.repeatAfterCompletion()) + if (task.repeatAfterCompletion()) detail = context.getString(R.string.repeat_detail_completion, interval); else detail = context.getString(R.string.repeat_detail_duedate, interval); @@ -98,22 +97,28 @@ public class RepeatDetailExposer extends BroadcastReceiver { private String getIntervalFor(Resources r, RRule rrule) { int plural; - switch(rrule.getFreq()) { - case MINUTELY: - plural = R.plurals.DUt_minutes; break; - case HOURLY: - plural = R.plurals.DUt_hours; break; - case DAILY: - plural = R.plurals.DUt_days; break; - case WEEKLY: - plural = R.plurals.DUt_weeks; break; - case MONTHLY: - plural = R.plurals.DUt_months; break; - case YEARLY: - plural = R.plurals.DUt_years; break; - default: - // not designed to be used, only a fail-safe - return rrule.getInterval() + "-" + rrule.getFreq().name(); //$NON-NLS-1$ + switch (rrule.getFreq()) { + case MINUTELY: + plural = R.plurals.DUt_minutes; + break; + case HOURLY: + plural = R.plurals.DUt_hours; + break; + case DAILY: + plural = R.plurals.DUt_days; + break; + case WEEKLY: + plural = R.plurals.DUt_weeks; + break; + case MONTHLY: + plural = R.plurals.DUt_months; + break; + case YEARLY: + plural = R.plurals.DUt_years; + break; + default: + // not designed to be used, only a fail-safe + return rrule.getInterval() + "-" + rrule.getFreq().name(); //$NON-NLS-1$ } return r.getQuantityString(plural, rrule.getInterval(), rrule.getInterval()); diff --git a/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatTaskCompleteListener.java b/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatTaskCompleteListener.java index 500e2c981..a7b6b91dd 100644 --- a/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatTaskCompleteListener.java +++ b/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatTaskCompleteListener.java @@ -5,14 +5,6 @@ */ package com.todoroo.astrid.repeats; -import java.text.ParseException; -import java.util.Calendar; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.List; -import java.util.TimeZone; - import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; @@ -40,30 +32,39 @@ import com.todoroo.astrid.service.StatisticsService; import com.todoroo.astrid.service.TaskService; import com.todoroo.astrid.utility.Flags; +import java.text.ParseException; +import java.util.Calendar; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.List; +import java.util.TimeZone; + public class RepeatTaskCompleteListener extends BroadcastReceiver { - @Autowired ActFmPreferenceService actFmPreferenceService; + @Autowired + ActFmPreferenceService actFmPreferenceService; @Override public void onReceive(Context context, Intent intent) { ContextManager.setContext(context); DependencyInjectionService.getInstance().inject(this); long taskId = intent.getLongExtra(AstridApiConstants.EXTRAS_TASK_ID, -1); - if(taskId == -1) + if (taskId == -1) return; Task task = PluginServices.getTaskService().fetchById(taskId, Task.PROPERTIES); - if(task == null || !task.isCompleted()) + if (task == null || !task.isCompleted()) return; String recurrence = task.sanitizedRecurrence(); boolean repeatAfterCompletion = task.repeatAfterCompletion(); - if(recurrence != null && recurrence.length() > 0) { + if (recurrence != null && recurrence.length() > 0) { long newDueDate; try { newDueDate = computeNextDueDate(task, recurrence, repeatAfterCompletion); - if(newDueDate == -1) + if (newDueDate == -1) return; } catch (ParseException e) { PluginServices.getExceptionService().reportError("repeat-parse", e); //$NON-NLS-1$ @@ -101,7 +102,7 @@ public class RepeatTaskCompleteListener extends BroadcastReceiver { public static void rescheduleTask(Task task, long newDueDate) { long hideUntil = task.getValue(Task.HIDE_UNTIL); - if(hideUntil > 0 && task.getValue(Task.DUE_DATE) > 0) { + if (hideUntil > 0 && task.getValue(Task.DUE_DATE) > 0) { hideUntil += newDueDate - task.getValue(Task.DUE_DATE); } @@ -115,7 +116,9 @@ public class RepeatTaskCompleteListener extends BroadcastReceiver { PluginServices.getTaskService().save(task); } - /** Compute next due date */ + /** + * Compute next due date + */ public static long computeNextDueDate(Task task, String recurrence, boolean repeatAfterCompletion) throws ParseException { RRule rrule = initRRule(recurrence); @@ -123,9 +126,9 @@ public class RepeatTaskCompleteListener extends BroadcastReceiver { Date original = setUpStartDate(task, repeatAfterCompletion, rrule.getFreq()); DateValue startDateAsDV = setUpStartDateAsDV(task, original); - if(rrule.getFreq() == Frequency.HOURLY || rrule.getFreq() == Frequency.MINUTELY) + if (rrule.getFreq() == Frequency.HOURLY || rrule.getFreq() == Frequency.MINUTELY) return handleSubdayRepeat(original, rrule); - else if(rrule.getFreq() == Frequency.WEEKLY && rrule.getByDay().size() > 0 && repeatAfterCompletion) + else if (rrule.getFreq() == Frequency.WEEKLY && rrule.getByDay().size() > 0 && repeatAfterCompletion) return handleWeeklyRepeatAfterComplete(rrule, original, task.hasDueTime()); else if (rrule.getFreq() == Frequency.MONTHLY) return handleMonthlyRepeat(original, startDateAsDV, task.hasDueTime(), rrule); @@ -134,7 +137,7 @@ public class RepeatTaskCompleteListener extends BroadcastReceiver { } private static long handleWeeklyRepeatAfterComplete(RRule rrule, Date original, - boolean hasDueTime) { + boolean hasDueTime) { List byDay = rrule.getByDay(); long newDate = original.getTime(); newDate += DateUtilities.ONE_WEEK * (rrule.getInterval() - 1); @@ -149,7 +152,7 @@ public class RepeatTaskCompleteListener extends BroadcastReceiver { } while (date.get(Calendar.DAY_OF_WEEK) != next.wday.javaDayNum); long time = date.getTimeInMillis(); - if(hasDueTime) + if (hasDueTime) return Task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, time); else return Task.createDueDate(Task.URGENCY_SPECIFIC_DAY, time); @@ -183,7 +186,7 @@ public class RepeatTaskCompleteListener extends BroadcastReceiver { }; private static WeekdayNum findNextWeekday(List byDay, - Calendar date) { + Calendar date) { WeekdayNum next = byDay.get(0); for (int i = 0; i < byDay.size(); i++) { WeekdayNum weekday = byDay.get(i); @@ -195,34 +198,36 @@ public class RepeatTaskCompleteListener extends BroadcastReceiver { } private static long invokeRecurrence(RRule rrule, Date original, - DateValue startDateAsDV) { + DateValue startDateAsDV) { long newDueDate = -1; RecurrenceIterator iterator = RecurrenceIteratorFactory.createRecurrenceIterator(rrule, startDateAsDV, TimeZone.getDefault()); DateValue nextDate = startDateAsDV; - for(int i = 0; i < 10; i++) { // ten tries then we give up - if(!iterator.hasNext()) + for (int i = 0; i < 10; i++) { // ten tries then we give up + if (!iterator.hasNext()) return -1; nextDate = iterator.next(); - if(nextDate.compareTo(startDateAsDV) == 0) + if (nextDate.compareTo(startDateAsDV) == 0) continue; newDueDate = buildNewDueDate(original, nextDate); // detect if we finished - if(newDueDate > original.getTime()) + if (newDueDate > original.getTime()) break; } return newDueDate; } - /** Compute long due date from DateValue */ + /** + * Compute long due date from DateValue + */ private static long buildNewDueDate(Date original, DateValue nextDate) { long newDueDate; - if(nextDate instanceof DateTimeValueImpl) { - DateTimeValueImpl newDateTime = (DateTimeValueImpl)nextDate; + if (nextDate instanceof DateTimeValueImpl) { + DateTimeValueImpl newDateTime = (DateTimeValueImpl) nextDate; Date date = new Date(Date.UTC(newDateTime.year() - 1900, newDateTime.month() - 1, newDateTime.day(), newDateTime.hour(), newDateTime.minute(), newDateTime.second())); @@ -239,30 +244,35 @@ public class RepeatTaskCompleteListener extends BroadcastReceiver { return newDueDate; } - /** Initialize RRule instance */ + /** + * Initialize RRule instance + */ private static RRule initRRule(String recurrence) throws ParseException { RRule rrule = new RRule(recurrence); // handle the iCalendar "byDay" field differently depending on if // we are weekly or otherwise - if(rrule.getFreq() != Frequency.WEEKLY) + if (rrule.getFreq() != Frequency.WEEKLY) rrule.setByDay(Collections.EMPTY_LIST); return rrule; } - /** Set up repeat start date - * @param frequency */ + /** + * Set up repeat start date + * + * @param frequency + */ private static Date setUpStartDate(Task task, boolean repeatAfterCompletion, Frequency frequency) { Date startDate = new Date(); - if(task.hasDueDate()) { + if (task.hasDueDate()) { Date dueDate = new Date(task.getValue(Task.DUE_DATE)); - if(repeatAfterCompletion) + if (repeatAfterCompletion) startDate = new Date(task.getValue(Task.COMPLETION_DATE)); else startDate = dueDate; - if(task.hasDueTime() && frequency != Frequency.HOURLY && frequency != Frequency.MINUTELY) { + if (task.hasDueTime() && frequency != Frequency.HOURLY && frequency != Frequency.MINUTELY) { startDate.setHours(dueDate.getHours()); startDate.setMinutes(dueDate.getMinutes()); startDate.setSeconds(dueDate.getSeconds()); @@ -272,7 +282,7 @@ public class RepeatTaskCompleteListener extends BroadcastReceiver { } private static DateValue setUpStartDateAsDV(Task task, Date startDate) { - if(task.hasDueTime()) + if (task.hasDueTime()) return new DateTimeValueImpl(startDate.getYear() + 1900, startDate.getMonth() + 1, startDate.getDate(), startDate.getHours(), startDate.getMinutes(), startDate.getSeconds()); @@ -283,15 +293,15 @@ public class RepeatTaskCompleteListener extends BroadcastReceiver { private static long handleSubdayRepeat(Date startDate, RRule rrule) { long millis; - switch(rrule.getFreq()) { - case HOURLY: - millis = DateUtilities.ONE_HOUR; - break; - case MINUTELY: - millis = DateUtilities.ONE_MINUTE; - break; - default: - throw new RuntimeException("Error handing subday repeat: " + rrule.getFreq()); //$NON-NLS-1$ + switch (rrule.getFreq()) { + case HOURLY: + millis = DateUtilities.ONE_HOUR; + break; + case MINUTELY: + millis = DateUtilities.ONE_MINUTE; + break; + default: + throw new RuntimeException("Error handing subday repeat: " + rrule.getFreq()); //$NON-NLS-1$ } long newDueDate = startDate.getTime() + millis * rrule.getInterval(); return Task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, diff --git a/astrid/plugin-src/com/todoroo/astrid/subtasks/AstridOrderedListFragmentHelper.java b/astrid/plugin-src/com/todoroo/astrid/subtasks/AstridOrderedListFragmentHelper.java index b4f8846f7..caf9948d2 100644 --- a/astrid/plugin-src/com/todoroo/astrid/subtasks/AstridOrderedListFragmentHelper.java +++ b/astrid/plugin-src/com/todoroo/astrid/subtasks/AstridOrderedListFragmentHelper.java @@ -1,11 +1,5 @@ package com.todoroo.astrid.subtasks; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.atomic.AtomicReference; - import android.app.Activity; import android.database.Cursor; import android.text.TextUtils; @@ -41,6 +35,12 @@ import com.todoroo.astrid.service.ThemeService; import com.todoroo.astrid.ui.DraggableListView; import com.todoroo.astrid.utility.AstridPreferences; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; + public class AstridOrderedListFragmentHelper implements OrderedListFragmentHelperInterface { @@ -48,8 +48,10 @@ public class AstridOrderedListFragmentHelper implements OrderedListFragmen private final AstridOrderedListUpdater updater; private final TaskListFragment fragment; - @Autowired TaskService taskService; - @Autowired MetadataService metadataService; + @Autowired + TaskService taskService; + @Autowired + MetadataService metadataService; private DraggableTaskAdapter taskAdapter; @@ -89,7 +91,7 @@ public class AstridOrderedListFragmentHelper implements OrderedListFragmen getTouchListView().setSwipeListener(swipeListener); getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics); - if(Preferences.getInt(AstridPreferences.P_SUBTASKS_HELP, 0) == 0) + if (Preferences.getInt(AstridPreferences.P_SUBTASKS_HELP, 0) == 0) showSubtasksHelp(); } @@ -119,11 +121,12 @@ public class AstridOrderedListFragmentHelper implements OrderedListFragmen @Override public void drop(int from, int to) { String targetTaskId = taskAdapter.getItemUuid(from); - if (!RemoteModel.isValidUuid(targetTaskId)) return; // This can happen with gestures on empty parts of the list (e.g. extra space below tasks) + if (!RemoteModel.isValidUuid(targetTaskId)) + return; // This can happen with gestures on empty parts of the list (e.g. extra space below tasks) String destinationTaskId = taskAdapter.getItemUuid(to); try { - if(to >= getListView().getCount()) + if (to >= getListView().getCount()) updater.moveTo(list, getFilter(), targetTaskId, "-1"); //$NON-NLS-1$ else updater.moveTo(list, getFilter(), targetTaskId, destinationTaskId); @@ -149,7 +152,8 @@ public class AstridOrderedListFragmentHelper implements OrderedListFragmen protected void indent(int which, int delta) { String targetTaskId = taskAdapter.getItemUuid(which); - if (!RemoteModel.isValidUuid(targetTaskId)) return; // This can happen with gestures on empty parts of the list (e.g. extra space below tasks) + if (!RemoteModel.isValidUuid(targetTaskId)) + return; // This can happen with gestures on empty parts of the list (e.g. extra space below tasks) try { updater.indent(list, getFilter(), targetTaskId, delta); } catch (Exception e) { @@ -164,7 +168,7 @@ public class AstridOrderedListFragmentHelper implements OrderedListFragmen private final GrabberClickListener rowClickListener = new GrabberClickListener() { @Override public void onLongClick(final View v) { - if(v == null) + if (v == null) return; fragment.registerForContextMenu(getListView()); @@ -174,14 +178,14 @@ public class AstridOrderedListFragmentHelper implements OrderedListFragmen @Override public void onClick(View v) { - if(v == null) + if (v == null) return; ((DraggableTaskAdapter) taskAdapter).getListener().onClick(v); } }; public TaskAdapter createTaskAdapter(TodorooCursor cursor, - AtomicReference sqlQueryTemplate) { + AtomicReference sqlQueryTemplate) { taskAdapter = new DraggableTaskAdapter(fragment, TaskListFragment.getTaskRowResource(), cursor, sqlQueryTemplate, false, null); @@ -201,8 +205,8 @@ public class AstridOrderedListFragmentHelper implements OrderedListFragmen private final class DraggableTaskAdapter extends TaskAdapter { private DraggableTaskAdapter(TaskListFragment activity, int resource, - Cursor c, AtomicReference query, boolean autoRequery, - OnCompletedTaskListener onCompletedTaskListener) { + Cursor c, AtomicReference query, boolean autoRequery, + OnCompletedTaskListener onCompletedTaskListener) { super(activity, resource, c, query, autoRequery, onCompletedTaskListener); @@ -211,7 +215,7 @@ public class AstridOrderedListFragmentHelper implements OrderedListFragmen @Override protected ViewHolder getTagFromCheckBox(View v) { - return (ViewHolder)((View)v.getParent()).getTag(); + return (ViewHolder) ((View) v.getParent()).getTag(); } @Override @@ -234,7 +238,7 @@ public class AstridOrderedListFragmentHelper implements OrderedListFragmen } private final Map> chainedCompletions = - Collections.synchronizedMap(new HashMap>()); + Collections.synchronizedMap(new HashMap>()); private void setCompletedForItemAndSubtasks(final Task item, final boolean completedState) { final String itemId = item.getUuid(); @@ -242,10 +246,10 @@ public class AstridOrderedListFragmentHelper implements OrderedListFragmen final Task model = new Task(); final long completionDate = completedState ? DateUtilities.now() : 0; - if(completedState == false) { + if (completedState == false) { ArrayList chained = chainedCompletions.get(itemId); - if(chained != null) { - for(String taskId : chained) { + if (chained != null) { + for (String taskId : chained) { model.setValue(Task.COMPLETION_DATE, completionDate); taskService.update(Task.UUID.eq(taskId), model); model.clear(); @@ -271,11 +275,11 @@ public class AstridOrderedListFragmentHelper implements OrderedListFragmen } }); - if(chained.size() > 0) { + if (chained.size() > 0) { // move recurring items to item parent TodorooCursor recurring = taskService.query(Query.select(Task.UUID, Task.RECURRENCE).where( Criterion.and(Task.UUID.in(chained.toArray(new String[chained.size()])), - Task.RECURRENCE.isNotNull(), Functions.length(Task.RECURRENCE).gt(0)))); + Task.RECURRENCE.isNotNull(), Functions.length(Task.RECURRENCE).gt(0)))); try { Task t = new Task(); boolean madeChanges = false; diff --git a/astrid/plugin-src/com/todoroo/astrid/subtasks/AstridOrderedListUpdater.java b/astrid/plugin-src/com/todoroo/astrid/subtasks/AstridOrderedListUpdater.java index d407b60c0..582911f37 100644 --- a/astrid/plugin-src/com/todoroo/astrid/subtasks/AstridOrderedListUpdater.java +++ b/astrid/plugin-src/com/todoroo/astrid/subtasks/AstridOrderedListUpdater.java @@ -1,14 +1,5 @@ package com.todoroo.astrid.subtasks; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.json.JSONArray; -import org.json.JSONException; - import android.util.Log; import com.todoroo.andlib.data.TodorooCursor; @@ -19,6 +10,15 @@ import com.todoroo.astrid.data.RemoteModel; import com.todoroo.astrid.data.Task; import com.todoroo.astrid.service.TaskService; +import org.json.JSONArray; +import org.json.JSONException; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + public abstract class AstridOrderedListUpdater { @Autowired @@ -51,7 +51,9 @@ public abstract class AstridOrderedListUpdater { private final HashMap idToNode; protected abstract String getSerializedTree(LIST list, Filter filter); + protected abstract void writeSerialization(LIST list, String serialized, boolean shouldQueueSync); + protected abstract void applyToFilter(Filter filter); public int getIndentForTask(String targetTaskId) { diff --git a/astrid/plugin-src/com/todoroo/astrid/subtasks/OrderedListFragmentHelperInterface.java b/astrid/plugin-src/com/todoroo/astrid/subtasks/OrderedListFragmentHelperInterface.java index 076b117d6..7f68c361a 100644 --- a/astrid/plugin-src/com/todoroo/astrid/subtasks/OrderedListFragmentHelperInterface.java +++ b/astrid/plugin-src/com/todoroo/astrid/subtasks/OrderedListFragmentHelperInterface.java @@ -1,20 +1,25 @@ package com.todoroo.astrid.subtasks; -import java.util.concurrent.atomic.AtomicReference; - import com.todoroo.andlib.data.Property; import com.todoroo.andlib.data.TodorooCursor; import com.todoroo.astrid.adapter.TaskAdapter; import com.todoroo.astrid.api.Filter; import com.todoroo.astrid.data.Task; +import java.util.concurrent.atomic.AtomicReference; + public interface OrderedListFragmentHelperInterface { void setUpUiComponents(); + void beforeSetUpTaskList(Filter filter); + void onCreateTask(Task task); + void onDeleteTask(Task task); + TaskAdapter createTaskAdapter(TodorooCursor cursor, AtomicReference queryTemplate); + Property[] taskProperties(); } diff --git a/astrid/plugin-src/com/todoroo/astrid/subtasks/OrderedMetadataListFragmentHelper.java b/astrid/plugin-src/com/todoroo/astrid/subtasks/OrderedMetadataListFragmentHelper.java index 54048d2ed..763f2d2be 100644 --- a/astrid/plugin-src/com/todoroo/astrid/subtasks/OrderedMetadataListFragmentHelper.java +++ b/astrid/plugin-src/com/todoroo/astrid/subtasks/OrderedMetadataListFragmentHelper.java @@ -5,13 +5,6 @@ */ package com.todoroo.astrid.subtasks; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.atomic.AtomicReference; - import android.app.Activity; import android.database.Cursor; import android.text.TextUtils; @@ -46,14 +39,23 @@ import com.todoroo.astrid.subtasks.OrderedMetadataListUpdater.OrderedListNodeVis import com.todoroo.astrid.ui.DraggableListView; import com.todoroo.astrid.utility.AstridPreferences; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; + public class OrderedMetadataListFragmentHelper implements OrderedListFragmentHelperInterface { private final DisplayMetrics metrics = new DisplayMetrics(); private final OrderedMetadataListUpdater updater; private final TaskListFragment fragment; - @Autowired TaskService taskService; - @Autowired MetadataService metadataService; + @Autowired + TaskService taskService; + @Autowired + MetadataService metadataService; private DraggableTaskAdapter taskAdapter; @@ -93,7 +95,7 @@ public class OrderedMetadataListFragmentHelper implements OrderedListFragm getTouchListView().setSwipeListener(swipeListener); getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics); - if(Preferences.getInt(AstridPreferences.P_SUBTASKS_HELP, 0) == 0) + if (Preferences.getInt(AstridPreferences.P_SUBTASKS_HELP, 0) == 0) showSubtasksHelp(); } @@ -135,11 +137,12 @@ public class OrderedMetadataListFragmentHelper implements OrderedListFragm @Override public void drop(int from, int to) { long targetTaskId = taskAdapter.getItemId(from); - if (targetTaskId <= 0) return; // This can happen with gestures on empty parts of the list (e.g. extra space below tasks) + if (targetTaskId <= 0) + return; // This can happen with gestures on empty parts of the list (e.g. extra space below tasks) long destinationTaskId = taskAdapter.getItemId(to); try { - if(to >= getListView().getCount()) + if (to >= getListView().getCount()) updater.moveTo(getFilter(), list, targetTaskId, -1); else updater.moveTo(getFilter(), list, targetTaskId, destinationTaskId); @@ -164,7 +167,8 @@ public class OrderedMetadataListFragmentHelper implements OrderedListFragm protected void indent(int which, int delta) { long targetTaskId = taskAdapter.getItemId(which); - if (targetTaskId <= 0) return; // This can happen with gestures on empty parts of the list (e.g. extra space below tasks) + if (targetTaskId <= 0) + return; // This can happen with gestures on empty parts of the list (e.g. extra space below tasks) try { updater.indent(getFilter(), list, targetTaskId, delta); } catch (Exception e) { @@ -177,7 +181,7 @@ public class OrderedMetadataListFragmentHelper implements OrderedListFragm private final GrabberClickListener rowClickListener = new GrabberClickListener() { @Override public void onLongClick(final View v) { - if(v == null) + if (v == null) return; fragment.registerForContextMenu(getListView()); @@ -187,14 +191,14 @@ public class OrderedMetadataListFragmentHelper implements OrderedListFragm @Override public void onClick(View v) { - if(v == null) + if (v == null) return; ((DraggableTaskAdapter) taskAdapter).getListener().onClick(v); } }; public TaskAdapter createTaskAdapter(TodorooCursor cursor, - AtomicReference sqlQueryTemplate) { + AtomicReference sqlQueryTemplate) { taskAdapter = new DraggableTaskAdapter(fragment, TaskListFragment.getTaskRowResource(), cursor, sqlQueryTemplate, false, null); @@ -212,8 +216,8 @@ public class OrderedMetadataListFragmentHelper implements OrderedListFragm private final class DraggableTaskAdapter extends TaskAdapter { private DraggableTaskAdapter(TaskListFragment activity, int resource, - Cursor c, AtomicReference query, boolean autoRequery, - OnCompletedTaskListener onCompletedTaskListener) { + Cursor c, AtomicReference query, boolean autoRequery, + OnCompletedTaskListener onCompletedTaskListener) { super(activity, resource, c, query, autoRequery, onCompletedTaskListener); @@ -222,7 +226,7 @@ public class OrderedMetadataListFragmentHelper implements OrderedListFragm @Override protected ViewHolder getTagFromCheckBox(View v) { - return (ViewHolder)((View)v.getParent()).getTag(); + return (ViewHolder) ((View) v.getParent()).getTag(); } @Override @@ -245,7 +249,7 @@ public class OrderedMetadataListFragmentHelper implements OrderedListFragm } private final Map> chainedCompletions = - Collections.synchronizedMap(new HashMap>()); + Collections.synchronizedMap(new HashMap>()); private void setCompletedForItemAndSubtasks(final Task item, final boolean completedState) { final long itemId = item.getId(); @@ -253,10 +257,10 @@ public class OrderedMetadataListFragmentHelper implements OrderedListFragm final Task model = new Task(); final long completionDate = completedState ? DateUtilities.now() : 0; - if(completedState == false) { + if (completedState == false) { ArrayList chained = chainedCompletions.get(itemId); - if(chained != null) { - for(Long taskId : chained) { + if (chained != null) { + for (Long taskId : chained) { model.setId(taskId); model.setValue(Task.COMPLETION_DATE, completionDate); taskService.save(model); @@ -275,7 +279,7 @@ public class OrderedMetadataListFragmentHelper implements OrderedListFragm @Override public void visitNode(Node node) { Task childTask = taskService.fetchById(node.taskId, Task.RECURRENCE); - if(!TextUtils.isEmpty(childTask.getValue(Task.RECURRENCE))) { + if (!TextUtils.isEmpty(childTask.getValue(Task.RECURRENCE))) { Metadata metadata = updater.getTaskMetadata(list, node.taskId); metadata.setValue(updater.indentProperty(), parentIndent); metadataService.save(metadata); @@ -291,7 +295,7 @@ public class OrderedMetadataListFragmentHelper implements OrderedListFragm } }); - if(chained.size() > 0) { + if (chained.size() > 0) { chainedCompletions.put(itemId, chained); taskAdapter.notifyDataSetInvalidated(); } diff --git a/astrid/plugin-src/com/todoroo/astrid/subtasks/OrderedMetadataListUpdater.java b/astrid/plugin-src/com/todoroo/astrid/subtasks/OrderedMetadataListUpdater.java index 60acb9f9b..7e64e152a 100644 --- a/astrid/plugin-src/com/todoroo/astrid/subtasks/OrderedMetadataListUpdater.java +++ b/astrid/plugin-src/com/todoroo/astrid/subtasks/OrderedMetadataListUpdater.java @@ -5,12 +5,6 @@ */ package com.todoroo.astrid.subtasks; -import java.util.ArrayList; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicReference; - import com.todoroo.andlib.data.Property.IntegerProperty; import com.todoroo.andlib.data.Property.LongProperty; import com.todoroo.andlib.service.DependencyInjectionService; @@ -18,7 +12,12 @@ import com.todoroo.astrid.api.Filter; import com.todoroo.astrid.core.PluginServices; import com.todoroo.astrid.data.Metadata; import com.todoroo.astrid.data.Task; -import com.todoroo.astrid.subtasks.OrderedMetadataListUpdater.OrderedListIterator; + +import java.util.ArrayList; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; abstract public class OrderedMetadataListUpdater { @@ -83,7 +82,7 @@ abstract public class OrderedMetadataListUpdater { * Indent a task and all its children */ public void indent(final Filter filter, final LIST list, final long targetTaskId, final int delta) { - if(list == null) + if (list == null) return; beforeIndent(list); @@ -96,7 +95,7 @@ abstract public class OrderedMetadataListUpdater { iterateThroughList(filter, list, new OrderedListIterator() { @Override public void processTask(long taskId, Metadata metadata) { - if(!metadata.isSaved()) + if (!metadata.isSaved()) metadata = createEmptyMetadata(list, taskId); int indent = metadata.containsNonNullValue(indentProperty()) ? metadata.getValue(indentProperty()) : 0; @@ -104,13 +103,13 @@ abstract public class OrderedMetadataListUpdater { long order = globalOrder.incrementAndGet(); metadata.setValue(orderProperty(), order); - if(targetTaskId == taskId) { + if (targetTaskId == taskId) { // if indenting is warranted, indent me and my children - if(indent + delta <= previousIndent.get() + 1 && indent + delta >= 0) { + if (indent + delta <= previousIndent.get() + 1 && indent + delta >= 0) { targetTaskIndent.set(indent); metadata.setValue(indentProperty(), indent + delta); - if(parentProperty() != null) { + if (parentProperty() != null) { long newParent = computeNewParent(filter, list, taskId, indent + delta - 1); if (newParent == taskId) @@ -120,9 +119,9 @@ abstract public class OrderedMetadataListUpdater { } saveAndUpdateModifiedDate(metadata); } - } else if(targetTaskIndent.get() > -1) { + } else if (targetTaskIndent.get() > -1) { // found first task that is not beneath target - if(indent <= targetTaskIndent.get()) + if (indent <= targetTaskIndent.get()) targetTaskIndent.set(-1); else { metadata.setValue(indentProperty(), indent + delta); @@ -133,7 +132,7 @@ abstract public class OrderedMetadataListUpdater { previousTask.set(taskId); } - if(!metadata.isSaved()) + if (!metadata.isSaved()) saveAndUpdateModifiedDate(metadata); } @@ -144,6 +143,7 @@ abstract public class OrderedMetadataListUpdater { /** * Helper function to iterate through a list and compute a new parent for the target task * based on the target parent's indent + * * @param list * @param targetTaskId * @param newIndent @@ -182,24 +182,24 @@ abstract public class OrderedMetadataListUpdater { * @param newTaskId task we will move above. if -1, moves to end of list */ public void moveTo(Filter filter, LIST list, final long targetTaskId, - final long moveBeforeTaskId) { - if(list == null) + final long moveBeforeTaskId) { + if (list == null) return; Node root = buildTreeModel(filter, list); Node target = findNode(root, targetTaskId); - if(target != null && target.parent != null) { - if(moveBeforeTaskId == -1) { + if (target != null && target.parent != null) { + if (moveBeforeTaskId == -1) { target.parent.children.remove(target); root.children.add(target); target.parent = root; } else { Node sibling = findNode(root, moveBeforeTaskId); - if(sibling != null && !ancestorOf(target, sibling)) { + if (sibling != null && !ancestorOf(target, sibling)) { int index = sibling.parent.children.indexOf(sibling); - if(target.parent == sibling.parent && + if (target.parent == sibling.parent && target.parent.children.indexOf(target) < index) index--; @@ -215,9 +215,9 @@ abstract public class OrderedMetadataListUpdater { } private boolean ancestorOf(Node ancestor, Node descendant) { - if(descendant.parent == ancestor) + if (descendant.parent == ancestor) return true; - if(descendant.parent == null) + if (descendant.parent == null) return false; return ancestorOf(ancestor, descendant.parent); } @@ -234,34 +234,34 @@ abstract public class OrderedMetadataListUpdater { } protected void traverseTreeAndWriteValues(LIST list, Node node, AtomicLong order, int indent) { - if(node.taskId != Task.NO_ID) { + if (node.taskId != Task.NO_ID) { Metadata metadata = getTaskMetadata(list, node.taskId); - if(metadata == null) + if (metadata == null) metadata = createEmptyMetadata(list, node.taskId); metadata.setValue(orderProperty(), order.getAndIncrement()); metadata.setValue(indentProperty(), indent); boolean parentChanged = false; - if(parentProperty() != null && metadata.getValue(parentProperty()) != + if (parentProperty() != null && metadata.getValue(parentProperty()) != node.parent.taskId) { parentChanged = true; metadata.setValue(parentProperty(), node.parent.taskId); } saveAndUpdateModifiedDate(metadata); - if(parentChanged) + if (parentChanged) onMovedOrIndented(metadata); } - for(Node child : node.children) { + for (Node child : node.children) { traverseTreeAndWriteValues(list, child, order, indent + 1); } } protected Node findNode(Node node, long taskId) { - if(node.taskId == taskId) + if (node.taskId == taskId) return node; - for(Node child : node.children) { + for (Node child : node.children) { Node found = findNode(child, taskId); - if(found != null) + if (found != null) return found; } return null; @@ -278,19 +278,19 @@ abstract public class OrderedMetadataListUpdater { int indent = metadata.getValue(indentProperty()); int previousIndentValue = previoustIndent.get(); - if(indent == previousIndentValue) { // sibling + if (indent == previousIndentValue) { // sibling Node parent = currentNode.get().parent; currentNode.set(new Node(taskId, parent)); parent.children.add(currentNode.get()); - } else if(indent > previousIndentValue) { // child + } else if (indent > previousIndentValue) { // child Node parent = currentNode.get(); currentNode.set(new Node(taskId, parent)); parent.children.add(currentNode.get()); } else { // in a different tree Node node = currentNode.get().parent; - for(int i = indent; i < previousIndentValue; i++) { + for (int i = indent; i < previousIndentValue; i++) { node = node.parent; - if(node == null) { + if (node == null) { node = root; break; } @@ -306,7 +306,7 @@ abstract public class OrderedMetadataListUpdater { } protected void saveAndUpdateModifiedDate(Metadata metadata) { - if(metadata.getSetValues().size() == 0) + if (metadata.getSetValues().size() == 0) return; PluginServices.getMetadataService().save(metadata); } @@ -321,39 +321,40 @@ abstract public class OrderedMetadataListUpdater { * Apply an operation only to the children of the task */ public void applyToChildren(Filter filter, LIST list, long targetTaskId, - OrderedListNodeVisitor visitor) { + OrderedListNodeVisitor visitor) { Node root = buildTreeModel(filter, list); Node target = findNode(root, targetTaskId); - if(target != null) - for(Node child : target.children) + if (target != null) + for (Node child : target.children) applyVisitor(child, visitor); } private void applyVisitor(Node node, OrderedListNodeVisitor visitor) { visitor.visitNode(node); - for(Node child : node.children) + for (Node child : node.children) applyVisitor(child, visitor); } /** * Removes a task from the order hierarchy and un-indent children + * * @param filter * @param list * @param targetTaskId */ public void onDeleteTask(Filter filter, LIST list, final long targetTaskId) { - if(list == null) + if (list == null) return; Node root = buildTreeModel(filter, list); Node target = findNode(root, targetTaskId); - if(target != null && target.parent != null) { + if (target != null && target.parent != null) { int targetIndex = target.parent.children.indexOf(target); target.parent.children.remove(targetIndex); - for(Node node : target.children) { + for (Node node : target.children) { node.parent = target.parent; target.parent.children.add(targetIndex++, node); } @@ -378,11 +379,11 @@ abstract public class OrderedMetadataListUpdater { @SuppressWarnings("nls") public void debugPrint(Node root, int depth) { - for(int i = 0; i < depth; i++) System.err.print(" + "); + for (int i = 0; i < depth; i++) System.err.print(" + "); System.err.format("%03d", root.taskId); System.err.print("\n"); - for(int i = 0; i < root.children.size(); i++) + for (int i = 0; i < root.children.size(); i++) debugPrint(root.children.get(i), depth + 1); } diff --git a/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksHelper.java b/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksHelper.java index 38e1779a1..750754fd8 100644 --- a/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksHelper.java +++ b/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksHelper.java @@ -1,8 +1,5 @@ package com.todoroo.astrid.subtasks; -import java.util.ArrayList; -import java.util.HashMap; - import android.content.SharedPreferences; import android.text.TextUtils; import android.util.Log; @@ -27,13 +24,16 @@ import com.todoroo.astrid.data.TaskListMetadata; import com.todoroo.astrid.subtasks.AstridOrderedListUpdater.Node; import com.todoroo.astrid.utility.AstridPreferences; +import java.util.ArrayList; +import java.util.HashMap; + public class SubtasksHelper { public static boolean shouldUseSubtasksFragmentForFilter(Filter filter) { - if(filter == null || CoreFilterExposer.isInbox(filter) || CoreFilterExposer.isTodayFilter(filter) || SubtasksHelper.isTagFilter(filter)) { + if (filter == null || CoreFilterExposer.isInbox(filter) || CoreFilterExposer.isTodayFilter(filter) || SubtasksHelper.isTagFilter(filter)) { SharedPreferences publicPrefs = AstridPreferences.getPublicPrefs(ContextManager.getContext()); int sortFlags = publicPrefs.getInt(SortHelper.PREF_SORT_FLAGS, 0); - if(SortHelper.isManualSort(sortFlags)) + if (SortHelper.isManualSort(sortFlags)) return true; } return false; @@ -125,6 +125,7 @@ public class SubtasksHelper { /** * Takes a subtasks string containing local ids and remaps it to one containing UUIDs + * * @param localTree * @return */ diff --git a/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksListFragment.java b/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksListFragment.java index a3b1601c0..e8775a9f9 100644 --- a/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksListFragment.java +++ b/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksListFragment.java @@ -20,7 +20,6 @@ import com.todoroo.astrid.data.TaskListMetadata; * Fragment for subtasks * * @author Tim Su - * */ public class SubtasksListFragment extends TaskListFragment { @@ -36,7 +35,7 @@ public class SubtasksListFragment extends TaskListFragment { protected OrderedListFragmentHelperInterface createFragmentHelper() { AstridOrderedListFragmentHelper olfh = - new AstridOrderedListFragmentHelper(this, new SubtasksFilterUpdater()); + new AstridOrderedListFragmentHelper(this, new SubtasksFilterUpdater()); return olfh; } @@ -73,7 +72,7 @@ public class SubtasksListFragment extends TaskListFragment { @Override public void onResume() { super.onResume(); - if (lastVisibleIndex >=0) { + if (lastVisibleIndex >= 0) { getListView().setSelection(lastVisibleIndex); } } diff --git a/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksMetadata.java b/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksMetadata.java index 1eb8dfdc9..4cbb021d1 100644 --- a/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksMetadata.java +++ b/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksMetadata.java @@ -14,17 +14,20 @@ import com.todoroo.astrid.data.Metadata; * Metadata entries for a Subtask list * * @author Tim Su - * */ @Deprecated public class SubtasksMetadata { public static final String LIST_ACTIVE_TASKS = "[AT]"; //$NON-NLS-1$ - /** metadata key */ + /** + * metadata key + */ public static final String METADATA_KEY = "subtasks"; //$NON-NLS-1$ - /** tag name */ + /** + * tag name + */ public static final StringProperty TAG = new StringProperty(Metadata.TABLE, Metadata.VALUE1.name); diff --git a/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksMetadataMigration.java b/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksMetadataMigration.java index f1e9ab91d..203521e0b 100644 --- a/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksMetadataMigration.java +++ b/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksMetadataMigration.java @@ -1,7 +1,5 @@ package com.todoroo.astrid.subtasks; -import java.util.ArrayList; - import android.util.Log; import com.todoroo.andlib.data.TodorooCursor; @@ -20,6 +18,8 @@ import com.todoroo.astrid.service.MetadataService; import com.todoroo.astrid.service.TagDataService; import com.todoroo.astrid.subtasks.AstridOrderedListUpdater.Node; +import java.util.ArrayList; + @SuppressWarnings("deprecation") // Subtasks metadata is deprecated public class SubtasksMetadataMigration { diff --git a/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksTagListFragment.java b/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksTagListFragment.java index 142c1bcd8..8e5273536 100644 --- a/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksTagListFragment.java +++ b/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksTagListFragment.java @@ -37,7 +37,7 @@ public class SubtasksTagListFragment extends TagViewFragment { R.layout.task_list_body_tag, root, false); taskListView = - getActivity().getLayoutInflater().inflate(R.layout.task_list_body_subtasks, root, false); + getActivity().getLayoutInflater().inflate(R.layout.task_list_body_subtasks, root, false); parent.addView(taskListView); return parent; diff --git a/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksTagUpdater.java b/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksTagUpdater.java index 4de2adcf2..de825accc 100644 --- a/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksTagUpdater.java +++ b/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksTagUpdater.java @@ -1,10 +1,10 @@ package com.todoroo.astrid.subtasks; -import java.util.concurrent.atomic.AtomicBoolean; - import com.todoroo.astrid.api.Filter; import com.todoroo.astrid.data.TaskListMetadata; +import java.util.concurrent.atomic.AtomicBoolean; + public class SubtasksTagUpdater extends SubtasksFilterUpdater { private final AtomicBoolean isBeingFiltered; diff --git a/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksUpdater.java b/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksUpdater.java index 049271960..6437dbea8 100644 --- a/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksUpdater.java +++ b/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksUpdater.java @@ -16,9 +16,12 @@ import com.todoroo.astrid.service.TaskService; public abstract class SubtasksUpdater extends AstridOrderedListUpdater { - @Autowired TaskListMetadataDao taskListMetadataDao; - @Autowired TaskService taskService; - @Autowired ActFmSyncService actFmSyncService; + @Autowired + TaskListMetadataDao taskListMetadataDao; + @Autowired + TaskService taskService; + @Autowired + ActFmSyncService actFmSyncService; public static final String ACTIVE_TASKS_ORDER = "active_tasks_order"; //$NON-NLS-1$ public static final String TODAY_TASKS_ORDER = "today_tasks_order"; //$NON-NLS-1$ diff --git a/astrid/plugin-src/com/todoroo/astrid/tags/TagCaseMigrator.java b/astrid/plugin-src/com/todoroo/astrid/tags/TagCaseMigrator.java index 7e852cd8c..fe28ef8ba 100644 --- a/astrid/plugin-src/com/todoroo/astrid/tags/TagCaseMigrator.java +++ b/astrid/plugin-src/com/todoroo/astrid/tags/TagCaseMigrator.java @@ -5,8 +5,6 @@ */ package com.todoroo.astrid.tags; -import java.util.HashMap; - import android.content.Context; import com.todoroo.andlib.data.TodorooCursor; @@ -26,11 +24,16 @@ import com.todoroo.astrid.service.TagDataService; import com.todoroo.astrid.service.TaskService; import com.todoroo.astrid.utility.Flags; +import java.util.HashMap; + public class TagCaseMigrator { - @Autowired TaskService taskService; - @Autowired TagDataService tagDataService; - @Autowired MetadataService metadataService; + @Autowired + TaskService taskService; + @Autowired + TagDataService tagDataService; + @Autowired + MetadataService metadataService; public static final String PREF_SHOW_MIGRATION_ALERT = "tag_case_migration_alert"; //$NON-NLS-1$ private static final String PREF_CASE_MIGRATION_PERFORMED = "tag_case_migration"; //$NON-NLS-1$ @@ -51,7 +54,7 @@ public class TagCaseMigrator { boolean shouldShowDialog = false; for (int i = 0; i < allTagData.length - 1; i++) { TagService.Tag first = allTagData[i]; - TagService.Tag second = allTagData[i+1]; + TagService.Tag second = allTagData[i + 1]; if (first.tag.equalsIgnoreCase(second.tag)) { shouldShowDialog = true; @@ -95,8 +98,8 @@ public class TagCaseMigrator { private void updateTagData(String tag) { long remoteId = nameToRemoteId.get(tag); TodorooCursor tagData = tagDataService.query(Query.select(TagData.NAME, TagData.UUID) - .where(Criterion.and( - TagData.NAME.eq(tag), TagData.UUID.eq(remoteId)))); + .where(Criterion.and( + TagData.NAME.eq(tag), TagData.UUID.eq(remoteId)))); try { for (tagData.moveToFirst(); !tagData.isAfterLast(); tagData.moveToNext()) { TagData curr = new TagData(tagData); @@ -119,12 +122,12 @@ public class TagCaseMigrator { private void addTasksToTargetTag(String tag, String target) { TodorooCursor tasks = taskService.query(Query.select(Task.ID).join(Join.inner(Metadata.TABLE, - Task.ID.eq(Metadata.TASK))).where(tagEq(tag, Criterion.all))); + Task.ID.eq(Metadata.TASK))).where(tagEq(tag, Criterion.all))); try { for (tasks.moveToFirst(); !tasks.isAfterLast(); tasks.moveToNext()) { Task curr = new Task(tasks); TodorooCursor tagMetadata = metadataService.query(Query.select(TaskToTagMetadata.TAG_NAME) - .where(Criterion.and(TaskToTagMetadata.TAG_NAME.eq(target), Metadata.KEY.eq(TaskToTagMetadata.KEY), Metadata.TASK.eq(curr.getId())))); + .where(Criterion.and(TaskToTagMetadata.TAG_NAME.eq(target), Metadata.KEY.eq(TaskToTagMetadata.KEY), Metadata.TASK.eq(curr.getId())))); try { if (tagMetadata.getCount() == 0) { Metadata newTag = new Metadata(); @@ -149,7 +152,7 @@ public class TagCaseMigrator { @Deprecated private int renameHelper(String oldTag, String newTag, boolean caseSensitive) { - // First remove newTag from all tasks that have both oldTag and newTag. + // First remove newTag from all tasks that have both oldTag and newTag. metadataService.deleteWhere( Criterion.and( Metadata.VALUE1.eq(newTag), diff --git a/astrid/plugin-src/com/todoroo/astrid/tags/TagCustomFilterCriteriaExposer.java b/astrid/plugin-src/com/todoroo/astrid/tags/TagCustomFilterCriteriaExposer.java index c9e182e50..a62a5c45b 100644 --- a/astrid/plugin-src/com/todoroo/astrid/tags/TagCustomFilterCriteriaExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/tags/TagCustomFilterCriteriaExposer.java @@ -41,9 +41,9 @@ public class TagCustomFilterCriteriaExposer extends BroadcastReceiver { // built in criteria: tags { TagService.Tag[] tags = TagService.getInstance().getGroupedTags(TagService.GROUPED_TAGS_BY_SIZE, - TaskDao.TaskCriteria.activeAndVisible()); + TaskDao.TaskCriteria.activeAndVisible()); String[] tagNames = new String[tags.length]; - for(int i = 0; i < tags.length; i++) + for (int i = 0; i < tags.length; i++) tagNames[i] = tags[i].tag; ContentValues values = new ContentValues(); values.put(Metadata.KEY.name, TaskToTagMetadata.KEY); @@ -52,12 +52,12 @@ public class TagCustomFilterCriteriaExposer extends BroadcastReceiver { IDENTIFIER_TAG_IS, context.getString(R.string.CFC_tag_text), Query.select(Metadata.TASK).from(Metadata.TABLE).join(Join.inner( - Task.TABLE, Metadata.TASK.eq(Task.ID))).where(Criterion.and( + Task.TABLE, Metadata.TASK.eq(Task.ID))).where(Criterion.and( TaskDao.TaskCriteria.activeAndVisible(), MetadataDao.MetadataCriteria.withKey(TaskToTagMetadata.KEY), TaskToTagMetadata.TAG_NAME.eq("?"), Metadata.DELETION_DATE.eq(0))).toString(), values, tagNames, tagNames, - ((BitmapDrawable)r.getDrawable(TagService.getDefaultImageIDForTag(RemoteModel.NO_UUID))).getBitmap(), + ((BitmapDrawable) r.getDrawable(TagService.getDefaultImageIDForTag(RemoteModel.NO_UUID))).getBitmap(), context.getString(R.string.CFC_tag_name)); ret[j++] = criterion; } @@ -65,16 +65,16 @@ public class TagCustomFilterCriteriaExposer extends BroadcastReceiver { // built in criteria: tags containing X { CustomFilterCriterion criterion = new TextInputCriterion( - IDENTIFIER_TAG_CONTAINS, - context.getString(R.string.CFC_tag_contains_text), - Query.select(Metadata.TASK).from(Metadata.TABLE).join(Join.inner( - Task.TABLE, Metadata.TASK.eq(Task.ID))).where(Criterion.and( - TaskDao.TaskCriteria.activeAndVisible(), - MetadataDao.MetadataCriteria.withKey(TaskToTagMetadata.KEY), - TaskToTagMetadata.TAG_NAME.like("%?%"), Metadata.DELETION_DATE.eq(0))).toString(), - null, context.getString(R.string.CFC_tag_contains_name), "", - ((BitmapDrawable)r.getDrawable(TagService.getDefaultImageIDForTag(RemoteModel.NO_UUID))).getBitmap(), - context.getString(R.string.CFC_tag_contains_name)); + IDENTIFIER_TAG_CONTAINS, + context.getString(R.string.CFC_tag_contains_text), + Query.select(Metadata.TASK).from(Metadata.TABLE).join(Join.inner( + Task.TABLE, Metadata.TASK.eq(Task.ID))).where(Criterion.and( + TaskDao.TaskCriteria.activeAndVisible(), + MetadataDao.MetadataCriteria.withKey(TaskToTagMetadata.KEY), + TaskToTagMetadata.TAG_NAME.like("%?%"), Metadata.DELETION_DATE.eq(0))).toString(), + null, context.getString(R.string.CFC_tag_contains_name), "", + ((BitmapDrawable) r.getDrawable(TagService.getDefaultImageIDForTag(RemoteModel.NO_UUID))).getBitmap(), + context.getString(R.string.CFC_tag_contains_name)); ret[j++] = criterion; } diff --git a/astrid/plugin-src/com/todoroo/astrid/tags/TagDetailExposer.java b/astrid/plugin-src/com/todoroo/astrid/tags/TagDetailExposer.java index e0265bc47..c00ca113b 100644 --- a/astrid/plugin-src/com/todoroo/astrid/tags/TagDetailExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/tags/TagDetailExposer.java @@ -15,7 +15,6 @@ import com.todoroo.astrid.api.AstridApiConstants; * Exposes Task Detail for tags, i.e. "Tags: frogs, animals" * * @author Tim Su - * */ public class TagDetailExposer extends BroadcastReceiver { @@ -23,11 +22,11 @@ public class TagDetailExposer extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { // get tags associated with this task long taskId = intent.getLongExtra(AstridApiConstants.EXTRAS_TASK_ID, -1); - if(taskId == -1) + if (taskId == -1) return; String taskDetail = getTaskDetails(taskId); - if(taskDetail == null) + if (taskDetail == null) return; // transmit @@ -40,7 +39,7 @@ public class TagDetailExposer extends BroadcastReceiver { public String getTaskDetails(long id) { String tagList = TagService.getInstance().getTagsAsString(id); - if(tagList.length() == 0) + if (tagList.length() == 0) return null; return /*" " +*/ tagList; diff --git a/astrid/plugin-src/com/todoroo/astrid/tags/TagFilterExposer.java b/astrid/plugin-src/com/todoroo/astrid/tags/TagFilterExposer.java index fd1fec40b..48798776c 100644 --- a/astrid/plugin-src/com/todoroo/astrid/tags/TagFilterExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/tags/TagFilterExposer.java @@ -5,9 +5,6 @@ */ package com.todoroo.astrid.tags; -import java.util.ArrayList; -import java.util.List; - import android.app.Activity; import android.content.BroadcastReceiver; import android.content.ComponentName; @@ -51,22 +48,28 @@ import com.todoroo.astrid.service.TagDataService; import com.todoroo.astrid.service.ThemeService; import com.todoroo.astrid.tags.TagService.Tag; +import java.util.ArrayList; +import java.util.List; + /** * Exposes filters based on tags * * @author Tim Su - * */ public class TagFilterExposer extends BroadcastReceiver implements AstridFilterExposer { private static final String TAG = "tag"; //$NON-NLS-1$ - @Autowired protected TagDataService tagDataService; - @Autowired GtasksPreferenceService gtasksPreferenceService; + @Autowired + protected TagDataService tagDataService; + @Autowired + GtasksPreferenceService gtasksPreferenceService; protected boolean addUntaggedFilter = true; - /** Create filter from new tag object */ + /** + * Create filter from new tag object + */ @SuppressWarnings("nls") public static FilterWithCustomIntent filterFromTag(Context context, Tag tag, Criterion criterion) { String title = tag.tag; @@ -81,7 +84,7 @@ public class TagFilterExposer extends BroadcastReceiver implements AstridFilterE FilterWithUpdate filter = new FilterWithUpdate(tag.tag, title, tagTemplate, contentValues); - if(!RemoteModel.NO_UUID.equals(tag.uuid)) { + if (!RemoteModel.NO_UUID.equals(tag.uuid)) { filter.listingTitle += " (" + tag.count + ")"; } @@ -91,17 +94,17 @@ public class TagFilterExposer extends BroadcastReceiver implements AstridFilterE else deleteIntentLabel = R.string.tag_cm_delete; - filter.contextMenuLabels = new String[] { - context.getString(R.string.tag_cm_rename), - context.getString(deleteIntentLabel) + filter.contextMenuLabels = new String[]{ + context.getString(R.string.tag_cm_rename), + context.getString(deleteIntentLabel) }; - filter.contextMenuIntents = new Intent[] { + filter.contextMenuIntents = new Intent[]{ newTagIntent(context, RenameTagActivity.class, tag, tag.uuid), newTagIntent(context, DeleteTagActivity.class, tag, tag.uuid) }; filter.customTaskList = new ComponentName(ContextManager.getContext(), TagViewFragment.class); - if(tag.image != null) + if (tag.image != null) filter.imageUrl = tag.image; Bundle extras = new Bundle(); extras.putString(TagViewFragment.EXTRA_TAG_NAME, tag.tag); @@ -111,7 +114,9 @@ public class TagFilterExposer extends BroadcastReceiver implements AstridFilterE return filter; } - /** Create a filter from tag data object */ + /** + * Create a filter from tag data object + */ public static FilterWithCustomIntent filterFromTagData(Context context, TagData tagData) { Tag tag = new Tag(tagData); return filterFromTag(context, tag, TaskCriteria.activeAndVisible()); @@ -174,12 +179,12 @@ public class TagFilterExposer extends BroadcastReceiver implements AstridFilterE r.getString(R.string.tag_FEx_untagged), TagService.getInstance().untaggedTemplate(), null); - untagged.listingIcon = ((BitmapDrawable)r.getDrawable( + untagged.listingIcon = ((BitmapDrawable) r.getDrawable( ThemeService.getDrawable(R.drawable.gl_lists, themeFlags))).getBitmap(); filters.add(untagged); } - for(int i = 0; i < tags.length; i++) { + for (int i = 0; i < tags.length; i++) { Filter f = constructFilter(context, tags[i]); if (f != null) filters.add(f); @@ -199,9 +204,12 @@ public class TagFilterExposer extends BroadcastReceiver implements AstridFilterE protected String tag; protected String uuid; - @Autowired public TagService tagService; - @Autowired public TagDataDao tagDataDao; - @Autowired public TagMetadataDao tagMetadataDao; + @Autowired + public TagService tagService; + @Autowired + public TagDataDao tagDataDao; + @Autowired + public TagMetadataDao tagMetadataDao; static { AstridDependencyInjector.initialize(); @@ -214,7 +222,7 @@ public class TagFilterExposer extends BroadcastReceiver implements AstridFilterE tag = getIntent().getStringExtra(TAG); uuid = getIntent().getStringExtra(TagViewFragment.EXTRA_TAG_UUID); - if(tag == null || RemoteModel.isUuidEmpty(uuid)) { + if (tag == null || RemoteModel.isUuidEmpty(uuid)) { finish(); return; } @@ -261,7 +269,7 @@ public class TagFilterExposer extends BroadcastReceiver implements AstridFilterE private void toastNoChanges() { Toast.makeText(this, R.string.TEA_no_tags_modified, - Toast.LENGTH_SHORT).show(); + Toast.LENGTH_SHORT).show(); } protected abstract void showDialog(TagData tagData); @@ -279,8 +287,7 @@ public class TagFilterExposer extends BroadcastReceiver implements AstridFilterE string = R.string.actfm_tag_operation_owner_delete; else string = R.string.DLG_leave_this_shared_tag_question; - } - else + } else string = R.string.DLG_delete_this_tag_question; DialogUtilities.okCancelDialog(this, getString(string, tag), getOkListener(), getCancelListener()); } @@ -304,7 +311,7 @@ public class TagFilterExposer extends BroadcastReceiver implements AstridFilterE @Override protected Intent ok() { - if(editor == null) + if (editor == null) return null; String text = editor.getText().toString(); diff --git a/astrid/plugin-src/com/todoroo/astrid/tags/TagService.java b/astrid/plugin-src/com/todoroo/astrid/tags/TagService.java index 5aca64063..d23f267d9 100644 --- a/astrid/plugin-src/com/todoroo/astrid/tags/TagService.java +++ b/astrid/plugin-src/com/todoroo/astrid/tags/TagService.java @@ -5,13 +5,6 @@ */ package com.todoroo.astrid.tags; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Set; - import android.content.Context; import android.content.Intent; import android.text.TextUtils; @@ -47,11 +40,17 @@ import com.todoroo.astrid.service.MetadataService; import com.todoroo.astrid.service.TagDataService; import com.todoroo.astrid.service.TaskService; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; + /** * Provides operations for working with tags * * @author Tim Su - * */ @SuppressWarnings("nls") public final class TagService { @@ -63,28 +62,32 @@ public final class TagService { private static TagService instance = null; - private static int[] default_tag_images = new int[] { - R.drawable.default_list_0, - R.drawable.default_list_1, - R.drawable.default_list_2, - R.drawable.default_list_3 + private static int[] default_tag_images = new int[]{ + R.drawable.default_list_0, + R.drawable.default_list_1, + R.drawable.default_list_2, + R.drawable.default_list_3 }; public static synchronized TagService getInstance() { - if(instance == null) + if (instance == null) instance = new TagService(); return instance; } // --- implementation details - @Autowired MetadataDao metadataDao; + @Autowired + MetadataDao metadataDao; - @Autowired TaskService taskService; + @Autowired + TaskService taskService; - @Autowired TagDataService tagDataService; + @Autowired + TagDataService tagDataService; - @Autowired TagDataDao tagDataDao; + @Autowired + TagDataDao tagDataDao; public TagService() { DependencyInjectionService.getInstance().inject(this); @@ -101,7 +104,6 @@ public final class TagService { * Helper class for returning a tag/task count pair * * @author Tim Su - * */ public static final class Tag { public String tag; @@ -185,16 +187,16 @@ public final class TagService { /** * Return all tags ordered by given clause * - * @param order ordering + * @param order ordering * @param activeStatus criterion for specifying completed or uncompleted * @return empty array if no tags, otherwise array */ public Tag[] getGroupedTags(Order order, Criterion activeStatus) { Criterion criterion = Criterion.and(activeStatus, MetadataCriteria.withKey(TaskToTagMetadata.KEY)); Query query = Query.select(TaskToTagMetadata.TAG_NAME, TaskToTagMetadata.TAG_UUID, COUNT). - join(Join.inner(Task.TABLE, Metadata.TASK.eq(Task.ID))). - where(criterion). - orderBy(order).groupBy(TaskToTagMetadata.TAG_NAME); + join(Join.inner(Task.TABLE, Metadata.TASK.eq(Task.ID))). + where(criterion). + orderBy(order).groupBy(TaskToTagMetadata.TAG_NAME); TodorooCursor cursor = metadataDao.query(query); try { ArrayList array = new ArrayList(); @@ -232,13 +234,14 @@ public final class TagService { public void createLink(Task task, String tagName, String tagUuid) { Metadata link = TaskToTagMetadata.newTagMetadata(task.getId(), task.getUuid(), tagName, tagUuid); if (metadataDao.update(Criterion.and(MetadataCriteria.byTaskAndwithKey(task.getId(), TaskToTagMetadata.KEY), - TaskToTagMetadata.TASK_UUID.eq(task.getValue(Task.UUID)), TaskToTagMetadata.TAG_UUID.eq(tagUuid)), link) <= 0) { + TaskToTagMetadata.TASK_UUID.eq(task.getValue(Task.UUID)), TaskToTagMetadata.TAG_UUID.eq(tagUuid)), link) <= 0) { metadataDao.createNew(link); } } /** * Creates a link for a nameless tag. We expect the server to fill in the tag name with a MakeChanges message later + * * @param taskId * @param taskUuid * @param tagUuid @@ -271,6 +274,7 @@ public final class TagService { /** * Delete a single task to tag link + * * @param taskUuid * @param tagUuid */ @@ -287,6 +291,7 @@ public final class TagService { /** * Delete all links between the specified task and the list of tags + * * @param taskUuid * @param tagUuids */ @@ -315,8 +320,8 @@ public final class TagService { */ public TodorooCursor getTags(long taskId) { Criterion criterion = Criterion.and(MetadataCriteria.withKey(TaskToTagMetadata.KEY), - Metadata.DELETION_DATE.eq(0), - MetadataCriteria.byTask(taskId)); + Metadata.DELETION_DATE.eq(0), + MetadataCriteria.byTask(taskId)); Query query = Query.select(TaskToTagMetadata.TAG_NAME, TaskToTagMetadata.TAG_UUID).where(criterion).orderBy(Order.asc(Functions.upper(TaskToTagMetadata.TAG_NAME))); return metadataDao.query(query); } @@ -378,7 +383,7 @@ public final class TagService { TagData tagData = tagDataDao.fetch(uuid, TagData.ID, TagData.UUID, TagData.DELETION_DATE, TagData.MEMBER_COUNT, TagData.USER_ID); boolean shared = false; Intent tagDeleted = new Intent(AstridApiConstants.BROADCAST_EVENT_TAG_DELETED); - if(tagData != null) { + if (tagData != null) { tagData.setValue(TagData.DELETION_DATE, DateUtilities.now()); PluginServices.getTagDataService().save(tagData); tagDeleted.putExtra(TagViewFragment.EXTRA_TAG_UUID, tagData.getUuid()); @@ -393,6 +398,7 @@ public final class TagService { /** * Return all tags (including metadata tags and TagData tags) in an array list + * * @return */ public ArrayList getTagList() { @@ -401,13 +407,13 @@ public final class TagService { TagData.IS_FOLDER.neq(1)), TagData.NAME.isNotNull())).orderBy(Order.asc(Functions.upper(TagData.NAME)))); try { TagData tagData = new TagData(); - for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { + for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { tagData.readFromCursor(cursor); - if(tagData.getFlag(TagData.FLAGS, TagData.FLAG_FEATURED)) { + if (tagData.getFlag(TagData.FLAGS, TagData.FLAG_FEATURED)) { continue; } Tag tag = new Tag(tagData); - if(TextUtils.isEmpty(tag.tag)) + if (TextUtils.isEmpty(tag.tag)) continue; tagList.add(tag); } @@ -424,13 +430,13 @@ public final class TagService { .where(Functions.bitwiseAnd(TagData.FLAGS, TagData.FLAG_FEATURED).gt(0))); try { TagData tagData = new TagData(); - for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { + for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { tagData.readFromCursor(cursor); if (tagData.getValue(TagData.DELETION_DATE) > 0) continue; String tagName = tagData.getValue(TagData.NAME).trim(); Tag tag = new Tag(tagData); - if(TextUtils.isEmpty(tag.tag)) + if (TextUtils.isEmpty(tag.tag)) continue; tags.put(tagName, tag); } @@ -440,16 +446,17 @@ public final class TagService { ArrayList tagList = new ArrayList(tags.values()); Collections.sort(tagList, new Comparator() { - @Override - public int compare(Tag object1, Tag object2) { - return object1.tag.compareToIgnoreCase(object2.tag); - } - }); + @Override + public int compare(Tag object1, Tag object2) { + return object1.tag.compareToIgnoreCase(object2.tag); + } + }); return tagList; } /** * Save the given array of tags into the database + * * @param taskId * @param tags */ @@ -490,6 +497,7 @@ public final class TagService { /** * If a tag already exists in the database that case insensitively matches the * given tag, return that. Otherwise, return the argument + * * @param tag * @return */ @@ -562,9 +570,9 @@ public final class TagService { public static int getDefaultImageIDForTag(String nameOrUUID) { if (RemoteModel.NO_UUID.equals(nameOrUUID)) { - int random = (int)(Math.random()*4); + int random = (int) (Math.random() * 4); return default_tag_images[random]; } - return default_tag_images[((int)Math.abs(nameOrUUID.hashCode()))%4]; + return default_tag_images[((int) Math.abs(nameOrUUID.hashCode())) % 4]; } } diff --git a/astrid/plugin-src/com/todoroo/astrid/tags/TagsControlSet.java b/astrid/plugin-src/com/todoroo/astrid/tags/TagsControlSet.java index e842c7c70..540fd3631 100644 --- a/astrid/plugin-src/com/todoroo/astrid/tags/TagsControlSet.java +++ b/astrid/plugin-src/com/todoroo/astrid/tags/TagsControlSet.java @@ -5,10 +5,6 @@ */ package com.todoroo.astrid.tags; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashSet; - import android.app.Activity; import android.text.Editable; import android.text.TextUtils; @@ -39,11 +35,14 @@ import com.todoroo.astrid.tags.TagService.Tag; import com.todoroo.astrid.ui.PopupControlSet; import com.todoroo.astrid.utility.Flags; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashSet; + /** * Control set to manage adding and removing tags * * @author Tim Su - * */ public final class TagsControlSet extends PopupControlSet { @@ -112,21 +111,21 @@ public final class TagsControlSet extends PopupControlSet { } else { allTagNames.add(tag); tagIndices.put(tag, allTagNames.size() - 1); - ((ArrayAdapter)selectedTags.getAdapter()).notifyDataSetChanged(); + ((ArrayAdapter) selectedTags.getAdapter()).notifyDataSetChanged(); } } private LinkedHashSet getTagSet() { LinkedHashSet tags = new LinkedHashSet(); if (initialized) { - for(int i = 0; i < selectedTags.getAdapter().getCount(); i++) { + for (int i = 0; i < selectedTags.getAdapter().getCount(); i++) { if (selectedTags.isItemChecked(i)) tags.add(allTagNames.get(i)); } - for(int i = 0; i < newTags.getChildCount(); i++) { + for (int i = 0; i < newTags.getChildCount(); i++) { TextView tagName = (TextView) newTags.getChildAt(i).findViewById(R.id.text1); - if(tagName.getText().length() == 0) + if (tagName.getText().length() == 0) continue; tags.add(tagName.getText().toString()); @@ -139,31 +138,33 @@ public final class TagsControlSet extends PopupControlSet { return tags; } - /** Adds a tag to the tag field */ + /** + * Adds a tag to the tag field + */ boolean addTag(String tagName, boolean reuse) { LayoutInflater inflater = activity.getLayoutInflater(); // check if already exists TextView lastText = null; - for(int i = 0; i < newTags.getChildCount(); i++) { + for (int i = 0; i < newTags.getChildCount(); i++) { View view = newTags.getChildAt(i); lastText = (TextView) view.findViewById(R.id.text1); - if(lastText.getText().equals(tagName)) + if (lastText.getText().equals(tagName)) return false; } final View tagItem; - if(reuse && lastText != null && lastText.getText().length() == 0) { + if (reuse && lastText != null && lastText.getText().length() == 0) { tagItem = (View) lastText.getParent(); } else { tagItem = inflater.inflate(R.layout.tag_edit_row, null); newTags.addView(tagItem); } - if(tagName == null) + if (tagName == null) tagName = ""; //$NON-NLS-1$ - final AutoCompleteTextView textView = (AutoCompleteTextView)tagItem. - findViewById(R.id.text1); + final AutoCompleteTextView textView = (AutoCompleteTextView) tagItem. + findViewById(R.id.text1); textView.setText(tagName); textView.addTextChangedListener(new TextWatcher() { @@ -171,15 +172,17 @@ public final class TagsControlSet extends PopupControlSet { public void afterTextChanged(Editable s) { // } + @Override public void beforeTextChanged(CharSequence s, int start, int count, - int after) { + int after) { // } + @Override public void onTextChanged(CharSequence s, int start, int before, - int count) { - if(count > 0 && newTags.getChildAt(newTags.getChildCount()-1) == + int count) { + if (count > 0 && newTags.getChildAt(newTags.getChildCount() - 1) == tagItem) addTag("", false); //$NON-NLS-1$ } @@ -188,9 +191,9 @@ public final class TagsControlSet extends PopupControlSet { textView.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView arg0, int actionId, KeyEvent arg2) { - if(actionId != EditorInfo.IME_NULL) + if (actionId != EditorInfo.IME_NULL) return false; - if(getLastTextView().getText().length() != 0) { + if (getLastTextView().getText().length() != 0) { addTag("", false); //$NON-NLS-1$ } return true; @@ -198,14 +201,14 @@ public final class TagsControlSet extends PopupControlSet { }); ImageButton reminderRemoveButton; - reminderRemoveButton = (ImageButton)tagItem.findViewById(R.id.button1); + reminderRemoveButton = (ImageButton) tagItem.findViewById(R.id.button1); reminderRemoveButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { TextView lastView = getLastTextView(); - if(lastView == textView && textView.getText().length() == 0) + if (lastView == textView && textView.getText().length() == 0) return; - if(newTags.getChildCount() > 1) + if (newTags.getChildCount() > 1) newTags.removeView(tagItem); else textView.setText(""); //$NON-NLS-1$ @@ -217,12 +220,13 @@ public final class TagsControlSet extends PopupControlSet { /** * Get tags container last text view. might be null + * * @return */ private TextView getLastTextView() { - if(newTags.getChildCount() == 0) + if (newTags.getChildCount() == 0) return null; - View lastItem = newTags.getChildAt(newTags.getChildCount()-1); + View lastItem = newTags.getChildAt(newTags.getChildCount() - 1); TextView lastText = (TextView) lastItem.findViewById(R.id.text1); return lastText; } @@ -230,11 +234,11 @@ public final class TagsControlSet extends PopupControlSet { @Override public void readFromTask(Task task) { super.readFromTask(task); - if(model.getId() != AbstractModel.NO_ID) { + if (model.getId() != AbstractModel.NO_ID) { TodorooCursor cursor = tagService.getTags(model.getId()); LinkedHashSet tags = new LinkedHashSet(cursor.getCount()); try { - for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { + for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { String tag = cursor.get(TaskToTagMetadata.TAG_NAME); tags.add(tag); } @@ -253,7 +257,7 @@ public final class TagsControlSet extends PopupControlSet { for (int i = 0; i < selectedTags.getCount(); i++) { // clear all selected items selectedTags.setItemChecked(i, false); } - if(model.getId() != AbstractModel.NO_ID) { + if (model.getId() != AbstractModel.NO_ID) { selectTagsFromModel(); } addTag("", false); //$NON-NLS-1$ @@ -293,12 +297,12 @@ public final class TagsControlSet extends PopupControlSet { @Override protected String writeToModelAfterInitialized(Task task) { // this is a case where we're asked to save but the UI was not yet populated - if(!populated) + if (!populated) return null; LinkedHashSet tags = getTagSet(); - if(TagService.getInstance().synchronizeTags(task.getId(), task.getValue(Task.UUID), tags)) { + if (TagService.getInstance().synchronizeTags(task.getId(), task.getValue(Task.UUID), tags)) { Flags.set(Flags.TAGS_CHANGED); task.setValue(Task.MODIFICATION_DATE, DateUtilities.now()); } diff --git a/astrid/plugin-src/com/todoroo/astrid/tags/TagsPlugin.java b/astrid/plugin-src/com/todoroo/astrid/tags/TagsPlugin.java index 38d8d2115..d88bdae4a 100644 --- a/astrid/plugin-src/com/todoroo/astrid/tags/TagsPlugin.java +++ b/astrid/plugin-src/com/todoroo/astrid/tags/TagsPlugin.java @@ -33,6 +33,7 @@ public class TagsPlugin extends BroadcastReceiver { /** * Create new tag data + * * @param activity */ public static Intent newTagDialog(Context context) { diff --git a/astrid/plugin-src/com/todoroo/astrid/tags/TaskToTagMetadata.java b/astrid/plugin-src/com/todoroo/astrid/tags/TaskToTagMetadata.java index 1002e42e8..f013c65fe 100644 --- a/astrid/plugin-src/com/todoroo/astrid/tags/TaskToTagMetadata.java +++ b/astrid/plugin-src/com/todoroo/astrid/tags/TaskToTagMetadata.java @@ -5,17 +5,25 @@ import com.todoroo.astrid.data.Metadata; public class TaskToTagMetadata { - /** Metadata key for tag data */ + /** + * Metadata key for tag data + */ public static final String KEY = "tags-tag"; //$NON-NLS-1$ - /** Property for reading tag values */ + /** + * Property for reading tag values + */ public static final StringProperty TAG_NAME = Metadata.VALUE1; - /** Tag uuid */ + /** + * Tag uuid + */ public static final StringProperty TAG_UUID = new StringProperty( Metadata.TABLE, Metadata.VALUE2.name); - /** Task uuid */ + /** + * Task uuid + */ public static final StringProperty TASK_UUID = new StringProperty( Metadata.TABLE, Metadata.VALUE3.name); @@ -26,6 +34,7 @@ public class TaskToTagMetadata { * New metadata object for linking a task to the specified tag. The task * object should be saved and have the uuid property. All parameters * are manditory + * * @param taskId * @param tagName * @param taskUuid diff --git a/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedListFilterAdapter.java b/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedListFilterAdapter.java index 14f22ce75..9e96040c4 100644 --- a/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedListFilterAdapter.java +++ b/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedListFilterAdapter.java @@ -15,7 +15,7 @@ public class FeaturedListFilterAdapter extends FilterAdapter { public static final String BROADCAST_SEND_FEATURED_LISTS = Constants.PACKAGE + ".SEND_FEATURED_LISTS"; //$NON-NLS-1$ public FeaturedListFilterAdapter(Activity activity, ListView listView, - int rowLayout, boolean skipIntentFilters) { + int rowLayout, boolean skipIntentFilters) { super(activity, listView, rowLayout, skipIntentFilters); } diff --git a/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedListFilterExposer.java b/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedListFilterExposer.java index c745ef4fb..21b198a8d 100644 --- a/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedListFilterExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedListFilterExposer.java @@ -1,7 +1,5 @@ package com.todoroo.astrid.tags.reusable; -import java.util.List; - import android.content.ComponentName; import android.content.ContentValues; import android.content.Context; @@ -30,6 +28,8 @@ import com.todoroo.astrid.tags.TagService; import com.todoroo.astrid.tags.TagService.Tag; import com.todoroo.astrid.tags.TaskToTagMetadata; +import java.util.List; + public class FeaturedListFilterExposer extends TagFilterExposer { public static final String PREF_SHOULD_SHOW_FEATURED_LISTS = "show_featured_lists"; //$NON-NLS-1$ @@ -58,7 +58,7 @@ public class FeaturedListFilterExposer extends TagFilterExposer { Class fragmentClass = FeaturedTaskListFragment.class; filter.customTaskList = new ComponentName(ContextManager.getContext(), fragmentClass); - if(tag.image != null) + if (tag.image != null) filter.imageUrl = tag.image; Bundle extras = new Bundle(); @@ -71,12 +71,12 @@ public class FeaturedListFilterExposer extends TagFilterExposer { public static Filter getDefaultFilter() { TodorooCursor firstFilter = PluginServices.getTagDataService() - .query(Query.select(TagData.PROPERTIES) - .where(Criterion.and( - Functions.bitwiseAnd(TagData.FLAGS, TagData.FLAG_FEATURED).gt(0), - TagData.DELETION_DATE.eq(0), - TagData.NAME.isNotNull(), - TagData.NAME.neq(""))) //$NON-NLS-1$ + .query(Query.select(TagData.PROPERTIES) + .where(Criterion.and( + Functions.bitwiseAnd(TagData.FLAGS, TagData.FLAG_FEATURED).gt(0), + TagData.DELETION_DATE.eq(0), + TagData.NAME.isNotNull(), + TagData.NAME.neq(""))) //$NON-NLS-1$ .orderBy(Order.asc(TagData.NAME)) .limit(1)); try { diff --git a/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedListFilterMode.java b/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedListFilterMode.java index ef6bc2264..b3e794364 100644 --- a/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedListFilterMode.java +++ b/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedListFilterMode.java @@ -19,8 +19,8 @@ public class FeaturedListFilterMode implements FilterModeSpec { } private static final int[] FORBIDDEN_MENU_ITEMS = { - TaskListFragment.MENU_NEW_FILTER_ID, - MainMenuPopover.MAIN_MENU_ITEM_FEATURED_LISTS + TaskListFragment.MENU_NEW_FILTER_ID, + MainMenuPopover.MAIN_MENU_ITEM_FEATURED_LISTS }; @Override diff --git a/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedTaskListFragment.java b/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedTaskListFragment.java index e03cc95e0..d167b6806 100644 --- a/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedTaskListFragment.java +++ b/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedTaskListFragment.java @@ -38,7 +38,8 @@ import com.todoroo.astrid.utility.ResourceDrawableCache; public class FeaturedTaskListFragment extends TagViewFragment { - @Autowired private TagDataService tagDataService; + @Autowired + private TagDataService tagDataService; private static final int MENU_CLONE_LIST = R.string.actfm_feat_list_clone; @@ -84,7 +85,7 @@ public class FeaturedTaskListFragment extends TagViewFragment { @Override public void onCreateContextMenu(ContextMenu menu, View v, - ContextMenuInfo menuInfo) { + ContextMenuInfo menuInfo) { // Do nothing } @@ -192,7 +193,7 @@ public class FeaturedTaskListFragment extends TagViewFragment { @Override protected void refresh() { loadTaskListContent(true); - ((TextView)taskListView.findViewById(android.R.id.empty)).setText(R.string.TLA_no_items); + ((TextView) taskListView.findViewById(android.R.id.empty)).setText(R.string.TLA_no_items); setUpMembersGallery(); } diff --git a/astrid/plugin-src/com/todoroo/astrid/tags/reusable/ReusableTaskAdapter.java b/astrid/plugin-src/com/todoroo/astrid/tags/reusable/ReusableTaskAdapter.java index acfc74efc..2ebb79d45 100644 --- a/astrid/plugin-src/com/todoroo/astrid/tags/reusable/ReusableTaskAdapter.java +++ b/astrid/plugin-src/com/todoroo/astrid/tags/reusable/ReusableTaskAdapter.java @@ -1,7 +1,5 @@ package com.todoroo.astrid.tags.reusable; -import java.util.concurrent.atomic.AtomicReference; - import android.content.Context; import android.database.Cursor; import android.view.View; @@ -20,17 +18,19 @@ import com.todoroo.astrid.data.RemoteModel; import com.todoroo.astrid.data.Task; import com.todoroo.astrid.utility.Flags; +import java.util.concurrent.atomic.AtomicReference; + public class ReusableTaskAdapter extends TaskAdapter { public ReusableTaskAdapter(TaskListFragment fragment, int resource, - Cursor c, AtomicReference query, boolean autoRequery, - OnCompletedTaskListener onCompletedTaskListener) { + Cursor c, AtomicReference query, boolean autoRequery, + OnCompletedTaskListener onCompletedTaskListener) { super(fragment, resource, c, query, autoRequery, onCompletedTaskListener); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { - ViewGroup view = (ViewGroup)inflater.inflate(resource, parent, false); + ViewGroup view = (ViewGroup) inflater.inflate(resource, parent, false); ReusableTaskViewHolder viewHolder = new ReusableTaskViewHolder(); viewHolder.task = new Task(); @@ -43,7 +43,7 @@ public class ReusableTaskAdapter extends TaskAdapter { } view.setTag(viewHolder); - for(int i = 0; i < view.getChildCount(); i++) + for (int i = 0; i < view.getChildCount(); i++) view.getChildAt(i).setTag(viewHolder); viewHolder.clone.setOnClickListener(new OnClickListener() { @@ -61,7 +61,7 @@ public class ReusableTaskAdapter extends TaskAdapter { @Override public void bindView(View view, Context context, Cursor c) { - TodorooCursor cursor = (TodorooCursor)c; + TodorooCursor cursor = (TodorooCursor) c; ReusableTaskViewHolder viewHolder = (ReusableTaskViewHolder) view.getTag(); Task task = viewHolder.task; diff --git a/astrid/plugin-src/com/todoroo/astrid/timers/TimerActionControlSet.java b/astrid/plugin-src/com/todoroo/astrid/timers/TimerActionControlSet.java index 9a856a6c4..e9a08cc5d 100644 --- a/astrid/plugin-src/com/todoroo/astrid/timers/TimerActionControlSet.java +++ b/astrid/plugin-src/com/todoroo/astrid/timers/TimerActionControlSet.java @@ -5,9 +5,6 @@ */ package com.todoroo.astrid.timers; -import java.util.LinkedList; -import java.util.List; - import android.app.Activity; import android.os.SystemClock; import android.text.format.DateFormat; @@ -23,6 +20,9 @@ import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.data.Task; import com.todoroo.astrid.helper.TaskEditControlSet; +import java.util.LinkedList; +import java.util.List; + public class TimerActionControlSet extends TaskEditControlSet { private final ImageView timerButton; @@ -66,12 +66,12 @@ public class TimerActionControlSet extends TaskEditControlSet { if (timerActive) { TimerPlugin.updateTimer(activity, model, false); - for(TimerActionListener listener : listeners) + for (TimerActionListener listener : listeners) listener.timerStopped(model); chronometer.stop(); } else { TimerPlugin.updateTimer(activity, model, true); - for(TimerActionListener listener : listeners) + for (TimerActionListener listener : listeners) listener.timerStarted(model); chronometer.start(); } @@ -82,7 +82,7 @@ public class TimerActionControlSet extends TaskEditControlSet { private void updateDisplay() { final int drawable; - if(timerActive) { + if (timerActive) { drawable = R.drawable.icn_timer_stop; } else { drawable = R.drawable.icn_edit_timer; @@ -113,6 +113,7 @@ public class TimerActionControlSet extends TaskEditControlSet { public interface TimerActionListener { public void timerStopped(Task task); + public void timerStarted(Task task); } diff --git a/astrid/plugin-src/com/todoroo/astrid/timers/TimerControlSet.java b/astrid/plugin-src/com/todoroo/astrid/timers/TimerControlSet.java index e8832cf87..17bb8290d 100644 --- a/astrid/plugin-src/com/todoroo/astrid/timers/TimerControlSet.java +++ b/astrid/plugin-src/com/todoroo/astrid/timers/TimerControlSet.java @@ -25,7 +25,6 @@ import com.todoroo.astrid.ui.TimeDurationControlSet; * Control Set for managing repeats * * @author Tim Su - * */ public class TimerControlSet extends PopupControlSet implements TimerActionListener { @@ -44,10 +43,10 @@ public class TimerControlSet extends PopupControlSet implements TimerActionListe estimated = new TimeDurationTaskEditControlSet(activity, getView(), Task.ESTIMATED_SECONDS, R.id.estimatedDuration, 0, R.string.DLG_hour_minutes - ); + ); elapsed = new TimeDurationTaskEditControlSet(activity, getView(), Task.ELAPSED_SECONDS, R.id.elapsedDuration, 0, R.string.DLG_hour_minutes - ); + ); } @Override @@ -74,15 +73,15 @@ public class TimerControlSet extends PopupControlSet implements TimerActionListe /** * Control set for mapping a Property to a TimeDurationControlSet - * @author Tim Su * + * @author Tim Su */ public class TimeDurationTaskEditControlSet extends TaskEditControlSet { private final TimeDurationControlSet controlSet; private final IntegerProperty property; public TimeDurationTaskEditControlSet(Activity activity, View v, IntegerProperty property, int timeButtonId, - int prefixResource, int titleResource) { + int prefixResource, int titleResource) { super(activity, -1); this.property = property; this.controlSet = new TimeDurationControlSet(activity, v, property, diff --git a/astrid/plugin-src/com/todoroo/astrid/timers/TimerDecorationExposer.java b/astrid/plugin-src/com/todoroo/astrid/timers/TimerDecorationExposer.java index a89bdb2b6..50a6676fb 100644 --- a/astrid/plugin-src/com/todoroo/astrid/timers/TimerDecorationExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/timers/TimerDecorationExposer.java @@ -25,7 +25,6 @@ import com.todoroo.astrid.data.Task; * Exposes {@link TaskDecoration} for timers * * @author Tim Su - * */ public class TimerDecorationExposer implements TaskDecorationExposer { @@ -33,7 +32,7 @@ public class TimerDecorationExposer implements TaskDecorationExposer { @Override public TaskDecoration expose(Task task) { - if(task == null || (task.getValue(Task.ELAPSED_SECONDS) == 0 && + if (task == null || (task.getValue(Task.ELAPSED_SECONDS) == 0 && task.getValue(Task.TIMER_START) == 0)) return null; @@ -44,7 +43,7 @@ public class TimerDecorationExposer implements TaskDecorationExposer { TaskDecoration.POSITION_LEFT, 0); long elapsed = task.getValue(Task.ELAPSED_SECONDS) * 1000L; - if(task.getValue(Task.TIMER_START) != 0) { + if (task.getValue(Task.TIMER_START) != 0) { decoration.color = TIMING_BG_COLOR; elapsed += DateUtilities.now() - task.getValue(Task.TIMER_START); decoration.decoration.setChronometer(R.id.timer, SystemClock.elapsedRealtime() - @@ -66,7 +65,7 @@ public class TimerDecorationExposer implements TaskDecorationExposer { public void updateDecoration(Context context, Task task) { TaskDecoration decoration = expose(task); - if(decoration == null) + if (decoration == null) return; Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_SEND_DECORATIONS); diff --git a/astrid/plugin-src/com/todoroo/astrid/timers/TimerFilterExposer.java b/astrid/plugin-src/com/todoroo/astrid/timers/TimerFilterExposer.java index 0b538730e..423a770b6 100644 --- a/astrid/plugin-src/com/todoroo/astrid/timers/TimerFilterExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/timers/TimerFilterExposer.java @@ -28,7 +28,6 @@ import com.todoroo.astrid.data.Task; * Exposes "working on" filter to the {@link FilterListFragment} * * @author Tim Su - * */ public final class TimerFilterExposer extends BroadcastReceiver implements AstridFilterExposer { @@ -43,7 +42,7 @@ public final class TimerFilterExposer extends BroadcastReceiver implements Astri } private FilterListItem[] prepareFilters(Context context) { - if(PluginServices.getTaskService().count(Query.select(Task.ID). + if (PluginServices.getTaskService().count(Query.select(Task.ID). where(Task.TIMER_START.gt(0))) == 0) return null; @@ -63,7 +62,7 @@ public final class TimerFilterExposer extends BroadcastReceiver implements Astri r.getString(R.string.TFE_workingOn), new QueryTemplate().where(Task.TIMER_START.gt(0)), values); - workingOn.listingIcon = ((BitmapDrawable)r.getDrawable(R.drawable.tango_clock)).getBitmap(); + workingOn.listingIcon = ((BitmapDrawable) r.getDrawable(R.drawable.tango_clock)).getBitmap(); return workingOn; } diff --git a/astrid/plugin-src/com/todoroo/astrid/timers/TimerPlugin.java b/astrid/plugin-src/com/todoroo/astrid/timers/TimerPlugin.java index 7d1185e30..9af185622 100644 --- a/astrid/plugin-src/com/todoroo/astrid/timers/TimerPlugin.java +++ b/astrid/plugin-src/com/todoroo/astrid/timers/TimerPlugin.java @@ -46,6 +46,7 @@ public class TimerPlugin extends BroadcastReceiver { /** * toggles timer and updates elapsed time. + * * @param task * @param start if true, start timer. else, stop it */ @@ -57,14 +58,14 @@ public class TimerPlugin extends BroadcastReceiver { if (task == null) return; - if(start) { - if(task.getValue(Task.TIMER_START) == 0) { + if (start) { + if (task.getValue(Task.TIMER_START) == 0) { task.setValue(Task.TIMER_START, DateUtilities.now()); StatisticsService.reportEvent(StatisticsConstants.TIMER_START); } } else { - if(task.getValue(Task.TIMER_START) > 0) { - int newElapsed = (int)((DateUtilities.now() - task.getValue(Task.TIMER_START)) / 1000L); + if (task.getValue(Task.TIMER_START) > 0) { + int newElapsed = (int) ((DateUtilities.now() - task.getValue(Task.TIMER_START)) / 1000L); task.setValue(Task.TIMER_START, 0L); task.setValue(Task.ELAPSED_SECONDS, task.getValue(Task.ELAPSED_SECONDS) + newElapsed); @@ -83,7 +84,7 @@ public class TimerPlugin extends BroadcastReceiver { int count = PluginServices.getTaskService().count(Query.select(Task.ID). where(Task.TIMER_START.gt(0))); - if(count == 0) { + if (count == 0) { nm.cancel(Constants.NOTIFICATION_TIMER); } else { Filter filter = TimerFilterExposer.createFilter(context); diff --git a/astrid/plugin-src/com/todoroo/astrid/timers/TimerTaskCompleteListener.java b/astrid/plugin-src/com/todoroo/astrid/timers/TimerTaskCompleteListener.java index 7182c351f..4ff249755 100644 --- a/astrid/plugin-src/com/todoroo/astrid/timers/TimerTaskCompleteListener.java +++ b/astrid/plugin-src/com/todoroo/astrid/timers/TimerTaskCompleteListener.java @@ -20,12 +20,12 @@ public class TimerTaskCompleteListener extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { ContextManager.setContext(context); long taskId = intent.getLongExtra(AstridApiConstants.EXTRAS_TASK_ID, -1); - if(taskId == -1) + if (taskId == -1) return; Task task = PluginServices.getTaskService().fetchById(taskId, Task.ID, Task.ELAPSED_SECONDS, Task.TIMER_START); - if(task == null || task.getValue(Task.TIMER_START) == 0) + if (task == null || task.getValue(Task.TIMER_START) == 0) return; TimerPlugin.updateTimer(context, task, false); diff --git a/astrid/res/anim/slide_bottom_in.xml b/astrid/res/anim/slide_bottom_in.xml index 01e1245b7..2a71f136a 100644 --- a/astrid/res/anim/slide_bottom_in.xml +++ b/astrid/res/anim/slide_bottom_in.xml @@ -15,5 +15,8 @@ --> - + diff --git a/astrid/res/anim/slide_bottom_out.xml b/astrid/res/anim/slide_bottom_out.xml index c297e8768..9b740a528 100644 --- a/astrid/res/anim/slide_bottom_out.xml +++ b/astrid/res/anim/slide_bottom_out.xml @@ -15,5 +15,8 @@ --> - + diff --git a/astrid/res/anim/slide_left_in.xml b/astrid/res/anim/slide_left_in.xml index 291a0f127..6bf096f84 100644 --- a/astrid/res/anim/slide_left_in.xml +++ b/astrid/res/anim/slide_left_in.xml @@ -15,5 +15,8 @@ --> - + diff --git a/astrid/res/anim/slide_left_out.xml b/astrid/res/anim/slide_left_out.xml index 2f3a5dfb1..fb8dfd4a7 100644 --- a/astrid/res/anim/slide_left_out.xml +++ b/astrid/res/anim/slide_left_out.xml @@ -15,5 +15,8 @@ --> - + diff --git a/astrid/res/anim/slide_none.xml b/astrid/res/anim/slide_none.xml index 2b818a771..e1544a3a6 100644 --- a/astrid/res/anim/slide_none.xml +++ b/astrid/res/anim/slide_none.xml @@ -15,5 +15,8 @@ --> - + diff --git a/astrid/res/anim/slide_right_in.xml b/astrid/res/anim/slide_right_in.xml index 749fb14cb..2e8cfc369 100644 --- a/astrid/res/anim/slide_right_in.xml +++ b/astrid/res/anim/slide_right_in.xml @@ -15,5 +15,8 @@ --> - + diff --git a/astrid/res/anim/slide_right_out.xml b/astrid/res/anim/slide_right_out.xml index 84dacfca6..bbfb8d8d9 100644 --- a/astrid/res/anim/slide_right_out.xml +++ b/astrid/res/anim/slide_right_out.xml @@ -15,5 +15,8 @@ --> - + diff --git a/astrid/res/color/new_list_button_text.xml b/astrid/res/color/new_list_button_text.xml index 28fe5af2e..f267fb5cb 100644 --- a/astrid/res/color/new_list_button_text.xml +++ b/astrid/res/color/new_list_button_text.xml @@ -4,9 +4,9 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - - - + + + \ No newline at end of file diff --git a/astrid/res/color/task_edit_toggle_button_text.xml b/astrid/res/color/task_edit_toggle_button_text.xml index 6be054e27..10a851dcc 100644 --- a/astrid/res/color/task_edit_toggle_button_text.xml +++ b/astrid/res/color/task_edit_toggle_button_text.xml @@ -4,9 +4,9 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - - - + + + \ No newline at end of file diff --git a/astrid/res/drawable-v11/importance_title_1.xml b/astrid/res/drawable-v11/importance_title_1.xml index e92f735c8..d43bbdefa 100644 --- a/astrid/res/drawable-v11/importance_title_1.xml +++ b/astrid/res/drawable-v11/importance_title_1.xml @@ -5,9 +5,9 @@ ** See the file "LICENSE" for the full license governing this code. --> - - + android:shape="rectangle"> + + diff --git a/astrid/res/drawable-v11/importance_title_2.xml b/astrid/res/drawable-v11/importance_title_2.xml index d72d40c67..0bbba6e24 100644 --- a/astrid/res/drawable-v11/importance_title_2.xml +++ b/astrid/res/drawable-v11/importance_title_2.xml @@ -5,9 +5,9 @@ ** See the file "LICENSE" for the full license governing this code. --> - - + android:shape="rectangle"> + + diff --git a/astrid/res/drawable-v11/importance_title_3.xml b/astrid/res/drawable-v11/importance_title_3.xml index 2e2a1b118..cf530ce56 100644 --- a/astrid/res/drawable-v11/importance_title_3.xml +++ b/astrid/res/drawable-v11/importance_title_3.xml @@ -5,9 +5,9 @@ ** See the file "LICENSE" for the full license governing this code. --> - - + android:shape="rectangle"> + + diff --git a/astrid/res/drawable-v11/importance_title_4.xml b/astrid/res/drawable-v11/importance_title_4.xml index 15bb40096..acd6bf833 100644 --- a/astrid/res/drawable-v11/importance_title_4.xml +++ b/astrid/res/drawable-v11/importance_title_4.xml @@ -5,9 +5,9 @@ ** See the file "LICENSE" for the full license governing this code. --> - - + android:shape="rectangle"> + + diff --git a/astrid/res/drawable-v11/importance_title_5.xml b/astrid/res/drawable-v11/importance_title_5.xml index cd9a211b1..8acc68ab1 100644 --- a/astrid/res/drawable-v11/importance_title_5.xml +++ b/astrid/res/drawable-v11/importance_title_5.xml @@ -5,9 +5,9 @@ ** See the file "LICENSE" for the full license governing this code. --> - - + android:shape="rectangle"> + + diff --git a/astrid/res/drawable-v11/importance_title_6.xml b/astrid/res/drawable-v11/importance_title_6.xml index 78d787149..462571c49 100644 --- a/astrid/res/drawable-v11/importance_title_6.xml +++ b/astrid/res/drawable-v11/importance_title_6.xml @@ -5,9 +5,9 @@ ** See the file "LICENSE" for the full license governing this code. --> - - + android:shape="rectangle"> + + diff --git a/astrid/res/drawable/astrid_com_gradient.xml b/astrid/res/drawable/astrid_com_gradient.xml index 1ec360c5c..d848d3198 100644 --- a/astrid/res/drawable/astrid_com_gradient.xml +++ b/astrid/res/drawable/astrid_com_gradient.xml @@ -5,12 +5,12 @@ ** See the file "LICENSE" for the full license governing this code. --> - + android:shape="rectangle"> + diff --git a/astrid/res/drawable/btn_add.xml b/astrid/res/drawable/btn_add.xml index eb597adab..10fd568b3 100644 --- a/astrid/res/drawable/btn_add.xml +++ b/astrid/res/drawable/btn_add.xml @@ -17,7 +17,7 @@ - + android:drawable="@drawable/btn_add_pressed"/> + diff --git a/astrid/res/drawable/btn_check.xml b/astrid/res/drawable/btn_check.xml index 80906df34..fdc7445d0 100644 --- a/astrid/res/drawable/btn_check.xml +++ b/astrid/res/drawable/btn_check.xml @@ -18,9 +18,9 @@ + android:drawable="@drawable/icn_check_off"/> + android:drawable="@drawable/icn_check_on"/> diff --git a/astrid/res/drawable/btn_check_small.xml b/astrid/res/drawable/btn_check_small.xml index 3ff6790be..c2b01d344 100644 --- a/astrid/res/drawable/btn_check_small.xml +++ b/astrid/res/drawable/btn_check_small.xml @@ -17,19 +17,19 @@ - + + android:drawable="@android:drawable/checkbox_off_background"/> + android:drawable="@android:drawable/checkbox_on_background"/> + android:drawable="@android:drawable/checkbox_off_background"/> + android:drawable="@android:drawable/checkbox_on_background"/> diff --git a/astrid/res/drawable/btn_clone.xml b/astrid/res/drawable/btn_clone.xml index ed1a20a15..b8cafcaa2 100644 --- a/astrid/res/drawable/btn_clone.xml +++ b/astrid/res/drawable/btn_clone.xml @@ -1,7 +1,7 @@ - + - + android:drawable="@drawable/icn_clone_down"/> + \ No newline at end of file diff --git a/astrid/res/drawable/btn_dismiss.xml b/astrid/res/drawable/btn_dismiss.xml index 78deabd1c..85f793cae 100644 --- a/astrid/res/drawable/btn_dismiss.xml +++ b/astrid/res/drawable/btn_dismiss.xml @@ -17,7 +17,7 @@ - + android:drawable="@drawable/btn_dismiss_pressed"/> + diff --git a/astrid/res/drawable/camera_button.xml b/astrid/res/drawable/camera_button.xml index ff317e87d..321c00cff 100644 --- a/astrid/res/drawable/camera_button.xml +++ b/astrid/res/drawable/camera_button.xml @@ -4,7 +4,7 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + diff --git a/astrid/res/drawable/comment_blue.xml b/astrid/res/drawable/comment_blue.xml index eb8874e7c..4194cf646 100644 --- a/astrid/res/drawable/comment_blue.xml +++ b/astrid/res/drawable/comment_blue.xml @@ -4,7 +4,7 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + diff --git a/astrid/res/drawable/comment_blue_alt.xml b/astrid/res/drawable/comment_blue_alt.xml index e58cf8227..c99077df5 100644 --- a/astrid/res/drawable/comment_blue_alt.xml +++ b/astrid/res/drawable/comment_blue_alt.xml @@ -4,7 +4,7 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + diff --git a/astrid/res/drawable/comment_blue_filled.xml b/astrid/res/drawable/comment_blue_filled.xml index 0999d1f70..c7d6de853 100644 --- a/astrid/res/drawable/comment_blue_filled.xml +++ b/astrid/res/drawable/comment_blue_filled.xml @@ -4,7 +4,7 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + diff --git a/astrid/res/drawable/comment_blue_filled_alt.xml b/astrid/res/drawable/comment_blue_filled_alt.xml index 0a04982a6..6132d0004 100644 --- a/astrid/res/drawable/comment_blue_filled_alt.xml +++ b/astrid/res/drawable/comment_blue_filled_alt.xml @@ -4,7 +4,7 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + diff --git a/astrid/res/drawable/comment_dark_blue.xml b/astrid/res/drawable/comment_dark_blue.xml index 5ec798a31..75f66a557 100644 --- a/astrid/res/drawable/comment_dark_blue.xml +++ b/astrid/res/drawable/comment_dark_blue.xml @@ -4,7 +4,7 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + diff --git a/astrid/res/drawable/comment_dark_blue_filled.xml b/astrid/res/drawable/comment_dark_blue_filled.xml index f8e030937..a10839600 100644 --- a/astrid/res/drawable/comment_dark_blue_filled.xml +++ b/astrid/res/drawable/comment_dark_blue_filled.xml @@ -4,7 +4,7 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + diff --git a/astrid/res/drawable/comment_red.xml b/astrid/res/drawable/comment_red.xml index 82a4c4268..4e8c432ba 100644 --- a/astrid/res/drawable/comment_red.xml +++ b/astrid/res/drawable/comment_red.xml @@ -4,7 +4,7 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + diff --git a/astrid/res/drawable/comment_red_filled.xml b/astrid/res/drawable/comment_red_filled.xml index 19cc37333..e0b5a9738 100644 --- a/astrid/res/drawable/comment_red_filled.xml +++ b/astrid/res/drawable/comment_red_filled.xml @@ -4,7 +4,7 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + diff --git a/astrid/res/drawable/custom_tab_indicator.xml b/astrid/res/drawable/custom_tab_indicator.xml index 58903a5a1..b4d0432de 100644 --- a/astrid/res/drawable/custom_tab_indicator.xml +++ b/astrid/res/drawable/custom_tab_indicator.xml @@ -16,7 +16,7 @@ - - + + diff --git a/astrid/res/drawable/custom_tab_indicator_alt.xml b/astrid/res/drawable/custom_tab_indicator_alt.xml index c190d8b34..8c71b9eb3 100644 --- a/astrid/res/drawable/custom_tab_indicator_alt.xml +++ b/astrid/res/drawable/custom_tab_indicator_alt.xml @@ -16,7 +16,7 @@ - - - + + + diff --git a/astrid/res/drawable/custom_tab_indicator_dark.xml b/astrid/res/drawable/custom_tab_indicator_dark.xml index 68e6f4433..9fa48be36 100644 --- a/astrid/res/drawable/custom_tab_indicator_dark.xml +++ b/astrid/res/drawable/custom_tab_indicator_dark.xml @@ -16,7 +16,7 @@ - - + + diff --git a/astrid/res/drawable/custom_tab_indicator_dark_blue.xml b/astrid/res/drawable/custom_tab_indicator_dark_blue.xml index 2d7df74aa..70a014547 100644 --- a/astrid/res/drawable/custom_tab_indicator_dark_blue.xml +++ b/astrid/res/drawable/custom_tab_indicator_dark_blue.xml @@ -16,7 +16,7 @@ - - + + diff --git a/astrid/res/drawable/custom_tab_indicator_dark_blue_selected_layer.xml b/astrid/res/drawable/custom_tab_indicator_dark_blue_selected_layer.xml index ad423f8f3..697536117 100644 --- a/astrid/res/drawable/custom_tab_indicator_dark_blue_selected_layer.xml +++ b/astrid/res/drawable/custom_tab_indicator_dark_blue_selected_layer.xml @@ -1,5 +1,5 @@ - + \ No newline at end of file diff --git a/astrid/res/drawable/custom_tab_indicator_dark_selected_layer.xml b/astrid/res/drawable/custom_tab_indicator_dark_selected_layer.xml index ef06b958d..48fab6038 100644 --- a/astrid/res/drawable/custom_tab_indicator_dark_selected_layer.xml +++ b/astrid/res/drawable/custom_tab_indicator_dark_selected_layer.xml @@ -1,6 +1,6 @@ - + - + \ No newline at end of file diff --git a/astrid/res/drawable/custom_tab_indicator_selected_alt_layer.xml b/astrid/res/drawable/custom_tab_indicator_selected_alt_layer.xml index b09be76d7..c50508067 100644 --- a/astrid/res/drawable/custom_tab_indicator_selected_alt_layer.xml +++ b/astrid/res/drawable/custom_tab_indicator_selected_alt_layer.xml @@ -1,5 +1,5 @@ - + \ No newline at end of file diff --git a/astrid/res/drawable/custom_tab_indicator_selected_layer.xml b/astrid/res/drawable/custom_tab_indicator_selected_layer.xml index ee32de8f4..094a317a4 100644 --- a/astrid/res/drawable/custom_tab_indicator_selected_layer.xml +++ b/astrid/res/drawable/custom_tab_indicator_selected_layer.xml @@ -1,5 +1,5 @@ - + \ No newline at end of file diff --git a/astrid/res/drawable/edit_title_background.xml b/astrid/res/drawable/edit_title_background.xml index 9c2e3427f..c42341c78 100644 --- a/astrid/res/drawable/edit_title_background.xml +++ b/astrid/res/drawable/edit_title_background.xml @@ -5,15 +5,16 @@ ** See the file "LICENSE" for the full license governing this code. --> + android:shape="rectangle"> - - + android:startColor="#eeeeee" + android:endColor="#ffffff" + android:angle="270" + android:height="20dp"/> + + diff --git a/astrid/res/drawable/edit_title_background_dark.xml b/astrid/res/drawable/edit_title_background_dark.xml index 53d249ee3..8b0a1e818 100644 --- a/astrid/res/drawable/edit_title_background_dark.xml +++ b/astrid/res/drawable/edit_title_background_dark.xml @@ -5,15 +5,16 @@ ** See the file "LICENSE" for the full license governing this code. --> + android:shape="rectangle"> - - + android:startColor="#111111" + android:endColor="#181818" + android:angle="270" + android:height="20dp"/> + + diff --git a/astrid/res/drawable/file_type_background.xml b/astrid/res/drawable/file_type_background.xml index 85a49c924..2ee7fe8f1 100644 --- a/astrid/res/drawable/file_type_background.xml +++ b/astrid/res/drawable/file_type_background.xml @@ -4,8 +4,8 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + \ No newline at end of file diff --git a/astrid/res/drawable/filter_count.xml b/astrid/res/drawable/filter_count.xml index 67557be45..405e2d9ac 100644 --- a/astrid/res/drawable/filter_count.xml +++ b/astrid/res/drawable/filter_count.xml @@ -5,13 +5,13 @@ ** See the file "LICENSE" for the full license governing this code. --> - - + xmlns:android="http://schemas.android.com/apk/res/android" + android:shape="rectangle"> + + \ No newline at end of file diff --git a/astrid/res/drawable/footer_editbutton.xml b/astrid/res/drawable/footer_editbutton.xml index 0449aa4d1..1cb273028 100644 --- a/astrid/res/drawable/footer_editbutton.xml +++ b/astrid/res/drawable/footer_editbutton.xml @@ -17,7 +17,7 @@ - + android:drawable="@drawable/footer_editbutton_pressed"/> + diff --git a/astrid/res/drawable/header_button.xml b/astrid/res/drawable/header_button.xml index 4e05b00bb..c5da31b01 100644 --- a/astrid/res/drawable/header_button.xml +++ b/astrid/res/drawable/header_button.xml @@ -17,11 +17,11 @@ + android:state_focused="true" android:drawable="@drawable/header_background_pressed"/> diff --git a/astrid/res/drawable/header_button_white.xml b/astrid/res/drawable/header_button_white.xml index 59f7bf0d3..bcc2ebedb 100644 --- a/astrid/res/drawable/header_button_white.xml +++ b/astrid/res/drawable/header_button_white.xml @@ -17,11 +17,11 @@ + android:state_focused="true" android:drawable="@drawable/header_background_pressed"/> diff --git a/astrid/res/drawable/importance_1.xml b/astrid/res/drawable/importance_1.xml index 1f4a9bc20..9f87b03e9 100644 --- a/astrid/res/drawable/importance_1.xml +++ b/astrid/res/drawable/importance_1.xml @@ -5,6 +5,6 @@ ** See the file "LICENSE" for the full license governing this code. --> - + android:shape="rectangle"> + diff --git a/astrid/res/drawable/importance_2.xml b/astrid/res/drawable/importance_2.xml index 51b0d8722..98b990bda 100644 --- a/astrid/res/drawable/importance_2.xml +++ b/astrid/res/drawable/importance_2.xml @@ -5,6 +5,6 @@ ** See the file "LICENSE" for the full license governing this code. --> - + android:shape="rectangle"> + diff --git a/astrid/res/drawable/importance_3.xml b/astrid/res/drawable/importance_3.xml index c16a4619c..093a7dc23 100644 --- a/astrid/res/drawable/importance_3.xml +++ b/astrid/res/drawable/importance_3.xml @@ -5,6 +5,6 @@ ** See the file "LICENSE" for the full license governing this code. --> - + android:shape="rectangle"> + diff --git a/astrid/res/drawable/importance_4.xml b/astrid/res/drawable/importance_4.xml index 648a9faa9..89809d50b 100644 --- a/astrid/res/drawable/importance_4.xml +++ b/astrid/res/drawable/importance_4.xml @@ -5,6 +5,6 @@ ** See the file "LICENSE" for the full license governing this code. --> - + android:shape="rectangle"> + diff --git a/astrid/res/drawable/importance_background_selected.xml b/astrid/res/drawable/importance_background_selected.xml index dabd34feb..8f9ea3f31 100644 --- a/astrid/res/drawable/importance_background_selected.xml +++ b/astrid/res/drawable/importance_background_selected.xml @@ -5,11 +5,12 @@ ** See the file "LICENSE" for the full license governing this code. --> - - - + android:shape="rectangle"> + + + diff --git a/astrid/res/drawable/importance_background_selected_dark.xml b/astrid/res/drawable/importance_background_selected_dark.xml index 3ec8b9bd2..579b71672 100644 --- a/astrid/res/drawable/importance_background_selected_dark.xml +++ b/astrid/res/drawable/importance_background_selected_dark.xml @@ -5,11 +5,12 @@ ** See the file "LICENSE" for the full license governing this code. --> - - - + android:shape="rectangle"> + + + diff --git a/astrid/res/drawable/importance_check_1.xml b/astrid/res/drawable/importance_check_1.xml index 5681ffe80..fd39518c7 100644 --- a/astrid/res/drawable/importance_check_1.xml +++ b/astrid/res/drawable/importance_check_1.xml @@ -8,9 +8,9 @@ + android:drawable="@drawable/check_box_1"/> + android:drawable="@drawable/check_box_checked_1"/> \ No newline at end of file diff --git a/astrid/res/drawable/importance_check_2.xml b/astrid/res/drawable/importance_check_2.xml index 9029f73a7..820d86df8 100644 --- a/astrid/res/drawable/importance_check_2.xml +++ b/astrid/res/drawable/importance_check_2.xml @@ -8,9 +8,9 @@ + android:drawable="@drawable/check_box_2"/> + android:drawable="@drawable/check_box_checked_2"/> \ No newline at end of file diff --git a/astrid/res/drawable/importance_check_3.xml b/astrid/res/drawable/importance_check_3.xml index d845b2e43..ba5abb979 100644 --- a/astrid/res/drawable/importance_check_3.xml +++ b/astrid/res/drawable/importance_check_3.xml @@ -8,9 +8,9 @@ + android:drawable="@drawable/check_box_3"/> + android:drawable="@drawable/check_box_checked_3"/> \ No newline at end of file diff --git a/astrid/res/drawable/importance_check_4.xml b/astrid/res/drawable/importance_check_4.xml index 32a513d4d..89da804a6 100644 --- a/astrid/res/drawable/importance_check_4.xml +++ b/astrid/res/drawable/importance_check_4.xml @@ -8,9 +8,9 @@ + android:drawable="@drawable/check_box_4"/> + android:drawable="@drawable/check_box_checked_4"/> \ No newline at end of file diff --git a/astrid/res/drawable/importance_check_repeat_1.xml b/astrid/res/drawable/importance_check_repeat_1.xml index 5c64a294d..568ff19da 100644 --- a/astrid/res/drawable/importance_check_repeat_1.xml +++ b/astrid/res/drawable/importance_check_repeat_1.xml @@ -8,9 +8,9 @@ + android:drawable="@drawable/check_box_repeat_1"/> + android:drawable="@drawable/check_box_repeat_checked_1"/> \ No newline at end of file diff --git a/astrid/res/drawable/importance_check_repeat_2.xml b/astrid/res/drawable/importance_check_repeat_2.xml index 645bec70b..d2cc5a0a3 100644 --- a/astrid/res/drawable/importance_check_repeat_2.xml +++ b/astrid/res/drawable/importance_check_repeat_2.xml @@ -8,9 +8,9 @@ + android:drawable="@drawable/check_box_repeat_2"/> + android:drawable="@drawable/check_box_repeat_checked_2"/> \ No newline at end of file diff --git a/astrid/res/drawable/importance_check_repeat_3.xml b/astrid/res/drawable/importance_check_repeat_3.xml index bdce11fc5..339f720a7 100644 --- a/astrid/res/drawable/importance_check_repeat_3.xml +++ b/astrid/res/drawable/importance_check_repeat_3.xml @@ -8,9 +8,9 @@ + android:drawable="@drawable/check_box_repeat_3"/> + android:drawable="@drawable/check_box_repeat_checked_3"/> \ No newline at end of file diff --git a/astrid/res/drawable/importance_check_repeat_4.xml b/astrid/res/drawable/importance_check_repeat_4.xml index 06e813ffa..c395ff6bc 100644 --- a/astrid/res/drawable/importance_check_repeat_4.xml +++ b/astrid/res/drawable/importance_check_repeat_4.xml @@ -8,9 +8,9 @@ + android:drawable="@drawable/check_box_repeat_4"/> + android:drawable="@drawable/check_box_repeat_checked_4"/> \ No newline at end of file diff --git a/astrid/res/drawable/lists_disclosure_blue.xml b/astrid/res/drawable/lists_disclosure_blue.xml index 8bf99a0e2..d9bb5d362 100644 --- a/astrid/res/drawable/lists_disclosure_blue.xml +++ b/astrid/res/drawable/lists_disclosure_blue.xml @@ -4,7 +4,7 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + \ No newline at end of file diff --git a/astrid/res/drawable/lists_disclosure_blue_alt.xml b/astrid/res/drawable/lists_disclosure_blue_alt.xml index 77c7beb70..6d7bc8a60 100644 --- a/astrid/res/drawable/lists_disclosure_blue_alt.xml +++ b/astrid/res/drawable/lists_disclosure_blue_alt.xml @@ -4,7 +4,7 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + \ No newline at end of file diff --git a/astrid/res/drawable/lists_disclosure_dark_blue.xml b/astrid/res/drawable/lists_disclosure_dark_blue.xml index e3e45f5ca..a68c50277 100644 --- a/astrid/res/drawable/lists_disclosure_dark_blue.xml +++ b/astrid/res/drawable/lists_disclosure_dark_blue.xml @@ -4,7 +4,7 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + \ No newline at end of file diff --git a/astrid/res/drawable/lists_disclosure_red.xml b/astrid/res/drawable/lists_disclosure_red.xml index 6de8eac42..4e1d49edc 100644 --- a/astrid/res/drawable/lists_disclosure_red.xml +++ b/astrid/res/drawable/lists_disclosure_red.xml @@ -4,7 +4,7 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + \ No newline at end of file diff --git a/astrid/res/drawable/menu_button_blue.xml b/astrid/res/drawable/menu_button_blue.xml index df7fce73b..d42526754 100644 --- a/astrid/res/drawable/menu_button_blue.xml +++ b/astrid/res/drawable/menu_button_blue.xml @@ -4,7 +4,7 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + \ No newline at end of file diff --git a/astrid/res/drawable/menu_button_blue_alt.xml b/astrid/res/drawable/menu_button_blue_alt.xml index d5f035274..827e9c16e 100644 --- a/astrid/res/drawable/menu_button_blue_alt.xml +++ b/astrid/res/drawable/menu_button_blue_alt.xml @@ -4,7 +4,7 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + \ No newline at end of file diff --git a/astrid/res/drawable/menu_button_dark_blue.xml b/astrid/res/drawable/menu_button_dark_blue.xml index 3ff8d7a21..6e9e7254c 100644 --- a/astrid/res/drawable/menu_button_dark_blue.xml +++ b/astrid/res/drawable/menu_button_dark_blue.xml @@ -4,7 +4,7 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + \ No newline at end of file diff --git a/astrid/res/drawable/menu_button_red.xml b/astrid/res/drawable/menu_button_red.xml index 9cb1709cc..d320df0c1 100644 --- a/astrid/res/drawable/menu_button_red.xml +++ b/astrid/res/drawable/menu_button_red.xml @@ -4,7 +4,7 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + \ No newline at end of file diff --git a/astrid/res/drawable/mic_button_blue.xml b/astrid/res/drawable/mic_button_blue.xml index eb5a244f2..2f529cec1 100644 --- a/astrid/res/drawable/mic_button_blue.xml +++ b/astrid/res/drawable/mic_button_blue.xml @@ -4,7 +4,7 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + diff --git a/astrid/res/drawable/mic_button_dark_blue.xml b/astrid/res/drawable/mic_button_dark_blue.xml index 04badd710..c5f55fa14 100644 --- a/astrid/res/drawable/mic_button_dark_blue.xml +++ b/astrid/res/drawable/mic_button_dark_blue.xml @@ -4,7 +4,7 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + diff --git a/astrid/res/drawable/mic_button_red.xml b/astrid/res/drawable/mic_button_red.xml index 34fd49602..3a2365ec7 100644 --- a/astrid/res/drawable/mic_button_red.xml +++ b/astrid/res/drawable/mic_button_red.xml @@ -4,7 +4,7 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + diff --git a/astrid/res/drawable/people_menu_button_blue.xml b/astrid/res/drawable/people_menu_button_blue.xml index 0d8cabd0b..865485ca3 100644 --- a/astrid/res/drawable/people_menu_button_blue.xml +++ b/astrid/res/drawable/people_menu_button_blue.xml @@ -4,7 +4,7 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + \ No newline at end of file diff --git a/astrid/res/drawable/people_menu_button_dark_blue.xml b/astrid/res/drawable/people_menu_button_dark_blue.xml index 8ccd97464..0f6eaefd2 100644 --- a/astrid/res/drawable/people_menu_button_dark_blue.xml +++ b/astrid/res/drawable/people_menu_button_dark_blue.xml @@ -4,7 +4,7 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + \ No newline at end of file diff --git a/astrid/res/drawable/people_menu_button_red.xml b/astrid/res/drawable/people_menu_button_red.xml index ecd369170..0255c9d1d 100644 --- a/astrid/res/drawable/people_menu_button_red.xml +++ b/astrid/res/drawable/people_menu_button_red.xml @@ -4,7 +4,7 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + \ No newline at end of file diff --git a/astrid/res/drawable/plus_button_blue.xml b/astrid/res/drawable/plus_button_blue.xml index bfa6b3052..b40486cb6 100644 --- a/astrid/res/drawable/plus_button_blue.xml +++ b/astrid/res/drawable/plus_button_blue.xml @@ -4,7 +4,7 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + diff --git a/astrid/res/drawable/plus_button_dark_blue.xml b/astrid/res/drawable/plus_button_dark_blue.xml index 9ec53bcbc..f0611067a 100644 --- a/astrid/res/drawable/plus_button_dark_blue.xml +++ b/astrid/res/drawable/plus_button_dark_blue.xml @@ -4,7 +4,7 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + diff --git a/astrid/res/drawable/plus_button_red.xml b/astrid/res/drawable/plus_button_red.xml index c748ab93b..7632a53a9 100644 --- a/astrid/res/drawable/plus_button_red.xml +++ b/astrid/res/drawable/plus_button_red.xml @@ -4,7 +4,7 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + diff --git a/astrid/res/drawable/reminder_dialog_background.xml b/astrid/res/drawable/reminder_dialog_background.xml index a4a09ee07..5169a17a3 100644 --- a/astrid/res/drawable/reminder_dialog_background.xml +++ b/astrid/res/drawable/reminder_dialog_background.xml @@ -4,10 +4,10 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - - - + + + \ No newline at end of file diff --git a/astrid/res/drawable/reminder_dialog_inset_background.xml b/astrid/res/drawable/reminder_dialog_inset_background.xml index f683ed047..9ab588654 100644 --- a/astrid/res/drawable/reminder_dialog_inset_background.xml +++ b/astrid/res/drawable/reminder_dialog_inset_background.xml @@ -5,8 +5,8 @@ ** See the file "LICENSE" for the full license governing this code. --> + xmlns:android="http://schemas.android.com/apk/res/android" + android:drawable="@drawable/reminder_dialog_background" + android:insetRight="10dp" + android:insetLeft="10dp"> \ No newline at end of file diff --git a/astrid/res/drawable/task_edit_background.xml b/astrid/res/drawable/task_edit_background.xml index 0bc4b6007..aba80828f 100644 --- a/astrid/res/drawable/task_edit_background.xml +++ b/astrid/res/drawable/task_edit_background.xml @@ -4,20 +4,24 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + - + - + android:color="#222"/> + - - - - + + + + diff --git a/astrid/res/drawable/task_edit_background_transparent_black.xml b/astrid/res/drawable/task_edit_background_transparent_black.xml index 4f42359e1..06eb51e24 100644 --- a/astrid/res/drawable/task_edit_background_transparent_black.xml +++ b/astrid/res/drawable/task_edit_background_transparent_black.xml @@ -4,22 +4,24 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + - + + android:endColor="#33111111" + android:startColor="#33222222"/> - + - - - - + + + + diff --git a/astrid/res/drawable/task_edit_background_transparent_white.xml b/astrid/res/drawable/task_edit_background_transparent_white.xml index 90210e05e..34cc8324c 100644 --- a/astrid/res/drawable/task_edit_background_transparent_white.xml +++ b/astrid/res/drawable/task_edit_background_transparent_white.xml @@ -4,22 +4,24 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + - + + android:endColor="#33eeeeee" + android:startColor="#33d8d8d8"/> - + - - - - + + + + diff --git a/astrid/res/drawable/task_edit_background_white.xml b/astrid/res/drawable/task_edit_background_white.xml index 3bfbaef2f..67167de5f 100644 --- a/astrid/res/drawable/task_edit_background_white.xml +++ b/astrid/res/drawable/task_edit_background_white.xml @@ -4,20 +4,24 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + - + - + android:color="#aaa"/> + - - - - + + + + diff --git a/astrid/res/drawable/task_row_bg_dark.xml b/astrid/res/drawable/task_row_bg_dark.xml index 1e629e27e..5f1dec51a 100644 --- a/astrid/res/drawable/task_row_bg_dark.xml +++ b/astrid/res/drawable/task_row_bg_dark.xml @@ -1,16 +1,16 @@ + android:exitFadeDuration="@android:integer/config_mediumAnimTime"> - + - + + android:drawable="@color/task_row_bg_dark_pressed"/> - + android:state_pressed="false" + android:drawable="@android:color/transparent"/> + \ No newline at end of file diff --git a/astrid/res/drawable/task_row_bg_white.xml b/astrid/res/drawable/task_row_bg_white.xml index 58ae75e9b..8e5d021c0 100644 --- a/astrid/res/drawable/task_row_bg_white.xml +++ b/astrid/res/drawable/task_row_bg_white.xml @@ -1,16 +1,16 @@ + android:exitFadeDuration="@android:integer/config_mediumAnimTime"> - + - + + android:drawable="@color/task_row_bg_white_pressed"/> - + android:state_pressed="false" + android:drawable="@android:color/transparent"/> + \ No newline at end of file diff --git a/astrid/res/drawable/timepicker_down_btn.xml b/astrid/res/drawable/timepicker_down_btn.xml index 17719b065..47e78942b 100644 --- a/astrid/res/drawable/timepicker_down_btn.xml +++ b/astrid/res/drawable/timepicker_down_btn.xml @@ -17,14 +17,14 @@ + android:state_focused="false" android:drawable="@drawable/timepicker_down_normal"/> + android:drawable="@drawable/timepicker_down_pressed"/> + android:state_focused="true" android:drawable="@drawable/timepicker_down_selected"/> + android:state_focused="false" android:drawable="@drawable/timepicker_down_disabled"/> + android:state_focused="true" android:drawable="@drawable/timepicker_down_normal"/> diff --git a/astrid/res/drawable/timepicker_input.xml b/astrid/res/drawable/timepicker_input.xml index b811d4e3a..894cab50a 100644 --- a/astrid/res/drawable/timepicker_input.xml +++ b/astrid/res/drawable/timepicker_input.xml @@ -17,14 +17,14 @@ + android:state_focused="false" android:drawable="@drawable/timepicker_input_normal"/> + android:drawable="@drawable/timepicker_input_pressed"/> + android:state_focused="true" android:drawable="@drawable/timepicker_input_selected"/> + android:state_focused="false" android:drawable="@drawable/timepicker_input_disabled"/> + android:state_focused="true" android:drawable="@drawable/timepicker_input_normal"/> diff --git a/astrid/res/drawable/timepicker_up_btn.xml b/astrid/res/drawable/timepicker_up_btn.xml index d684c37d0..f4ed5891e 100644 --- a/astrid/res/drawable/timepicker_up_btn.xml +++ b/astrid/res/drawable/timepicker_up_btn.xml @@ -17,14 +17,14 @@ + android:state_focused="false" android:drawable="@drawable/timepicker_up_normal"/> + android:drawable="@drawable/timepicker_up_pressed"/> + android:state_focused="true" android:drawable="@drawable/timepicker_up_selected"/> + android:state_focused="false" android:drawable="@drawable/timepicker_up_disabled"/> + android:state_focused="true" android:drawable="@drawable/timepicker_up_normal"/> diff --git a/astrid/res/drawable/vertical_separator.xml b/astrid/res/drawable/vertical_separator.xml index 3ba573afe..97de5ac45 100644 --- a/astrid/res/drawable/vertical_separator.xml +++ b/astrid/res/drawable/vertical_separator.xml @@ -4,8 +4,8 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - - + + \ No newline at end of file diff --git a/astrid/res/drawable/widget_body_legacy.xml b/astrid/res/drawable/widget_body_legacy.xml index c2f0c334a..d3e0fad49 100644 --- a/astrid/res/drawable/widget_body_legacy.xml +++ b/astrid/res/drawable/widget_body_legacy.xml @@ -4,11 +4,11 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - - - + + + \ No newline at end of file diff --git a/astrid/res/drawable/widget_header_legacy.xml b/astrid/res/drawable/widget_header_legacy.xml index bf5d830b7..f03b9665e 100644 --- a/astrid/res/drawable/widget_header_legacy.xml +++ b/astrid/res/drawable/widget_header_legacy.xml @@ -4,14 +4,14 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - - - + + + \ No newline at end of file diff --git a/astrid/res/drawable/wom_edit_background_white.xml b/astrid/res/drawable/wom_edit_background_white.xml index 5c953e9a2..58ee3e814 100644 --- a/astrid/res/drawable/wom_edit_background_white.xml +++ b/astrid/res/drawable/wom_edit_background_white.xml @@ -4,20 +4,24 @@ ** ** See the file "LICENSE" for the full license governing this code. --> - + - + - + android:color="#aaa"/> + - - - - + + + + diff --git a/astrid/res/layout-land/actfm_login_activity.xml b/astrid/res/layout-land/actfm_login_activity.xml index 3be7cf17e..7c680c8e5 100644 --- a/astrid/res/layout-land/actfm_login_activity.xml +++ b/astrid/res/layout-land/actfm_login_activity.xml @@ -1,143 +1,150 @@ - + + android:layout_width="fill_parent" + android:layout_height="fill_parent" + android:paddingLeft="4dip" + android:paddingRight="4dip" + android:background="@drawable/astrid_com_gradient" + android:orientation="vertical"> - - + android:orientation="horizontal"> + + + + + - + android:id="@+id/fb_login" + android:layout_width="fill_parent" + android:layout_height="45dip" + android:layout_marginLeft="15dip" + android:layout_marginRight="15dip" + android:layout_marginBottom="15dip" + android:layout_marginTop="15dip" + android:paddingLeft="70dip" + android:textSize="14sp" + android:gravity="left|center_vertical" + android:background="@drawable/fb_login_background" + android:textColor="@android:color/white" + android:text="@string/actfm_ALA_fb_login" + android:visibility="gone"/> +