From 02a112e3b37fbfdd713269278ab27ecfdca52d94 Mon Sep 17 00:00:00 2001 From: Alex Baker Date: Fri, 30 Mar 2018 15:29:51 -0500 Subject: [PATCH] Apply google-java-format 1.5.1 --- .../amazon/java/org/tasks/FlavorSetup.java | 6 +- .../java/org/tasks/analytics/Tracker.java | 49 +- .../org/tasks/billing/PurchaseHelper.java | 28 +- .../java/org/tasks/gtasks/PlayServices.java | 16 +- .../java/org/tasks/location/GeofenceApi.java | 16 +- .../GeofenceTransitionsIntentService.java | 4 +- .../todoroo/andlib/test/TranslationTests.java | 120 ++-- .../andlib/utility/DateUtilitiesTest.java | 231 ++++--- .../com/todoroo/astrid/dao/TaskDaoTests.java | 24 +- .../com/todoroo/astrid/data/TaskTest.java | 122 ++-- .../com/todoroo/astrid/model/TaskTest.java | 14 +- .../astrid/reminders/ReminderServiceTest.java | 353 ++++++----- .../astrid/repeats/AdvancedRepeatTest.java | 46 +- .../astrid/repeats/NewRepeatTests.java | 90 +-- .../astrid/repeats/RepeatTaskHelperTest.java | 149 ++--- .../astrid/service/QuickAddMarkupTest.java | 3 +- .../astrid/service/TitleParserTest.java | 191 ++---- .../astrid/subtasks/SubtasksHelperTest.java | 13 +- .../astrid/subtasks/SubtasksMovingTest.java | 4 +- .../astrid/subtasks/SubtasksTestCase.java | 4 +- .../todoroo/astrid/sync/SyncModelTest.java | 1 - .../androidTest/java/org/tasks/Snippet.java | 4 +- .../org/tasks/date/DateTimeUtilsTest.java | 20 +- .../tasks/injection/InjectingTestCase.java | 5 +- .../java/org/tasks/jobs/BackupJobTest.java | 19 +- .../org/tasks/jobs/BackupServiceTests.java | 7 +- .../org/tasks/jobs/NotificationQueueTest.java | 138 +++-- .../java/org/tasks/makers/GtaskListMaker.java | 24 +- .../java/org/tasks/makers/Maker.java | 4 +- .../java/org/tasks/makers/TaskMaker.java | 151 ++--- .../tasks/preferences/PreferenceTests.java | 16 +- .../tasks/repeats/RepeatRuleToStringTest.java | 9 +- .../java/org/tasks/time/DateTimeTest.java | 115 ++-- .../astrid/gtasks/GtasksIndentActionTest.java | 6 +- .../astrid/gtasks/GtasksListServiceTest.java | 35 +- .../gtasks/GtasksMetadataServiceTest.java | 7 +- .../gtasks/GtasksTaskListUpdaterTest.java | 46 +- .../astrid/gtasks/GtasksTaskMovingTest.java | 21 +- .../gtasks/GtasksTestPreferenceService.java | 3 +- .../gtasks/api/GtasksApiUtilitiesTest.java | 3 +- .../gtasks/GoogleTaskSynchronizerTest.java | 52 +- .../tasks/makers/RemoteGtaskListMaker.java | 10 +- .../debug/java/org/tasks/BaseApplication.java | 4 +- app/src/debug/java/org/tasks/BuildSetup.java | 24 +- .../generic/java/org/tasks/FlavorSetup.java | 6 +- .../java/org/tasks/analytics/Tracker.java | 24 +- .../org/tasks/billing/PurchaseHelper.java | 23 +- .../java/org/tasks/gtasks/PlayServices.java | 16 +- .../java/org/tasks/location/GeofenceApi.java | 16 +- .../GeofenceTransitionsIntentService.java | 4 +- .../vending/billing/IabBroadcastReceiver.java | 26 +- .../android/vending/billing/IabException.java | 13 +- .../android/vending/billing/IabHelper.java | 577 +++++++++--------- .../android/vending/billing/IabResult.java | 11 +- .../android/vending/billing/Inventory.java | 46 +- .../com/android/vending/billing/Purchase.java | 6 +- .../com/android/vending/billing/Security.java | 35 +- .../android/vending/billing/SkuDetails.java | 4 +- .../java/org/tasks/analytics/Tracker.java | 60 +- .../org/tasks/billing/InventoryHelper.java | 11 +- .../org/tasks/billing/PurchaseHelper.java | 161 ++--- .../java/org/tasks/gtasks/PlayServices.java | 44 +- .../java/org/tasks/location/GeofenceApi.java | 76 ++- .../GeofenceTransitionsIntentService.java | 13 +- .../java/org/tasks/location/GoogleApi.java | 19 +- .../java/org/tasks/location/PlacePicker.java | 5 +- .../mdimension/jchronic/AstridChronic.java | 79 +-- .../com/todoroo/andlib/data/Property.java | 47 +- .../java/com/todoroo/andlib/data/Table.java | 13 +- .../com/todoroo/andlib/sql/Criterion.java | 17 +- .../java/com/todoroo/andlib/sql/DBObject.java | 6 +- .../java/com/todoroo/andlib/sql/Field.java | 15 +- .../com/todoroo/andlib/sql/Functions.java | 7 +- .../java/com/todoroo/andlib/sql/Join.java | 14 +- .../java/com/todoroo/andlib/sql/JoinType.java | 6 +- .../java/com/todoroo/andlib/sql/Operator.java | 3 +- .../java/com/todoroo/andlib/sql/Order.java | 9 +- .../com/todoroo/andlib/sql/OrderType.java | 6 +- .../java/com/todoroo/andlib/sql/Query.java | 7 +- .../com/todoroo/andlib/sql/QueryTemplate.java | 6 +- .../com/todoroo/andlib/sql/SqlConstants.java | 3 +- .../java/com/todoroo/andlib/sql/SqlTable.java | 3 +- .../todoroo/andlib/sql/UnaryCriterion.java | 7 +- .../andlib/utility/AndroidUtilities.java | 112 ++-- .../todoroo/andlib/utility/DateUtilities.java | 63 +- .../andlib/utility/DialogUtilities.java | 23 +- .../astrid/activity/BeastModePreferences.java | 22 +- .../astrid/activity/ShareLinkActivity.java | 8 +- .../astrid/activity/TaskEditFragment.java | 106 ++-- .../astrid/activity/TaskListActivity.java | 107 ++-- .../astrid/activity/TaskListFragment.java | 188 +++--- .../todoroo/astrid/adapter/FilterAdapter.java | 107 ++-- .../todoroo/astrid/adapter/TaskAdapter.java | 42 +- .../todoroo/astrid/alarms/AlarmService.java | 15 +- .../astrid/api/AstridApiConstants.java | 19 +- .../com/todoroo/astrid/api/CaldavFilter.java | 48 +- .../com/todoroo/astrid/api/CustomFilter.java | 42 +- .../astrid/api/CustomFilterCriterion.java | 57 +- .../java/com/todoroo/astrid/api/Filter.java | 114 ++-- .../todoroo/astrid/api/FilterListItem.java | 22 +- .../com/todoroo/astrid/api/GtasksFilter.java | 53 +- .../astrid/api/MultipleSelectCriterion.java | 81 ++- .../java/com/todoroo/astrid/api/PermaSql.java | 130 ++-- .../com/todoroo/astrid/api/TagFilter.java | 47 +- .../com/todoroo/astrid/api/TaskAction.java | 15 +- .../astrid/api/TextInputCriterion.java | 79 +-- .../astrid/backup/BackupConstants.java | 27 +- .../astrid/backup/TasksXmlImporter.java | 78 +-- .../calls/PhoneStateChangedReceiver.java | 81 +-- .../astrid/core/BuiltInFilterExposer.java | 47 +- .../astrid/core/CustomFilterActivity.java | 147 ++--- .../astrid/core/CustomFilterAdapter.java | 132 ++-- .../astrid/core/CustomFilterExposer.java | 7 +- .../astrid/core/DefaultsPreferences.java | 56 +- .../astrid/core/LinkActionExposer.java | 10 +- .../astrid/core/OldTaskPreferences.java | 167 ++--- .../com/todoroo/astrid/core/SortHelper.java | 54 +- .../java/com/todoroo/astrid/dao/Database.java | 65 +- .../java/com/todoroo/astrid/dao/TaskDao.java | 134 ++-- .../com/todoroo/astrid/data/SyncFlags.java | 4 +- .../java/com/todoroo/astrid/data/Task.java | 394 ++++++------ .../astrid/files/AACRecordingActivity.java | 17 +- .../com/todoroo/astrid/files/FilesAction.java | 3 +- .../todoroo/astrid/files/FilesControlSet.java | 69 ++- .../astrid/gcal/CalendarAlarmReceiver.java | 4 +- .../astrid/gcal/CalendarReminderActivity.java | 71 ++- .../com/todoroo/astrid/gcal/GCalHelper.java | 20 +- .../astrid/gtasks/GtasksFilterExposer.java | 3 +- .../astrid/gtasks/GtasksListService.java | 17 +- .../gtasks/GtasksPreferenceService.java | 35 +- .../gtasks/GtasksSubtaskListFragment.java | 7 +- .../astrid/gtasks/GtasksTaskListUpdater.java | 256 ++++---- .../OrderedMetadataListFragmentHelper.java | 40 +- .../astrid/gtasks/api/GtasksApiUtilities.java | 15 +- .../astrid/gtasks/api/GtasksInvoker.java | 87 ++- .../astrid/gtasks/api/MoveRequest.java | 9 +- .../gtasks/auth/GtasksLoginActivity.java | 49 +- .../astrid/gtasks/sync/GtasksSyncService.java | 64 +- .../gtasks/sync/GtasksTaskContainer.java | 8 +- .../com/todoroo/astrid/helper/UUIDHelper.java | 4 +- .../astrid/notes/CommentsController.java | 55 +- .../com/todoroo/astrid/notes/NotesAction.java | 3 +- .../astrid/provider/Astrid2TaskProvider.java | 77 +-- .../astrid/reminders/ReminderPreferences.java | 139 +++-- .../astrid/reminders/ReminderService.java | 58 +- .../astrid/repeats/RepeatControlSet.java | 170 +++--- .../astrid/repeats/RepeatTaskHelper.java | 109 ++-- .../astrid/service/StartupService.java | 28 +- .../todoroo/astrid/service/SyncV2Service.java | 29 +- .../todoroo/astrid/service/TaskCreator.java | 51 +- .../todoroo/astrid/service/TaskDeleter.java | 19 +- .../astrid/service/TaskDuplicator.java | 12 +- .../AstridOrderedListFragmentHelper.java | 20 +- .../subtasks/SubtasksFilterUpdater.java | 40 +- .../astrid/subtasks/SubtasksHelper.java | 55 +- .../astrid/subtasks/SubtasksListFragment.java | 5 +- .../subtasks/SubtasksTagListFragment.java | 7 +- .../astrid/sync/SyncResultCallback.java | 11 +- .../todoroo/astrid/tags/TagFilterExposer.java | 7 +- .../com/todoroo/astrid/tags/TagService.java | 11 +- .../todoroo/astrid/tags/TagsControlSet.java | 156 ++--- .../astrid/timers/TimerControlSet.java | 46 +- .../astrid/timers/TimerFilterExposer.java | 8 +- .../todoroo/astrid/timers/TimerPlugin.java | 37 +- .../todoroo/astrid/ui/CheckableImageView.java | 9 +- .../astrid/ui/EditTitleControlSet.java | 28 +- .../astrid/ui/HideUntilControlSet.java | 127 ++-- .../ui/MultilineCheckboxPreference.java | 3 +- .../todoroo/astrid/ui/MultilineHelper.java | 3 +- .../astrid/ui/MultilineListPreference.java | 3 +- .../astrid/ui/MultilinePreference.java | 3 +- .../astrid/ui/NNumberPickerDialog.java | 36 +- .../com/todoroo/astrid/ui/NumberPicker.java | 138 +++-- .../todoroo/astrid/ui/NumberPickerButton.java | 13 +- .../astrid/ui/RandomReminderControlSet.java | 30 +- .../todoroo/astrid/ui/ReminderControlSet.java | 65 +- .../astrid/ui/TimeDurationControlSet.java | 59 +- .../com/todoroo/astrid/utility/Constants.java | 8 +- .../com/todoroo/astrid/utility/Flags.java | 13 +- .../todoroo/astrid/utility/TitleParser.java | 167 ++--- .../astrid/voice/VoiceOutputAssistant.java | 26 +- .../android/tasker/TaskerPlugin.java | 99 +-- .../ErrorReportingSingleThreadExecutor.java | 15 +- .../java/org/tasks/LocalBroadcastManager.java | 6 +- app/src/main/java/org/tasks/Notifier.java | 82 +-- .../activities/AddAttachmentActivity.java | 12 +- .../activities/CalendarSelectionActivity.java | 16 +- .../activities/CalendarSelectionDialog.java | 31 +- .../org/tasks/activities/CameraActivity.java | 4 +- .../tasks/activities/ColorPickerActivity.java | 27 +- .../activities/DateAndTimePickerActivity.java | 23 +- .../tasks/activities/DatePickerActivity.java | 20 +- .../activities/FilterSelectionActivity.java | 37 +- .../activities/FilterSettingsActivity.java | 59 +- .../GoogleTaskListSettingsActivity.java | 71 ++- .../activities/RemoteListSupportPicker.java | 35 +- .../tasks/activities/TagSettingsActivity.java | 83 +-- .../tasks/activities/TimePickerActivity.java | 31 +- .../java/org/tasks/analytics/Tracking.java | 28 +- .../org/tasks/backup/BackupContainer.java | 18 +- .../org/tasks/backup/TasksJsonExporter.java | 154 +++-- .../org/tasks/backup/TasksJsonImporter.java | 65 +- .../main/java/org/tasks/backup/XmlReader.java | 2 +- .../tasks/caldav/CalDAVSettingsActivity.java | 125 ++-- .../java/org/tasks/caldav/CaldavClient.java | 37 +- .../org/tasks/caldav/CaldavListFragment.java | 7 +- .../tasks/caldav/CaldavSettingsActivity.java | 125 ++-- .../org/tasks/caldav/CaldavSynchronizer.java | 103 ++-- .../org/tasks/caldav/MemoryCookieStore.java | 14 +- .../java/org/tasks/caldav/TaskConverter.java | 21 +- .../org/tasks/calendars/AndroidCalendar.java | 15 +- .../tasks/calendars/AndroidCalendarEvent.java | 30 +- .../AndroidCalendarEventAttendee.java | 12 +- .../CalendarEventAttendeeProvider.java | 25 +- .../calendars/CalendarEventProvider.java | 42 +- .../org/tasks/calendars/CalendarProvider.java | 19 +- .../tasks/dashclock/DashClockExtension.java | 45 +- .../tasks/dashclock/DashClockSettings.java | 29 +- app/src/main/java/org/tasks/data/Alarm.java | 10 +- .../main/java/org/tasks/data/AlarmDao.java | 15 +- .../java/org/tasks/data/CaldavAccount.java | 67 +- .../main/java/org/tasks/data/CaldavTask.java | 43 +- app/src/main/java/org/tasks/data/Filter.java | 23 +- .../main/java/org/tasks/data/GoogleTask.java | 52 +- .../java/org/tasks/data/GoogleTaskDao.java | 9 +- .../java/org/tasks/data/GoogleTaskList.java | 59 +- .../org/tasks/data/LimitOffsetDataSource.java | 12 +- .../main/java/org/tasks/data/Location.java | 56 +- .../main/java/org/tasks/data/LocationDao.java | 6 +- app/src/main/java/org/tasks/data/Tag.java | 9 +- app/src/main/java/org/tasks/data/TagData.java | 54 +- .../main/java/org/tasks/data/TagDataDao.java | 1 - .../java/org/tasks/data/TaskAttachment.java | 33 +- .../org/tasks/data/TaskAttachmentDao.java | 1 - .../java/org/tasks/data/TaskListMetadata.java | 1 - .../org/tasks/data/TaskListMetadataDao.java | 1 - .../java/org/tasks/data/UserActivity.java | 30 +- .../java/org/tasks/date/DateTimeUtils.java | 4 +- .../main/java/org/tasks/db/Migrations.java | 425 ++++++------- .../tasks/dialogs/AddAttachmentDialog.java | 3 +- .../org/tasks/dialogs/AlertDialogBuilder.java | 34 +- .../org/tasks/dialogs/ColorPickerDialog.java | 59 +- .../java/org/tasks/dialogs/DialogBuilder.java | 8 +- .../org/tasks/dialogs/DonationDialog.java | 32 +- .../org/tasks/dialogs/ExportTasksDialog.java | 4 +- .../tasks/dialogs/NativeDatePickerDialog.java | 13 +- .../tasks/dialogs/NativeTimePickerDialog.java | 13 +- .../org/tasks/dialogs/RecordAudioDialog.java | 12 +- .../java/org/tasks/dialogs/SeekBarDialog.java | 23 +- .../java/org/tasks/dialogs/SortDialog.java | 23 +- .../java/org/tasks/files/FileExplore.java | 10 +- .../main/java/org/tasks/files/FileHelper.java | 17 +- .../java/org/tasks/files/ImageHelper.java | 7 +- .../java/org/tasks/filters/FilterCounter.java | 38 +- .../tasks/filters/FilterCriteriaProvider.java | 141 +++-- .../org/tasks/filters/FilterProvider.java | 9 +- .../tasks/filters/NavigationDrawerAction.java | 48 +- .../filters/NavigationDrawerSeparator.java | 33 +- .../filters/NavigationDrawerSubheader.java | 43 +- .../tasks/fragments/CommentBarFragment.java | 72 ++- .../TaskEditControlSetFragmentManager.java | 82 +-- .../tasks/gtasks/GoogleAccountManager.java | 4 +- .../tasks/gtasks/GoogleTaskSynchronizer.java | 105 ++-- ...oogleTasksUnsuccessfulResponseHandler.java | 8 +- .../tasks/gtasks/GtaskSyncAdapterHelper.java | 21 +- .../org/tasks/injection/ActivityScope.java | 4 +- .../tasks/injection/ApplicationModule.java | 3 +- .../org/tasks/injection/ApplicationScope.java | 4 +- .../org/tasks/injection/BroadcastModule.java | 4 +- .../injection/ContentProviderComponent.java | 5 +- .../injection/ContentProviderModule.java | 4 +- .../main/java/org/tasks/injection/Dagger.java | 10 +- .../java/org/tasks/injection/ForActivity.java | 4 +- .../org/tasks/injection/ForApplication.java | 4 +- .../injection/InjectingAppCompatActivity.java | 8 +- .../injection/InjectingAppWidgetProvider.java | 7 +- .../injection/InjectingBroadcastReceiver.java | 7 +- .../injection/InjectingContentProvider.java | 9 +- .../injection/InjectingDialogFragment.java | 4 +- .../tasks/injection/InjectingFragment.java | 4 +- .../injection/InjectingJobIntentService.java | 6 +- .../InjectingNativeDialogFragment.java | 5 +- .../InjectingPreferenceActivity.java | 29 +- .../tasks/injection/IntentServiceModule.java | 4 +- .../ThemedInjectingAppCompatActivity.java | 8 +- .../java/org/tasks/intents/TaskIntents.java | 4 +- .../tasks/jobs/AfterSaveIntentService.java | 22 +- .../main/java/org/tasks/jobs/AlarmEntry.java | 6 +- .../main/java/org/tasks/jobs/BackupJob.java | 28 +- .../main/java/org/tasks/jobs/JobCreator.java | 27 +- .../main/java/org/tasks/jobs/JobManager.java | 33 +- .../org/tasks/jobs/NotificationQueue.java | 11 +- .../java/org/tasks/jobs/ReminderEntry.java | 7 +- app/src/main/java/org/tasks/jobs/SyncJob.java | 2 +- .../main/java/org/tasks/locale/Locale.java | 55 +- .../org/tasks/locale/LocalePickerDialog.java | 12 +- .../locale/bundle/ListNotificationBundle.java | 3 +- .../locale/bundle/TaskCreationBundle.java | 4 +- .../tasks/locale/receiver/FireReceiver.java | 16 +- .../locale/receiver/TaskerIntentService.java | 11 +- .../locale/receiver/TaskerTaskCreator.java | 16 +- ...stractFragmentPluginAppCompatActivity.java | 69 +-- ...tractFragmentPluginPreferenceActivity.java | 65 +- .../ui/activity/TaskerCreateTaskActivity.java | 78 ++- .../ui/activity/TaskerSettingsActivity.java | 49 +- .../org/tasks/location/GeofenceService.java | 4 +- .../org/tasks/notifications/Notification.java | 22 +- .../notifications/NotificationManager.java | 254 ++++---- .../tasks/notifications/TelephonyManager.java | 4 +- .../AppCompatPreferenceActivity.java | 8 +- .../preferences/AppearancePreferences.java | 87 +-- .../tasks/preferences/BasicPreferences.java | 286 +++++---- .../preferences/DateTimePreferences.java | 34 +- .../preferences/DefaultFilterProvider.java | 18 +- .../java/org/tasks/preferences/Device.java | 50 +- .../preferences/HelpAndFeedbackActivity.java | 8 +- .../preferences/MiscellaneousPreferences.java | 88 +-- .../tasks/preferences/PermissionChecker.java | 6 +- .../preferences/PermissionRequestor.java | 18 +- .../org/tasks/preferences/Preferences.java | 31 +- .../beast/BeastModeRecyclerAdapter.java | 13 +- .../beast/BeastModeViewHolder.java | 4 +- .../main/java/org/tasks/receivers/Badger.java | 22 +- .../org/tasks/receivers/PushReceiver.java | 6 +- .../receivers/RepeatConfirmationReceiver.java | 53 +- .../tasks/reminders/MissedCallActivity.java | 25 +- .../org/tasks/reminders/MissedCallDialog.java | 40 +- .../tasks/reminders/NotificationActivity.java | 12 +- .../tasks/reminders/NotificationDialog.java | 40 +- .../org/tasks/reminders/SnoozeActivity.java | 15 +- .../org/tasks/reminders/SnoozeCallback.java | 1 - .../org/tasks/reminders/SnoozeDialog.java | 45 +- .../org/tasks/reminders/SnoozeOption.java | 7 +- .../tasks/repeats/CustomRecurrenceDialog.java | 221 ++++--- .../org/tasks/repeats/RepeatRuleToString.java | 63 +- .../org/tasks/scheduling/AlarmManager.java | 4 +- .../tasks/scheduling/BackgroundScheduler.java | 5 +- .../CalendarNotificationIntentService.java | 21 +- .../GeofenceSchedulingIntentService.java | 7 +- .../NotificationSchedulerIntentService.java | 14 +- .../RecurringIntervalIntentService.java | 6 +- .../tasks/sync/RecordSyncStatusCallback.java | 3 +- .../java/org/tasks/sync/SyncAdapters.java | 5 +- .../java/org/tasks/sync/SyncExecutor.java | 8 +- .../sync/SynchronizationPreferences.java | 115 ++-- .../java/org/tasks/tasklist/ActionUtils.java | 26 +- .../tasks/tasklist/GtasksListFragment.java | 35 +- .../java/org/tasks/tasklist/TagFormatter.java | 56 +- .../org/tasks/tasklist/TagListFragment.java | 7 +- .../tasklist/TaskListRecyclerAdapter.java | 136 +++-- .../java/org/tasks/tasklist/ViewHolder.java | 90 ++- .../org/tasks/tasklist/ViewHolderFactory.java | 28 +- .../java/org/tasks/themes/ThemeAccent.java | 60 +- .../main/java/org/tasks/themes/ThemeBase.java | 39 +- .../java/org/tasks/themes/ThemeCache.java | 83 ++- .../java/org/tasks/themes/ThemeColor.java | 77 +-- .../java/org/tasks/themes/WidgetTheme.java | 32 +- .../main/java/org/tasks/time/DateTime.java | 26 +- .../java/org/tasks/time/DateTimeUtils.java | 4 +- .../java/org/tasks/ui/CalendarControlSet.java | 51 +- .../main/java/org/tasks/ui/CheckBoxes.java | 11 +- .../java/org/tasks/ui/DeadlineControlSet.java | 191 +++--- .../org/tasks/ui/DescriptionControlSet.java | 7 +- .../org/tasks/ui/EmptyTaskEditFragment.java | 4 +- .../org/tasks/ui/HiddenTopArrayAdapter.java | 10 +- .../main/java/org/tasks/ui/MenuColorizer.java | 16 +- .../tasks/ui/NavigationDrawerFragment.java | 44 +- .../java/org/tasks/ui/PriorityControlSet.java | 31 +- .../java/org/tasks/ui/RemoteListFragment.java | 40 +- .../org/tasks/ui/ScrimInsetsFrameLayout.java | 6 +- .../tasks/ui/SingleCheckedArrayAdapter.java | 21 +- .../org/tasks/ui/TaskEditControlFragment.java | 4 +- .../java/org/tasks/ui/TaskListViewModel.java | 40 +- .../java/org/tasks/ui/TimePreference.java | 4 +- .../java/org/tasks/ui/WidgetCheckBoxes.java | 42 +- .../org/tasks/widget/AppWidgetManager.java | 4 +- .../tasks/widget/ScrollableViewsFactory.java | 27 +- .../widget/ScrollableWidgetUpdateService.java | 14 +- .../tasks/widget/ShortcutConfigActivity.java | 6 +- .../java/org/tasks/widget/TasksWidget.java | 29 +- .../tasks/widget/WidgetConfigActivity.java | 106 ++-- .../java/org/tasks/BaseApplication.java | 4 +- .../release/java/org/tasks/BuildSetup.java | 4 +- 383 files changed, 8637 insertions(+), 7658 deletions(-) diff --git a/app/src/amazon/java/org/tasks/FlavorSetup.java b/app/src/amazon/java/org/tasks/FlavorSetup.java index 08cc80bdd..c610bb8d9 100644 --- a/app/src/amazon/java/org/tasks/FlavorSetup.java +++ b/app/src/amazon/java/org/tasks/FlavorSetup.java @@ -5,9 +5,7 @@ import javax.inject.Inject; public class FlavorSetup { @Inject - public FlavorSetup() { - } + public FlavorSetup() {} - public void setup() { - } + public void setup() {} } diff --git a/app/src/amazon/java/org/tasks/analytics/Tracker.java b/app/src/amazon/java/org/tasks/analytics/Tracker.java index d52263f2c..d8d4cfe9b 100644 --- a/app/src/amazon/java/org/tasks/analytics/Tracker.java +++ b/app/src/amazon/java/org/tasks/analytics/Tracker.java @@ -28,24 +28,23 @@ public class Tracker { analytics = GoogleAnalytics.getInstance(context); tracker = analytics.newTracker(R.xml.google_analytics); tracker.setAppVersion(Integer.toString(BuildConfig.VERSION_CODE)); - final StandardExceptionParser standardExceptionParser = new StandardExceptionParser(context, - null); - exceptionParser = (thread, throwable) -> { - StringBuilder stack = new StringBuilder() - .append(standardExceptionParser.getDescription(thread, throwable)) - .append("\n") - .append(throwable.getClass().getName()) - .append("\n"); - for (StackTraceElement element : throwable.getStackTrace()) { - stack.append(element.toString()) - .append("\n"); - } - return stack.toString(); - }; - ExceptionReporter reporter = new ExceptionReporter( - tracker, - Thread.getDefaultUncaughtExceptionHandler(), - context); + final StandardExceptionParser standardExceptionParser = + new StandardExceptionParser(context, null); + exceptionParser = + (thread, throwable) -> { + StringBuilder stack = + new StringBuilder() + .append(standardExceptionParser.getDescription(thread, throwable)) + .append("\n") + .append(throwable.getClass().getName()) + .append("\n"); + for (StackTraceElement element : throwable.getStackTrace()) { + stack.append(element.toString()).append("\n"); + } + return stack.toString(); + }; + ExceptionReporter reporter = + new ExceptionReporter(tracker, Thread.getDefaultUncaughtExceptionHandler(), context); reporter.setExceptionParser(exceptionParser); Thread.setDefaultUncaughtExceptionHandler(reporter); } @@ -60,10 +59,11 @@ public class Tracker { public void reportException(Thread thread, Throwable t) { Timber.e(t, t.getMessage()); - tracker.send(new HitBuilders.ExceptionBuilder() - .setDescription(exceptionParser.getDescription(thread.getName(), t)) - .setFatal(false) - .build()); + tracker.send( + new HitBuilders.ExceptionBuilder() + .setDescription(exceptionParser.getDescription(thread.getName(), t)) + .setFatal(false) + .build()); } public void reportEvent(Tracking.Events event) { @@ -83,9 +83,8 @@ public class Tracker { } private void reportEvent(int category, String action, String label) { - HitBuilders.EventBuilder eventBuilder = new HitBuilders.EventBuilder() - .setCategory(context.getString(category)) - .setAction(action); + HitBuilders.EventBuilder eventBuilder = + new HitBuilders.EventBuilder().setCategory(context.getString(category)).setAction(action); if (!Strings.isNullOrEmpty(label)) { eventBuilder.setLabel(label); } diff --git a/app/src/amazon/java/org/tasks/billing/PurchaseHelper.java b/app/src/amazon/java/org/tasks/billing/PurchaseHelper.java index c3cd9d136..7e79d27d1 100644 --- a/app/src/amazon/java/org/tasks/billing/PurchaseHelper.java +++ b/app/src/amazon/java/org/tasks/billing/PurchaseHelper.java @@ -7,26 +7,22 @@ import javax.inject.Inject; public class PurchaseHelper { @Inject - public PurchaseHelper() { - } - - public boolean purchase(final Activity activity, - final String sku, final String pref, - final int requestCode, final PurchaseHelperCallback callback) { + public PurchaseHelper() {} + + public boolean purchase( + final Activity activity, + final String sku, + final String pref, + final int requestCode, + final PurchaseHelperCallback callback) { callback.purchaseCompleted(false, sku); return false; } - public void handleActivityResult(PurchaseHelperCallback callback, int requestCode, int resultCode, - Intent data) { - - } - - public void disposeIabHelper() { - - } + public void handleActivityResult( + PurchaseHelperCallback callback, int requestCode, int resultCode, Intent data) {} - public void consumePurchases() { + public void disposeIabHelper() {} - } + public void consumePurchases() {} } diff --git a/app/src/amazon/java/org/tasks/gtasks/PlayServices.java b/app/src/amazon/java/org/tasks/gtasks/PlayServices.java index 64ea8bd8d..7c2cfbc93 100644 --- a/app/src/amazon/java/org/tasks/gtasks/PlayServices.java +++ b/app/src/amazon/java/org/tasks/gtasks/PlayServices.java @@ -8,9 +8,7 @@ import javax.inject.Inject; public class PlayServices { @Inject - public PlayServices() { - - } + public PlayServices() {} public boolean isPlayServicesAvailable() { return false; @@ -20,9 +18,7 @@ public class PlayServices { return false; } - public void resolve(Activity activity) { - - } + public void resolve(Activity activity) {} public String getStatus() { return null; @@ -32,8 +28,8 @@ public class PlayServices { return false; } - public void getAuthToken(GtasksLoginActivity gtasksLoginActivity, String a, - GtasksLoginActivity.AuthResultHandler authResultHandler) { - - } + public void getAuthToken( + GtasksLoginActivity gtasksLoginActivity, + String a, + GtasksLoginActivity.AuthResultHandler authResultHandler) {} } diff --git a/app/src/amazon/java/org/tasks/location/GeofenceApi.java b/app/src/amazon/java/org/tasks/location/GeofenceApi.java index 09f51e547..e77a061a1 100644 --- a/app/src/amazon/java/org/tasks/location/GeofenceApi.java +++ b/app/src/amazon/java/org/tasks/location/GeofenceApi.java @@ -8,19 +8,11 @@ import org.tasks.data.Location; public class GeofenceApi { @Inject - public GeofenceApi() { + public GeofenceApi() {} - } + public void register(List activeGeofences) {} - public void register(List activeGeofences) { + public void cancel(Location geofence) {} - } - - public void cancel(Location geofence) { - - } - - public void cancel(List geofences) { - - } + public void cancel(List geofences) {} } diff --git a/app/src/amazon/java/org/tasks/location/GeofenceTransitionsIntentService.java b/app/src/amazon/java/org/tasks/location/GeofenceTransitionsIntentService.java index 508a57af7..b8a779793 100644 --- a/app/src/amazon/java/org/tasks/location/GeofenceTransitionsIntentService.java +++ b/app/src/amazon/java/org/tasks/location/GeofenceTransitionsIntentService.java @@ -1,5 +1,3 @@ package org.tasks.location; -public class GeofenceTransitionsIntentService { - -} +public class GeofenceTransitionsIntentService {} diff --git a/app/src/androidTest/java/com/todoroo/andlib/test/TranslationTests.java b/app/src/androidTest/java/com/todoroo/andlib/test/TranslationTests.java index 0a7929783..dc6942e7d 100644 --- a/app/src/androidTest/java/com/todoroo/andlib/test/TranslationTests.java +++ b/app/src/androidTest/java/com/todoroo/andlib/test/TranslationTests.java @@ -1,12 +1,10 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.andlib.test; - import static android.support.test.InstrumentationRegistry.getTargetContext; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertFalse; @@ -24,18 +22,15 @@ import org.junit.runner.RunWith; import org.tasks.R; /** - * Tests translations for consistency with the default values. You must - * extend this class and create it with your own values for strings - * and arrays. + * Tests translations for consistency with the default values. You must extend this class and create + * it with your own values for strings and arrays. * * @author Tim Su */ @RunWith(AndroidJUnit4.class) public class TranslationTests { - /** - * Loop through each locale and call runnable - */ + /** Loop through each locale and call runnable */ private void forEachLocale(Callback callback) { Locale[] locales = Locale.getAvailableLocales(); for (Locale locale : locales) { @@ -50,9 +45,7 @@ public class TranslationTests { return new Resources(resources.getAssets(), resources.getDisplayMetrics(), configuration); } - /** - * Internal test of format string parser - */ + /** Internal test of format string parser */ @Test public void testFormatStringParser() { String s = "abc"; @@ -84,8 +77,8 @@ public class TranslationTests { } /** - * Test that the format specifiers in translations match exactly the - * translations in the default text + * Test that the format specifiers in translations match exactly the translations in the default + * text */ @Test public void testFormatStringsMatch() { @@ -101,72 +94,68 @@ public class TranslationTests { formatStrings[i] = new FormatStringData(string); } catch (Exception e) { String name = resources.getResourceName(strings[i]); - failures.append(String.format("error opening %s: %s\n", - name, e.getMessage())); + failures.append(String.format("error opening %s: %s\n", name, e.getMessage())); } } - forEachLocale(r -> { - Locale locale = r.getConfiguration().locale; - for (int i = 0; i < strings.length; i++) { - try { - switch (strings[i]) { - case R.string.abc_shareactionprovider_share_with_application: - continue; - } - String string = r.getString(strings[i]); - FormatStringData newFS = new FormatStringData(string); - if (!newFS.matches(formatStrings[i])) { - String name = r.getResourceName(strings[i]); - failures.append(String.format("%s (%s): %s != %s\n", - name, locale.toString(), newFS, formatStrings[i])); + forEachLocale( + r -> { + Locale locale = r.getConfiguration().locale; + for (int i = 0; i < strings.length; i++) { + try { + switch (strings[i]) { + case R.string.abc_shareactionprovider_share_with_application: + continue; + } + String string = r.getString(strings[i]); + FormatStringData newFS = new FormatStringData(string); + if (!newFS.matches(formatStrings[i])) { + String name = r.getResourceName(strings[i]); + failures.append( + String.format( + "%s (%s): %s != %s\n", name, locale.toString(), newFS, formatStrings[i])); + } + } catch (Exception e) { + String name = r.getResourceName(strings[i]); + failures.append( + String.format( + "%s: error opening %s: %s\n", locale.toString(), name, e.getMessage())); + } } - } catch (Exception e) { - String name = r.getResourceName(strings[i]); - failures.append(String.format("%s: error opening %s: %s\n", - locale.toString(), name, e.getMessage())); - } - } - }); + }); assertTrue(failures.toString(), errorCount(failures) == 0); } - /** - * check if string contains contains substrings - */ + /** check if string contains contains substrings */ private void contains(Resources r, int resource, StringBuilder failures, String expected) { String translation = r.getString(resource); if (!translation.contains(expected)) { Locale locale = r.getConfiguration().locale; String name = r.getResourceName(resource); - failures.append(String.format("%s: %s did not contain: %s\n", - locale.toString(), name, expected)); + failures.append( + String.format("%s: %s did not contain: %s\n", locale.toString(), name, expected)); } } - /** - * Test dollar sign resources - */ + /** Test dollar sign resources */ @Test public void testSpecialStringsMatch() { final StringBuilder failures = new StringBuilder(); - forEachLocale(r -> { - contains(r, R.string.CFC_tag_text, failures, "?"); - contains(r, R.string.CFC_title_contains_text, failures, "?"); - contains(r, R.string.CFC_dueBefore_text, failures, "?"); - contains(r, R.string.CFC_tag_contains_text, failures, "?"); - contains(r, R.string.CFC_gtasks_list_text, failures, "?"); - }); + forEachLocale( + r -> { + contains(r, R.string.CFC_tag_text, failures, "?"); + contains(r, R.string.CFC_title_contains_text, failures, "?"); + contains(r, R.string.CFC_dueBefore_text, failures, "?"); + contains(r, R.string.CFC_tag_contains_text, failures, "?"); + contains(r, R.string.CFC_gtasks_list_text, failures, "?"); + }); - assertEquals(failures.toString(), 0, - failures.toString().replaceAll("[^\n]", "").length()); + assertEquals(failures.toString(), 0, failures.toString().replaceAll("[^\n]", "").length()); } - /** - * Count newlines - */ + /** Count newlines */ private int errorCount(StringBuilder failures) { int count = 0; int pos = -1; @@ -179,9 +168,7 @@ public class TranslationTests { } } - /** - * @return an array of all string resource id's - */ + /** @return an array of all string resource id's */ private int[] getResourceIds(Class resources) { Field[] fields = resources.getDeclaredFields(); List ids = new ArrayList<>(fields.length); @@ -208,14 +195,10 @@ public class TranslationTests { private static final char[] scratch = new char[10]; - /** - * format characters - */ + /** format characters */ final char[] characters; - /** - * the original string - */ + /** the original string */ final String string; public FormatStringData(String string) { @@ -240,9 +223,7 @@ public class TranslationTests { } } - /** - * test that the characters match - */ + /** test that the characters match */ boolean matches(FormatStringData other) { if (characters.length != other.characters.length) { return false; @@ -259,7 +240,6 @@ public class TranslationTests { } else if (characters[i] != other.characters[i]) { return false; } - } return true; } diff --git a/app/src/androidTest/java/com/todoroo/andlib/utility/DateUtilitiesTest.java b/app/src/androidTest/java/com/todoroo/andlib/utility/DateUtilitiesTest.java index 5bd95a2d9..54d8c9ed2 100644 --- a/app/src/androidTest/java/com/todoroo/andlib/utility/DateUtilitiesTest.java +++ b/app/src/androidTest/java/com/todoroo/andlib/utility/DateUtilitiesTest.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.andlib.utility; import static android.support.test.InstrumentationRegistry.getTargetContext; @@ -66,33 +65,35 @@ public class DateUtilitiesTest { @Test public void testTimeString() { - forEachLocale(() -> { - DateTime d = newDateTime(); + forEachLocale( + () -> { + DateTime d = newDateTime(); - DateUtilities.is24HourOverride = false; - for (int i = 0; i < 24; i++) { - d = d.withHourOfDay(i); - getTimeString(getTargetContext(), d); - } + DateUtilities.is24HourOverride = false; + for (int i = 0; i < 24; i++) { + d = d.withHourOfDay(i); + getTimeString(getTargetContext(), d); + } - DateUtilities.is24HourOverride = true; - for (int i = 0; i < 24; i++) { - d = d.withHourOfDay(i); - getTimeString(getTargetContext(), d); - } - }); + DateUtilities.is24HourOverride = true; + for (int i = 0; i < 24; i++) { + d = d.withHourOfDay(i); + getTimeString(getTargetContext(), d); + } + }); } @Test public void testDateString() { - forEachLocale(() -> { - DateTime d = newDateTime(); + forEachLocale( + () -> { + DateTime d = newDateTime(); - for (int i = 0; i < 12; i++) { - d = d.withMonthOfYear(i); - getDateString(d); - } - }); + for (int i = 0; i < 12; i++) { + d = d.withMonthOfYear(i); + getDateString(d); + } + }); } @Test @@ -122,16 +123,24 @@ public class DateUtilitiesTest { @Test public void testGetDateStringHidingYear() { - freezeAt(newDate(2014, 1, 1)).thawAfter(new Snippet() {{ - assertEquals("Jan 1", getDateString(newDateTime())); - }}); + freezeAt(newDate(2014, 1, 1)) + .thawAfter( + new Snippet() { + { + assertEquals("Jan 1", getDateString(newDateTime())); + } + }); } @Test public void testGetDateStringWithDifferentYear() { - freezeAt(newDate(2013, 12, 31)).thawAfter(new Snippet() {{ - assertEquals("Jan 1 '14", getDateString(new DateTime(2014, 1, 1, 0, 0, 0))); - }}); + freezeAt(newDate(2013, 12, 31)) + .thawAfter( + new Snippet() { + { + assertEquals("Jan 1 '14", getDateString(new DateTime(2014, 1, 1, 0, 0, 0))); + } + }); } @Test @@ -139,9 +148,13 @@ public class DateUtilitiesTest { DateTime now = new DateTime(2013, 12, 1, 12, 19, 45, 192); final long expected = new DateTime(2014, 1, 1, 12, 19, 45, 192).getMillis(); - freezeAt(now).thawAfter(new Snippet() {{ - assertEquals(expected, oneMonthFromNow()); - }}); + freezeAt(now) + .thawAfter( + new Snippet() { + { + assertEquals(expected, oneMonthFromNow()); + } + }); } @Test @@ -149,9 +162,13 @@ public class DateUtilitiesTest { DateTime now = new DateTime(2013, 12, 31, 16, 31, 20, 597); final long expected = new DateTime(2014, 1, 31, 16, 31, 20, 597).getMillis(); - freezeAt(now).thawAfter(new Snippet() {{ - assertEquals(expected, oneMonthFromNow()); - }}); + freezeAt(now) + .thawAfter( + new Snippet() { + { + assertEquals(expected, oneMonthFromNow()); + } + }); } @Test @@ -159,9 +176,13 @@ public class DateUtilitiesTest { final DateTime now = new DateTime(2013, 12, 31, 17, 17, 32, 900); final long expected = new DateTime(2014, 7, 1, 17, 17, 32, 900).getMillis(); - freezeAt(now).thawAfter(new Snippet() {{ - assertEquals(expected, addCalendarMonthsToUnixtime(now.getMillis(), 6)); - }}); + freezeAt(now) + .thawAfter( + new Snippet() { + { + assertEquals(expected, addCalendarMonthsToUnixtime(now.getMillis(), 6)); + } + }); } @Test @@ -169,9 +190,13 @@ public class DateUtilitiesTest { DateTime now = new DateTime(2014, 1, 31, 12, 54, 33, 175); final long expected = new DateTime(2014, 3, 3, 12, 54, 33, 175).getMillis(); - freezeAt(now).thawAfter(new Snippet() {{ - assertEquals(expected, oneMonthFromNow()); - }}); + freezeAt(now) + .thawAfter( + new Snippet() { + { + assertEquals(expected, oneMonthFromNow()); + } + }); } @Test @@ -179,17 +204,19 @@ public class DateUtilitiesTest { DateTime now = new DateTime(2014, 2, 28, 9, 19, 7, 990); final long expected = new DateTime(2014, 3, 28, 9, 19, 7, 990).getMillis(); - freezeAt(now).thawAfter(new Snippet() {{ - assertEquals(expected, oneMonthFromNow()); - }}); + freezeAt(now) + .thawAfter( + new Snippet() { + { + assertEquals(expected, oneMonthFromNow()); + } + }); } @Test public void testShouldGetStartOfDay() { DateTime now = new DateTime(2014, 1, 3, 10, 41, 41, 520); - assertEquals( - now.startOfDay().getMillis(), - getStartOfDay(now.getMillis())); + assertEquals(now.startOfDay().getMillis(), getStartOfDay(now.getMillis())); } @Test @@ -216,101 +243,145 @@ public class DateUtilitiesTest { @Test public void testAddMonthsToTimestamp() { - assertEquals(newDate(2014, 1, 1).getMillis(), + assertEquals( + newDate(2014, 1, 1).getMillis(), addCalendarMonthsToUnixtime(newDate(2013, 12, 1).getMillis(), 1)); - assertEquals(newDate(2014, 12, 31).getMillis(), + assertEquals( + newDate(2014, 12, 31).getMillis(), addCalendarMonthsToUnixtime(newDate(2013, 12, 31).getMillis(), 12)); } @Test public void testAddMonthsWithLessDays() { - assertEquals(newDate(2014, 3, 3).getMillis(), + assertEquals( + newDate(2014, 3, 3).getMillis(), addCalendarMonthsToUnixtime(newDate(2013, 12, 31).getMillis(), 2)); } @Test public void testAddMonthsWithMoreDays() { - assertEquals(newDate(2014, 1, 30).getMillis(), + assertEquals( + newDate(2014, 1, 30).getMillis(), addCalendarMonthsToUnixtime(newDate(2013, 11, 30).getMillis(), 2)); } @Test public void usDateNoYear() { setLocale(Locale.US); - freezeAt(new DateTime(2018, 1, 1)).thawAfter(() -> - assertEquals("Jan 14", DateUtilities.getRelativeDateStringWithTime(getTargetContext(), - new DateTime(2018, 1, 14).getMillis()))); + freezeAt(new DateTime(2018, 1, 1)) + .thawAfter( + () -> + assertEquals( + "Jan 14", + DateUtilities.getRelativeDateStringWithTime( + getTargetContext(), new DateTime(2018, 1, 14).getMillis()))); } @Test public void usDateWithYear() { setLocale(Locale.US); - freezeAt(new DateTime(2017, 12, 12)).thawAfter(() -> - assertEquals("Jan 14 '18", DateUtilities.getRelativeDateStringWithTime(getTargetContext(), - new DateTime(2018, 1, 14).getMillis()))); + freezeAt(new DateTime(2017, 12, 12)) + .thawAfter( + () -> + assertEquals( + "Jan 14 '18", + DateUtilities.getRelativeDateStringWithTime( + getTargetContext(), new DateTime(2018, 1, 14).getMillis()))); } @Test public void germanDateNoYear() { setLocale(Locale.GERMAN); - freezeAt(new DateTime(2018, 1, 1)).thawAfter(() -> - assertEquals("14 Jan.", DateUtilities.getRelativeDateStringWithTime(getTargetContext(), - new DateTime(2018, 1, 14).getMillis()))); + freezeAt(new DateTime(2018, 1, 1)) + .thawAfter( + () -> + assertEquals( + "14 Jan.", + DateUtilities.getRelativeDateStringWithTime( + getTargetContext(), new DateTime(2018, 1, 14).getMillis()))); } @Test public void germanDateWithYear() { setLocale(Locale.GERMAN); - freezeAt(new DateTime(2017, 12, 12)).thawAfter(() -> - assertEquals("14 Jan. '18", DateUtilities.getRelativeDateStringWithTime(getTargetContext(), - new DateTime(2018, 1, 14).getMillis()))); + freezeAt(new DateTime(2017, 12, 12)) + .thawAfter( + () -> + assertEquals( + "14 Jan. '18", + DateUtilities.getRelativeDateStringWithTime( + getTargetContext(), new DateTime(2018, 1, 14).getMillis()))); } @Test public void koreanDateNoYear() { setLocale(Locale.KOREAN); - freezeAt(new DateTime(2018, 1, 1)).thawAfter(() -> - assertEquals("1월 14일", DateUtilities.getRelativeDateStringWithTime(getTargetContext(), - new DateTime(2018, 1, 14).getMillis()))); + freezeAt(new DateTime(2018, 1, 1)) + .thawAfter( + () -> + assertEquals( + "1월 14일", + DateUtilities.getRelativeDateStringWithTime( + getTargetContext(), new DateTime(2018, 1, 14).getMillis()))); } @Test public void koreanDateWithYear() { setLocale(Locale.KOREAN); - freezeAt(new DateTime(2017, 12, 12)).thawAfter(() -> - assertEquals("18년 1월 14일", DateUtilities.getRelativeDateStringWithTime(getTargetContext(), - new DateTime(2018, 1, 14).getMillis()))); + freezeAt(new DateTime(2017, 12, 12)) + .thawAfter( + () -> + assertEquals( + "18년 1월 14일", + DateUtilities.getRelativeDateStringWithTime( + getTargetContext(), new DateTime(2018, 1, 14).getMillis()))); } @Test public void japaneseDateNoYear() { setLocale(Locale.JAPANESE); - freezeAt(new DateTime(2018, 1, 1)).thawAfter(() -> - assertEquals("1月 14日", DateUtilities.getRelativeDateStringWithTime(getTargetContext(), - new DateTime(2018, 1, 14).getMillis()))); + freezeAt(new DateTime(2018, 1, 1)) + .thawAfter( + () -> + assertEquals( + "1月 14日", + DateUtilities.getRelativeDateStringWithTime( + getTargetContext(), new DateTime(2018, 1, 14).getMillis()))); } @Test public void japaneseDateWithYear() { setLocale(Locale.JAPANESE); - freezeAt(new DateTime(2017, 12, 12)).thawAfter(() -> - assertEquals("18年 1月 14日", DateUtilities.getRelativeDateStringWithTime(getTargetContext(), - new DateTime(2018, 1, 14).getMillis()))); + freezeAt(new DateTime(2017, 12, 12)) + .thawAfter( + () -> + assertEquals( + "18年 1月 14日", + DateUtilities.getRelativeDateStringWithTime( + getTargetContext(), new DateTime(2018, 1, 14).getMillis()))); } @Test public void chineseDateNoYear() { setLocale(Locale.CHINESE); - freezeAt(new DateTime(2018, 1, 1)).thawAfter(() -> - assertEquals("1月 14日", DateUtilities.getRelativeDateStringWithTime(getTargetContext(), - new DateTime(2018, 1, 14).getMillis()))); + freezeAt(new DateTime(2018, 1, 1)) + .thawAfter( + () -> + assertEquals( + "1月 14日", + DateUtilities.getRelativeDateStringWithTime( + getTargetContext(), new DateTime(2018, 1, 14).getMillis()))); } @Test public void chineseDateWithYear() { setLocale(Locale.CHINESE); - freezeAt(new DateTime(2017, 12, 12)).thawAfter(() -> - assertEquals("18年 1月 14日", DateUtilities.getRelativeDateStringWithTime(getTargetContext(), - new DateTime(2018, 1, 14).getMillis()))); + freezeAt(new DateTime(2017, 12, 12)) + .thawAfter( + () -> + assertEquals( + "18年 1月 14日", + DateUtilities.getRelativeDateStringWithTime( + getTargetContext(), new DateTime(2018, 1, 14).getMillis()))); } } diff --git a/app/src/androidTest/java/com/todoroo/astrid/dao/TaskDaoTests.java b/app/src/androidTest/java/com/todoroo/astrid/dao/TaskDaoTests.java index 3b50dee45..83093e4b9 100644 --- a/app/src/androidTest/java/com/todoroo/astrid/dao/TaskDaoTests.java +++ b/app/src/androidTest/java/com/todoroo/astrid/dao/TaskDaoTests.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.dao; import static junit.framework.Assert.assertEquals; @@ -24,9 +23,7 @@ public class TaskDaoTests extends InjectingTestCase { @Inject TaskDao taskDao; - /** - * Test basic task creation, fetch, and save - */ + /** Test basic task creation, fetch, and save */ @Test public void testTaskCreation() { assertEquals(0, taskDao.getAll().size()); @@ -61,9 +58,7 @@ public class TaskDaoTests extends InjectingTestCase { assertEquals("melancholy", task.getTitle()); } - /** - * Test various task fetch conditions - */ + /** Test various task fetch conditions */ @Test public void testTaskConditions() { // create normal task @@ -106,9 +101,7 @@ public class TaskDaoTests extends InjectingTestCase { assertEquals(5, taskDao.getVisibleTasks().size()); } - /** - * Test task deletion - */ + /** Test task deletion */ @Test public void testTDeletion() { assertEquals(0, taskDao.getAll().size()); @@ -125,9 +118,7 @@ public class TaskDaoTests extends InjectingTestCase { assertEquals(0, taskDao.getAll().size()); } - /** - * Test save without prior create doesn't work - */ + /** Test save without prior create doesn't work */ @Test public void testSaveWithoutCreate() { // try to save task "happy" @@ -140,9 +131,7 @@ public class TaskDaoTests extends InjectingTestCase { assertEquals(0, taskDao.getAll().size()); } - /** - * Test passing invalid task indices to various things - */ + /** Test passing invalid task indices to various things */ @Test public void testInvalidIndex() { assertEquals(0, taskDao.getAll().size()); @@ -162,4 +151,3 @@ public class TaskDaoTests extends InjectingTestCase { // TODO check eventing } - diff --git a/app/src/androidTest/java/com/todoroo/astrid/data/TaskTest.java b/app/src/androidTest/java/com/todoroo/astrid/data/TaskTest.java index b65841adb..d08986d6a 100644 --- a/app/src/androidTest/java/com/todoroo/astrid/data/TaskTest.java +++ b/app/src/androidTest/java/com/todoroo/astrid/data/TaskTest.java @@ -88,21 +88,19 @@ public class TaskTest { @Test public void testRemoveTimeForSpecificDay() { - long expected = specificDueDate - .withHourOfDay(12) - .withMinuteOfHour(0) - .withSecondOfMinute(0) - .withMillisOfSecond(0) - .getMillis(); + long expected = + specificDueDate + .withHourOfDay(12) + .withMinuteOfHour(0) + .withSecondOfMinute(0) + .withMillisOfSecond(0) + .getMillis(); assertEquals(expected, createDueDate(URGENCY_SPECIFIC_DAY, specificDueDate.getMillis())); } @Test public void testRemoveSecondsForSpecificTime() { - long expected = specificDueDate - .withSecondOfMinute(1) - .withMillisOfSecond(0) - .getMillis(); + long expected = specificDueDate.withSecondOfMinute(1).withMillisOfSecond(0).getMillis(); assertEquals(expected, createDueDate(URGENCY_SPECIFIC_DAY_TIME, specificDueDate.getMillis())); } @@ -176,21 +174,29 @@ public class TaskTest { @Test public void testTaskIsNotHiddenAtHideUntilTime() { final long now = currentTimeMillis(); - freezeAt(now).thawAfter(new Snippet() {{ - Task task = new Task(); - task.setHideUntil(now); - assertFalse(task.isHidden()); - }}); + freezeAt(now) + .thawAfter( + new Snippet() { + { + Task task = new Task(); + task.setHideUntil(now); + assertFalse(task.isHidden()); + } + }); } @Test public void testTaskIsHiddenBeforeHideUntilTime() { final long now = currentTimeMillis(); - freezeAt(now).thawAfter(new Snippet() {{ - Task task = new Task(); - task.setHideUntil(now + 1); - assertTrue(task.isHidden()); - }}); + freezeAt(now) + .thawAfter( + new Snippet() { + { + Task task = new Task(); + task.setHideUntil(now + 1); + assertTrue(task.isHidden()); + } + }); } @Test @@ -208,54 +214,74 @@ public class TaskTest { @Test public void testTaskNotOverdueAtDueTime() { final long now = currentTimeMillis(); - freezeAt(now).thawAfter(new Snippet() {{ - Task task = new Task(); - task.setDueDate(now); - assertFalse(task.isOverdue()); - }}); + freezeAt(now) + .thawAfter( + new Snippet() { + { + Task task = new Task(); + task.setDueDate(now); + assertFalse(task.isOverdue()); + } + }); } @Test public void testTaskIsOverduePastDueTime() { final long dueDate = currentTimeMillis(); - freezeAt(dueDate + 1).thawAfter(new Snippet() {{ - Task task = new Task(); - task.setDueDate(dueDate); - assertTrue(task.isOverdue()); - }}); + freezeAt(dueDate + 1) + .thawAfter( + new Snippet() { + { + Task task = new Task(); + task.setDueDate(dueDate); + assertTrue(task.isOverdue()); + } + }); } @Test public void testTaskNotOverdueBeforeNoonOnDueDate() { final DateTime dueDate = new DateTime().startOfDay(); - freezeAt(dueDate.plusHours(12).minusMillis(1)).thawAfter(new Snippet() {{ - Task task = new Task(); - task.setDueDate(dueDate.getMillis()); - assertFalse(task.hasDueTime()); - assertFalse(task.isOverdue()); - }}); + freezeAt(dueDate.plusHours(12).minusMillis(1)) + .thawAfter( + new Snippet() { + { + Task task = new Task(); + task.setDueDate(dueDate.getMillis()); + assertFalse(task.hasDueTime()); + assertFalse(task.isOverdue()); + } + }); } @Test public void testTaskOverdueAtNoonOnDueDate() { final DateTime dueDate = new DateTime().startOfDay(); - freezeAt(dueDate.plusHours(12)).thawAfter(new Snippet() {{ - Task task = new Task(); - task.setDueDate(dueDate.getMillis()); - assertFalse(task.hasDueTime()); - assertFalse(task.isOverdue()); - }}); + freezeAt(dueDate.plusHours(12)) + .thawAfter( + new Snippet() { + { + Task task = new Task(); + task.setDueDate(dueDate.getMillis()); + assertFalse(task.hasDueTime()); + assertFalse(task.isOverdue()); + } + }); } @Test public void testTaskWithNoDueTimeIsOverdue() { final DateTime dueDate = new DateTime().startOfDay(); - freezeAt(dueDate.plusDays(1)).thawAfter(new Snippet() {{ - Task task = new Task(); - task.setDueDate(dueDate.getMillis()); - assertFalse(task.hasDueTime()); - assertTrue(task.isOverdue()); - }}); + freezeAt(dueDate.plusDays(1)) + .thawAfter( + new Snippet() { + { + Task task = new Task(); + task.setDueDate(dueDate.getMillis()); + assertFalse(task.hasDueTime()); + assertTrue(task.isOverdue()); + } + }); } @Test diff --git a/app/src/androidTest/java/com/todoroo/astrid/model/TaskTest.java b/app/src/androidTest/java/com/todoroo/astrid/model/TaskTest.java index 5ee7627ad..ac152c440 100644 --- a/app/src/androidTest/java/com/todoroo/astrid/model/TaskTest.java +++ b/app/src/androidTest/java/com/todoroo/astrid/model/TaskTest.java @@ -21,11 +21,15 @@ public class TaskTest extends InjectingTestCase { @Test public void testSavedTaskHasCreationDate() { - freezeClock().thawAfter(new Snippet() {{ - Task task = new Task(); - taskDao.createNew(task); - assertEquals(currentTimeMillis(), (long) task.getCreationDate()); - }}); + freezeClock() + .thawAfter( + new Snippet() { + { + Task task = new Task(); + taskDao.createNew(task); + assertEquals(currentTimeMillis(), (long) task.getCreationDate()); + } + }); } @Test diff --git a/app/src/androidTest/java/com/todoroo/astrid/reminders/ReminderServiceTest.java b/app/src/androidTest/java/com/todoroo/astrid/reminders/ReminderServiceTest.java index a785fdc92..c55ac21a1 100644 --- a/app/src/androidTest/java/com/todoroo/astrid/reminders/ReminderServiceTest.java +++ b/app/src/androidTest/java/com/todoroo/astrid/reminders/ReminderServiceTest.java @@ -89,10 +89,11 @@ public class ReminderServiceTest extends InjectingTestCase { @Test public void schedulePastDueDate() { - Task task = newTask( - with(ID, 1L), - with(DUE_TIME, newDateTime().minusDays(1)), - with(REMINDERS, NOTIFY_AT_DEADLINE)); + Task task = + newTask( + with(ID, 1L), + with(DUE_TIME, newDateTime().minusDays(1)), + with(REMINDERS, NOTIFY_AT_DEADLINE)); service.scheduleAlarm(task); InOrder order = inOrder(jobs); @@ -102,10 +103,11 @@ public class ReminderServiceTest extends InjectingTestCase { @Test public void scheduleFutureDueDate() { - Task task = newTask( - with(ID, 1L), - with(DUE_TIME, newDateTime().plusDays(1)), - with(REMINDERS, NOTIFY_AT_DEADLINE)); + Task task = + newTask( + with(ID, 1L), + with(DUE_TIME, newDateTime().plusDays(1)), + with(REMINDERS, NOTIFY_AT_DEADLINE)); service.scheduleAlarm(task); InOrder order = inOrder(jobs); @@ -116,26 +118,27 @@ public class ReminderServiceTest extends InjectingTestCase { @Test public void scheduleReminderAtDefaultDueTime() { DateTime now = newDateTime(); - Task task = newTask( - with(ID, 1L), - with(DUE_DATE, now), - with(REMINDERS, NOTIFY_AT_DEADLINE)); + Task task = newTask(with(ID, 1L), with(DUE_DATE, now), with(REMINDERS, NOTIFY_AT_DEADLINE)); service.scheduleAlarm(task); InOrder order = inOrder(jobs); order.verify(jobs).cancelReminder(1); - order.verify(jobs).add( - new ReminderEntry(1, now.startOfDay().withHourOfDay(18).getMillis(), ReminderService.TYPE_DUE)); + order + .verify(jobs) + .add( + new ReminderEntry( + 1, now.startOfDay().withHourOfDay(18).getMillis(), ReminderService.TYPE_DUE)); } @Test public void dontScheduleReminderForCompletedTask() { - Task task = newTask( - with(ID, 1L), - with(DUE_TIME, newDateTime().plusDays(1)), - with(COMPLETION_TIME, newDateTime()), - with(REMINDERS, NOTIFY_AT_DEADLINE)); + Task task = + newTask( + with(ID, 1L), + with(DUE_TIME, newDateTime().plusDays(1)), + with(COMPLETION_TIME, newDateTime()), + with(REMINDERS, NOTIFY_AT_DEADLINE)); service.scheduleAlarm(task); @@ -144,11 +147,12 @@ public class ReminderServiceTest extends InjectingTestCase { @Test public void dontScheduleReminderForDeletedTask() { - Task task = newTask( - with(ID, 1L), - with(DUE_TIME, newDateTime().plusDays(1)), - with(DELETION_TIME, newDateTime()), - with(REMINDERS, NOTIFY_AT_DEADLINE)); + Task task = + newTask( + with(ID, 1L), + with(DUE_TIME, newDateTime().plusDays(1)), + with(DELETION_TIME, newDateTime()), + with(REMINDERS, NOTIFY_AT_DEADLINE)); service.scheduleAlarm(task); @@ -158,11 +162,12 @@ public class ReminderServiceTest extends InjectingTestCase { @Test public void dontScheduleDueDateReminderWhenAlreadyReminded() { DateTime now = newDateTime(); - Task task = newTask( - with(ID, 1L), - with(DUE_TIME, now), - with(REMINDER_LAST, now.plusSeconds(1)), - with(REMINDERS, NOTIFY_AT_DEADLINE)); + Task task = + newTask( + with(ID, 1L), + with(DUE_TIME, now), + with(REMINDER_LAST, now.plusSeconds(1)), + with(REMINDERS, NOTIFY_AT_DEADLINE)); service.scheduleAlarm(task); @@ -171,12 +176,13 @@ public class ReminderServiceTest extends InjectingTestCase { @Test public void ignoreStaleSnoozeTime() { - Task task = newTask( - with(ID, 1L), - with(DUE_TIME, newDateTime()), - with(SNOOZE_TIME, newDateTime().minusMinutes(5)), - with(REMINDER_LAST, newDateTime().minusMinutes(4)), - with(REMINDERS, NOTIFY_AT_DEADLINE)); + Task task = + newTask( + with(ID, 1L), + with(DUE_TIME, newDateTime()), + with(SNOOZE_TIME, newDateTime().minusMinutes(5)), + with(REMINDER_LAST, newDateTime().minusMinutes(4)), + with(REMINDERS, NOTIFY_AT_DEADLINE)); service.scheduleAlarm(task); InOrder order = inOrder(jobs); @@ -187,191 +193,260 @@ public class ReminderServiceTest extends InjectingTestCase { @Test public void dontIgnoreMissedSnoozeTime() { DateTime dueDate = newDateTime(); - Task task = newTask( - with(ID, 1L), - with(DUE_TIME, dueDate), - with(SNOOZE_TIME, dueDate.minusMinutes(4)), - with(REMINDER_LAST, dueDate.minusMinutes(5)), - with(REMINDERS, NOTIFY_AT_DEADLINE)); + Task task = + newTask( + with(ID, 1L), + with(DUE_TIME, dueDate), + with(SNOOZE_TIME, dueDate.minusMinutes(4)), + with(REMINDER_LAST, dueDate.minusMinutes(5)), + with(REMINDERS, NOTIFY_AT_DEADLINE)); service.scheduleAlarm(task); InOrder order = inOrder(jobs); order.verify(jobs).cancelReminder(1); - order.verify(jobs).add(new ReminderEntry(1, task.getReminderSnooze(), ReminderService.TYPE_SNOOZE)); + order + .verify(jobs) + .add(new ReminderEntry(1, task.getReminderSnooze(), ReminderService.TYPE_SNOOZE)); } @Test public void scheduleInitialRandomReminder() { - freezeClock().thawAfter(new Snippet() {{ - DateTime now = newDateTime(); - when(random.nextFloat()).thenReturn(0.3865f); - Task task = newTask( - with(ID, 1L), - with(REMINDER_LAST, (DateTime) null), - with(CREATION_TIME, now.minusDays(1)), - with(RANDOM_REMINDER_PERIOD, ONE_WEEK)); - - service.scheduleAlarm(task); - - InOrder order = inOrder(jobs); - order.verify(jobs).cancelReminder(1); - order.verify(jobs).add( - new ReminderEntry(1L, now.minusDays(1).getMillis() + 584206592, ReminderService.TYPE_RANDOM)); - }}); + freezeClock() + .thawAfter( + new Snippet() { + { + DateTime now = newDateTime(); + when(random.nextFloat()).thenReturn(0.3865f); + Task task = + newTask( + with(ID, 1L), + with(REMINDER_LAST, (DateTime) null), + with(CREATION_TIME, now.minusDays(1)), + with(RANDOM_REMINDER_PERIOD, ONE_WEEK)); + + service.scheduleAlarm(task); + + InOrder order = inOrder(jobs); + order.verify(jobs).cancelReminder(1); + order + .verify(jobs) + .add( + new ReminderEntry( + 1L, + now.minusDays(1).getMillis() + 584206592, + ReminderService.TYPE_RANDOM)); + } + }); } @Test public void scheduleNextRandomReminder() { - freezeClock().thawAfter(new Snippet() {{ - DateTime now = newDateTime(); - when(random.nextFloat()).thenReturn(0.3865f); - Task task = newTask( - with(ID, 1L), - with(REMINDER_LAST, now.minusDays(1)), - with(CREATION_TIME, now.minusDays(30)), - with(RANDOM_REMINDER_PERIOD, ONE_WEEK)); - - service.scheduleAlarm(task); - - InOrder order = inOrder(jobs); - order.verify(jobs).cancelReminder(1); - order.verify(jobs).add( - new ReminderEntry(1L, now.minusDays(1).getMillis() + 584206592, ReminderService.TYPE_RANDOM)); - }}); + freezeClock() + .thawAfter( + new Snippet() { + { + DateTime now = newDateTime(); + when(random.nextFloat()).thenReturn(0.3865f); + Task task = + newTask( + with(ID, 1L), + with(REMINDER_LAST, now.minusDays(1)), + with(CREATION_TIME, now.minusDays(30)), + with(RANDOM_REMINDER_PERIOD, ONE_WEEK)); + + service.scheduleAlarm(task); + + InOrder order = inOrder(jobs); + order.verify(jobs).cancelReminder(1); + order + .verify(jobs) + .add( + new ReminderEntry( + 1L, + now.minusDays(1).getMillis() + 584206592, + ReminderService.TYPE_RANDOM)); + } + }); } @Test public void scheduleOverdueRandomReminder() { - freezeClock().thawAfter(new Snippet() {{ - DateTime now = newDateTime(); - when(random.nextFloat()).thenReturn(0.3865f); - Task task = newTask( - with(ID, 1L), - with(REMINDER_LAST, now.minusDays(14)), - with(CREATION_TIME, now.minusDays(30)), - with(RANDOM_REMINDER_PERIOD, ONE_WEEK)); - - service.scheduleAlarm(task); - - InOrder order = inOrder(jobs); - order.verify(jobs).cancelReminder(1); - order.verify(jobs) - .add(new ReminderEntry(1L, now.getMillis() + 10148400, ReminderService.TYPE_RANDOM)); - }}); + freezeClock() + .thawAfter( + new Snippet() { + { + DateTime now = newDateTime(); + when(random.nextFloat()).thenReturn(0.3865f); + Task task = + newTask( + with(ID, 1L), + with(REMINDER_LAST, now.minusDays(14)), + with(CREATION_TIME, now.minusDays(30)), + with(RANDOM_REMINDER_PERIOD, ONE_WEEK)); + + service.scheduleAlarm(task); + + InOrder order = inOrder(jobs); + order.verify(jobs).cancelReminder(1); + order + .verify(jobs) + .add( + new ReminderEntry( + 1L, now.getMillis() + 10148400, ReminderService.TYPE_RANDOM)); + } + }); } @Test public void scheduleOverdueNoLastReminder() { - Task task = newTask( - with(ID, 1L), - with(DUE_TIME, new DateTime(2017, 9, 22, 15, 30)), - with(REMINDER_LAST, (DateTime) null), - with(REMINDERS, NOTIFY_AFTER_DEADLINE)); + Task task = + newTask( + with(ID, 1L), + with(DUE_TIME, new DateTime(2017, 9, 22, 15, 30)), + with(REMINDER_LAST, (DateTime) null), + with(REMINDERS, NOTIFY_AFTER_DEADLINE)); service.scheduleAlarm(task); InOrder order = inOrder(jobs); order.verify(jobs).cancelReminder(1); - order.verify(jobs).add(new ReminderEntry(1L, new DateTime(2017, 9, 23, 15, 30, 1, 0).getMillis(), - ReminderService.TYPE_OVERDUE)); + order + .verify(jobs) + .add( + new ReminderEntry( + 1L, + new DateTime(2017, 9, 23, 15, 30, 1, 0).getMillis(), + ReminderService.TYPE_OVERDUE)); } @Test public void scheduleOverduePastLastReminder() { - Task task = newTask( - with(ID, 1L), - with(DUE_TIME, new DateTime(2017, 9, 22, 15, 30)), - with(REMINDER_LAST, new DateTime(2017, 9, 24, 12, 0)), - with(REMINDERS, NOTIFY_AFTER_DEADLINE)); + Task task = + newTask( + with(ID, 1L), + with(DUE_TIME, new DateTime(2017, 9, 22, 15, 30)), + with(REMINDER_LAST, new DateTime(2017, 9, 24, 12, 0)), + with(REMINDERS, NOTIFY_AFTER_DEADLINE)); service.scheduleAlarm(task); InOrder order = inOrder(jobs); order.verify(jobs).cancelReminder(1); - order.verify(jobs).add(new ReminderEntry(1L, new DateTime(2017, 9, 24, 15, 30, 1, 0).getMillis(), - ReminderService.TYPE_OVERDUE)); + order + .verify(jobs) + .add( + new ReminderEntry( + 1L, + new DateTime(2017, 9, 24, 15, 30, 1, 0).getMillis(), + ReminderService.TYPE_OVERDUE)); } @Test public void scheduleOverdueBeforeLastReminder() { - Task task = newTask( - with(ID, 1L), - with(DUE_TIME, new DateTime(2017, 9, 22, 12, 30)), - with(REMINDER_LAST, new DateTime(2017, 9, 24, 15, 0)), - with(REMINDERS, NOTIFY_AFTER_DEADLINE)); + Task task = + newTask( + with(ID, 1L), + with(DUE_TIME, new DateTime(2017, 9, 22, 12, 30)), + with(REMINDER_LAST, new DateTime(2017, 9, 24, 15, 0)), + with(REMINDERS, NOTIFY_AFTER_DEADLINE)); service.scheduleAlarm(task); InOrder order = inOrder(jobs); order.verify(jobs).cancelReminder(1); - order.verify(jobs).add(new ReminderEntry(1L, new DateTime(2017, 9, 25, 12, 30, 1, 0).getMillis(), - ReminderService.TYPE_OVERDUE)); + order + .verify(jobs) + .add( + new ReminderEntry( + 1L, + new DateTime(2017, 9, 25, 12, 30, 1, 0).getMillis(), + ReminderService.TYPE_OVERDUE)); } @Test public void scheduleOverdueWithNoDueTime() { preferences.setInt(R.string.p_rmd_time, (int) TimeUnit.HOURS.toMillis(15)); - Task task = newTask( - with(ID, 1L), - with(DUE_DATE, new DateTime(2017, 9, 22)), - with(REMINDER_LAST, new DateTime(2017, 9, 23, 12, 17, 59, 999)), - with(REMINDERS, NOTIFY_AFTER_DEADLINE)); + Task task = + newTask( + with(ID, 1L), + with(DUE_DATE, new DateTime(2017, 9, 22)), + with(REMINDER_LAST, new DateTime(2017, 9, 23, 12, 17, 59, 999)), + with(REMINDERS, NOTIFY_AFTER_DEADLINE)); service.scheduleAlarm(task); InOrder order = inOrder(jobs); order.verify(jobs).cancelReminder(1); - order.verify(jobs).add(new ReminderEntry(1L, new DateTime(2017, 9, 23, 15, 0, 0, 0).getMillis(), - ReminderService.TYPE_OVERDUE)); + order + .verify(jobs) + .add( + new ReminderEntry( + 1L, + new DateTime(2017, 9, 23, 15, 0, 0, 0).getMillis(), + ReminderService.TYPE_OVERDUE)); } @Test public void scheduleSubsequentOverdueReminder() { - Task task = newTask( - with(ID, 1L), - with(DUE_TIME, new DateTime(2017, 9, 22, 15, 30)), - with(REMINDER_LAST, new DateTime(2017, 9, 23, 15, 30, 59, 999)), - with(REMINDERS, NOTIFY_AFTER_DEADLINE)); + Task task = + newTask( + with(ID, 1L), + with(DUE_TIME, new DateTime(2017, 9, 22, 15, 30)), + with(REMINDER_LAST, new DateTime(2017, 9, 23, 15, 30, 59, 999)), + with(REMINDERS, NOTIFY_AFTER_DEADLINE)); service.scheduleAlarm(task); InOrder order = inOrder(jobs); order.verify(jobs).cancelReminder(1); - order.verify(jobs).add(new ReminderEntry(1L, new DateTime(2017, 9, 24, 15, 30, 1, 0).getMillis(), - ReminderService.TYPE_OVERDUE)); + order + .verify(jobs) + .add( + new ReminderEntry( + 1L, + new DateTime(2017, 9, 24, 15, 30, 1, 0).getMillis(), + ReminderService.TYPE_OVERDUE)); } @Test public void scheduleOverdueAfterLastReminder() { - Task task = newTask( - with(ID, 1L), - with(DUE_TIME, new DateTime(2017, 9, 22, 15, 30)), - with(REMINDER_LAST, new DateTime(2017, 9, 23, 12, 17, 59, 999)), - with(REMINDERS, NOTIFY_AFTER_DEADLINE)); + Task task = + newTask( + with(ID, 1L), + with(DUE_TIME, new DateTime(2017, 9, 22, 15, 30)), + with(REMINDER_LAST, new DateTime(2017, 9, 23, 12, 17, 59, 999)), + with(REMINDERS, NOTIFY_AFTER_DEADLINE)); service.scheduleAlarm(task); InOrder order = inOrder(jobs); order.verify(jobs).cancelReminder(1); - order.verify(jobs).add(new ReminderEntry(1L, new DateTime(2017, 9, 23, 15, 30, 1, 0).getMillis(), - ReminderService.TYPE_OVERDUE)); + order + .verify(jobs) + .add( + new ReminderEntry( + 1L, + new DateTime(2017, 9, 23, 15, 30, 1, 0).getMillis(), + ReminderService.TYPE_OVERDUE)); } @Test public void snoozeOverridesAll() { DateTime now = newDateTime(); - Task task = newTask( - with(ID, 1L), - with(DUE_TIME, now), - with(SNOOZE_TIME, now.plusMonths(12)), - with(REMINDERS, NOTIFY_AT_DEADLINE | NOTIFY_AFTER_DEADLINE), - with(RANDOM_REMINDER_PERIOD, ONE_HOUR)); + Task task = + newTask( + with(ID, 1L), + with(DUE_TIME, now), + with(SNOOZE_TIME, now.plusMonths(12)), + with(REMINDERS, NOTIFY_AT_DEADLINE | NOTIFY_AFTER_DEADLINE), + with(RANDOM_REMINDER_PERIOD, ONE_HOUR)); service.scheduleAlarm(task); InOrder order = inOrder(jobs); order.verify(jobs).cancelReminder(1); - order.verify(jobs) + order + .verify(jobs) .add(new ReminderEntry(1, now.plusMonths(12).getMillis(), ReminderService.TYPE_SNOOZE)); } } diff --git a/app/src/androidTest/java/com/todoroo/astrid/repeats/AdvancedRepeatTest.java b/app/src/androidTest/java/com/todoroo/astrid/repeats/AdvancedRepeatTest.java index 5db2889df..76cb42917 100644 --- a/app/src/androidTest/java/com/todoroo/astrid/repeats/AdvancedRepeatTest.java +++ b/app/src/androidTest/java/com/todoroo/astrid/repeats/AdvancedRepeatTest.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.repeats; import static junit.framework.Assert.assertEquals; @@ -37,8 +36,7 @@ public class AdvancedRepeatTest { private RRule rrule; public static void assertDateTimeEquals(long date, long other) { - assertEquals("Expected: " + newDateTime(date) + ", Actual: " + newDateTime(other), - date, other); + assertEquals("Expected: " + newDateTime(date) + ", Actual: " + newDateTime(other), date, other); } // --- date with time tests @@ -55,8 +53,9 @@ public class AdvancedRepeatTest { buildRRule(1, Frequency.DAILY); // test specific day & time - long dayWithTime = Task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, - new DateTime(2010, 8, 1, 10, 4, 0).getMillis()); + long dayWithTime = + Task.createDueDate( + Task.URGENCY_SPECIFIC_DAY_TIME, new DateTime(2010, 8, 1, 10, 4, 0).getMillis()); task.setDueDate(dayWithTime); long nextDayWithTime = dayWithTime + DateUtilities.ONE_DAY; @@ -71,14 +70,13 @@ public class AdvancedRepeatTest { buildRRule(1, Frequency.DAILY); // test specific day & time - long dayWithTime = Task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, - new DateTime(2010, 8, 1, 10, 4, 0).getMillis()); + long dayWithTime = + Task.createDueDate( + Task.URGENCY_SPECIFIC_DAY_TIME, new DateTime(2010, 8, 1, 10, 4, 0).getMillis()); task.setDueDate(dayWithTime); - DateTime todayWithTime = newDateTime() - .withHourOfDay(10) - .withMinuteOfHour(4) - .withSecondOfMinute(1); + DateTime todayWithTime = + newDateTime().withHourOfDay(10).withMinuteOfHour(4).withSecondOfMinute(1); long nextDayWithTimeLong = todayWithTime.getMillis(); nextDayWithTimeLong += DateUtilities.ONE_DAY; nextDayWithTimeLong = nextDayWithTimeLong / 1000L * 1000; @@ -87,9 +85,7 @@ public class AdvancedRepeatTest { assertDateTimeEquals(nextDayWithTimeLong, nextDueDate); } - /** - * test multiple days per week - DUE DATE - */ + /** test multiple days per week - DUE DATE */ @Test public void testDueDateInPastSingleWeekMultiDay() throws Exception { buildRRule(1, Frequency.WEEKLY, Weekday.MO, Weekday.WE, Weekday.FR); @@ -107,9 +103,7 @@ public class AdvancedRepeatTest { assertDueDate(nextDueDate, THIS, Calendar.MONDAY); } - /** - * test single day repeats - DUE DATE - */ + /** test single day repeats - DUE DATE */ @Test public void testDueDateSingleDay() throws Exception { buildRRule(1, Frequency.WEEKLY, Weekday.MO); @@ -139,9 +133,7 @@ public class AdvancedRepeatTest { assertDueDate(nextDueDate, NEXT, Calendar.MONDAY); } - /** - * test multiple days per week - DUE DATE - */ + /** test multiple days per week - DUE DATE */ @Test public void testDueDateSingleWeekMultiDay() throws Exception { @@ -162,9 +154,7 @@ public class AdvancedRepeatTest { // --- completion tests - /** - * test multiple days per week, multiple intervals - DUE DATE - */ + /** test multiple days per week, multiple intervals - DUE DATE */ @Test public void testDueDateMultiWeekMultiDay() throws Exception { buildRRule(2, Frequency.WEEKLY, Weekday.MO, Weekday.WE, Weekday.FR); @@ -182,9 +172,7 @@ public class AdvancedRepeatTest { assertDueDate(nextDueDate, NEXT, Calendar.MONDAY); } - /** - * test multiple days per week - COMPLETE DATE - */ + /** test multiple days per week - COMPLETE DATE */ @Test public void testCompleteDateSingleWeek() throws Exception { for (Weekday wday : Weekday.values()) { @@ -213,9 +201,7 @@ public class AdvancedRepeatTest { // --- helpers - /** - * test multiple days per week, multiple intervals - COMPLETE DATE - */ + /** test multiple days per week, multiple intervals - COMPLETE DATE */ @Test public void testCompleteDateMultiWeek() throws Exception { for (Weekday wday : Weekday.values()) { diff --git a/app/src/androidTest/java/com/todoroo/astrid/repeats/NewRepeatTests.java b/app/src/androidTest/java/com/todoroo/astrid/repeats/NewRepeatTests.java index 47b12ac60..b08182667 100644 --- a/app/src/androidTest/java/com/todoroo/astrid/repeats/NewRepeatTests.java +++ b/app/src/androidTest/java/com/todoroo/astrid/repeats/NewRepeatTests.java @@ -66,10 +66,7 @@ public class NewRepeatTests { assertEquals(newDayTime(2017, 8, 28, 1, 44), calculateNextDueDate(task)); } - /** - * Tests for repeating from completionDate - */ - + /** Tests for repeating from completionDate */ @Test public void testRepeatMinutelyFromCompleteDateCompleteBefore() throws ParseException { DateTime dueDateTime = newDayTime(2016, 8, 30, 0, 25); @@ -181,8 +178,9 @@ public class NewRepeatTests { @Test public void testAdvancedRepeatWeeklyFromDueDate() throws ParseException { DateTime dueDateTime = newDayTime(2016, 8, 29, 0, 25); - Task task = newWeeklyFromDue(1, dueDateTime, new WeekdayNum(0, Weekday.MO), - new WeekdayNum(0, Weekday.WE)); + Task task = + newWeeklyFromDue( + 1, dueDateTime, new WeekdayNum(0, Weekday.MO), new WeekdayNum(0, Weekday.WE)); assertEquals(newDayTime(2016, 8, 31, 0, 25), calculateNextDueDate(task)); } @@ -191,8 +189,13 @@ public class NewRepeatTests { public void testAdvancedRepeatWeeklyFromCompleteDateCompleteBefore() throws ParseException { DateTime dueDateTime = newDayTime(2016, 8, 29, 0, 25); DateTime completionDateTime = newDayTime(2016, 8, 28, 1, 9); - Task task = newWeeklyFromCompleted(1, dueDateTime, completionDateTime, - new WeekdayNum(0, Weekday.MO), new WeekdayNum(0, Weekday.WE)); + Task task = + newWeeklyFromCompleted( + 1, + dueDateTime, + completionDateTime, + new WeekdayNum(0, Weekday.MO), + new WeekdayNum(0, Weekday.WE)); assertEquals(newDayTime(2016, 8, 29, 0, 25), calculateNextDueDate(task)); } @@ -201,15 +204,22 @@ public class NewRepeatTests { public void testAdvancedRepeatWeeklyFromCompleteDateCompleteAfter() throws ParseException { DateTime dueDateTime = newDayTime(2016, 8, 29, 0, 25); DateTime completionDateTime = newDayTime(2016, 9, 1, 1, 9); - Task task = newWeeklyFromCompleted(1, dueDateTime, completionDateTime, - new WeekdayNum(0, Weekday.MO), new WeekdayNum(0, Weekday.WE)); + Task task = + newWeeklyFromCompleted( + 1, + dueDateTime, + completionDateTime, + new WeekdayNum(0, Weekday.MO), + new WeekdayNum(0, Weekday.WE)); assertEquals(newDayTime(2016, 9, 5, 0, 25), calculateNextDueDate(task)); } private DateTime newDayTime(int year, int month, int day, int hour, int minute) { - return new DateTime(Task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, - new DateTime(year, month, day, hour, minute).getMillis())); + return new DateTime( + Task.createDueDate( + Task.URGENCY_SPECIFIC_DAY_TIME, + new DateTime(year, month, day, hour, minute).getMillis())); } private DateTime calculateNextDueDate(Task task) throws ParseException { @@ -218,39 +228,47 @@ public class NewRepeatTests { } private Task newFromDue(Frequency frequency, int interval, DateTime dueDateTime) { - return new Task() {{ - setRecurrence(getRecurrenceRule(frequency, interval, false)); - setDueDate(dueDateTime.getMillis()); - }}; + return new Task() { + { + setRecurrence(getRecurrenceRule(frequency, interval, false)); + setDueDate(dueDateTime.getMillis()); + } + }; } private Task newWeeklyFromDue(int interval, DateTime dueDateTime, WeekdayNum... weekdays) { - return new Task() {{ - setRecurrence(getRecurrenceRule(Frequency.WEEKLY, interval, false, weekdays)); - setDueDate(dueDateTime.getMillis()); - }}; + return new Task() { + { + setRecurrence(getRecurrenceRule(Frequency.WEEKLY, interval, false, weekdays)); + setDueDate(dueDateTime.getMillis()); + } + }; } - private Task newFromCompleted(Frequency frequency, int interval, DateTime dueDateTime, - DateTime completionDate) { - return new Task() {{ - setRecurrence(getRecurrenceRule(frequency, interval, true)); - setDueDate(dueDateTime.getMillis()); - setCompletionDate(completionDate.getMillis()); - }}; + private Task newFromCompleted( + Frequency frequency, int interval, DateTime dueDateTime, DateTime completionDate) { + return new Task() { + { + setRecurrence(getRecurrenceRule(frequency, interval, true)); + setDueDate(dueDateTime.getMillis()); + setCompletionDate(completionDate.getMillis()); + } + }; } - private Task newWeeklyFromCompleted(int interval, DateTime dueDateTime, DateTime completionDate, - WeekdayNum... weekdays) { - return new Task() {{ - setRecurrence(getRecurrenceRule(Frequency.WEEKLY, interval, true, weekdays)); - setDueDate(dueDateTime.getMillis()); - setCompletionDate(completionDate.getMillis()); - }}; + private Task newWeeklyFromCompleted( + int interval, DateTime dueDateTime, DateTime completionDate, WeekdayNum... weekdays) { + return new Task() { + { + setRecurrence(getRecurrenceRule(Frequency.WEEKLY, interval, true, weekdays)); + setDueDate(dueDateTime.getMillis()); + setCompletionDate(completionDate.getMillis()); + } + }; } - private String getRecurrenceRule(Frequency frequency, int interval, boolean fromCompletion, - WeekdayNum... weekdays) { + private String getRecurrenceRule( + Frequency frequency, int interval, boolean fromCompletion, WeekdayNum... weekdays) { RRule rrule = new RRule(); rrule.setFreq(frequency); rrule.setInterval(interval); diff --git a/app/src/androidTest/java/com/todoroo/astrid/repeats/RepeatTaskHelperTest.java b/app/src/androidTest/java/com/todoroo/astrid/repeats/RepeatTaskHelperTest.java index 0f68a8c85..b5eb605a1 100644 --- a/app/src/androidTest/java/com/todoroo/astrid/repeats/RepeatTaskHelperTest.java +++ b/app/src/androidTest/java/com/todoroo/astrid/repeats/RepeatTaskHelperTest.java @@ -64,127 +64,139 @@ public class RepeatTaskHelperTest extends InjectingTestCase { @Test public void testMinutelyRepeat() throws ParseException { - Task task = newTask(with(ID, 1L), - with(DUE_TIME, new DateTime(2017, 10, 4, 13, 30)), - with(RRULE, new RRule("RRULE:FREQ=MINUTELY;INTERVAL=30"))); + Task task = + newTask( + with(ID, 1L), + with(DUE_TIME, new DateTime(2017, 10, 4, 13, 30)), + with(RRULE, new RRule("RRULE:FREQ=MINUTELY;INTERVAL=30"))); - repeatAndVerify(task, - new DateTime(2017, 10, 4, 13, 30, 1), - new DateTime(2017, 10, 4, 14, 0, 1)); + repeatAndVerify( + task, new DateTime(2017, 10, 4, 13, 30, 1), new DateTime(2017, 10, 4, 14, 0, 1)); } @Test public void testMinutelyRepeatAfterCompletion() throws ParseException { - Task task = newTask(with(ID, 1L), - with(DUE_TIME, new DateTime(2017, 10, 4, 13, 30)), - with(COMPLETION_TIME, new DateTime(2017, 10, 4, 13, 17, 45, 340)), - with(RRULE, new RRule("RRULE:FREQ=MINUTELY;INTERVAL=30")), - with(AFTER_COMPLETE, true)); + Task task = + newTask( + with(ID, 1L), + with(DUE_TIME, new DateTime(2017, 10, 4, 13, 30)), + with(COMPLETION_TIME, new DateTime(2017, 10, 4, 13, 17, 45, 340)), + with(RRULE, new RRule("RRULE:FREQ=MINUTELY;INTERVAL=30")), + with(AFTER_COMPLETE, true)); - repeatAndVerify(task, - new DateTime(2017, 10, 4, 13, 30, 1), - new DateTime(2017, 10, 4, 13, 47, 1)); + repeatAndVerify( + task, new DateTime(2017, 10, 4, 13, 30, 1), new DateTime(2017, 10, 4, 13, 47, 1)); } @Test public void testMinutelyDecrementCount() throws ParseException { - Task task = newTask(with(ID, 1L), - with(DUE_TIME, new DateTime(2017, 10, 4, 13, 30)), - with(RRULE, new RRule("RRULE:FREQ=MINUTELY;COUNT=2;INTERVAL=30"))); + Task task = + newTask( + with(ID, 1L), + with(DUE_TIME, new DateTime(2017, 10, 4, 13, 30)), + with(RRULE, new RRule("RRULE:FREQ=MINUTELY;COUNT=2;INTERVAL=30"))); - repeatAndVerify(task, - new DateTime(2017, 10, 4, 13, 30, 1), - new DateTime(2017, 10, 4, 14, 0, 1)); + repeatAndVerify( + task, new DateTime(2017, 10, 4, 13, 30, 1), new DateTime(2017, 10, 4, 14, 0, 1)); assertEquals(1, new RRule(task.getRecurrenceWithoutFrom()).getCount()); } @Test public void testMinutelyLastOccurrence() throws ParseException { - Task task = newTask(with(ID, 1L), - with(DUE_TIME, new DateTime(2017, 10, 4, 13, 30)), - with(RRULE, new RRule("RRULE:FREQ=MINUTELY;COUNT=1;INTERVAL=30"))); + Task task = + newTask( + with(ID, 1L), + with(DUE_TIME, new DateTime(2017, 10, 4, 13, 30)), + with(RRULE, new RRule("RRULE:FREQ=MINUTELY;COUNT=1;INTERVAL=30"))); helper.handleRepeat(task); } @Test public void testHourlyRepeat() throws ParseException { - Task task = newTask(with(ID, 1L), - with(DUE_TIME, new DateTime(2017, 10, 4, 13, 30)), - with(RRULE, new RRule("RRULE:FREQ=HOURLY;INTERVAL=6"))); + Task task = + newTask( + with(ID, 1L), + with(DUE_TIME, new DateTime(2017, 10, 4, 13, 30)), + with(RRULE, new RRule("RRULE:FREQ=HOURLY;INTERVAL=6"))); - repeatAndVerify(task, - new DateTime(2017, 10, 4, 13, 30, 1), - new DateTime(2017, 10, 4, 19, 30, 1)); + repeatAndVerify( + task, new DateTime(2017, 10, 4, 13, 30, 1), new DateTime(2017, 10, 4, 19, 30, 1)); } @Test public void testHourlyRepeatAfterCompletion() throws ParseException { - Task task = newTask(with(ID, 1L), - with(DUE_TIME, new DateTime(2017, 10, 4, 13, 30)), - with(COMPLETION_TIME, new DateTime(2017, 10, 4, 13, 17, 45, 340)), - with(RRULE, new RRule("RRULE:FREQ=HOURLY;INTERVAL=6")), - with(AFTER_COMPLETE, true)); + Task task = + newTask( + with(ID, 1L), + with(DUE_TIME, new DateTime(2017, 10, 4, 13, 30)), + with(COMPLETION_TIME, new DateTime(2017, 10, 4, 13, 17, 45, 340)), + with(RRULE, new RRule("RRULE:FREQ=HOURLY;INTERVAL=6")), + with(AFTER_COMPLETE, true)); - repeatAndVerify(task, - new DateTime(2017, 10, 4, 13, 30, 1), - new DateTime(2017, 10, 4, 19, 17, 1)); + repeatAndVerify( + task, new DateTime(2017, 10, 4, 13, 30, 1), new DateTime(2017, 10, 4, 19, 17, 1)); } @Test public void testDailyRepeat() throws ParseException { - Task task = newTask(with(ID, 1L), - with(DUE_TIME, new DateTime(2017, 10, 4, 13, 30)), - with(RRULE, new RRule("RRULE:FREQ=DAILY;INTERVAL=6"))); + Task task = + newTask( + with(ID, 1L), + with(DUE_TIME, new DateTime(2017, 10, 4, 13, 30)), + with(RRULE, new RRule("RRULE:FREQ=DAILY;INTERVAL=6"))); - repeatAndVerify(task, - new DateTime(2017, 10, 4, 13, 30, 1), - new DateTime(2017, 10, 10, 13, 30, 1)); + repeatAndVerify( + task, new DateTime(2017, 10, 4, 13, 30, 1), new DateTime(2017, 10, 10, 13, 30, 1)); } @Test public void testRepeatWeeklyNoDays() throws ParseException { - Task task = newTask(with(ID, 1L), - with(DUE_TIME, new DateTime(2017, 10, 4, 13, 30)), - with(RRULE, new RRule("RRULE:FREQ=WEEKLY;INTERVAL=2"))); + Task task = + newTask( + with(ID, 1L), + with(DUE_TIME, new DateTime(2017, 10, 4, 13, 30)), + with(RRULE, new RRule("RRULE:FREQ=WEEKLY;INTERVAL=2"))); - repeatAndVerify(task, - new DateTime(2017, 10, 4, 13, 30, 1), - new DateTime(2017, 10, 18, 13, 30, 1)); + repeatAndVerify( + task, new DateTime(2017, 10, 4, 13, 30, 1), new DateTime(2017, 10, 18, 13, 30, 1)); } @Test public void testYearly() throws ParseException { - Task task = newTask(with(ID, 1L), - with(DUE_TIME, new DateTime(2017, 10, 4, 13, 30)), - with(RRULE, new RRule("RRULE:FREQ=YEARLY;INTERVAL=3"))); + Task task = + newTask( + with(ID, 1L), + with(DUE_TIME, new DateTime(2017, 10, 4, 13, 30)), + with(RRULE, new RRule("RRULE:FREQ=YEARLY;INTERVAL=3"))); - repeatAndVerify(task, - new DateTime(2017, 10, 4, 13, 30, 1), - new DateTime(2020, 10, 4, 13, 30, 1)); + repeatAndVerify( + task, new DateTime(2017, 10, 4, 13, 30, 1), new DateTime(2020, 10, 4, 13, 30, 1)); } @Test public void testMonthlyRepeat() throws ParseException { - Task task = newTask(with(ID, 1L), - with(DUE_TIME, new DateTime(2017, 10, 4, 13, 30)), - with(RRULE, new RRule("RRULE:FREQ=MONTHLY;INTERVAL=3"))); + Task task = + newTask( + with(ID, 1L), + with(DUE_TIME, new DateTime(2017, 10, 4, 13, 30)), + with(RRULE, new RRule("RRULE:FREQ=MONTHLY;INTERVAL=3"))); - repeatAndVerify(task, - new DateTime(2017, 10, 4, 13, 30, 1), - new DateTime(2018, 1, 4, 13, 30, 1)); + repeatAndVerify( + task, new DateTime(2017, 10, 4, 13, 30, 1), new DateTime(2018, 1, 4, 13, 30, 1)); } @Test public void testMonthlyRepeatAtEndOfMonth() throws ParseException { - Task task = newTask(with(ID, 1L), - with(DUE_TIME, new DateTime(2017, 1, 31, 13, 30)), - with(RRULE, new RRule("RRULE:FREQ=MONTHLY;INTERVAL=1"))); + Task task = + newTask( + with(ID, 1L), + with(DUE_TIME, new DateTime(2017, 1, 31, 13, 30)), + with(RRULE, new RRule("RRULE:FREQ=MONTHLY;INTERVAL=1"))); - repeatAndVerify(task, - new DateTime(2017, 1, 31, 13, 30, 1), - new DateTime(2017, 2, 28, 13, 30, 1)); + repeatAndVerify( + task, new DateTime(2017, 1, 31, 13, 30, 1), new DateTime(2017, 2, 28, 13, 30, 1)); } private void repeatAndVerify(Task task, DateTime oldDueDate, DateTime newDueDate) { @@ -192,7 +204,8 @@ public class RepeatTaskHelperTest extends InjectingTestCase { mocks.verify(gCalHelper).rescheduleRepeatingTask(task); mocks.verify(alarmService).rescheduleAlarms(1, oldDueDate.getMillis(), newDueDate.getMillis()); - mocks.verify(localBroadcastManager) + mocks + .verify(localBroadcastManager) .broadcastRepeat(1, oldDueDate.getMillis(), newDueDate.getMillis()); } diff --git a/app/src/androidTest/java/com/todoroo/astrid/service/QuickAddMarkupTest.java b/app/src/androidTest/java/com/todoroo/astrid/service/QuickAddMarkupTest.java index 30d4a9c3d..6976a6a59 100644 --- a/app/src/androidTest/java/com/todoroo/astrid/service/QuickAddMarkupTest.java +++ b/app/src/androidTest/java/com/todoroo/astrid/service/QuickAddMarkupTest.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.service; import static junit.framework.Assert.assertEquals; diff --git a/app/src/androidTest/java/com/todoroo/astrid/service/TitleParserTest.java b/app/src/androidTest/java/com/todoroo/astrid/service/TitleParserTest.java index 7f5e42453..65149727c 100644 --- a/app/src/androidTest/java/com/todoroo/astrid/service/TitleParserTest.java +++ b/app/src/androidTest/java/com/todoroo/astrid/service/TitleParserTest.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc - *

- * See the file "LICENSE" for the full license governing this code. + * + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.service; import static junit.framework.Assert.assertEquals; @@ -60,24 +59,22 @@ public class TitleParserTest extends InjectingTestCase { assertEquals(task.getRecurrence(), nothing.getRecurrence()); } - /** - * Tests correct date is parsed - **/ + /** Tests correct date is parsed */ @Test public void testMonthDate() { String[] titleMonthStrings = { - "Jan.", "January", - "Feb.", "February", - "Mar.", "March", - "Apr.", "April", - "May", "May", - "Jun.", "June", - "Jul.", "July", - "Aug.", "August", - "Sep.", "September", - "Oct.", "October", - "Nov.", "November", - "Dec.", "December" + "Jan.", "January", + "Feb.", "February", + "Mar.", "March", + "Apr.", "April", + "May", "May", + "Jun.", "June", + "Jul.", "July", + "Aug.", "August", + "Sep.", "September", + "Oct.", "October", + "Nov.", "November", + "Dec.", "December" }; for (int i = 0; i < 23; i++) { String testTitle = "Jog on " + titleMonthStrings[i] + " 12."; @@ -138,11 +135,7 @@ public class TitleParserTest extends InjectingTestCase { @Test public void test_several_forms_of_eight() { - String[] testTitles = { - "Jog 8 AM", - "Jog 8 o'clock AM", - "at 8:00 AM" - }; + String[] testTitles = {"Jog 8 AM", "Jog 8 o'clock AM", "at 8:00 AM"}; for (String testTitle : testTitles) { Task task = insertTitleAddTask(testTitle); DateTime date = newDateTime(task.getDueDate()); @@ -154,11 +147,7 @@ public class TitleParserTest extends InjectingTestCase { @Test public void test_several_forms_of_1230PM() { String[] testTitles = { - "Jog 12:30 PM", - "at 12:30 PM", - "Do something on 12:30 PM", - "Jog at 12:30 PM Friday" - + "Jog 12:30 PM", "at 12:30 PM", "Do something on 12:30 PM", "Jog at 12:30 PM Friday" }; for (String testTitle : testTitles) { Task task = insertTitleAddTask(testTitle); @@ -172,7 +161,6 @@ public class TitleParserTest extends InjectingTestCase { return taskCreator.createWithValues(null, title); } - // ----------------Days begin----------------// @Test public void testDays() { @@ -182,7 +170,7 @@ public class TitleParserTest extends InjectingTestCase { Task task = taskCreator.createWithValues(null, title); DateTime date = newDateTime(task.getDueDate()); assertEquals(date.getDayOfWeek(), today.get(Calendar.DAY_OF_WEEK)); - //Calendar starts 1-6, date.getDay() starts at 0 + // Calendar starts 1-6, date.getDay() starts at 0 title = "Jog tomorrow"; task = taskCreator.createWithValues(null, title); @@ -190,23 +178,9 @@ public class TitleParserTest extends InjectingTestCase { assertEquals((date.getDayOfWeek()) % 7, (today.get(Calendar.DAY_OF_WEEK) + 1) % 7); String[] days = { - "sunday", - "monday", - "tuesday", - "wednesday", - "thursday", - "friday", - "saturday", - }; - String[] abrevDays = { - "sun.", - "mon.", - "tue.", - "wed.", - "thu.", - "fri.", - "sat." + "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", }; + String[] abrevDays = {"sun.", "mon.", "tue.", "wed.", "thu.", "fri.", "sat."}; for (int i = 1; i <= 6; i++) { title = "Jog " + days[i]; @@ -219,24 +193,16 @@ public class TitleParserTest extends InjectingTestCase { date = newDateTime(task.getDueDate()); assertEquals(date.getDayOfWeek(), i + 1); } - } - //----------------Days end----------------// + // ----------------Days end----------------// - //----------------Priority begin----------------// + // ----------------Priority begin----------------// - /** - * tests all words using priority 0 - */ + /** tests all words using priority 0 */ @Test public void testPriority0() { - String[] acceptedStrings = { - "priority 0", - "least priority", - "lowest priority", - "bang 0" - }; + String[] acceptedStrings = {"priority 0", "least priority", "lowest priority", "bang 0"}; for (String acceptedString : acceptedStrings) { String title = "Jog " + acceptedString; Task task = taskCreator.createWithValues(null, title); @@ -251,50 +217,39 @@ public class TitleParserTest extends InjectingTestCase { @Test public void testPriority1() { - String[] acceptedStringsAtEnd = { - "priority 1", - "low priority", - "bang", - "bang 1" - }; - String[] acceptedStringsAnywhere = { - "!1", - "!" - }; + String[] acceptedStringsAtEnd = {"priority 1", "low priority", "bang", "bang 1"}; + String[] acceptedStringsAnywhere = {"!1", "!"}; Task task; for (String acceptedStringAtEnd : acceptedStringsAtEnd) { - task = taskCreator.basicQuickAddTask( - "Jog " + acceptedStringAtEnd); //test at end of task. should set importance. + task = + taskCreator.basicQuickAddTask( + "Jog " + acceptedStringAtEnd); // test at end of task. should set importance. assertEquals((int) task.getImportance(), Task.IMPORTANCE_SHOULD_DO); } for (String acceptedStringAtEnd : acceptedStringsAtEnd) { - task = taskCreator.basicQuickAddTask( - acceptedStringAtEnd + " jog"); //test at beginning of task. should not set importance. + task = + taskCreator.basicQuickAddTask( + acceptedStringAtEnd + + " jog"); // test at beginning of task. should not set importance. assertEquals((int) task.getImportance(), Task.IMPORTANCE_SHOULD_DO); } for (String acceptedStringAnywhere : acceptedStringsAnywhere) { - task = taskCreator.basicQuickAddTask( - "Jog " + acceptedStringAnywhere); //test at end of task. should set importance. + task = + taskCreator.basicQuickAddTask( + "Jog " + acceptedStringAnywhere); // test at end of task. should set importance. assertEquals((int) task.getImportance(), Task.IMPORTANCE_SHOULD_DO); - task = taskCreator.basicQuickAddTask( - acceptedStringAnywhere + " jog"); //test at beginning of task. should set importance. + task = + taskCreator.basicQuickAddTask( + acceptedStringAnywhere + " jog"); // test at beginning of task. should set importance. assertEquals((int) task.getImportance(), Task.IMPORTANCE_SHOULD_DO); } } @Test public void testPriority2() { - String[] acceptedStringsAtEnd = { - "priority 2", - "high priority", - "bang bang", - "bang 2" - }; - String[] acceptedStringsAnywhere = { - "!2", - "!!" - }; + String[] acceptedStringsAtEnd = {"priority 2", "high priority", "bang bang", "bang 2"}; + String[] acceptedStringsAnywhere = {"!2", "!!"}; for (String acceptedStringAtEnd : acceptedStringsAtEnd) { String title = "Jog " + acceptedStringAtEnd; Task task = taskCreator.createWithValues(null, title); @@ -318,18 +273,13 @@ public class TitleParserTest extends InjectingTestCase { @Test public void testPriority3() { String[] acceptedStringsAtEnd = { - "priority 3", - "highest priority", - "bang bang bang", - "bang 3", - "bang bang bang bang bang bang bang" - }; - String[] acceptedStringsAnywhere = { - "!3", - "!!!", - "!6", - "!!!!!!!!!!!!!" + "priority 3", + "highest priority", + "bang bang bang", + "bang 3", + "bang bang bang bang bang bang bang" }; + String[] acceptedStringsAnywhere = {"!3", "!!!", "!6", "!!!!!!!!!!!!!"}; for (String acceptedStringAtEnd : acceptedStringsAtEnd) { String title = "Jog " + acceptedStringAtEnd; Task task = taskCreator.createWithValues(null, title); @@ -350,13 +300,11 @@ public class TitleParserTest extends InjectingTestCase { } } - //----------------Priority end----------------// + // ----------------Priority end----------------// - //----------------Repeats begin----------------// + // ----------------Repeats begin----------------// - /** - * test daily repeat from due date, but with no due date set - */ + /** test daily repeat from due date, but with no due date set */ @Test public void testDailyWithNoDueDate() { String title = "Jog daily"; @@ -382,12 +330,9 @@ public class TitleParserTest extends InjectingTestCase { assertFalse(task.hasDueTime()); assertFalse(task.hasDueDate()); } - } - /** - * test weekly repeat from due date, with no due date & time set - */ + /** test weekly repeat from due date, with no due date & time set */ @Test public void testWeeklyWithNoDueDate() { String title = "Jog weekly"; @@ -415,9 +360,7 @@ public class TitleParserTest extends InjectingTestCase { } } - /** - * test hourly repeat from due date, with no due date but no time - */ + /** test hourly repeat from due date, with no due date but no time */ @Test public void testMonthlyFromNoDueDate() { String title = "Jog monthly"; @@ -493,25 +436,18 @@ public class TitleParserTest extends InjectingTestCase { } } -//----------------Repeats end----------------// + // ----------------Repeats end----------------// - //----------------Tags begin----------------// + // ----------------Tags begin----------------// - /** - * tests all words using priority 0 - */ + /** tests all words using priority 0 */ @Test public void testTagsPound() { - String[] acceptedStrings = { - "#tag", - "#a", - "#(a cool tag)", - "#(cool)" - }; + String[] acceptedStrings = {"#tag", "#a", "#(a cool tag)", "#(cool)"}; Task task; for (String acceptedString : acceptedStrings) { task = new Task(); - task.setTitle("Jog " + acceptedString); //test at end of task. should set importance. + task.setTitle("Jog " + acceptedString); // test at end of task. should set importance. ArrayList tags = new ArrayList<>(); TitleParser.listHelper(tagService, task, tags); String tag = TitleParser.trimParenthesis(acceptedString); @@ -521,21 +457,14 @@ public class TitleParserTest extends InjectingTestCase { } } - /** - * tests all words using priority 0 - */ + /** tests all words using priority 0 */ @Test public void testTagsAt() { - String[] acceptedStrings = { - "@tag", - "@a", - "@(a cool tag)", - "@(cool)" - }; + String[] acceptedStrings = {"@tag", "@a", "@(a cool tag)", "@(cool)"}; Task task; for (String acceptedString : acceptedStrings) { task = new Task(); - task.setTitle("Jog " + acceptedString); //test at end of task. should set importance. + task.setTitle("Jog " + acceptedString); // test at end of task. should set importance. ArrayList tags = new ArrayList<>(); TitleParser.listHelper(tagService, task, tags); String tag = TitleParser.trimParenthesis(acceptedString); diff --git a/app/src/androidTest/java/com/todoroo/astrid/subtasks/SubtasksHelperTest.java b/app/src/androidTest/java/com/todoroo/astrid/subtasks/SubtasksHelperTest.java index 6eaf2d47c..0b8f6b0bf 100644 --- a/app/src/androidTest/java/com/todoroo/astrid/subtasks/SubtasksHelperTest.java +++ b/app/src/androidTest/java/com/todoroo/astrid/subtasks/SubtasksHelperTest.java @@ -15,8 +15,8 @@ import org.tasks.injection.TestComponent; public class SubtasksHelperTest extends SubtasksTestCase { private static final String[] EXPECTED_ORDER = {"-1", "1", "2", "3", "4", "5", "6"}; - private static final String EXPECTED_REMOTE = "[\"-1\", [\"6\", \"4\", [\"3\", \"1\"]], \"2\", \"5\"]" - .replaceAll("\\s", ""); + private static final String EXPECTED_REMOTE = + "[\"-1\", [\"6\", \"4\", [\"3\", \"1\"]], \"2\", \"5\"]".replaceAll("\\s", ""); @Inject TaskDao taskDao; @Override @@ -25,8 +25,8 @@ public class SubtasksHelperTest extends SubtasksTestCase { createTasks(); TaskListMetadata m = new TaskListMetadata(); m.setFilter(TaskListMetadata.FILTER_ID_ALL); - updater.initializeFromSerializedTree(m, filter, - SubtasksHelper.convertTreeToRemoteIds(taskDao, DEFAULT_SERIALIZED_TREE)); + updater.initializeFromSerializedTree( + m, filter, SubtasksHelper.convertTreeToRemoteIds(taskDao, DEFAULT_SERIALIZED_TREE)); } private void createTask(String title, String uuid) { @@ -58,8 +58,9 @@ public class SubtasksHelperTest extends SubtasksTestCase { @Test public void testLocalToRemoteIdMapping() { - String mapped = SubtasksHelper.convertTreeToRemoteIds(taskDao, DEFAULT_SERIALIZED_TREE) - .replaceAll("\\s", ""); + String mapped = + SubtasksHelper.convertTreeToRemoteIds(taskDao, DEFAULT_SERIALIZED_TREE) + .replaceAll("\\s", ""); assertEquals(EXPECTED_REMOTE, mapped); } diff --git a/app/src/androidTest/java/com/todoroo/astrid/subtasks/SubtasksMovingTest.java b/app/src/androidTest/java/com/todoroo/astrid/subtasks/SubtasksMovingTest.java index e7f90cc5f..700e9f496 100644 --- a/app/src/androidTest/java/com/todoroo/astrid/subtasks/SubtasksMovingTest.java +++ b/app/src/androidTest/java/com/todoroo/astrid/subtasks/SubtasksMovingTest.java @@ -22,8 +22,8 @@ public class SubtasksMovingTest extends SubtasksTestCase { createTasks(); TaskListMetadata m = new TaskListMetadata(); m.setFilter(TaskListMetadata.FILTER_ID_ALL); - updater.initializeFromSerializedTree(m, filter, - SubtasksHelper.convertTreeToRemoteIds(taskDao, DEFAULT_SERIALIZED_TREE)); + updater.initializeFromSerializedTree( + m, filter, SubtasksHelper.convertTreeToRemoteIds(taskDao, DEFAULT_SERIALIZED_TREE)); // Assert initial state is correct expectParentAndPosition(A, null, 0); diff --git a/app/src/androidTest/java/com/todoroo/astrid/subtasks/SubtasksTestCase.java b/app/src/androidTest/java/com/todoroo/astrid/subtasks/SubtasksTestCase.java index a8fde370a..9cfbec5d1 100644 --- a/app/src/androidTest/java/com/todoroo/astrid/subtasks/SubtasksTestCase.java +++ b/app/src/androidTest/java/com/todoroo/astrid/subtasks/SubtasksTestCase.java @@ -31,8 +31,7 @@ public class SubtasksTestCase extends InjectingTestCase { * E * F */ - static final String DEFAULT_SERIALIZED_TREE = "[-1, [1, 2, [3, 4]], 5, 6]" - .replaceAll("\\s", ""); + static final String DEFAULT_SERIALIZED_TREE = "[-1, [1, 2, [3, 4]], 5, 6]".replaceAll("\\s", ""); SubtasksFilterUpdater updater; Filter filter; @Inject TaskListMetadataDao taskListMetadataDao; @@ -59,5 +58,4 @@ public class SubtasksTestCase extends InjectingTestCase { assertEquals("Parent mismatch", parentId, n.parent.uuid); assertEquals("Position mismatch", positionInParent, n.parent.children.indexOf(n)); } - } diff --git a/app/src/androidTest/java/com/todoroo/astrid/sync/SyncModelTest.java b/app/src/androidTest/java/com/todoroo/astrid/sync/SyncModelTest.java index a74a319bd..ae28d354a 100644 --- a/app/src/androidTest/java/com/todoroo/astrid/sync/SyncModelTest.java +++ b/app/src/androidTest/java/com/todoroo/astrid/sync/SyncModelTest.java @@ -22,5 +22,4 @@ public class SyncModelTest extends NewSyncTestCase { TagData tag = createTagData(); assertFalse(Task.NO_UUID.equals(tag.getRemoteId())); } - } diff --git a/app/src/androidTest/java/org/tasks/Snippet.java b/app/src/androidTest/java/org/tasks/Snippet.java index 798033f10..3fb193082 100644 --- a/app/src/androidTest/java/org/tasks/Snippet.java +++ b/app/src/androidTest/java/org/tasks/Snippet.java @@ -1,5 +1,3 @@ package org.tasks; -public class Snippet { - -} +public class Snippet {} diff --git a/app/src/androidTest/java/org/tasks/date/DateTimeUtilsTest.java b/app/src/androidTest/java/org/tasks/date/DateTimeUtilsTest.java index 18f16c02e..36d0c83ed 100644 --- a/app/src/androidTest/java/org/tasks/date/DateTimeUtilsTest.java +++ b/app/src/androidTest/java/org/tasks/date/DateTimeUtilsTest.java @@ -19,16 +19,26 @@ public class DateTimeUtilsTest { @Test public void testGetCurrentTime() { - freezeAt(now).thawAfter(new Snippet() {{ - assertEquals(now.getMillis(), currentTimeMillis()); - }}); + freezeAt(now) + .thawAfter( + new Snippet() { + { + assertEquals(now.getMillis(), currentTimeMillis()); + } + }); } @Test public void testCreateNewUtcDate() { DateTime utc = now.toUTC(); - DateTime actual = newDateUtc(utc.getYear(), utc.getMonthOfYear(), utc.getDayOfMonth(), - utc.getHourOfDay(), utc.getMinuteOfHour(), utc.getSecondOfMinute()); + DateTime actual = + newDateUtc( + utc.getYear(), + utc.getMonthOfYear(), + utc.getDayOfMonth(), + utc.getHourOfDay(), + utc.getMinuteOfHour(), + utc.getSecondOfMinute()); assertEquals(utc.getMillis(), actual.getMillis()); } diff --git a/app/src/androidTest/java/org/tasks/injection/InjectingTestCase.java b/app/src/androidTest/java/org/tasks/injection/InjectingTestCase.java index d8eb61fb4..f8d645e66 100644 --- a/app/src/androidTest/java/org/tasks/injection/InjectingTestCase.java +++ b/app/src/androidTest/java/org/tasks/injection/InjectingTestCase.java @@ -13,9 +13,8 @@ public abstract class InjectingTestCase { public void setUp() { initializeMockito(getTargetContext()); - component = DaggerTestComponent.builder() - .testModule(new TestModule(getTargetContext())) - .build(); + component = + DaggerTestComponent.builder().testModule(new TestModule(getTargetContext())).build(); inject(component); } diff --git a/app/src/androidTest/java/org/tasks/jobs/BackupJobTest.java b/app/src/androidTest/java/org/tasks/jobs/BackupJobTest.java index 0070ddd91..dccb3fec8 100644 --- a/app/src/androidTest/java/org/tasks/jobs/BackupJobTest.java +++ b/app/src/androidTest/java/org/tasks/jobs/BackupJobTest.java @@ -17,6 +17,12 @@ import org.tasks.time.DateTime; @RunWith(AndroidJUnit4.class) public class BackupJobTest { + private static File newFile(DateTime lastModified) { + File result = mock(File.class); + stub(result.lastModified()).toReturn(lastModified.getMillis()); + return result; + } + @Test public void filterExcludesXmlFiles() { assertFalse(BackupJob.FILE_FILTER.accept(new File("/a/b/c/d/auto.180329-0001.xml"))); @@ -33,9 +39,7 @@ public class BackupJobTest { File file2 = newFile(newDate(2018, 3, 28)); File file3 = newFile(newDate(2018, 3, 29)); - assertEquals( - emptyList(), - BackupJob.getDeleteList(new File[] {file2, file1, file3}, 7)); + assertEquals(emptyList(), BackupJob.getDeleteList(new File[] {file2, file1, file3}, 7)); } @Test @@ -50,13 +54,6 @@ public class BackupJobTest { File file3 = newFile(newDate(2018, 3, 29)); assertEquals( - singletonList(file1), - BackupJob.getDeleteList(new File[] {file2, file1, file3}, 2)); - } - - private static File newFile(DateTime lastModified) { - File result = mock(File.class); - stub(result.lastModified()).toReturn(lastModified.getMillis()); - return result; + singletonList(file1), BackupJob.getDeleteList(new File[] {file2, file1, file3}, 2)); } } diff --git a/app/src/androidTest/java/org/tasks/jobs/BackupServiceTests.java b/app/src/androidTest/java/org/tasks/jobs/BackupServiceTests.java index 55f461ecf..f47915cbb 100644 --- a/app/src/androidTest/java/org/tasks/jobs/BackupServiceTests.java +++ b/app/src/androidTest/java/org/tasks/jobs/BackupServiceTests.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package org.tasks.jobs; import static android.support.test.InstrumentationRegistry.getTargetContext; @@ -31,12 +30,10 @@ import org.tasks.preferences.Preferences; public class BackupServiceTests extends InjectingTestCase { private static final long BACKUP_WAIT_TIME = 500L; - - private File temporaryDirectory = null; - @Inject TasksJsonExporter jsonExporter; @Inject TaskDao taskDao; @Inject Preferences preferences; + private File temporaryDirectory = null; @Override public void setUp() { diff --git a/app/src/androidTest/java/org/tasks/jobs/NotificationQueueTest.java b/app/src/androidTest/java/org/tasks/jobs/NotificationQueueTest.java index 9fd3ae169..72a55cddf 100644 --- a/app/src/androidTest/java/org/tasks/jobs/NotificationQueueTest.java +++ b/app/src/androidTest/java/org/tasks/jobs/NotificationQueueTest.java @@ -59,12 +59,15 @@ public class NotificationQueueTest { verify(jobManager).scheduleNotification(now); - Freeze.freezeAt(now).thawAfter(new Snippet() {{ - assertEquals( - newHashSet(new AlarmEntry(1, 1, now), - new ReminderEntry(1, now, TYPE_DUE)), - newHashSet(queue.getOverdueJobs())); - }}); + Freeze.freezeAt(now) + .thawAfter( + new Snippet() { + { + assertEquals( + newHashSet(new AlarmEntry(1, 1, now), new ReminderEntry(1, now, TYPE_DUE)), + newHashSet(queue.getOverdueJobs())); + } + }); } @Test @@ -78,11 +81,14 @@ public class NotificationQueueTest { queue.remove(singletonList(new AlarmEntry(1, 1, now))); - Freeze.freezeAt(now).thawAfter(new Snippet() {{ - assertEquals( - singletonList(new ReminderEntry(1, now, TYPE_DUE)), - queue.getOverdueJobs()); - }}); + Freeze.freezeAt(now) + .thawAfter( + new Snippet() { + { + assertEquals( + singletonList(new ReminderEntry(1, now, TYPE_DUE)), queue.getOverdueJobs()); + } + }); } @Test @@ -96,11 +102,13 @@ public class NotificationQueueTest { queue.remove(singletonList(new ReminderEntry(1, now, TYPE_DUE))); - Freeze.freezeAt(now).thawAfter(new Snippet() {{ - assertEquals( - singletonList(new AlarmEntry(1, 1, now)), - queue.getOverdueJobs()); - }}); + Freeze.freezeAt(now) + .thawAfter( + new Snippet() { + { + assertEquals(singletonList(new AlarmEntry(1, 1, now)), queue.getOverdueJobs()); + } + }); } @Test @@ -194,11 +202,14 @@ public class NotificationQueueTest { verify(jobManager).scheduleNotification(now); - Freeze.freezeAt(now).thawAfter(new Snippet() {{ - assertEquals( - singletonList(new ReminderEntry(1, now, TYPE_DUE)), - queue.getOverdueJobs()); - }}); + Freeze.freezeAt(now) + .thawAfter( + new Snippet() { + { + assertEquals( + singletonList(new ReminderEntry(1, now, TYPE_DUE)), queue.getOverdueJobs()); + } + }); } @Test @@ -210,11 +221,16 @@ public class NotificationQueueTest { verify(jobManager).scheduleNotification(now); - Freeze.freezeAt(now).thawAfter(new Snippet() {{ - assertEquals( - asList(new ReminderEntry(1, now, TYPE_DUE), new ReminderEntry(2, now, TYPE_DUE)), - queue.getOverdueJobs()); - }}); + Freeze.freezeAt(now) + .thawAfter( + new Snippet() { + { + assertEquals( + asList( + new ReminderEntry(1, now, TYPE_DUE), new ReminderEntry(2, now, TYPE_DUE)), + queue.getOverdueJobs()); + } + }); } @Test @@ -226,11 +242,17 @@ public class NotificationQueueTest { verify(jobManager).scheduleNotification(now); - Freeze.freezeAt(now + 2 * ONE_MINUTE).thawAfter(new Snippet() {{ - assertEquals( - asList(new ReminderEntry(1, now, TYPE_DUE), new ReminderEntry(2, now + ONE_MINUTE, TYPE_DUE)), - queue.getOverdueJobs()); - }}); + Freeze.freezeAt(now + 2 * ONE_MINUTE) + .thawAfter( + new Snippet() { + { + assertEquals( + asList( + new ReminderEntry(1, now, TYPE_DUE), + new ReminderEntry(2, now + ONE_MINUTE, TYPE_DUE)), + queue.getOverdueJobs()); + } + }); } @Test @@ -242,13 +264,15 @@ public class NotificationQueueTest { verify(jobManager).scheduleNotification(now); - Freeze.freezeAt(now).thawAfter(new Snippet() {{ - queue.remove(queue.getOverdueJobs()); - }}); + Freeze.freezeAt(now) + .thawAfter( + new Snippet() { + { + queue.remove(queue.getOverdueJobs()); + } + }); - assertEquals( - singletonList(new ReminderEntry(2, now + ONE_MINUTE, TYPE_DUE)), - queue.getJobs()); + assertEquals(singletonList(new ReminderEntry(2, now + ONE_MINUTE, TYPE_DUE)), queue.getJobs()); } @Test @@ -261,13 +285,16 @@ public class NotificationQueueTest { verify(jobManager).scheduleNotification(now); - Freeze.freezeAt(now + ONE_MINUTE).thawAfter(new Snippet() {{ - queue.remove(queue.getOverdueJobs()); - }}); + Freeze.freezeAt(now + ONE_MINUTE) + .thawAfter( + new Snippet() { + { + queue.remove(queue.getOverdueJobs()); + } + }); assertEquals( - singletonList(new ReminderEntry(3, now + 2 * ONE_MINUTE, TYPE_DUE)), - queue.getJobs()); + singletonList(new ReminderEntry(3, now + 2 * ONE_MINUTE, TYPE_DUE)), queue.getJobs()); } @Test @@ -304,16 +331,21 @@ public class NotificationQueueTest { verify(jobManager).scheduleNotification(due.getMillis()); - Freeze.freezeAt(now).thawAfter(new Snippet() {{ - List overdueJobs = queue.getOverdueJobs(); - assertEquals( - asList(new ReminderEntry(1, due.getMillis(), TYPE_DUE), - new ReminderEntry(2, snooze.getMillis(), TYPE_SNOOZE)), - overdueJobs); - queue.remove(overdueJobs); - assertEquals( - singletonList(new ReminderEntry(3, due.plusMinutes(1).getMillis(), TYPE_DUE)), - queue.getJobs()); - }}); + Freeze.freezeAt(now) + .thawAfter( + new Snippet() { + { + List overdueJobs = queue.getOverdueJobs(); + assertEquals( + asList( + new ReminderEntry(1, due.getMillis(), TYPE_DUE), + new ReminderEntry(2, snooze.getMillis(), TYPE_SNOOZE)), + overdueJobs); + queue.remove(overdueJobs); + assertEquals( + singletonList(new ReminderEntry(3, due.plusMinutes(1).getMillis(), TYPE_DUE)), + queue.getJobs()); + } + }); } } diff --git a/app/src/androidTest/java/org/tasks/makers/GtaskListMaker.java b/app/src/androidTest/java/org/tasks/makers/GtaskListMaker.java index d93724e40..8dcbedadd 100644 --- a/app/src/androidTest/java/org/tasks/makers/GtaskListMaker.java +++ b/app/src/androidTest/java/org/tasks/makers/GtaskListMaker.java @@ -11,20 +11,24 @@ import org.tasks.data.GoogleTaskList; public class GtaskListMaker { public static final Property ID = newProperty(); - private static final Property ORDER = newProperty(); public static final Property REMOTE_ID = newProperty(); public static final Property LAST_SYNC = newProperty(); public static final Property NAME = newProperty(); + private static final Property ORDER = newProperty(); private static final Property COLOR = newProperty(); - private static final Instantiator instantiator = lookup -> new GoogleTaskList() {{ - setDeleted(0L); - setId(lookup.valueOf(GtaskListMaker.ID, 0L)); - setRemoteId(lookup.valueOf(REMOTE_ID, "1")); - setTitle(lookup.valueOf(NAME, "Default")); - setRemoteOrder(lookup.valueOf(ORDER, 0)); - setLastSync(lookup.valueOf(LAST_SYNC, 0L)); - setColor(lookup.valueOf(COLOR, -1)); - }}; + private static final Instantiator instantiator = + lookup -> + new GoogleTaskList() { + { + setDeleted(0L); + setId(lookup.valueOf(GtaskListMaker.ID, 0L)); + setRemoteId(lookup.valueOf(REMOTE_ID, "1")); + setTitle(lookup.valueOf(NAME, "Default")); + setRemoteOrder(lookup.valueOf(ORDER, 0)); + setLastSync(lookup.valueOf(LAST_SYNC, 0L)); + setColor(lookup.valueOf(COLOR, -1)); + } + }; public static GoogleTaskList newGtaskList( PropertyValue... properties) { diff --git a/app/src/androidTest/java/org/tasks/makers/Maker.java b/app/src/androidTest/java/org/tasks/makers/Maker.java index 5b7d40dcf..bf3c99679 100644 --- a/app/src/androidTest/java/org/tasks/makers/Maker.java +++ b/app/src/androidTest/java/org/tasks/makers/Maker.java @@ -8,8 +8,8 @@ import com.natpryce.makeiteasy.PropertyValue; class Maker { @SuppressWarnings("unchecked") - public static T make(Instantiator instantiator, - PropertyValue... properties) { + public static T make( + Instantiator instantiator, PropertyValue... properties) { return com.natpryce.makeiteasy.MakeItEasy.make(a(instantiator, properties)); } } diff --git a/app/src/androidTest/java/org/tasks/makers/TaskMaker.java b/app/src/androidTest/java/org/tasks/makers/TaskMaker.java index 23f05f789..6e9f10e98 100644 --- a/app/src/androidTest/java/org/tasks/makers/TaskMaker.java +++ b/app/src/androidTest/java/org/tasks/makers/TaskMaker.java @@ -15,10 +15,8 @@ import org.tasks.time.DateTime; public class TaskMaker { public static final Property ID = newProperty(); - private static final Property TITLE = newProperty(); public static final Property DUE_DATE = newProperty(); public static final Property DUE_TIME = newProperty(); - private static final Property PRIORITY = newProperty(); public static final Property REMINDER_LAST = newProperty(); public static final Property RANDOM_REMINDER_PERIOD = newProperty(); public static final Property HIDE_TYPE = newProperty(); @@ -29,79 +27,82 @@ public class TaskMaker { public static final Property SNOOZE_TIME = newProperty(); public static final Property RRULE = newProperty(); public static final Property AFTER_COMPLETE = newProperty(); - private static final Instantiator instantiator = lookup -> { - Task task = new Task(); - - String title = lookup.valueOf(TITLE, (String) null); - if (!Strings.isNullOrEmpty(title)) { - task.setTitle(title); - } - - long id = lookup.valueOf(ID, Task.NO_ID); - if (id != Task.NO_ID) { - task.setId(id); - } - - int priority = lookup.valueOf(PRIORITY, -1); - if (priority >= 0) { - task.setImportance(priority); - } - - DateTime dueDate = lookup.valueOf(DUE_DATE, (DateTime) null); - if (dueDate != null) { - task.setDueDate(Task.createDueDate(Task.URGENCY_SPECIFIC_DAY, dueDate.getMillis())); - } - - DateTime dueTime = lookup.valueOf(DUE_TIME, (DateTime) null); - if (dueTime != null) { - task.setDueDate(Task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, dueTime.getMillis())); - } - - DateTime completionTime = lookup.valueOf(COMPLETION_TIME, (DateTime) null); - if (completionTime != null) { - task.setCompletionDate(completionTime.getMillis()); - } - - DateTime deletedTime = lookup.valueOf(DELETION_TIME, (DateTime) null); - if (deletedTime != null) { - task.setDeletionDate(deletedTime.getMillis()); - } - - DateTime snoozeTime = lookup.valueOf(SNOOZE_TIME, (DateTime) null); - if (snoozeTime != null) { - task.setReminderSnooze(snoozeTime.getMillis()); - } - - int hideType = lookup.valueOf(HIDE_TYPE, -1); - if (hideType >= 0) { - task.setHideUntil(task.createHideUntil(hideType, 0)); - } - - int reminderFlags = lookup.valueOf(REMINDERS, -1); - if (reminderFlags >= 0) { - task.setReminderFlags(reminderFlags); - } - - DateTime reminderLast = lookup.valueOf(REMINDER_LAST, (DateTime) null); - if (reminderLast != null) { - task.setReminderLast(reminderLast.getMillis()); - } - - long randomReminderPeriod = lookup.valueOf(RANDOM_REMINDER_PERIOD, 0L); - if (randomReminderPeriod > 0) { - task.setReminderPeriod(randomReminderPeriod); - } - - RRule rrule = lookup.valueOf(RRULE, (RRule) null); - if (rrule != null) { - task.setRecurrence(rrule, lookup.valueOf(AFTER_COMPLETE, false)); - } - - DateTime creationTime = lookup.valueOf(CREATION_TIME, newDateTime()); - task.setCreationDate(creationTime.getMillis()); - - return task; - }; + private static final Property TITLE = newProperty(); + private static final Property PRIORITY = newProperty(); + private static final Instantiator instantiator = + lookup -> { + Task task = new Task(); + + String title = lookup.valueOf(TITLE, (String) null); + if (!Strings.isNullOrEmpty(title)) { + task.setTitle(title); + } + + long id = lookup.valueOf(ID, Task.NO_ID); + if (id != Task.NO_ID) { + task.setId(id); + } + + int priority = lookup.valueOf(PRIORITY, -1); + if (priority >= 0) { + task.setImportance(priority); + } + + DateTime dueDate = lookup.valueOf(DUE_DATE, (DateTime) null); + if (dueDate != null) { + task.setDueDate(Task.createDueDate(Task.URGENCY_SPECIFIC_DAY, dueDate.getMillis())); + } + + DateTime dueTime = lookup.valueOf(DUE_TIME, (DateTime) null); + if (dueTime != null) { + task.setDueDate(Task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, dueTime.getMillis())); + } + + DateTime completionTime = lookup.valueOf(COMPLETION_TIME, (DateTime) null); + if (completionTime != null) { + task.setCompletionDate(completionTime.getMillis()); + } + + DateTime deletedTime = lookup.valueOf(DELETION_TIME, (DateTime) null); + if (deletedTime != null) { + task.setDeletionDate(deletedTime.getMillis()); + } + + DateTime snoozeTime = lookup.valueOf(SNOOZE_TIME, (DateTime) null); + if (snoozeTime != null) { + task.setReminderSnooze(snoozeTime.getMillis()); + } + + int hideType = lookup.valueOf(HIDE_TYPE, -1); + if (hideType >= 0) { + task.setHideUntil(task.createHideUntil(hideType, 0)); + } + + int reminderFlags = lookup.valueOf(REMINDERS, -1); + if (reminderFlags >= 0) { + task.setReminderFlags(reminderFlags); + } + + DateTime reminderLast = lookup.valueOf(REMINDER_LAST, (DateTime) null); + if (reminderLast != null) { + task.setReminderLast(reminderLast.getMillis()); + } + + long randomReminderPeriod = lookup.valueOf(RANDOM_REMINDER_PERIOD, 0L); + if (randomReminderPeriod > 0) { + task.setReminderPeriod(randomReminderPeriod); + } + + RRule rrule = lookup.valueOf(RRULE, (RRule) null); + if (rrule != null) { + task.setRecurrence(rrule, lookup.valueOf(AFTER_COMPLETE, false)); + } + + DateTime creationTime = lookup.valueOf(CREATION_TIME, newDateTime()); + task.setCreationDate(creationTime.getMillis()); + + return task; + }; @SafeVarargs public static Task newTask(PropertyValue... properties) { diff --git a/app/src/androidTest/java/org/tasks/preferences/PreferenceTests.java b/app/src/androidTest/java/org/tasks/preferences/PreferenceTests.java index 39741c2d4..6d2dcfa71 100644 --- a/app/src/androidTest/java/org/tasks/preferences/PreferenceTests.java +++ b/app/src/androidTest/java/org/tasks/preferences/PreferenceTests.java @@ -45,8 +45,8 @@ public class PreferenceTests { long dueDate = new DateTime(2015, 12, 29, 18, 0, 1).getMillis(); - assertEquals(new DateTime(2015, 12, 29, 19, 0).getMillis(), - preferences.adjustForQuietHours(dueDate)); + assertEquals( + new DateTime(2015, 12, 29, 19, 0).getMillis(), preferences.adjustForQuietHours(dueDate)); } @Test @@ -56,8 +56,8 @@ public class PreferenceTests { long dueDate = new DateTime(2015, 12, 29, 22, 0, 1).getMillis(); - assertEquals(new DateTime(2015, 12, 30, 10, 0).getMillis(), - preferences.adjustForQuietHours(dueDate)); + assertEquals( + new DateTime(2015, 12, 30, 10, 0).getMillis(), preferences.adjustForQuietHours(dueDate)); } @Test @@ -67,8 +67,8 @@ public class PreferenceTests { long dueDate = new DateTime(2015, 12, 29, 23, 30).getMillis(); - assertEquals(new DateTime(2015, 12, 30, 10, 0).getMillis(), - preferences.adjustForQuietHours(dueDate)); + assertEquals( + new DateTime(2015, 12, 30, 10, 0).getMillis(), preferences.adjustForQuietHours(dueDate)); } @Test @@ -78,8 +78,8 @@ public class PreferenceTests { long dueDate = new DateTime(2015, 12, 30, 7, 15).getMillis(); - assertEquals(new DateTime(2015, 12, 30, 10, 0).getMillis(), - preferences.adjustForQuietHours(dueDate)); + assertEquals( + new DateTime(2015, 12, 30, 10, 0).getMillis(), preferences.adjustForQuietHours(dueDate)); } @Test diff --git a/app/src/androidTest/java/org/tasks/repeats/RepeatRuleToStringTest.java b/app/src/androidTest/java/org/tasks/repeats/RepeatRuleToStringTest.java index 55d76b9b2..496fb1abe 100644 --- a/app/src/androidTest/java/org/tasks/repeats/RepeatRuleToStringTest.java +++ b/app/src/androidTest/java/org/tasks/repeats/RepeatRuleToStringTest.java @@ -25,19 +25,22 @@ public class RepeatRuleToStringTest { @Test public void weeklyByDay() { - assertEquals("Repeats weekly on Mon, Tue, Wed, Thu, Fri", + assertEquals( + "Repeats weekly on Mon, Tue, Wed, Thu, Fri", toString("RRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY=MO,TU,WE,TH,FR")); } @Test public void printDaysInRepeatRuleOrder() { - assertEquals("Repeats weekly on Fri, Thu, Wed, Tue, Mon", + assertEquals( + "Repeats weekly on Fri, Thu, Wed, Tue, Mon", toString("RRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY=FR,TH,WE,TU,MO")); } @Test public void useLocaleForDays() { - assertEquals("Wiederhole wöchentlich am Sa., So.", + assertEquals( + "Wiederhole wöchentlich am Sa., So.", toString("de", "RRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY=SA,SU")); } diff --git a/app/src/androidTest/java/org/tasks/time/DateTimeTest.java b/app/src/androidTest/java/org/tasks/time/DateTimeTest.java index 623a5c704..48e8c78bc 100644 --- a/app/src/androidTest/java/org/tasks/time/DateTimeTest.java +++ b/app/src/androidTest/java/org/tasks/time/DateTimeTest.java @@ -32,8 +32,10 @@ public class DateTimeTest { TimeZone def = TimeZone.getDefault(); try { TimeZone.setDefault(TimeZone.getTimeZone("America/Chicago")); - assertEquals(2, - new DateTime(2015, 10, 31, 2, 0, 0).withMillisOfDay((int) TimeUnit.HOURS.toMillis(2)) + assertEquals( + 2, + new DateTime(2015, 10, 31, 2, 0, 0) + .withMillisOfDay((int) TimeUnit.HOURS.toMillis(2)) .getHourOfDay()); } finally { TimeZone.setDefault(def); @@ -45,8 +47,10 @@ public class DateTimeTest { TimeZone def = TimeZone.getDefault(); try { TimeZone.setDefault(TimeZone.getTimeZone("America/Chicago")); - assertEquals(2, - new DateTime(2015, 11, 2, 2, 0, 0).withMillisOfDay((int) TimeUnit.HOURS.toMillis(2)) + assertEquals( + 2, + new DateTime(2015, 11, 2, 2, 0, 0) + .withMillisOfDay((int) TimeUnit.HOURS.toMillis(2)) .getHourOfDay()); } finally { TimeZone.setDefault(def); @@ -58,23 +62,33 @@ public class DateTimeTest { TimeZone def = TimeZone.getDefault(); try { TimeZone.setDefault(TimeZone.getTimeZone("America/Chicago")); - assertEquals(1, - new DateTime(2015, 3, 8, 0, 0, 0).withMillisOfDay((int) TimeUnit.HOURS.toMillis(1)) + assertEquals( + 1, + new DateTime(2015, 3, 8, 0, 0, 0) + .withMillisOfDay((int) TimeUnit.HOURS.toMillis(1)) .getHourOfDay()); - assertEquals(3, - new DateTime(2015, 3, 8, 0, 0, 0).withMillisOfDay((int) TimeUnit.HOURS.toMillis(2)) + assertEquals( + 3, + new DateTime(2015, 3, 8, 0, 0, 0) + .withMillisOfDay((int) TimeUnit.HOURS.toMillis(2)) .getHourOfDay()); - assertEquals(3, - new DateTime(2015, 3, 8, 0, 0, 0).withMillisOfDay((int) TimeUnit.HOURS.toMillis(3)) + assertEquals( + 3, + new DateTime(2015, 3, 8, 0, 0, 0) + .withMillisOfDay((int) TimeUnit.HOURS.toMillis(3)) .getHourOfDay()); - assertEquals(4, - new DateTime(2015, 3, 8, 0, 0, 0).withMillisOfDay((int) TimeUnit.HOURS.toMillis(4)) + assertEquals( + 4, + new DateTime(2015, 3, 8, 0, 0, 0) + .withMillisOfDay((int) TimeUnit.HOURS.toMillis(4)) .getHourOfDay()); assertEquals( - new DateTime(2015, 3, 8, 0, 0, 0).withMillisOfDay((int) TimeUnit.HOURS.toMillis(2)) + new DateTime(2015, 3, 8, 0, 0, 0) + .withMillisOfDay((int) TimeUnit.HOURS.toMillis(2)) .getMillis(), - new DateTime(2015, 3, 8, 0, 0, 0).withMillisOfDay((int) TimeUnit.HOURS.toMillis(3)) + new DateTime(2015, 3, 8, 0, 0, 0) + .withMillisOfDay((int) TimeUnit.HOURS.toMillis(3)) .getMillis()); } finally { TimeZone.setDefault(def); @@ -86,14 +100,20 @@ public class DateTimeTest { TimeZone def = TimeZone.getDefault(); try { TimeZone.setDefault(TimeZone.getTimeZone("America/Chicago")); - assertEquals(1, - new DateTime(2015, 11, 1, 0, 0, 0).withMillisOfDay((int) TimeUnit.HOURS.toMillis(1)) + assertEquals( + 1, + new DateTime(2015, 11, 1, 0, 0, 0) + .withMillisOfDay((int) TimeUnit.HOURS.toMillis(1)) .getHourOfDay()); - assertEquals(2, - new DateTime(2015, 11, 1, 0, 0, 0).withMillisOfDay((int) TimeUnit.HOURS.toMillis(2)) + assertEquals( + 2, + new DateTime(2015, 11, 1, 0, 0, 0) + .withMillisOfDay((int) TimeUnit.HOURS.toMillis(2)) .getHourOfDay()); - assertEquals(3, - new DateTime(2015, 11, 1, 0, 0, 0).withMillisOfDay((int) TimeUnit.HOURS.toMillis(3)) + assertEquals( + 3, + new DateTime(2015, 11, 1, 0, 0, 0) + .withMillisOfDay((int) TimeUnit.HOURS.toMillis(3)) .getHourOfDay()); } finally { TimeZone.setDefault(def); @@ -196,8 +216,7 @@ public class DateTimeTest { @Test public void testWithHourOfDay() { assertEquals( - new DateTime(2015, 11, 6, 23, 0, 0), - new DateTime(2015, 11, 6, 1, 0, 0).withHourOfDay(23)); + new DateTime(2015, 11, 6, 23, 0, 0), new DateTime(2015, 11, 6, 1, 0, 0).withHourOfDay(23)); } @Test @@ -222,17 +241,15 @@ public class DateTimeTest { @Test public void testMinusMinutes() { assertEquals( - new DateTime(2015, 11, 4, 23, 59, 0), - new DateTime(2015, 11, 5, 0, 1, 0).minusMinutes(2)); + new DateTime(2015, 11, 4, 23, 59, 0), new DateTime(2015, 11, 5, 0, 1, 0).minusMinutes(2)); } @Test public void testIsBefore() { - assertTrue(new DateTime(2015, 11, 4, 23, 59, 0) - .isBefore(new DateTime(2015, 11, 4, 23, 59, 1))); + assertTrue(new DateTime(2015, 11, 4, 23, 59, 0).isBefore(new DateTime(2015, 11, 4, 23, 59, 1))); - assertFalse(new DateTime(2015, 11, 4, 23, 59, 0) - .isBefore(new DateTime(2015, 11, 4, 23, 59, 0))); + assertFalse( + new DateTime(2015, 11, 4, 23, 59, 0).isBefore(new DateTime(2015, 11, 4, 23, 59, 0))); } @Test @@ -242,25 +259,21 @@ public class DateTimeTest { @Test public void testIsAfter() { - assertTrue(new DateTime(2015, 11, 4, 23, 59, 1) - .isAfter(new DateTime(2015, 11, 4, 23, 59, 0))); + assertTrue(new DateTime(2015, 11, 4, 23, 59, 1).isAfter(new DateTime(2015, 11, 4, 23, 59, 0))); - assertFalse(new DateTime(2015, 11, 4, 23, 59, 0) - .isAfter(new DateTime(2015, 11, 4, 23, 59, 0))); + assertFalse(new DateTime(2015, 11, 4, 23, 59, 0).isAfter(new DateTime(2015, 11, 4, 23, 59, 0))); } @Test public void testWithYear() { assertEquals( - new DateTime(2016, 1, 1, 1, 1, 1), - new DateTime(2015, 1, 1, 1, 1, 1).withYear(2016)); + new DateTime(2016, 1, 1, 1, 1, 1), new DateTime(2015, 1, 1, 1, 1, 1).withYear(2016)); } @Test public void testWithMonthOfYear() { assertEquals( - new DateTime(2015, 1, 2, 3, 4, 5), - new DateTime(2015, 2, 2, 3, 4, 5).withMonthOfYear(1)); + new DateTime(2015, 1, 2, 3, 4, 5), new DateTime(2015, 2, 2, 3, 4, 5).withMonthOfYear(1)); } @Test @@ -271,37 +284,37 @@ public class DateTimeTest { @Test public void testWithDayOfMonth() { assertEquals( - new DateTime(2015, 1, 2, 3, 4, 5), - new DateTime(2015, 1, 1, 3, 4, 5).withDayOfMonth(2)); + new DateTime(2015, 1, 2, 3, 4, 5), new DateTime(2015, 1, 1, 3, 4, 5).withDayOfMonth(2)); } @Test public void testPlusMinutes() { assertEquals( - new DateTime(2015, 1, 2, 3, 4, 5), - new DateTime(2015, 1, 2, 2, 59, 5).plusMinutes(5)); + new DateTime(2015, 1, 2, 3, 4, 5), new DateTime(2015, 1, 2, 2, 59, 5).plusMinutes(5)); } @Test public void testPlusHours() { assertEquals( - new DateTime(2015, 1, 2, 3, 4, 5), - new DateTime(2015, 1, 1, 3, 4, 5).plusHours(24)); + new DateTime(2015, 1, 2, 3, 4, 5), new DateTime(2015, 1, 1, 3, 4, 5).plusHours(24)); } @Test public void testPlusWeeks() { assertEquals( - new DateTime(2015, 1, 2, 3, 4, 5), - new DateTime(2014, 12, 12, 3, 4, 5).plusWeeks(3)); + new DateTime(2015, 1, 2, 3, 4, 5), new DateTime(2014, 12, 12, 3, 4, 5).plusWeeks(3)); } @Test public void testIsBeforeNow() { - Freeze.freezeAt(new DateTime(2015, 10, 6, 16, 15, 27)).thawAfter(new Snippet() {{ - assertFalse(new DateTime(2015, 10, 6, 16, 15, 27).isBeforeNow()); - assertTrue(new DateTime(2015, 10, 6, 16, 15, 26).isBeforeNow()); - }}); + Freeze.freezeAt(new DateTime(2015, 10, 6, 16, 15, 27)) + .thawAfter( + new Snippet() { + { + assertFalse(new DateTime(2015, 10, 6, 16, 15, 27).isBeforeNow()); + assertTrue(new DateTime(2015, 10, 6, 16, 15, 26).isBeforeNow()); + } + }); } @Test @@ -314,12 +327,10 @@ public class DateTimeTest { @Test public void testMinusDays() { assertEquals( - new DateTime(2015, 11, 6, 16, 19, 16), - new DateTime(2015, 12, 4, 16, 19, 16).minusDays(28)); + new DateTime(2015, 11, 6, 16, 19, 16), new DateTime(2015, 12, 4, 16, 19, 16).minusDays(28)); assertEquals( - new DateTime(2015, 11, 6, 16, 19, 16), - new DateTime(2015, 11, 7, 16, 19, 16).minusDays(1)); + new DateTime(2015, 11, 6, 16, 19, 16), new DateTime(2015, 11, 7, 16, 19, 16).minusDays(1)); } @Test diff --git a/app/src/androidTestGoogleplay/java/com/todoroo/astrid/gtasks/GtasksIndentActionTest.java b/app/src/androidTestGoogleplay/java/com/todoroo/astrid/gtasks/GtasksIndentActionTest.java index 57b799280..ee278288a 100644 --- a/app/src/androidTestGoogleplay/java/com/todoroo/astrid/gtasks/GtasksIndentActionTest.java +++ b/app/src/androidTestGoogleplay/java/com/todoroo/astrid/gtasks/GtasksIndentActionTest.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.gtasks; import static junit.framework.Assert.assertNotNull; @@ -188,8 +187,7 @@ public class GtasksIndentActionTest extends InjectingTestCase { GoogleTask metadata = googleTaskDao.getByTaskId(targetTask.getId()); assertNotNull("task has metadata", metadata); int indentation = metadata.getIndent(); - assertTrue("indentation: " + indentation, - indentation == expected); + assertTrue("indentation: " + indentation, indentation == expected); } private void givenTask(Task taskToTest) { diff --git a/app/src/androidTestGoogleplay/java/com/todoroo/astrid/gtasks/GtasksListServiceTest.java b/app/src/androidTestGoogleplay/java/com/todoroo/astrid/gtasks/GtasksListServiceTest.java index 0c3d32351..73059a9a5 100644 --- a/app/src/androidTestGoogleplay/java/com/todoroo/astrid/gtasks/GtasksListServiceTest.java +++ b/app/src/androidTestGoogleplay/java/com/todoroo/astrid/gtasks/GtasksListServiceTest.java @@ -43,8 +43,9 @@ public class GtasksListServiceTest extends InjectingTestCase { @Override public void setUp() { super.setUp(); - gtasksListService = new GtasksListService(googleTaskListDao, taskDeleter, - localBroadcastManager, googleTaskDao, taskDao); + gtasksListService = + new GtasksListService( + googleTaskListDao, taskDeleter, localBroadcastManager, googleTaskDao, taskDao); } @Override @@ -54,15 +55,12 @@ public class GtasksListServiceTest extends InjectingTestCase { @Test public void testCreateNewList() { - setLists(newRemoteList( - with(RemoteGtaskListMaker.REMOTE_ID, "1"), - with(RemoteGtaskListMaker.NAME, "Default"))); + setLists( + newRemoteList( + with(RemoteGtaskListMaker.REMOTE_ID, "1"), with(RemoteGtaskListMaker.NAME, "Default"))); assertEquals( - newGtaskList( - with(ID, 1L), - with(REMOTE_ID, "1"), - with(NAME, "Default")), + newGtaskList(with(ID, 1L), with(REMOTE_ID, "1"), with(NAME, "Default")), googleTaskListDao.getById(1L)); } @@ -87,20 +85,19 @@ public class GtasksListServiceTest extends InjectingTestCase { setLists(taskList); - assertEquals(singletonList(newGtaskList(with(ID, 2L), with(REMOTE_ID, "2"))), + assertEquals( + singletonList(newGtaskList(with(ID, 2L), with(REMOTE_ID, "2"))), googleTaskListDao.getActiveLists()); } @Test public void testUpdateListName() { - googleTaskListDao.insertOrReplace(newGtaskList( - with(ID, 1L), - with(REMOTE_ID, "1"), - with(NAME, "oldName"))); + googleTaskListDao.insertOrReplace( + newGtaskList(with(ID, 1L), with(REMOTE_ID, "1"), with(NAME, "oldName"))); - setLists(newRemoteList( - with(RemoteGtaskListMaker.REMOTE_ID, "1"), - with(RemoteGtaskListMaker.NAME, "newName"))); + setLists( + newRemoteList( + with(RemoteGtaskListMaker.REMOTE_ID, "1"), with(RemoteGtaskListMaker.NAME, "newName"))); assertEquals("newName", googleTaskListDao.getById(1).getTitle()); } @@ -114,8 +111,8 @@ public class GtasksListServiceTest extends InjectingTestCase { @Test public void testNewListNeedsUpdate() { - TaskList taskList = new TaskList().setId("1").setTitle("Default") - .setUpdated(new DateTime(currentTimeMillis())); + TaskList taskList = + new TaskList().setId("1").setTitle("Default").setUpdated(new DateTime(currentTimeMillis())); setLists(taskList); diff --git a/app/src/androidTestGoogleplay/java/com/todoroo/astrid/gtasks/GtasksMetadataServiceTest.java b/app/src/androidTestGoogleplay/java/com/todoroo/astrid/gtasks/GtasksMetadataServiceTest.java index f1ad352bc..40f70537a 100644 --- a/app/src/androidTestGoogleplay/java/com/todoroo/astrid/gtasks/GtasksMetadataServiceTest.java +++ b/app/src/androidTestGoogleplay/java/com/todoroo/astrid/gtasks/GtasksMetadataServiceTest.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.gtasks; import static android.support.test.InstrumentationRegistry.getTargetContext; @@ -37,9 +36,7 @@ public class GtasksMetadataServiceTest extends InjectingTestCase { @Override protected void inject(TestComponent component) { - component - .plus(new GtasksMetadataServiceTestModule(getTargetContext())) - .inject(this); + component.plus(new GtasksMetadataServiceTestModule(getTargetContext())).inject(this); } @Test diff --git a/app/src/androidTestGoogleplay/java/com/todoroo/astrid/gtasks/GtasksTaskListUpdaterTest.java b/app/src/androidTestGoogleplay/java/com/todoroo/astrid/gtasks/GtasksTaskListUpdaterTest.java index 8ed0f1169..ea7cb32ef 100644 --- a/app/src/androidTestGoogleplay/java/com/todoroo/astrid/gtasks/GtasksTaskListUpdaterTest.java +++ b/app/src/androidTestGoogleplay/java/com/todoroo/astrid/gtasks/GtasksTaskListUpdaterTest.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.gtasks; import static junit.framework.Assert.assertEquals; @@ -110,8 +109,10 @@ public class GtasksTaskListUpdaterTest extends InjectingTestCase { if (expectedParent == null) { assertEquals("Task " + task.getTitle() + " parent none", 0, parent); } else { - assertEquals("Task " + task.getTitle() + " parent " + - expectedParent.getTitle(), expectedParent.getId(), parent); + assertEquals( + "Task " + task.getTitle() + " parent " + expectedParent.getTitle(), + expectedParent.getId(), + parent); } } @@ -120,8 +121,10 @@ public class GtasksTaskListUpdaterTest extends InjectingTestCase { if (expectedSibling == null) { assertEquals("Task " + task.getTitle() + " sibling null", 0L, sibling); } else { - assertEquals("Task " + task.getTitle() + " sibling " + - expectedSibling.getTitle(), expectedSibling.getId(), sibling); + assertEquals( + "Task " + task.getTitle() + " sibling " + expectedSibling.getTitle(), + expectedSibling.getId(), + sibling); } } @@ -130,8 +133,10 @@ public class GtasksTaskListUpdaterTest extends InjectingTestCase { if (expectedParent == null) { assertEquals("Task " + task.getTitle() + " parent null", 0L, parent); } else { - assertEquals("Task " + task.getTitle() + " parent " + - expectedParent.getTitle(), expectedParent.getId(), parent); + assertEquals( + "Task " + task.getTitle() + " parent " + expectedParent.getTitle(), + expectedParent.getId(), + parent); } } @@ -162,24 +167,21 @@ public class GtasksTaskListUpdaterTest extends InjectingTestCase { } } - /** - * A - * B - * C - * D - * E - */ + // A + // B + // C + // D + // E private Task[] givenTasksABCDE() { - return new Task[]{ - createTask("A", 0, 0), - createTask("B", 1, 1), - createTask("C", 2, 1), - createTask("D", 3, 2), - createTask("E", 4, 0), + return new Task[] { + createTask("A", 0, 0), + createTask("B", 1, 1), + createTask("C", 2, 1), + createTask("D", 3, 2), + createTask("E", 4, 0), }; } - private Task createTask(String title, long order, int indent) { Task task = new Task(); task.setTitle(title); diff --git a/app/src/androidTestGoogleplay/java/com/todoroo/astrid/gtasks/GtasksTaskMovingTest.java b/app/src/androidTestGoogleplay/java/com/todoroo/astrid/gtasks/GtasksTaskMovingTest.java index dc14a5545..ef6328a86 100644 --- a/app/src/androidTestGoogleplay/java/com/todoroo/astrid/gtasks/GtasksTaskMovingTest.java +++ b/app/src/androidTestGoogleplay/java/com/todoroo/astrid/gtasks/GtasksTaskMovingTest.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.gtasks; import static junit.framework.Assert.assertEquals; @@ -245,9 +244,7 @@ public class GtasksTaskMovingTest extends InjectingTestCase { // --- helpers - /** - * moveTo = null => move to end - */ + /** moveTo = null => move to end */ private void whenTriggerMove(Task target, Task moveTo) { gtasksTaskListUpdater.moveTo(list, target.getId(), moveTo == null ? -1 : moveTo.getId()); } @@ -278,14 +275,12 @@ public class GtasksTaskMovingTest extends InjectingTestCase { component.inject(this); } - /** - * A - * B - * C - * D - * E - * F - */ + // A + // B + // C + // D + // E + // F private void givenTasksABCDEF() { A = createTask("A", 0, 0); B = createTask("B", 1, 1); diff --git a/app/src/androidTestGoogleplay/java/com/todoroo/astrid/gtasks/GtasksTestPreferenceService.java b/app/src/androidTestGoogleplay/java/com/todoroo/astrid/gtasks/GtasksTestPreferenceService.java index e722fe390..57fdf4199 100644 --- a/app/src/androidTestGoogleplay/java/com/todoroo/astrid/gtasks/GtasksTestPreferenceService.java +++ b/app/src/androidTestGoogleplay/java/com/todoroo/astrid/gtasks/GtasksTestPreferenceService.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.gtasks; import org.tasks.preferences.Preferences; diff --git a/app/src/androidTestGoogleplay/java/com/todoroo/astrid/gtasks/api/GtasksApiUtilitiesTest.java b/app/src/androidTestGoogleplay/java/com/todoroo/astrid/gtasks/api/GtasksApiUtilitiesTest.java index 5a87fc8ff..1159e9570 100644 --- a/app/src/androidTestGoogleplay/java/com/todoroo/astrid/gtasks/api/GtasksApiUtilitiesTest.java +++ b/app/src/androidTestGoogleplay/java/com/todoroo/astrid/gtasks/api/GtasksApiUtilitiesTest.java @@ -65,8 +65,7 @@ public class GtasksApiUtilitiesTest { TimeZone.getTimeZone("GMT")); assertEquals( - new DateTime(2014, 1, 8, 6, 0, 0, 0).getMillis(), - gtasksDueTimeToUnixTime(googleDueDate)); + new DateTime(2014, 1, 8, 6, 0, 0, 0).getMillis(), gtasksDueTimeToUnixTime(googleDueDate)); } @Test diff --git a/app/src/androidTestGoogleplay/java/org/tasks/gtasks/GoogleTaskSynchronizerTest.java b/app/src/androidTestGoogleplay/java/org/tasks/gtasks/GoogleTaskSynchronizerTest.java index a49896270..e596e8644 100644 --- a/app/src/androidTestGoogleplay/java/org/tasks/gtasks/GoogleTaskSynchronizerTest.java +++ b/app/src/androidTestGoogleplay/java/org/tasks/gtasks/GoogleTaskSynchronizerTest.java @@ -25,9 +25,7 @@ public class GoogleTaskSynchronizerTest { mergeDates(newTask(with(DUE_DATE, new DateTime(2016, 3, 11))).getDueDate(), local); - assertEquals( - new DateTime(2016, 3, 11, 12, 0).getMillis(), - local.getDueDate().longValue()); + assertEquals(new DateTime(2016, 3, 11, 12, 0).getMillis(), local.getDueDate().longValue()); } @Test @@ -36,63 +34,59 @@ public class GoogleTaskSynchronizerTest { mergeDates(newTask(with(DUE_DATE, new DateTime(2016, 3, 11))).getDueDate(), local); - assertEquals( - new DateTime(2016, 3, 11, 13, 30, 1).getMillis(), - local.getDueDate().longValue()); + assertEquals(new DateTime(2016, 3, 11, 13, 30, 1).getMillis(), local.getDueDate().longValue()); } @Test public void testDueDateAdjustHideBackwards() { - Task local = newTask(with(DUE_DATE, new DateTime(2016, 3, 12)), - with(HIDE_TYPE, HIDE_UNTIL_DUE)); + Task local = + newTask(with(DUE_DATE, new DateTime(2016, 3, 12)), with(HIDE_TYPE, HIDE_UNTIL_DUE)); mergeDates(newTask(with(DUE_DATE, new DateTime(2016, 3, 11))).getDueDate(), local); - assertEquals( - new DateTime(2016, 3, 11).getMillis(), - local.getHideUntil().longValue()); + assertEquals(new DateTime(2016, 3, 11).getMillis(), local.getHideUntil().longValue()); } @Test public void testDueDateAdjustHideForwards() { - Task local = newTask(with(DUE_DATE, new DateTime(2016, 3, 12)), - with(HIDE_TYPE, HIDE_UNTIL_DUE)); + Task local = + newTask(with(DUE_DATE, new DateTime(2016, 3, 12)), with(HIDE_TYPE, HIDE_UNTIL_DUE)); mergeDates(newTask(with(DUE_DATE, new DateTime(2016, 3, 14))).getDueDate(), local); - assertEquals( - new DateTime(2016, 3, 14).getMillis(), - local.getHideUntil().longValue()); + assertEquals(new DateTime(2016, 3, 14).getMillis(), local.getHideUntil().longValue()); } @Test public void testDueTimeAdjustHideBackwards() { - Task local = newTask(with(DUE_TIME, new DateTime(2016, 3, 12, 13, 30)), - with(HIDE_TYPE, HIDE_UNTIL_DUE_TIME)); + Task local = + newTask( + with(DUE_TIME, new DateTime(2016, 3, 12, 13, 30)), + with(HIDE_TYPE, HIDE_UNTIL_DUE_TIME)); mergeDates(newTask(with(DUE_DATE, new DateTime(2016, 3, 11))).getDueDate(), local); assertEquals( - new DateTime(2016, 3, 11, 13, 30, 1).getMillis(), - local.getHideUntil().longValue()); + new DateTime(2016, 3, 11, 13, 30, 1).getMillis(), local.getHideUntil().longValue()); } @Test public void testDueTimeAdjustTimeForwards() { - Task local = newTask(with(DUE_TIME, new DateTime(2016, 3, 12, 13, 30)), - with(HIDE_TYPE, HIDE_UNTIL_DUE_TIME)); + Task local = + newTask( + with(DUE_TIME, new DateTime(2016, 3, 12, 13, 30)), + with(HIDE_TYPE, HIDE_UNTIL_DUE_TIME)); mergeDates(newTask(with(DUE_DATE, new DateTime(2016, 3, 14))).getDueDate(), local); assertEquals( - new DateTime(2016, 3, 14, 13, 30, 1).getMillis(), - local.getHideUntil().longValue()); + new DateTime(2016, 3, 14, 13, 30, 1).getMillis(), local.getHideUntil().longValue()); } @Test public void testDueDateClearHide() { - Task local = newTask(with(DUE_DATE, new DateTime(2016, 3, 12)), - with(HIDE_TYPE, HIDE_UNTIL_DUE)); + Task local = + newTask(with(DUE_DATE, new DateTime(2016, 3, 12)), with(HIDE_TYPE, HIDE_UNTIL_DUE)); mergeDates(newTask().getDueDate(), local); @@ -101,8 +95,10 @@ public class GoogleTaskSynchronizerTest { @Test public void testDueTimeClearHide() { - Task local = newTask(with(DUE_TIME, new DateTime(2016, 3, 12, 13, 30)), - with(HIDE_TYPE, HIDE_UNTIL_DUE_TIME)); + Task local = + newTask( + with(DUE_TIME, new DateTime(2016, 3, 12, 13, 30)), + with(HIDE_TYPE, HIDE_UNTIL_DUE_TIME)); mergeDates(newTask().getDueDate(), local); diff --git a/app/src/androidTestGoogleplay/java/org/tasks/makers/RemoteGtaskListMaker.java b/app/src/androidTestGoogleplay/java/org/tasks/makers/RemoteGtaskListMaker.java index 546c61aa7..160728362 100644 --- a/app/src/androidTestGoogleplay/java/org/tasks/makers/RemoteGtaskListMaker.java +++ b/app/src/androidTestGoogleplay/java/org/tasks/makers/RemoteGtaskListMaker.java @@ -14,10 +14,12 @@ public class RemoteGtaskListMaker { public static final Property REMOTE_ID = newProperty(); public static final Property NAME = newProperty(); - private static final Instantiator instantiator = lookup -> new TaskList() - .setId(lookup.valueOf(REMOTE_ID, "1")) - .setTitle(lookup.valueOf(NAME, "Default")) - .setUpdated(new DateTime(currentTimeMillis())); + private static final Instantiator instantiator = + lookup -> + new TaskList() + .setId(lookup.valueOf(REMOTE_ID, "1")) + .setTitle(lookup.valueOf(NAME, "Default")) + .setUpdated(new DateTime(currentTimeMillis())); public static TaskList newRemoteList(PropertyValue... properties) { return make(instantiator, properties); diff --git a/app/src/debug/java/org/tasks/BaseApplication.java b/app/src/debug/java/org/tasks/BaseApplication.java index 8ab740bac..653a14b7d 100644 --- a/app/src/debug/java/org/tasks/BaseApplication.java +++ b/app/src/debug/java/org/tasks/BaseApplication.java @@ -2,6 +2,4 @@ package org.tasks; import android.support.multidex.MultiDexApplication; -public abstract class BaseApplication extends MultiDexApplication { - -} +public abstract class BaseApplication extends MultiDexApplication {} diff --git a/app/src/debug/java/org/tasks/BuildSetup.java b/app/src/debug/java/org/tasks/BuildSetup.java index 142232fb8..c695584a7 100644 --- a/app/src/debug/java/org/tasks/BuildSetup.java +++ b/app/src/debug/java/org/tasks/BuildSetup.java @@ -32,17 +32,19 @@ public class BuildSetup { } LeakCanary.install(application); if (preferences.getBoolean(R.string.p_strict_mode, false)) { - StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() - .detectDiskReads() - .detectDiskWrites() - .detectNetwork() - .penaltyLog() - .build()); - StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() - .detectLeakedSqlLiteObjects() - .detectLeakedClosableObjects() - .penaltyLog() - .build()); + StrictMode.setThreadPolicy( + new StrictMode.ThreadPolicy.Builder() + .detectDiskReads() + .detectDiskWrites() + .detectNetwork() + .penaltyLog() + .build()); + StrictMode.setVmPolicy( + new StrictMode.VmPolicy.Builder() + .detectLeakedSqlLiteObjects() + .detectLeakedClosableObjects() + .penaltyLog() + .build()); } return true; } diff --git a/app/src/generic/java/org/tasks/FlavorSetup.java b/app/src/generic/java/org/tasks/FlavorSetup.java index 08cc80bdd..c610bb8d9 100644 --- a/app/src/generic/java/org/tasks/FlavorSetup.java +++ b/app/src/generic/java/org/tasks/FlavorSetup.java @@ -5,9 +5,7 @@ import javax.inject.Inject; public class FlavorSetup { @Inject - public FlavorSetup() { - } + public FlavorSetup() {} - public void setup() { - } + public void setup() {} } diff --git a/app/src/generic/java/org/tasks/analytics/Tracker.java b/app/src/generic/java/org/tasks/analytics/Tracker.java index b73df922d..1ea511d90 100644 --- a/app/src/generic/java/org/tasks/analytics/Tracker.java +++ b/app/src/generic/java/org/tasks/analytics/Tracker.java @@ -6,13 +6,9 @@ import timber.log.Timber; public class Tracker { @Inject - public Tracker() { + public Tracker() {} - } - - public void setTrackingEnabled(boolean enabled) { - - } + public void setTrackingEnabled(boolean enabled) {} public void reportException(Throwable t) { Timber.e(t, t.getMessage()); @@ -22,19 +18,11 @@ public class Tracker { Timber.e(t, t.getMessage()); } - public void reportEvent(Tracking.Events event) { - - } - - public void reportEvent(Tracking.Events event, String string) { - - } - - public void reportEvent(Tracking.Events setPreference, int resId, String s) { + public void reportEvent(Tracking.Events event) {} - } + public void reportEvent(Tracking.Events event, String string) {} - public void reportEvent(Tracking.Events category, String action, String label) { + public void reportEvent(Tracking.Events setPreference, int resId, String s) {} - } + public void reportEvent(Tracking.Events category, String action, String label) {} } diff --git a/app/src/generic/java/org/tasks/billing/PurchaseHelper.java b/app/src/generic/java/org/tasks/billing/PurchaseHelper.java index e8648d04a..c5413d577 100644 --- a/app/src/generic/java/org/tasks/billing/PurchaseHelper.java +++ b/app/src/generic/java/org/tasks/billing/PurchaseHelper.java @@ -14,24 +14,21 @@ public class PurchaseHelper { this.preferences = preferences; } - public boolean purchase(final Activity activity, - final String sku, final String pref, - final int requestCode, final PurchaseHelperCallback callback) { + public boolean purchase( + final Activity activity, + final String sku, + final String pref, + final int requestCode, + final PurchaseHelperCallback callback) { preferences.setBoolean(pref, true); callback.purchaseCompleted(true, sku); return true; } - public void handleActivityResult(PurchaseHelperCallback callback, int requestCode, int resultCode, - Intent data) { + public void handleActivityResult( + PurchaseHelperCallback callback, int requestCode, int resultCode, Intent data) {} - } - - public void disposeIabHelper() { - - } - - public void consumePurchases() { + public void disposeIabHelper() {} - } + public void consumePurchases() {} } diff --git a/app/src/generic/java/org/tasks/gtasks/PlayServices.java b/app/src/generic/java/org/tasks/gtasks/PlayServices.java index 64ea8bd8d..7c2cfbc93 100644 --- a/app/src/generic/java/org/tasks/gtasks/PlayServices.java +++ b/app/src/generic/java/org/tasks/gtasks/PlayServices.java @@ -8,9 +8,7 @@ import javax.inject.Inject; public class PlayServices { @Inject - public PlayServices() { - - } + public PlayServices() {} public boolean isPlayServicesAvailable() { return false; @@ -20,9 +18,7 @@ public class PlayServices { return false; } - public void resolve(Activity activity) { - - } + public void resolve(Activity activity) {} public String getStatus() { return null; @@ -32,8 +28,8 @@ public class PlayServices { return false; } - public void getAuthToken(GtasksLoginActivity gtasksLoginActivity, String a, - GtasksLoginActivity.AuthResultHandler authResultHandler) { - - } + public void getAuthToken( + GtasksLoginActivity gtasksLoginActivity, + String a, + GtasksLoginActivity.AuthResultHandler authResultHandler) {} } diff --git a/app/src/generic/java/org/tasks/location/GeofenceApi.java b/app/src/generic/java/org/tasks/location/GeofenceApi.java index 09f51e547..e77a061a1 100644 --- a/app/src/generic/java/org/tasks/location/GeofenceApi.java +++ b/app/src/generic/java/org/tasks/location/GeofenceApi.java @@ -8,19 +8,11 @@ import org.tasks.data.Location; public class GeofenceApi { @Inject - public GeofenceApi() { + public GeofenceApi() {} - } + public void register(List activeGeofences) {} - public void register(List activeGeofences) { + public void cancel(Location geofence) {} - } - - public void cancel(Location geofence) { - - } - - public void cancel(List geofences) { - - } + public void cancel(List geofences) {} } diff --git a/app/src/generic/java/org/tasks/location/GeofenceTransitionsIntentService.java b/app/src/generic/java/org/tasks/location/GeofenceTransitionsIntentService.java index 508a57af7..b8a779793 100644 --- a/app/src/generic/java/org/tasks/location/GeofenceTransitionsIntentService.java +++ b/app/src/generic/java/org/tasks/location/GeofenceTransitionsIntentService.java @@ -1,5 +1,3 @@ package org.tasks.location; -public class GeofenceTransitionsIntentService { - -} +public class GeofenceTransitionsIntentService {} diff --git a/app/src/googleplay/java/com/android/vending/billing/IabBroadcastReceiver.java b/app/src/googleplay/java/com/android/vending/billing/IabBroadcastReceiver.java index e0f8e52d2..0bf9e38fb 100644 --- a/app/src/googleplay/java/com/android/vending/billing/IabBroadcastReceiver.java +++ b/app/src/googleplay/java/com/android/vending/billing/IabBroadcastReceiver.java @@ -20,24 +20,20 @@ import android.content.Context; import android.content.Intent; /** - * Receiver for the "com.android.vending.billing.PURCHASES_UPDATED" Action - * from the Play Store. + * Receiver for the "com.android.vending.billing.PURCHASES_UPDATED" Action from the Play Store. * - *

It is possible that an in-app item may be acquired without the - * application calling getBuyIntent(), for example if the item can be - * redeemed from inside the Play Store using a promotional code. If this - * application isn't running at the time, then when it is started a call - * to getPurchases() will be sufficient notification. However, if the - * application is already running in the background when the item is acquired, - * a message to this BroadcastReceiver will indicate that the an item - * has been acquired.

+ *

It is possible that an in-app item may be acquired without the application calling + * getBuyIntent(), for example if the item can be redeemed from inside the Play Store using a + * promotional code. If this application isn't running at the time, then when it is started a call + * to getPurchases() will be sufficient notification. However, if the application is already running + * in the background when the item is acquired, a message to this BroadcastReceiver will indicate + * that the an item has been acquired. */ public class IabBroadcastReceiver extends BroadcastReceiver { - /** - * The Intent action that this Receiver should filter for. - */ + /** The Intent action that this Receiver should filter for. */ public static final String ACTION = "com.android.vending.billing.PURCHASES_UPDATED"; + private final IabBroadcastListener mListener; public IabBroadcastReceiver(IabBroadcastListener listener) { @@ -51,9 +47,7 @@ public class IabBroadcastReceiver extends BroadcastReceiver { } } - /** - * Listener interface for received broadcast messages. - */ + /** Listener interface for received broadcast messages. */ public interface IabBroadcastListener { void receivedBroadcast(); diff --git a/app/src/googleplay/java/com/android/vending/billing/IabException.java b/app/src/googleplay/java/com/android/vending/billing/IabException.java index 2ca6058e6..adbdd34c8 100644 --- a/app/src/googleplay/java/com/android/vending/billing/IabException.java +++ b/app/src/googleplay/java/com/android/vending/billing/IabException.java @@ -16,10 +16,9 @@ package com.android.vending.billing; /** - * Exception thrown when something went wrong with in-app billing. - * An IabException has an associated IabResult (an error). - * To get the IAB result that caused this exception to be thrown, - * call {@link #getResult()}. + * Exception thrown when something went wrong with in-app billing. An IabException has an associated + * IabResult (an error). To get the IAB result that caused this exception to be thrown, call {@link + * #getResult()}. */ @SuppressWarnings("ALL") public class IabException extends Exception { @@ -43,10 +42,8 @@ public class IabException extends Exception { this(new IabResult(response, message), cause); } - /** - * Returns the IAB result (error) that this exception signals. - */ + /** Returns the IAB result (error) that this exception signals. */ public IabResult getResult() { return mResult; } -} \ No newline at end of file +} diff --git a/app/src/googleplay/java/com/android/vending/billing/IabHelper.java b/app/src/googleplay/java/com/android/vending/billing/IabHelper.java index 86a318b41..8c4c73ebf 100644 --- a/app/src/googleplay/java/com/android/vending/billing/IabHelper.java +++ b/app/src/googleplay/java/com/android/vending/billing/IabHelper.java @@ -35,35 +35,29 @@ import java.util.List; import java.util.concurrent.Executor; import org.json.JSONException; - /** - * Provides convenience methods for in-app billing. You can create one instance of this - * class for your application and use it to process in-app billing operations. - * It provides synchronous (blocking) and asynchronous (non-blocking) methods for - * many common in-app billing operations, as well as automatic signature - * verification. + * Provides convenience methods for in-app billing. You can create one instance of this class for + * your application and use it to process in-app billing operations. It provides synchronous + * (blocking) and asynchronous (non-blocking) methods for many common in-app billing operations, as + * well as automatic signature verification. * - * After instantiating, you must perform setup in order to start using the object. - * To perform setup, call the {@link #startSetup} method and provide a listener; - * that listener will be notified when setup is complete, after which (and not before) - * you may call other methods. + *

After instantiating, you must perform setup in order to start using the object. To perform + * setup, call the {@link #startSetup} method and provide a listener; that listener will be notified + * when setup is complete, after which (and not before) you may call other methods. * - * After setup is complete, you will typically want to request an inventory of owned - * items and subscriptions. See {@link #queryInventory}, {@link #queryInventoryAsync} - * and related methods. + *

After setup is complete, you will typically want to request an inventory of owned items and + * subscriptions. See {@link #queryInventory}, {@link #queryInventoryAsync} and related methods. * - * When you are done with this object, don't forget to call {@link #dispose} - * to ensure proper cleanup. This object holds a binding to the in-app billing - * service, which will leak unless you dispose of it correctly. If you created - * the object on an Activity's onCreate method, then the recommended - * place to dispose of it is the Activity's onDestroy method. + *

When you are done with this object, don't forget to call {@link #dispose} to ensure proper + * cleanup. This object holds a binding to the in-app billing service, which will leak unless you + * dispose of it correctly. If you created the object on an Activity's onCreate method, then the + * recommended place to dispose of it is the Activity's onDestroy method. * - * A note about threading: When using this object from a background thread, you may - * call the blocking versions of methods; when using from a UI thread, call - * only the asynchronous versions and handle the results via callbacks. - * Also, notice that you can only call one asynchronous operation at a time; - * attempting to start a second asynchronous operation while the first one - * has not yet completed will result in an exception being thrown. + *

A note about threading: When using this object from a background thread, you may call the + * blocking versions of methods; when using from a UI thread, call only the asynchronous versions + * and handle the results via callbacks. Also, notice that you can only call one asynchronous + * operation at a time; attempting to start a second asynchronous operation while the first one has + * not yet completed will result in an exception being thrown. */ @SuppressWarnings("ALL") @SuppressLint("all") @@ -142,15 +136,15 @@ public class IabHelper { OnIabPurchaseFinishedListener mPurchaseListener; /** - * Creates an instance. After creation, it will not yet be ready to use. You must perform - * setup by calling {@link #startSetup} and wait for setup to complete. This constructor does not - * block and is safe to call from a UI thread. + * Creates an instance. After creation, it will not yet be ready to use. You must perform setup by + * calling {@link #startSetup} and wait for setup to complete. This constructor does not block and + * is safe to call from a UI thread. * * @param ctx Your application or Activity context. Needed to bind to the in-app billing service. * @param base64PublicKey Your application's public key, encoded in base64. This is used for - * verification of purchase signatures. You can find your app's base64-encoded public key in your - * application's page on Google Play Developer Console. Note that this is NOT your "developer - * public key". + * verification of purchase signatures. You can find your app's base64-encoded public key in + * your application's page on Google Play Developer Console. Note that this is NOT your + * "developer public key". */ public IabHelper(Context ctx, String base64PublicKey, Executor executor) { mContext = ctx.getApplicationContext(); @@ -164,23 +158,27 @@ public class IabHelper { * * @param code The response code * @return A human-readable string explaining the result code. It also includes the result code - * numerically. + * numerically. */ public static String getResponseDesc(int code) { - String[] iab_msgs = ("0:OK/1:User Canceled/2:Unknown/" + - "3:Billing Unavailable/4:Item unavailable/" + - "5:Developer Error/6:Error/7:Item Already Owned/" + - "8:Item not owned").split("/"); - String[] iabhelper_msgs = ("0:OK/-1001:Remote exception during initialization/" + - "-1002:Bad response received/" + - "-1003:Purchase signature verification failed/" + - "-1004:Send intent failed/" + - "-1005:User cancelled/" + - "-1006:Unknown purchase response/" + - "-1007:Missing token/" + - "-1008:Unknown error/" + - "-1009:Subscriptions not available/" + - "-1010:Invalid consumption attempt").split("/"); + String[] iab_msgs = + ("0:OK/1:User Canceled/2:Unknown/" + + "3:Billing Unavailable/4:Item unavailable/" + + "5:Developer Error/6:Error/7:Item Already Owned/" + + "8:Item not owned") + .split("/"); + String[] iabhelper_msgs = + ("0:OK/-1001:Remote exception during initialization/" + + "-1002:Bad response received/" + + "-1003:Purchase signature verification failed/" + + "-1004:Send intent failed/" + + "-1005:User cancelled/" + + "-1006:Unknown purchase response/" + + "-1007:Missing token/" + + "-1008:Unknown error/" + + "-1009:Subscriptions not available/" + + "-1010:Invalid consumption attempt") + .split("/"); if (code <= IABHELPER_ERROR_BASE) { int index = IABHELPER_ERROR_BASE - code; @@ -196,9 +194,7 @@ public class IabHelper { } } - /** - * Enables or disable debug logging through LogCat. - */ + /** Enables or disable debug logging through LogCat. */ public void enableDebugLogging(boolean enable, String tag) { checkNotDisposed(); mDebugLog = enable; @@ -211,9 +207,9 @@ public class IabHelper { } /** - * Starts the setup process. This will start up the setup process asynchronously. - * You will be notified through the listener when the setup process is complete. - * This method is safe to call from a UI thread. + * Starts the setup process. This will start up the setup process asynchronously. You will be + * notified through the listener when the setup process is complete. This method is safe to call + * from a UI thread. * * @param listener The listener to notify when the setup process is complete. */ @@ -226,87 +222,90 @@ public class IabHelper { // Connection to IAB service logDebug("Starting in-app billing setup."); - mServiceConn = new ServiceConnection() { - @Override - public void onServiceDisconnected(ComponentName name) { - logDebug("Billing service disconnected."); - mService = null; - } - - @Override - public void onServiceConnected(ComponentName name, IBinder service) { - if (mDisposed) { - return; - } - logDebug("Billing service connected."); - mService = IInAppBillingService.Stub.asInterface(service); - String packageName = mContext.getPackageName(); - try { - logDebug("Checking for in-app billing 3 support."); - - // check for in-app billing v3 support - int response = mService.isBillingSupported(3, packageName, ITEM_TYPE_INAPP); - if (response != BILLING_RESPONSE_RESULT_OK) { - if (listener != null) { - listener.onIabSetupFinished(new IabResult(response, - "Error checking for billing v3 support.")); - } - - // if in-app purchases aren't supported, neither are subscriptions - mSubscriptionsSupported = false; - mSubscriptionUpdateSupported = false; - return; - } else { - logDebug("In-app billing version 3 supported for " + packageName); + mServiceConn = + new ServiceConnection() { + @Override + public void onServiceDisconnected(ComponentName name) { + logDebug("Billing service disconnected."); + mService = null; } - // Check for v5 subscriptions support. This is needed for - // getBuyIntentToReplaceSku which allows for subscription update - response = mService.isBillingSupported(5, packageName, ITEM_TYPE_SUBS); - if (response == BILLING_RESPONSE_RESULT_OK) { - logDebug("Subscription re-signup AVAILABLE."); - mSubscriptionUpdateSupported = true; - } else { - logDebug("Subscription re-signup not available."); - mSubscriptionUpdateSupported = false; - } - - if (mSubscriptionUpdateSupported) { - mSubscriptionsSupported = true; - } else { - // check for v3 subscriptions support - response = mService.isBillingSupported(3, packageName, ITEM_TYPE_SUBS); - if (response == BILLING_RESPONSE_RESULT_OK) { - logDebug("Subscriptions AVAILABLE."); - mSubscriptionsSupported = true; - } else { - logDebug("Subscriptions NOT AVAILABLE. Response: " + response); - mSubscriptionsSupported = false; - mSubscriptionUpdateSupported = false; + @Override + public void onServiceConnected(ComponentName name, IBinder service) { + if (mDisposed) { + return; + } + logDebug("Billing service connected."); + mService = IInAppBillingService.Stub.asInterface(service); + String packageName = mContext.getPackageName(); + try { + logDebug("Checking for in-app billing 3 support."); + + // check for in-app billing v3 support + int response = mService.isBillingSupported(3, packageName, ITEM_TYPE_INAPP); + if (response != BILLING_RESPONSE_RESULT_OK) { + if (listener != null) { + listener.onIabSetupFinished( + new IabResult(response, "Error checking for billing v3 support.")); + } + + // if in-app purchases aren't supported, neither are subscriptions + mSubscriptionsSupported = false; + mSubscriptionUpdateSupported = false; + return; + } else { + logDebug("In-app billing version 3 supported for " + packageName); + } + + // Check for v5 subscriptions support. This is needed for + // getBuyIntentToReplaceSku which allows for subscription update + response = mService.isBillingSupported(5, packageName, ITEM_TYPE_SUBS); + if (response == BILLING_RESPONSE_RESULT_OK) { + logDebug("Subscription re-signup AVAILABLE."); + mSubscriptionUpdateSupported = true; + } else { + logDebug("Subscription re-signup not available."); + mSubscriptionUpdateSupported = false; + } + + if (mSubscriptionUpdateSupported) { + mSubscriptionsSupported = true; + } else { + // check for v3 subscriptions support + response = mService.isBillingSupported(3, packageName, ITEM_TYPE_SUBS); + if (response == BILLING_RESPONSE_RESULT_OK) { + logDebug("Subscriptions AVAILABLE."); + mSubscriptionsSupported = true; + } else { + logDebug("Subscriptions NOT AVAILABLE. Response: " + response); + mSubscriptionsSupported = false; + mSubscriptionUpdateSupported = false; + } + } + + mSetupDone = true; + } catch (RemoteException e) { + if (listener != null) { + listener.onIabSetupFinished( + new IabResult( + IABHELPER_REMOTE_EXCEPTION, + "RemoteException while setting up in-app billing.")); + } + e.printStackTrace(); + return; } - } - mSetupDone = true; - } catch (RemoteException e) { - if (listener != null) { - listener.onIabSetupFinished(new IabResult(IABHELPER_REMOTE_EXCEPTION, - "RemoteException while setting up in-app billing.")); + if (listener != null) { + listener.onIabSetupFinished( + new IabResult(BILLING_RESPONSE_RESULT_OK, "Setup successful.")); + } } - e.printStackTrace(); - return; - } - - if (listener != null) { - listener - .onIabSetupFinished(new IabResult(BILLING_RESPONSE_RESULT_OK, "Setup successful.")); - } - } - }; + }; Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND"); serviceIntent.setPackage("com.android.vending"); - List intentServices = mContext.getPackageManager() - .queryIntentServices(serviceIntent, 0); + List intentServices = + mContext.getPackageManager().queryIntentServices(serviceIntent, 0); if (intentServices != null && !intentServices.isEmpty()) { // service available to handle that Intent mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE); @@ -314,17 +313,17 @@ public class IabHelper { // no service available to handle that Intent if (listener != null) { listener.onIabSetupFinished( - new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE, + new IabResult( + BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE, "Billing service unavailable on device.")); } } } /** - * Dispose of object, releasing resources. It's very important to call this - * method when you are done with this object. It will release any resources - * used by it such as service connections. Naturally, once the object is - * disposed of, it can't be used again. + * Dispose of object, releasing resources. It's very important to call this method when you are + * done with this object. It will release any resources used by it such as service connections. + * Naturally, once the object is disposed of, it can't be used again. */ public void dispose() { logDebug("Disposing."); @@ -348,64 +347,76 @@ public class IabHelper { } } - /** - * Returns whether subscriptions are supported. - */ + /** Returns whether subscriptions are supported. */ public boolean subscriptionsSupported() { checkNotDisposed(); return mSubscriptionsSupported; } - public void launchPurchaseFlow(Activity act, String sku, int requestCode, - OnIabPurchaseFinishedListener listener) { + public void launchPurchaseFlow( + Activity act, String sku, int requestCode, OnIabPurchaseFinishedListener listener) { launchPurchaseFlow(act, sku, requestCode, listener, ""); } - public void launchPurchaseFlow(Activity act, String sku, int requestCode, - OnIabPurchaseFinishedListener listener, String extraData) { + public void launchPurchaseFlow( + Activity act, + String sku, + int requestCode, + OnIabPurchaseFinishedListener listener, + String extraData) { launchPurchaseFlow(act, sku, ITEM_TYPE_INAPP, null, requestCode, listener, extraData); } - public void launchSubscriptionPurchaseFlow(Activity act, String sku, int requestCode, - OnIabPurchaseFinishedListener listener) { + public void launchSubscriptionPurchaseFlow( + Activity act, String sku, int requestCode, OnIabPurchaseFinishedListener listener) { launchSubscriptionPurchaseFlow(act, sku, requestCode, listener, ""); } - public void launchSubscriptionPurchaseFlow(Activity act, String sku, int requestCode, - OnIabPurchaseFinishedListener listener, String extraData) { + public void launchSubscriptionPurchaseFlow( + Activity act, + String sku, + int requestCode, + OnIabPurchaseFinishedListener listener, + String extraData) { launchPurchaseFlow(act, sku, ITEM_TYPE_SUBS, null, requestCode, listener, extraData); } /** * Initiate the UI flow for an in-app purchase. Call this method to initiate an in-app purchase, * which will involve bringing up the Google Play screen. The calling activity will be paused - * while the user interacts with Google Play, and the result will be delivered via the - * activity's {@link android.app.Activity#onActivityResult} method, at which point you must call - * this object's {@link #handleActivityResult} method to continue the purchase flow. This method - * MUST be called from the UI thread of the Activity. + * while the user interacts with Google Play, and the result will be delivered via the activity's + * {@link android.app.Activity#onActivityResult} method, at which point you must call this + * object's {@link #handleActivityResult} method to continue the purchase flow. This method MUST + * be called from the UI thread of the Activity. * * @param act The calling activity. * @param sku The sku of the item to purchase. * @param itemType indicates if it's a product or a subscription (ITEM_TYPE_INAPP or - * ITEM_TYPE_SUBS) + * ITEM_TYPE_SUBS) * @param oldSkus A list of SKUs which the new SKU is replacing or null if there are none * @param requestCode A request code (to differentiate from other responses -- as in {@link - * android.app.Activity#startActivityForResult}). + * android.app.Activity#startActivityForResult}). * @param listener The listener to notify when the purchase process finishes * @param extraData Extra data (developer payload), which will be returned with the purchase data - * when the purchase completes. This extra data will be permanently bound to that purchase and - * will always be returned when the purchase is queried. + * when the purchase completes. This extra data will be permanently bound to that purchase and + * will always be returned when the purchase is queried. */ - public void launchPurchaseFlow(Activity act, String sku, String itemType, List oldSkus, - int requestCode, OnIabPurchaseFinishedListener listener, String extraData) { + public void launchPurchaseFlow( + Activity act, + String sku, + String itemType, + List oldSkus, + int requestCode, + OnIabPurchaseFinishedListener listener, + String extraData) { checkNotDisposed(); checkSetupDone("launchPurchaseFlow"); flagStartAsync("launchPurchaseFlow"); IabResult result; if (itemType.equals(ITEM_TYPE_SUBS) && !mSubscriptionsSupported) { - IabResult r = new IabResult(IABHELPER_SUBSCRIPTIONS_NOT_AVAILABLE, - "Subscriptions are not available."); + IabResult r = + new IabResult(IABHELPER_SUBSCRIPTIONS_NOT_AVAILABLE, "Subscriptions are not available."); flagEndAsync(); if (listener != null) { listener.onIabPurchaseFinished(r, null); @@ -418,21 +429,24 @@ public class IabHelper { Bundle buyIntentBundle; if (oldSkus == null || oldSkus.isEmpty()) { // Purchasing a new item or subscription re-signup - buyIntentBundle = mService.getBuyIntent(3, mContext.getPackageName(), sku, itemType, - extraData); + buyIntentBundle = + mService.getBuyIntent(3, mContext.getPackageName(), sku, itemType, extraData); } else { // Subscription upgrade/downgrade if (!mSubscriptionUpdateSupported) { - IabResult r = new IabResult(IABHELPER_SUBSCRIPTION_UPDATE_NOT_AVAILABLE, - "Subscription updates are not available."); + IabResult r = + new IabResult( + IABHELPER_SUBSCRIPTION_UPDATE_NOT_AVAILABLE, + "Subscription updates are not available."); flagEndAsync(); if (listener != null) { listener.onIabPurchaseFinished(r, null); } return; } - buyIntentBundle = mService.getBuyIntentToReplaceSkus(5, mContext.getPackageName(), - oldSkus, sku, itemType, extraData); + buyIntentBundle = + mService.getBuyIntentToReplaceSkus( + 5, mContext.getPackageName(), oldSkus, sku, itemType, extraData); } int response = getResponseCodeFromBundle(buyIntentBundle); if (response != BILLING_RESPONSE_RESULT_OK) { @@ -450,9 +464,12 @@ public class IabHelper { mRequestCode = requestCode; mPurchaseListener = listener; mPurchasingItemType = itemType; - act.startIntentSenderForResult(pendingIntent.getIntentSender(), - requestCode, new Intent(), - Integer.valueOf(0), Integer.valueOf(0), + act.startIntentSenderForResult( + pendingIntent.getIntentSender(), + requestCode, + new Intent(), + Integer.valueOf(0), + Integer.valueOf(0), Integer.valueOf(0)); } catch (SendIntentException e) { logError("SendIntentException while launching purchase flow for sku " + sku); @@ -468,8 +485,9 @@ public class IabHelper { e.printStackTrace(); flagEndAsync(); - result = new IabResult(IABHELPER_REMOTE_EXCEPTION, - "Remote exception while starting purchase flow"); + result = + new IabResult( + IABHELPER_REMOTE_EXCEPTION, "Remote exception while starting purchase flow"); if (listener != null) { listener.onIabPurchaseFinished(result, null); } @@ -477,16 +495,16 @@ public class IabHelper { } /** - * Handles an activity result that's part of the purchase flow in in-app billing. If you - * are calling {@link #launchPurchaseFlow}, then you must call this method from your - * Activity's {@link android.app.Activity@onActivityResult} method. This method - * MUST be called from the UI thread of the Activity. + * Handles an activity result that's part of the purchase flow in in-app billing. If you are + * calling {@link #launchPurchaseFlow}, then you must call this method from your Activity's {@link + * android.app.Activity@onActivityResult} method. This method MUST be called from the UI thread of + * the Activity. * * @param requestCode The requestCode as you received it. * @param resultCode The resultCode as you received it. * @param data The data (Intent) as you received it. * @return Returns true if the result was related to a purchase flow and was handled; false if the - * result was not related to a purchase, in which case you should handle it normally. + * result was not related to a purchase, in which case you should handle it normally. */ public boolean handleActivityResult(int requestCode, int resultCode, Intent data) { IabResult result; @@ -523,8 +541,9 @@ public class IabHelper { if (purchaseData == null || dataSignature == null) { logError("BUG: either purchaseData or dataSignature is null."); logDebug("Extras: " + data.getExtras().toString()); - result = new IabResult(IABHELPER_UNKNOWN_ERROR, - "IAB returned null purchaseData or dataSignature"); + result = + new IabResult( + IABHELPER_UNKNOWN_ERROR, "IAB returned null purchaseData or dataSignature"); if (mPurchaseListener != null) { mPurchaseListener.onIabPurchaseFinished(result, null); } @@ -539,8 +558,9 @@ public class IabHelper { // Verify signature if (!Security.verifyPurchase(mSignatureBase64, purchaseData, dataSignature)) { logError("Purchase signature verification FAILED for sku " + sku); - result = new IabResult(IABHELPER_VERIFICATION_FAILED, - "Signature verification failed for sku " + sku); + result = + new IabResult( + IABHELPER_VERIFICATION_FAILED, "Signature verification failed for sku " + sku); if (mPurchaseListener != null) { mPurchaseListener.onIabPurchaseFinished(result, purchase); } @@ -558,13 +578,14 @@ public class IabHelper { } if (mPurchaseListener != null) { - mPurchaseListener - .onIabPurchaseFinished(new IabResult(BILLING_RESPONSE_RESULT_OK, "Success"), purchase); + mPurchaseListener.onIabPurchaseFinished( + new IabResult(BILLING_RESPONSE_RESULT_OK, "Success"), purchase); } } else if (resultCode == Activity.RESULT_OK) { // result code was OK, but in-app billing response was not OK. - logDebug("Result code was OK but in-app billing response was not OK: " + getResponseDesc( - responseCode)); + logDebug( + "Result code was OK but in-app billing response was not OK: " + + getResponseDesc(responseCode)); if (mPurchaseListener != null) { result = new IabResult(responseCode, "Problem purchashing item."); mPurchaseListener.onIabPurchaseFinished(result, null); @@ -576,8 +597,11 @@ public class IabHelper { mPurchaseListener.onIabPurchaseFinished(result, null); } } else { - logError("Purchase failed. Result code: " + Integer.toString(resultCode) - + ". Response: " + getResponseDesc(responseCode)); + logError( + "Purchase failed. Result code: " + + Integer.toString(resultCode) + + ". Response: " + + getResponseDesc(responseCode)); result = new IabResult(IABHELPER_UNKNOWN_PURCHASE_RESPONSE, "Unknown purchase response."); if (mPurchaseListener != null) { mPurchaseListener.onIabPurchaseFinished(result, null); @@ -597,15 +621,16 @@ public class IabHelper { * from a UI thread. For that, use the non-blocking version {@link #queryInventoryAsync}. * * @param querySkuDetails if true, SKU details (price, description, etc) will be queried as well - * as purchase information. + * as purchase information. * @param moreItemSkus additional PRODUCT skus to query information on, regardless of ownership. - * Ignored if null or if querySkuDetails is false. + * Ignored if null or if querySkuDetails is false. * @param moreSubsSkus additional SUBSCRIPTIONS skus to query information on, regardless of - * ownership. Ignored if null or if querySkuDetails is false. + * ownership. Ignored if null or if querySkuDetails is false. * @throws IabException if a problem occurs while refreshing the inventory. */ - public Inventory queryInventory(boolean querySkuDetails, List moreItemSkus, - List moreSubsSkus) throws IabException { + public Inventory queryInventory( + boolean querySkuDetails, List moreItemSkus, List moreSubsSkus) + throws IabException { checkNotDisposed(); checkSetupDone("queryInventory"); try { @@ -632,71 +657,73 @@ public class IabHelper { if (querySkuDetails) { r = querySkuDetails(ITEM_TYPE_SUBS, inv, moreSubsSkus); if (r != BILLING_RESPONSE_RESULT_OK) { - throw new IabException(r, - "Error refreshing inventory (querying prices of subscriptions)."); + throw new IabException( + r, "Error refreshing inventory (querying prices of subscriptions)."); } } } return inv; } catch (RemoteException e) { - throw new IabException(IABHELPER_REMOTE_EXCEPTION, - "Remote exception while refreshing inventory.", e); + throw new IabException( + IABHELPER_REMOTE_EXCEPTION, "Remote exception while refreshing inventory.", e); } catch (JSONException e) { - throw new IabException(IABHELPER_BAD_RESPONSE, - "Error parsing JSON response while refreshing inventory.", e); + throw new IabException( + IABHELPER_BAD_RESPONSE, "Error parsing JSON response while refreshing inventory.", e); } } /** - * Asynchronous wrapper for inventory query. This will perform an inventory - * query as described in {@link #queryInventory}, but will do so asynchronously - * and call back the specified listener upon completion. This method is safe to - * call from a UI thread. + * Asynchronous wrapper for inventory query. This will perform an inventory query as described in + * {@link #queryInventory}, but will do so asynchronously and call back the specified listener + * upon completion. This method is safe to call from a UI thread. * * @param querySkuDetails as in {@link #queryInventory} * @param moreSkus as in {@link #queryInventory} * @param listener The listener to notify when the refresh operation completes. */ - public void queryInventoryAsync(final boolean querySkuDetails, final List moreSkus, + public void queryInventoryAsync( + final boolean querySkuDetails, + final List moreSkus, final QueryInventoryFinishedListener listener) { final Handler handler = new Handler(); checkNotDisposed(); checkSetupDone("queryInventory"); flagStartAsync("refresh inventory"); - executor.execute(() -> { - IabResult result = new IabResult(BILLING_RESPONSE_RESULT_OK, "Inventory refresh successful."); - Inventory inv = null; - try { - inv = queryInventory(querySkuDetails, moreSkus); - } catch (IabException ex) { - result = ex.getResult(); - } + executor.execute( + () -> { + IabResult result = + new IabResult(BILLING_RESPONSE_RESULT_OK, "Inventory refresh successful."); + Inventory inv = null; + try { + inv = queryInventory(querySkuDetails, moreSkus); + } catch (IabException ex) { + result = ex.getResult(); + } - flagEndAsync(); + flagEndAsync(); - final IabResult result_f = result; - final Inventory inv_f = inv; - if (!mDisposed && listener != null) { - handler.post(() -> listener.onQueryInventoryFinished(result_f, inv_f)); - } - }); + final IabResult result_f = result; + final Inventory inv_f = inv; + if (!mDisposed && listener != null) { + handler.post(() -> listener.onQueryInventoryFinished(result_f, inv_f)); + } + }); } public void queryInventoryAsync(QueryInventoryFinishedListener listener) { queryInventoryAsync(true, null, listener); } - public void queryInventoryAsync(boolean querySkuDetails, - QueryInventoryFinishedListener listener) { + public void queryInventoryAsync( + boolean querySkuDetails, QueryInventoryFinishedListener listener) { queryInventoryAsync(querySkuDetails, null, listener); } /** - * Consumes a given in-app product. Consuming can only be done on an item - * that's owned, and as a result of consumption, the user will no longer own it. - * This method may block or take long to return. Do not call from the UI thread. - * For that, see {@link #consumeAsync}. + * Consumes a given in-app product. Consuming can only be done on an item that's owned, and as a + * result of consumption, the user will no longer own it. This method may block or take long to + * return. Do not call from the UI thread. For that, see {@link #consumeAsync}. * * @param itemInfo The PurchaseInfo that represents the item to consume. * @throws IabException if there is a problem during consumption. @@ -706,7 +733,8 @@ public class IabHelper { checkSetupDone("consume"); if (!itemInfo.mItemType.equals(ITEM_TYPE_INAPP)) { - throw new IabException(IABHELPER_INVALID_CONSUMPTION, + throw new IabException( + IABHELPER_INVALID_CONSUMPTION, "Items of type '" + itemInfo.mItemType + "' can't be consumed."); } @@ -715,8 +743,9 @@ public class IabHelper { String sku = itemInfo.getSku(); if (token == null || token.equals("")) { logError("Can't consume " + sku + ". No token."); - throw new IabException(IABHELPER_MISSING_TOKEN, "PurchaseInfo is missing token for sku: " - + sku + " " + itemInfo); + throw new IabException( + IABHELPER_MISSING_TOKEN, + "PurchaseInfo is missing token for sku: " + sku + " " + itemInfo); } logDebug("Consuming sku: " + sku + ", token: " + token); @@ -728,15 +757,17 @@ public class IabHelper { throw new IabException(response, "Error consuming sku " + sku); } } catch (RemoteException e) { - throw new IabException(IABHELPER_REMOTE_EXCEPTION, - "Remote exception while consuming. PurchaseInfo: " + itemInfo, e); + throw new IabException( + IABHELPER_REMOTE_EXCEPTION, + "Remote exception while consuming. PurchaseInfo: " + itemInfo, + e); } } /** - * Asynchronous wrapper to item consumption. Works like {@link #consume}, but - * performs the consumption in the background and notifies completion through - * the provided listener. This method is safe to call from a UI thread. + * Asynchronous wrapper to item consumption. Works like {@link #consume}, but performs the + * consumption in the background and notifies completion through the provided listener. This + * method is safe to call from a UI thread. * * @param purchase The purchase to be consumed. * @param listener The listener to notify when the consumption operation finishes. @@ -808,8 +839,12 @@ public class IabHelper { void flagStartAsync(String operation) { if (mAsyncInProgress) { - throw new IllegalStateException("Can't start async operation (" + - operation + ") because another async operation(" + mAsyncOperation + ") is in progress."); + throw new IllegalStateException( + "Can't start async operation (" + + operation + + ") because another async operation(" + + mAsyncOperation + + ") is in progress."); } mAsyncOperation = operation; mAsyncInProgress = true; @@ -831,8 +866,8 @@ public class IabHelper { do { logDebug("Calling getPurchases with continuation token: " + continueToken); - Bundle ownedItems = mService.getPurchases(3, mContext.getPackageName(), - itemType, continueToken); + Bundle ownedItems = + mService.getPurchases(3, mContext.getPackageName(), itemType, continueToken); int response = getResponseCodeFromBundle(ownedItems); logDebug("Owned items response: " + String.valueOf(response)); @@ -847,12 +882,11 @@ public class IabHelper { return IABHELPER_BAD_RESPONSE; } - ArrayList ownedSkus = ownedItems.getStringArrayList( - RESPONSE_INAPP_ITEM_LIST); - ArrayList purchaseDataList = ownedItems.getStringArrayList( - RESPONSE_INAPP_PURCHASE_DATA_LIST); - ArrayList signatureList = ownedItems.getStringArrayList( - RESPONSE_INAPP_SIGNATURE_LIST); + ArrayList ownedSkus = ownedItems.getStringArrayList(RESPONSE_INAPP_ITEM_LIST); + ArrayList purchaseDataList = + ownedItems.getStringArrayList(RESPONSE_INAPP_PURCHASE_DATA_LIST); + ArrayList signatureList = + ownedItems.getStringArrayList(RESPONSE_INAPP_SIGNATURE_LIST); for (int i = 0; i < purchaseDataList.size(); ++i) { String purchaseData = purchaseDataList.get(i); @@ -925,8 +959,7 @@ public class IabHelper { for (ArrayList skuPartList : packs) { Bundle querySkus = new Bundle(); querySkus.putStringArrayList(GET_SKU_DETAILS_ITEM_LIST, skuPartList); - Bundle skuDetails = mService.getSkuDetails(3, mContext.getPackageName(), - itemType, querySkus); + Bundle skuDetails = mService.getSkuDetails(3, mContext.getPackageName(), itemType, querySkus); if (!skuDetails.containsKey(RESPONSE_GET_SKU_DETAILS_LIST)) { int response = getResponseCodeFromBundle(skuDetails); @@ -939,8 +972,7 @@ public class IabHelper { } } - ArrayList responseList = skuDetails.getStringArrayList( - RESPONSE_GET_SKU_DETAILS_LIST); + ArrayList responseList = skuDetails.getStringArrayList(RESPONSE_GET_SKU_DETAILS_LIST); for (String thisResponse : responseList) { SkuDetails d = new SkuDetails(itemType, thisResponse); @@ -952,31 +984,35 @@ public class IabHelper { return BILLING_RESPONSE_RESULT_OK; } - void consumeAsyncInternal(final List purchases, + void consumeAsyncInternal( + final List purchases, final OnConsumeFinishedListener singleListener, final OnConsumeMultiFinishedListener multiListener) { final Handler handler = new Handler(); flagStartAsync("consume"); - executor.execute(() -> { - final List results = new ArrayList(); - for (Purchase purchase : purchases) { - try { - consume(purchase); - results.add(new IabResult(BILLING_RESPONSE_RESULT_OK, - "Successful consume of sku " + purchase.getSku())); - } catch (IabException ex) { - results.add(ex.getResult()); - } - } + executor.execute( + () -> { + final List results = new ArrayList(); + for (Purchase purchase : purchases) { + try { + consume(purchase); + results.add( + new IabResult( + BILLING_RESPONSE_RESULT_OK, + "Successful consume of sku " + purchase.getSku())); + } catch (IabException ex) { + results.add(ex.getResult()); + } + } - flagEndAsync(); - if (!mDisposed && singleListener != null) { - handler.post(() -> singleListener.onConsumeFinished(purchases.get(0), results.get(0))); - } - if (!mDisposed && multiListener != null) { - handler.post(() -> multiListener.onConsumeMultiFinished(purchases, results)); - } - }); + flagEndAsync(); + if (!mDisposed && singleListener != null) { + handler.post(() -> singleListener.onConsumeFinished(purchases.get(0), results.get(0))); + } + if (!mDisposed && multiListener != null) { + handler.post(() -> multiListener.onConsumeMultiFinished(purchases, results)); + } + }); } void logDebug(String msg) { @@ -994,8 +1030,8 @@ public class IabHelper { } /** - * Callback for setup process. This listener's {@link #onIabSetupFinished} method is called - * when the setup process is complete. + * Callback for setup process. This listener's {@link #onIabSetupFinished} method is called when + * the setup process is complete. */ public interface OnIabSetupFinishedListener { @@ -1007,16 +1043,13 @@ public class IabHelper { void onIabSetupFinished(IabResult result); } - /** - * Callback that notifies when a purchase is finished. - */ + /** Callback that notifies when a purchase is finished. */ public interface OnIabPurchaseFinishedListener { /** - * Called to notify that an in-app purchase finished. If the purchase was successful, - * then the sku parameter specifies which item was purchased. If the purchase failed, - * the sku and extraData parameters may or may not be null, depending on how far the purchase - * process went. + * Called to notify that an in-app purchase finished. If the purchase was successful, then the + * sku parameter specifies which item was purchased. If the purchase failed, the sku and + * extraData parameters may or may not be null, depending on how far the purchase process went. * * @param result The result of the purchase. * @param info The purchase information (null if purchase failed) @@ -1024,9 +1057,7 @@ public class IabHelper { void onIabPurchaseFinished(IabResult result, Purchase info); } - /** - * Listener that notifies when an inventory query operation completes. - */ + /** Listener that notifies when an inventory query operation completes. */ public interface QueryInventoryFinishedListener { /** @@ -1038,9 +1069,7 @@ public class IabHelper { void onQueryInventoryFinished(IabResult result, Inventory inv); } - /** - * Callback that notifies when a consumption operation finishes. - */ + /** Callback that notifies when a consumption operation finishes. */ public interface OnConsumeFinishedListener { /** @@ -1052,9 +1081,7 @@ public class IabHelper { void onConsumeFinished(Purchase purchase, IabResult result); } - /** - * Callback that notifies when a multi-item consumption operation finishes. - */ + /** Callback that notifies when a multi-item consumption operation finishes. */ public interface OnConsumeMultiFinishedListener { /** diff --git a/app/src/googleplay/java/com/android/vending/billing/IabResult.java b/app/src/googleplay/java/com/android/vending/billing/IabResult.java index 74f639918..cdbc125e9 100644 --- a/app/src/googleplay/java/com/android/vending/billing/IabResult.java +++ b/app/src/googleplay/java/com/android/vending/billing/IabResult.java @@ -16,12 +16,10 @@ package com.android.vending.billing; /** - * Represents the result of an in-app billing operation. - * A result is composed of a response code (an integer) and possibly a - * message (String). You can get those by calling - * {@link #getResponse} and {@link #getMessage()}, respectively. You - * can also inquire whether a result is a success or a failure by - * calling {@link #isSuccess()} and {@link #isFailure()}. + * Represents the result of an in-app billing operation. A result is composed of a response code (an + * integer) and possibly a message (String). You can get those by calling {@link #getResponse} and + * {@link #getMessage()}, respectively. You can also inquire whether a result is a success or a + * failure by calling {@link #isSuccess()} and {@link #isFailure()}. */ @SuppressWarnings("ALL") public class IabResult { @@ -58,4 +56,3 @@ public class IabResult { return "IabResult: " + getMessage(); } } - diff --git a/app/src/googleplay/java/com/android/vending/billing/Inventory.java b/app/src/googleplay/java/com/android/vending/billing/Inventory.java index e4079a444..09010ad1f 100644 --- a/app/src/googleplay/java/com/android/vending/billing/Inventory.java +++ b/app/src/googleplay/java/com/android/vending/billing/Inventory.java @@ -21,8 +21,8 @@ import java.util.List; import java.util.Map; /** - * Represents a block of information about in-app items. - * An Inventory is returned by such methods as {@link IabHelper#queryInventory}. + * Represents a block of information about in-app items. An Inventory is returned by such methods as + * {@link IabHelper#queryInventory}. */ @SuppressWarnings("ALL") public class Inventory { @@ -30,44 +30,34 @@ public class Inventory { Map mSkuMap = new HashMap(); Map mPurchaseMap = new HashMap(); - Inventory() { - } + Inventory() {} - /** - * Returns the listing details for an in-app product. - */ + /** Returns the listing details for an in-app product. */ public SkuDetails getSkuDetails(String sku) { return mSkuMap.get(sku); } - /** - * Returns purchase information for a given product, or null if there is no purchase. - */ + /** Returns purchase information for a given product, or null if there is no purchase. */ public Purchase getPurchase(String sku) { return mPurchaseMap.get(sku); } - /** - * Returns whether or not there exists a purchase of the given product. - */ + /** Returns whether or not there exists a purchase of the given product. */ public boolean hasPurchase(String sku) { return mPurchaseMap.containsKey(sku); } - /** - * Return whether or not details about the given product are available. - */ + /** Return whether or not details about the given product are available. */ public boolean hasDetails(String sku) { return mSkuMap.containsKey(sku); } /** - * Erase a purchase (locally) from the inventory, given its product ID. This just - * modifies the Inventory object locally and has no effect on the server! This is - * useful when you have an existing Inventory object which you know to be up to date, - * and you have just consumed an item successfully, which means that erasing its - * purchase data from the Inventory you already have is quicker than querying for - * a new Inventory. + * Erase a purchase (locally) from the inventory, given its product ID. This just modifies the + * Inventory object locally and has no effect on the server! This is useful when you have an + * existing Inventory object which you know to be up to date, and you have just consumed an item + * successfully, which means that erasing its purchase data from the Inventory you already have is + * quicker than querying for a new Inventory. */ public void erasePurchase(String sku) { if (mPurchaseMap.containsKey(sku)) { @@ -75,16 +65,12 @@ public class Inventory { } } - /** - * Returns a list of all owned product IDs. - */ + /** Returns a list of all owned product IDs. */ List getAllOwnedSkus() { return new ArrayList(mPurchaseMap.keySet()); } - /** - * Returns a list of all owned product IDs of a given type - */ + /** Returns a list of all owned product IDs of a given type */ List getAllOwnedSkus(String itemType) { List result = new ArrayList(); for (Purchase p : mPurchaseMap.values()) { @@ -95,9 +81,7 @@ public class Inventory { return result; } - /** - * Returns a list of all purchases. - */ + /** Returns a list of all purchases. */ List getAllPurchases() { return new ArrayList(mPurchaseMap.values()); } diff --git a/app/src/googleplay/java/com/android/vending/billing/Purchase.java b/app/src/googleplay/java/com/android/vending/billing/Purchase.java index 89e6f78af..7d2e2395b 100644 --- a/app/src/googleplay/java/com/android/vending/billing/Purchase.java +++ b/app/src/googleplay/java/com/android/vending/billing/Purchase.java @@ -18,13 +18,11 @@ package com.android.vending.billing; import org.json.JSONException; import org.json.JSONObject; -/** - * Represents an in-app billing purchase. - */ +/** Represents an in-app billing purchase. */ @SuppressWarnings("ALL") public class Purchase { - String mItemType; // ITEM_TYPE_INAPP or ITEM_TYPE_SUBS + String mItemType; // ITEM_TYPE_INAPP or ITEM_TYPE_SUBS String mOrderId; String mPackageName; String mSku; diff --git a/app/src/googleplay/java/com/android/vending/billing/Security.java b/app/src/googleplay/java/com/android/vending/billing/Security.java index 5dc0a11f9..03479ed81 100644 --- a/app/src/googleplay/java/com/android/vending/billing/Security.java +++ b/app/src/googleplay/java/com/android/vending/billing/Security.java @@ -29,13 +29,11 @@ import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; /** - * Security-related methods. For a secure implementation, all of this code - * should be implemented on a server that communicates with the - * application on the device. For the sake of simplicity and clarity of this - * example, this code is included here and is executed on the device. If you - * must verify the purchases on the phone, you should obfuscate this code to - * make it harder for an attacker to replace the code with stubs that treat all - * purchases as verified. + * Security-related methods. For a secure implementation, all of this code should be implemented on + * a server that communicates with the application on the device. For the sake of simplicity and + * clarity of this example, this code is included here and is executed on the device. If you must + * verify the purchases on the phone, you should obfuscate this code to make it harder for an + * attacker to replace the code with stubs that treat all purchases as verified. */ @SuppressWarnings("ALL") @SuppressLint("all") @@ -47,19 +45,19 @@ public class Security { private static final String SIGNATURE_ALGORITHM = "SHA1withRSA"; /** - * Verifies that the data was signed with the given signature, and returns - * the verified purchase. The data is in JSON format and signed - * with a private key. The data also contains the {@link PurchaseState} - * and product ID of the purchase. + * Verifies that the data was signed with the given signature, and returns the verified purchase. + * The data is in JSON format and signed with a private key. The data also contains the {@link + * PurchaseState} and product ID of the purchase. * * @param base64PublicKey the base64-encoded public key to use for verifying. * @param signedData the signed JSON string (signed, not encrypted) * @param signature the signature for the data, signed with the private key */ - public static boolean verifyPurchase(String base64PublicKey, String signedData, - String signature) { - if (TextUtils.isEmpty(signedData) || TextUtils.isEmpty(base64PublicKey) || - TextUtils.isEmpty(signature)) { + public static boolean verifyPurchase( + String base64PublicKey, String signedData, String signature) { + if (TextUtils.isEmpty(signedData) + || TextUtils.isEmpty(base64PublicKey) + || TextUtils.isEmpty(signature)) { Log.e(TAG, "Purchase verification failed: missing data."); return false; } @@ -69,8 +67,7 @@ public class Security { } /** - * Generates a PublicKey instance from a string containing the - * Base64-encoded public key. + * Generates a PublicKey instance from a string containing the Base64-encoded public key. * * @param encodedPublicKey Base64-encoded public key * @throws IllegalArgumentException if encodedPublicKey is invalid @@ -89,8 +86,8 @@ public class Security { } /** - * Verifies that the signature from the server matches the computed - * signature on the data. Returns true if the data is correctly signed. + * Verifies that the signature from the server matches the computed signature on the data. Returns + * true if the data is correctly signed. * * @param publicKey public key associated with the developer account * @param signedData signed data from server diff --git a/app/src/googleplay/java/com/android/vending/billing/SkuDetails.java b/app/src/googleplay/java/com/android/vending/billing/SkuDetails.java index ebca60586..ced974234 100644 --- a/app/src/googleplay/java/com/android/vending/billing/SkuDetails.java +++ b/app/src/googleplay/java/com/android/vending/billing/SkuDetails.java @@ -18,9 +18,7 @@ package com.android.vending.billing; import org.json.JSONException; import org.json.JSONObject; -/** - * Represents an in-app product's listing details. - */ +/** Represents an in-app product's listing details. */ @SuppressWarnings("ALL") public class SkuDetails { diff --git a/app/src/googleplay/java/org/tasks/analytics/Tracker.java b/app/src/googleplay/java/org/tasks/analytics/Tracker.java index dce479544..957460b22 100644 --- a/app/src/googleplay/java/org/tasks/analytics/Tracker.java +++ b/app/src/googleplay/java/org/tasks/analytics/Tracker.java @@ -29,24 +29,23 @@ public class Tracker { analytics = GoogleAnalytics.getInstance(context); tracker = analytics.newTracker(R.xml.google_analytics); tracker.setAppVersion(Integer.toString(BuildConfig.VERSION_CODE)); - final StandardExceptionParser standardExceptionParser = new StandardExceptionParser(context, - null); - exceptionParser = (thread, throwable) -> { - StringBuilder stack = new StringBuilder() - .append(standardExceptionParser.getDescription(thread, throwable)) - .append("\n") - .append(throwable.getClass().getName()) - .append("\n"); - for (StackTraceElement element : throwable.getStackTrace()) { - stack.append(element.toString()) - .append("\n"); - } - return stack.toString(); - }; - ExceptionReporter reporter = new ExceptionReporter( - tracker, - Thread.getDefaultUncaughtExceptionHandler(), - context); + final StandardExceptionParser standardExceptionParser = + new StandardExceptionParser(context, null); + exceptionParser = + (thread, throwable) -> { + StringBuilder stack = + new StringBuilder() + .append(standardExceptionParser.getDescription(thread, throwable)) + .append("\n") + .append(throwable.getClass().getName()) + .append("\n"); + for (StackTraceElement element : throwable.getStackTrace()) { + stack.append(element.toString()).append("\n"); + } + return stack.toString(); + }; + ExceptionReporter reporter = + new ExceptionReporter(tracker, Thread.getDefaultUncaughtExceptionHandler(), context); reporter.setExceptionParser(exceptionParser); Thread.setDefaultUncaughtExceptionHandler(reporter); } @@ -61,10 +60,11 @@ public class Tracker { public void reportException(Thread thread, Throwable t) { Timber.e(t, t.getMessage()); - tracker.send(new HitBuilders.ExceptionBuilder() - .setDescription(exceptionParser.getDescription(thread.getName(), t)) - .setFatal(false) - .build()); + tracker.send( + new HitBuilders.ExceptionBuilder() + .setDescription(exceptionParser.getDescription(thread.getName(), t)) + .setFatal(false) + .build()); } public void reportEvent(Tracking.Events event) { @@ -84,9 +84,8 @@ public class Tracker { } private void reportEvent(int category, String action, String label) { - HitBuilders.EventBuilder eventBuilder = new HitBuilders.EventBuilder() - .setCategory(context.getString(category)) - .setAction(action); + HitBuilders.EventBuilder eventBuilder = + new HitBuilders.EventBuilder().setCategory(context.getString(category)).setAction(action); if (!Strings.isNullOrEmpty(label)) { eventBuilder.setLabel(label); } @@ -94,10 +93,11 @@ public class Tracker { } public void reportIabResult(IabResult result, String sku) { - tracker.send(new HitBuilders.EventBuilder() - .setCategory(context.getString(R.string.tracking_category_iab)) - .setAction(sku) - .setLabel(result.getMessage()) - .build()); + tracker.send( + new HitBuilders.EventBuilder() + .setCategory(context.getString(R.string.tracking_category_iab)) + .setAction(sku) + .setLabel(result.getMessage()) + .build()); } } diff --git a/app/src/googleplay/java/org/tasks/billing/InventoryHelper.java b/app/src/googleplay/java/org/tasks/billing/InventoryHelper.java index 57dfa7fd6..6f2c7aa72 100644 --- a/app/src/googleplay/java/org/tasks/billing/InventoryHelper.java +++ b/app/src/googleplay/java/org/tasks/billing/InventoryHelper.java @@ -27,8 +27,11 @@ public class InventoryHelper implements IabBroadcastReceiver.IabBroadcastListene private Inventory inventory; @Inject - public InventoryHelper(@ForApplication Context context, Preferences preferences, - LocalBroadcastManager localBroadcastManager, @Named("iab-executor") Executor executor) { + public InventoryHelper( + @ForApplication Context context, + Preferences preferences, + LocalBroadcastManager localBroadcastManager, + @Named("iab-executor") Executor executor) { this.context = context; this.preferences = preferences; this.localBroadcastManager = localBroadcastManager; @@ -36,8 +39,8 @@ public class InventoryHelper implements IabBroadcastReceiver.IabBroadcastListene } public void initialize() { - context.registerReceiver(new IabBroadcastReceiver(this), - new IntentFilter(IabBroadcastReceiver.ACTION)); + context.registerReceiver( + new IabBroadcastReceiver(this), new IntentFilter(IabBroadcastReceiver.ACTION)); refreshInventory(); } diff --git a/app/src/googleplay/java/org/tasks/billing/PurchaseHelper.java b/app/src/googleplay/java/org/tasks/billing/PurchaseHelper.java index ad053c15c..083775373 100644 --- a/app/src/googleplay/java/org/tasks/billing/PurchaseHelper.java +++ b/app/src/googleplay/java/org/tasks/billing/PurchaseHelper.java @@ -36,8 +36,12 @@ public class PurchaseHelper implements IabHelper.OnIabSetupFinishedListener { private IabHelper iabHelper; @Inject - public PurchaseHelper(@ForApplication Context context, Preferences preferences, Tracker tracker, - InventoryHelper inventory, @Named("iab-executor") Executor executor, + public PurchaseHelper( + @ForApplication Context context, + Preferences preferences, + Tracker tracker, + InventoryHelper inventory, + @Named("iab-executor") Executor executor, LocalBroadcastManager localBroadcastManager) { this.context = context; this.preferences = preferences; @@ -54,8 +58,12 @@ public class PurchaseHelper implements IabHelper.OnIabSetupFinishedListener { } } - public boolean purchase(final Activity activity, final String sku, final String pref, - final int requestCode, final PurchaseHelperCallback callback) { + public boolean purchase( + final Activity activity, + final String sku, + final String pref, + final int requestCode, + final PurchaseHelperCallback callback) { launchPurchaseFlow(activity, sku, pref, requestCode, callback); return true; } @@ -75,43 +83,50 @@ public class PurchaseHelper implements IabHelper.OnIabSetupFinishedListener { if (themes != null) { purchases.add(themes); } - final IabHelper iabHelper = new IabHelper(context, context.getString(R.string.gp_key), - executor); + final IabHelper iabHelper = + new IabHelper(context, context.getString(R.string.gp_key), executor); iabHelper.enableDebugLogging(true); - iabHelper.startSetup(result -> { - if (result.isSuccess()) { - iabHelper.consumeAsync(purchases, (purchases1, results) -> { - for (int i = 0; i < purchases1.size(); i++) { - Purchase purchase = purchases1.get(i); - IabResult iabResult = results.get(i); - if (iabResult.isSuccess()) { - if (purchase.equals(tasker)) { - preferences.setBoolean(R.string.p_purchased_tasker, false); - } else if (purchase.equals(dashclock)) { - preferences.setBoolean(R.string.p_purchased_dashclock, false); - } else if (purchase.equals(themes)) { - preferences.setBoolean(R.string.p_purchased_themes, false); - } else { - Timber.e("Unhandled consumption for purchase: %s", purchase); - } - inventory.erasePurchase(purchase.getSku()); - Timber.d("Consumed %s", purchase); - } else { - Timber.e("Consume failed: %s, %s", purchase, iabResult); - } + iabHelper.startSetup( + result -> { + if (result.isSuccess()) { + iabHelper.consumeAsync( + purchases, + (purchases1, results) -> { + for (int i = 0; i < purchases1.size(); i++) { + Purchase purchase = purchases1.get(i); + IabResult iabResult = results.get(i); + if (iabResult.isSuccess()) { + if (purchase.equals(tasker)) { + preferences.setBoolean(R.string.p_purchased_tasker, false); + } else if (purchase.equals(dashclock)) { + preferences.setBoolean(R.string.p_purchased_dashclock, false); + } else if (purchase.equals(themes)) { + preferences.setBoolean(R.string.p_purchased_themes, false); + } else { + Timber.e("Unhandled consumption for purchase: %s", purchase); + } + inventory.erasePurchase(purchase.getSku()); + Timber.d("Consumed %s", purchase); + } else { + Timber.e("Consume failed: %s, %s", purchase, iabResult); + } + } + iabHelper.dispose(); + }); + } else { + Timber.e("setup failed: %s", result.getMessage()); + iabHelper.dispose(); } - iabHelper.dispose(); }); - } else { - Timber.e("setup failed: %s", result.getMessage()); - iabHelper.dispose(); - } - }); } } - private void launchPurchaseFlow(final Activity activity, final String sku, final String pref, - final int requestCode, final PurchaseHelperCallback callback) { + private void launchPurchaseFlow( + final Activity activity, + final String sku, + final String pref, + final int requestCode, + final PurchaseHelperCallback callback) { if (iabHelper != null) { Toast.makeText(activity, R.string.billing_service_busy, Toast.LENGTH_LONG).show(); callback.purchaseCompleted(false, sku); @@ -120,41 +135,47 @@ public class PurchaseHelper implements IabHelper.OnIabSetupFinishedListener { iabHelper = new IabHelper(context, context.getString(R.string.gp_key), executor); iabHelper.enableDebugLogging(BuildConfig.DEBUG); Timber.d("%s: startSetup", iabHelper); - iabHelper.startSetup(result -> { - if (result.isSuccess()) { - try { - Timber.d("%s: launchPurchaseFlow for %s", iabHelper, sku); - iabHelper.launchPurchaseFlow(activity, sku, requestCode, (result1, info) -> { - Timber.d(result1.toString()); - tracker.reportIabResult(result1, sku); - if (result1.isSuccess()) { - if (!Strings.isNullOrEmpty(pref)) { - preferences.setBoolean(pref, true); - localBroadcastManager.broadcastRefresh(); - } - inventory.refreshInventory(); - } else if (result1.getResponse() != IabHelper.BILLING_RESPONSE_RESULT_USER_CANCELED && - result1.getResponse() != IabHelper.IABHELPER_USER_CANCELLED) { - Toast.makeText(activity, result1.getMessage(), Toast.LENGTH_LONG).show(); - } - if (activityResultCallback != null) { - activityResultCallback.purchaseCompleted(result1.isSuccess(), sku); + iabHelper.startSetup( + result -> { + if (result.isSuccess()) { + try { + Timber.d("%s: launchPurchaseFlow for %s", iabHelper, sku); + iabHelper.launchPurchaseFlow( + activity, + sku, + requestCode, + (result1, info) -> { + Timber.d(result1.toString()); + tracker.reportIabResult(result1, sku); + if (result1.isSuccess()) { + if (!Strings.isNullOrEmpty(pref)) { + preferences.setBoolean(pref, true); + localBroadcastManager.broadcastRefresh(); + } + inventory.refreshInventory(); + } else if (result1.getResponse() + != IabHelper.BILLING_RESPONSE_RESULT_USER_CANCELED + && result1.getResponse() != IabHelper.IABHELPER_USER_CANCELLED) { + Toast.makeText(activity, result1.getMessage(), Toast.LENGTH_LONG).show(); + } + if (activityResultCallback != null) { + activityResultCallback.purchaseCompleted(result1.isSuccess(), sku); + } + disposeIabHelper(); + }); + } catch (IllegalStateException e) { + tracker.reportException(e); + Toast.makeText(activity, R.string.billing_service_busy, Toast.LENGTH_LONG).show(); + callback.purchaseCompleted(false, sku); + disposeIabHelper(); } + } else { + Timber.e(result.toString()); + Toast.makeText(activity, result.getMessage(), Toast.LENGTH_LONG).show(); + callback.purchaseCompleted(false, sku); disposeIabHelper(); - }); - } catch (IllegalStateException e) { - tracker.reportException(e); - Toast.makeText(activity, R.string.billing_service_busy, Toast.LENGTH_LONG).show(); - callback.purchaseCompleted(false, sku); - disposeIabHelper(); - } - } else { - Timber.e(result.toString()); - Toast.makeText(activity, result.getMessage(), Toast.LENGTH_LONG).show(); - callback.purchaseCompleted(false, sku); - disposeIabHelper(); - } - }); + } + }); } public void disposeIabHelper() { @@ -165,8 +186,8 @@ public class PurchaseHelper implements IabHelper.OnIabSetupFinishedListener { } } - public void handleActivityResult(PurchaseHelperCallback callback, int requestCode, int resultCode, - Intent data) { + public void handleActivityResult( + PurchaseHelperCallback callback, int requestCode, int resultCode, Intent data) { this.activityResultCallback = callback; if (iabHelper != null) { diff --git a/app/src/googleplay/java/org/tasks/gtasks/PlayServices.java b/app/src/googleplay/java/org/tasks/gtasks/PlayServices.java index c54d42576..b697080c9 100644 --- a/app/src/googleplay/java/org/tasks/gtasks/PlayServices.java +++ b/app/src/googleplay/java/org/tasks/gtasks/PlayServices.java @@ -28,7 +28,9 @@ public class PlayServices { private final GoogleAccountManager accountManager; @Inject - public PlayServices(@ForApplication Context context, Preferences preferences, + public PlayServices( + @ForApplication Context context, + Preferences preferences, GoogleAccountManager googleAccountManager) { this.context = context; this.preferences = preferences; @@ -60,8 +62,9 @@ public class PlayServices { if (googleApiAvailability.isUserResolvableError(error)) { googleApiAvailability.getErrorDialog(activity, error, REQUEST_RESOLUTION).show(); } else { - Toast.makeText(activity, R.string.common_google_play_services_notification_ticker, - Toast.LENGTH_LONG).show(); + Toast.makeText( + activity, R.string.common_google_play_services_notification_ticker, Toast.LENGTH_LONG) + .show(); } } @@ -78,8 +81,8 @@ public class PlayServices { String token = credential.getToken(); Timber.d("Invalidating %s", token); GoogleAuthUtil.clearToken(context, token); - GoogleAuthUtil - .getToken(context, credential.getSelectedAccount(), "oauth2:" + TasksScopes.TASKS, null); + GoogleAuthUtil.getToken( + context, credential.getSelectedAccount(), "oauth2:" + TasksScopes.TASKS, null); return true; } catch (GoogleAuthException e) { Timber.e(e, e.getMessage()); @@ -90,25 +93,30 @@ public class PlayServices { } } - public void getAuthToken(final Activity activity, final String accountName, + public void getAuthToken( + final Activity activity, + final String accountName, final GtasksLoginActivity.AuthResultHandler handler) { final Account account = accountManager.getAccount(accountName); if (account == null) { handler.authenticationFailed( activity.getString(R.string.gtasks_error_accountNotFound, accountName)); } else { - new Thread(() -> { - try { - GoogleAuthUtil.getToken(activity, account, "oauth2:" + TasksScopes.TASKS, null); - handler.authenticationSuccessful(accountName); - } catch (UserRecoverableAuthException e) { - Timber.e(e, e.getMessage()); - activity.startActivityForResult(e.getIntent(), GtasksLoginActivity.RC_REQUEST_OAUTH); - } catch (GoogleAuthException | IOException e) { - Timber.e(e, e.getMessage()); - handler.authenticationFailed(activity.getString(R.string.gtasks_GLA_errorIOAuth)); - } - }).start(); + new Thread( + () -> { + try { + GoogleAuthUtil.getToken(activity, account, "oauth2:" + TasksScopes.TASKS, null); + handler.authenticationSuccessful(accountName); + } catch (UserRecoverableAuthException e) { + Timber.e(e, e.getMessage()); + activity.startActivityForResult( + e.getIntent(), GtasksLoginActivity.RC_REQUEST_OAUTH); + } catch (GoogleAuthException | IOException e) { + Timber.e(e, e.getMessage()); + handler.authenticationFailed(activity.getString(R.string.gtasks_GLA_errorIOAuth)); + } + }) + .start(); } } } diff --git a/app/src/googleplay/java/org/tasks/location/GeofenceApi.java b/app/src/googleplay/java/org/tasks/location/GeofenceApi.java index e59df132f..bf67409c6 100644 --- a/app/src/googleplay/java/org/tasks/location/GeofenceApi.java +++ b/app/src/googleplay/java/org/tasks/location/GeofenceApi.java @@ -31,7 +31,9 @@ public class GeofenceApi { private final PermissionChecker permissionChecker; @Inject - public GeofenceApi(@ForApplication Context context, Preferences preferences, + public GeofenceApi( + @ForApplication Context context, + Preferences preferences, PermissionChecker permissionChecker) { this.context = context; this.preferences = preferences; @@ -43,25 +45,30 @@ public class GeofenceApi { return; } - newClient(client -> { - @SuppressWarnings("ResourceType") - @SuppressLint("MissingPermission") - PendingResult result = LocationServices.GeofencingApi.addGeofences( - client, - getRequests(locations), - PendingIntent.getBroadcast(context, 0, - new Intent(context, GeofenceTransitionsIntentService.Broadcast.class), - PendingIntent.FLAG_UPDATE_CURRENT)); - result.setResultCallback(status -> { - if (status.isSuccess()) { - Timber.i("Registered %s", locations); - } else { - Timber.e("Failed to register %s", locations); - } - - client.disconnect(); - }); - }); + newClient( + client -> { + @SuppressWarnings("ResourceType") + @SuppressLint("MissingPermission") + PendingResult result = + LocationServices.GeofencingApi.addGeofences( + client, + getRequests(locations), + PendingIntent.getBroadcast( + context, + 0, + new Intent(context, GeofenceTransitionsIntentService.Broadcast.class), + PendingIntent.FLAG_UPDATE_CURRENT)); + result.setResultCallback( + status -> { + if (status.isSuccess()) { + Timber.i("Registered %s", locations); + } else { + Timber.e("Failed to register %s", locations); + } + + client.disconnect(); + }); + }); } public void cancel(final Location location) { @@ -75,16 +82,19 @@ public class GeofenceApi { List ids = Lists.transform(locations, geofence -> Long.toString(geofence.getId())); - newClient(client -> LocationServices.GeofencingApi.removeGeofences(client, ids) - .setResultCallback(status -> { - if (status.isSuccess()) { - Timber.i("Removed %s", locations); - } else { - Timber.e("Failed to remove %s", locations); - } - - client.disconnect(); - })); + newClient( + client -> + LocationServices.GeofencingApi.removeGeofences(client, ids) + .setResultCallback( + status -> { + if (status.isSuccess()) { + Timber.i("Removed %s", locations); + } else { + Timber.e("Failed to remove %s", locations); + } + + client.disconnect(); + })); } private void newClient(final GoogleApi.GoogleApiClientConnectionHandler handler) { @@ -97,8 +107,10 @@ public class GeofenceApi { private com.google.android.gms.location.Geofence toGoogleGeofence(Location location) { int radius = preferences.getIntegerFromString(R.string.p_geofence_radius, 250); - int responsiveness = (int) TimeUnit.SECONDS - .toMillis(preferences.getIntegerFromString(R.string.p_geofence_responsiveness, 60)); + int responsiveness = + (int) + TimeUnit.SECONDS.toMillis( + preferences.getIntegerFromString(R.string.p_geofence_responsiveness, 60)); return new com.google.android.gms.location.Geofence.Builder() .setCircularRegion(location.getLatitude(), location.getLongitude(), radius) .setNotificationResponsiveness(responsiveness) diff --git a/app/src/googleplay/java/org/tasks/location/GeofenceTransitionsIntentService.java b/app/src/googleplay/java/org/tasks/location/GeofenceTransitionsIntentService.java index fcf8949c8..e23bcf599 100644 --- a/app/src/googleplay/java/org/tasks/location/GeofenceTransitionsIntentService.java +++ b/app/src/googleplay/java/org/tasks/location/GeofenceTransitionsIntentService.java @@ -33,8 +33,8 @@ public class GeofenceTransitionsIntentService extends InjectingJobIntentService int transitionType = geofencingEvent.getGeofenceTransition(); - List triggeringGeofences = geofencingEvent - .getTriggeringGeofences(); + List triggeringGeofences = + geofencingEvent.getTriggeringGeofences(); Timber.i("Received geofence transition: %s, %s", transitionType, triggeringGeofences); if (transitionType == com.google.android.gms.location.Geofence.GEOFENCE_TRANSITION_ENTER) { for (com.google.android.gms.location.Geofence triggerGeofence : triggeringGeofences) { @@ -64,8 +64,11 @@ public class GeofenceTransitionsIntentService extends InjectingJobIntentService @Override public void onReceive(Context context, Intent intent) { - JobIntentService.enqueueWork(context, GeofenceTransitionsIntentService.class, - JobManager.JOB_ID_GEOFENCE_TRANSITION, intent); + JobIntentService.enqueueWork( + context, + GeofenceTransitionsIntentService.class, + JobManager.JOB_ID_GEOFENCE_TRANSITION, + intent); } } -} \ No newline at end of file +} diff --git a/app/src/googleplay/java/org/tasks/location/GoogleApi.java b/app/src/googleplay/java/org/tasks/location/GoogleApi.java index 2eef930ba..c93fe2ede 100644 --- a/app/src/googleplay/java/org/tasks/location/GoogleApi.java +++ b/app/src/googleplay/java/org/tasks/location/GoogleApi.java @@ -17,23 +17,24 @@ public class GoogleApi implements GoogleApiClient.ConnectionCallbacks { @Inject public GoogleApi(@ForApplication Context context) { - builder = new GoogleApiClient.Builder(context) - .addApi(LocationServices.API) - .addApi(Places.GEO_DATA_API) - .addConnectionCallbacks(this); + builder = + new GoogleApiClient.Builder(context) + .addApi(LocationServices.API) + .addApi(Places.GEO_DATA_API) + .addConnectionCallbacks(this); } public void connect(final GoogleApiClientConnectionHandler googleApiClientConnectionHandler) { - connect(googleApiClientConnectionHandler, + connect( + googleApiClientConnectionHandler, connectionResult -> Timber.e("onConnectionFailed(%s)", connectionResult)); } - private void connect(final GoogleApiClientConnectionHandler googleApiClientConnectionHandler, + private void connect( + final GoogleApiClientConnectionHandler googleApiClientConnectionHandler, GoogleApiClient.OnConnectionFailedListener onConnectionFailedListener) { this.googleApiClientConnectionHandler = googleApiClientConnectionHandler; - googleApiClient = builder - .addOnConnectionFailedListener(onConnectionFailedListener) - .build(); + googleApiClient = builder.addOnConnectionFailedListener(onConnectionFailedListener).build(); googleApiClient.connect(); } diff --git a/app/src/googleplay/java/org/tasks/location/PlacePicker.java b/app/src/googleplay/java/org/tasks/location/PlacePicker.java index 4b026df20..25aa745e7 100644 --- a/app/src/googleplay/java/org/tasks/location/PlacePicker.java +++ b/app/src/googleplay/java/org/tasks/location/PlacePicker.java @@ -25,8 +25,9 @@ public class PlacePicker { activity.startActivity(e.getIntent()); } catch (GooglePlayServicesNotAvailableException e) { Timber.e(e, e.getMessage()); - Toast.makeText(activity, R.string.common_google_play_services_notification_ticker, - Toast.LENGTH_LONG).show(); + Toast.makeText( + activity, R.string.common_google_play_services_notification_ticker, Toast.LENGTH_LONG) + .show(); } return null; } diff --git a/app/src/main/java/com/mdimension/jchronic/AstridChronic.java b/app/src/main/java/com/mdimension/jchronic/AstridChronic.java index 625460558..65ae3d4a0 100644 --- a/app/src/main/java/com/mdimension/jchronic/AstridChronic.java +++ b/app/src/main/java/com/mdimension/jchronic/AstridChronic.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.mdimension.jchronic; import com.mdimension.jchronic.handlers.Handler; @@ -30,47 +29,41 @@ public class AstridChronic { } /** - * 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. + * 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: + *

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

[: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. + *

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) + *

[: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 + *

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+) + *

[: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. + *

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)) + *

[: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. + *

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. */ private static Span parse(String text, Options options) { // store now for later =) - //_now = options.getNow(); + // _now = options.getNow(); // put the text into a normal format to ease scanning String normalizedText = AstridChronic.preNormalize(text); @@ -114,10 +107,9 @@ public class AstridChronic { } /** - * 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) + * 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) */ private static String preNormalize(String text) { String normalizedText = text.toLowerCase(); @@ -135,8 +127,8 @@ public class AstridChronic { 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("\\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"); @@ -144,17 +136,12 @@ public class AstridChronic { return normalizedText; } - /** - * Convert ordinal words to numeric ordinals (third => 3rd) - */ + /** Convert ordinal words to numeric ordinals (third => 3rd) */ private static String numericizeOrdinals(String text) { return text; } - /** - * Split the text on spaces and convert each word into - * a Token - */ + /** Split the text on spaces and convert each word into a Token */ private static List baseTokenize(String text) { String[] words = text.split(" "); List tokens = new LinkedList<>(); @@ -164,9 +151,7 @@ public class AstridChronic { return tokens; } - /** - * Guess a specific time within the given span - */ + /** Guess a specific time within the given span */ // DIFF: We return Span instead of Date private static Span guess(Span span) { if (span == null) { diff --git a/app/src/main/java/com/todoroo/andlib/data/Property.java b/app/src/main/java/com/todoroo/andlib/data/Property.java index 96bc014ad..a5dc83728 100644 --- a/app/src/main/java/com/todoroo/andlib/data/Property.java +++ b/app/src/main/java/com/todoroo/andlib/data/Property.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.andlib.data; import android.text.TextUtils; @@ -12,9 +11,9 @@ import com.todoroo.andlib.sql.Field; /** * 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. + *

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 @@ -23,37 +22,27 @@ public abstract class Property extends Field implements Cloneable { // --- implementation - /** - * The database table name this property - */ - private final Table table; - - /** - * The database column name for this property - */ + /** The database column name for this property */ public final String name; + /** The database table name this property */ + private final Table table; /** - * Create a property by table and column name. Uses the default property - * expression which is derived from default table name + * Create a property by table and column name. Uses the default property expression which is + * derived from default table name */ Property(Table table, String columnName) { this(table, columnName, (table == null) ? (columnName) : (table.name() + "." + columnName)); } - /** - * Create a property by table and column name, manually specifying an - * expression to use in SQL - */ + /** Create a property by table and column name, manually specifying an expression to use in SQL */ Property(Table table, String columnName, String expression) { super(expression); this.table = table; this.name = columnName; } - /** - * Return a clone of this property - */ + /** Return a clone of this property */ @Override public Property clone() { try { @@ -63,9 +52,7 @@ public abstract class Property extends Field implements Cloneable { } } - /** - * Return a clone of this property - */ + /** Return a clone of this property */ Property cloneAs(String tableAlias, String columnAlias) { Table aliasedTable = this.table; if (!TextUtils.isEmpty(tableAlias)) { @@ -73,8 +60,10 @@ public abstract class Property extends Field implements Cloneable { } try { - Property newInstance = this.getClass().getConstructor(Table.class, String.class) - .newInstance(aliasedTable, this.name); + Property newInstance = + this.getClass() + .getConstructor(Table.class, String.class) + .newInstance(aliasedTable, this.name); if (!TextUtils.isEmpty(columnAlias)) { return (Property) newInstance.as(columnAlias); } @@ -136,9 +125,7 @@ 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 CountProperty extends IntegerProperty { public CountProperty() { diff --git a/app/src/main/java/com/todoroo/andlib/data/Table.java b/app/src/main/java/com/todoroo/andlib/data/Table.java index 86a565713..e85ffed6c 100644 --- a/app/src/main/java/com/todoroo/andlib/data/Table.java +++ b/app/src/main/java/com/todoroo/andlib/data/Table.java @@ -1,16 +1,15 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.andlib.data; import com.todoroo.andlib.sql.SqlTable; /** - * Table class. Most fields are final, so methods such as as will - * clone the table when it returns. + * Table class. Most fields are final, so methods such as as will clone the table when + * it returns. * * @author Tim Su */ @@ -28,9 +27,7 @@ public final class Table extends SqlTable { this.alias = alias; } - /** - * Create a new join table based on this table, but with an alias - */ + /** Create a new join table based on this table, but with an alias */ @Override public Table as(String newAlias) { return new Table(name, newAlias); @@ -39,7 +36,7 @@ public final class Table extends SqlTable { @Override public String toString() { if (hasAlias()) { - return expression + " AS " + alias; //$NON-NLS-1$ + return expression + " AS " + alias; // $NON-NLS-1$ } return expression; } diff --git a/app/src/main/java/com/todoroo/andlib/sql/Criterion.java b/app/src/main/java/com/todoroo/andlib/sql/Criterion.java index d8b2e5134..2a0423ae3 100644 --- a/app/src/main/java/com/todoroo/andlib/sql/Criterion.java +++ b/app/src/main/java/com/todoroo/andlib/sql/Criterion.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.andlib.sql; import static com.todoroo.andlib.sql.SqlConstants.AND; @@ -15,12 +14,13 @@ import static com.todoroo.andlib.sql.SqlConstants.SPACE; public abstract class Criterion { - public static final Criterion all = new Criterion(Operator.exists) { - @Override - protected void populate(StringBuilder sb) { - sb.append(1); - } - }; + public static final Criterion all = + new Criterion(Operator.exists) { + @Override + protected void populate(StringBuilder sb) { + sb.append(1); + } + }; final Operator operator; public Criterion(Operator operator) { @@ -73,5 +73,4 @@ public abstract class Criterion { builder.append(RIGHT_PARENTHESIS); return builder.toString(); } - } diff --git a/app/src/main/java/com/todoroo/andlib/sql/DBObject.java b/app/src/main/java/com/todoroo/andlib/sql/DBObject.java index 1522f387c..f40fa8423 100644 --- a/app/src/main/java/com/todoroo/andlib/sql/DBObject.java +++ b/app/src/main/java/com/todoroo/andlib/sql/DBObject.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.andlib.sql; import static com.todoroo.andlib.sql.SqlConstants.AS; @@ -46,7 +45,8 @@ public abstract class DBObject> implements Cloneable { if (alias != null ? !alias.equals(dbObject.alias) : dbObject.alias != null) { return false; } - if (expression != null ? !expression.equals(dbObject.expression) + if (expression != null + ? !expression.equals(dbObject.expression) : dbObject.expression != null) { return false; } diff --git a/app/src/main/java/com/todoroo/andlib/sql/Field.java b/app/src/main/java/com/todoroo/andlib/sql/Field.java index 2a4c29a8c..e5ecce03e 100644 --- a/app/src/main/java/com/todoroo/andlib/sql/Field.java +++ b/app/src/main/java/com/todoroo/andlib/sql/Field.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.andlib.sql; import static com.todoroo.andlib.sql.SqlConstants.COMMA; @@ -57,7 +56,11 @@ public class Field extends DBObject { @Override protected void populate(StringBuilder sb) { - sb.append(field).append(SPACE).append(Operator.in).append(SPACE).append(LEFT_PARENTHESIS) + sb.append(field) + .append(SPACE) + .append(Operator.in) + .append(SPACE) + .append(LEFT_PARENTHESIS) .append(SPACE); for (T t : value) { sb.append(t.toString()).append(COMMA); @@ -73,7 +76,11 @@ public class Field extends DBObject { @Override protected void populate(StringBuilder sb) { - sb.append(field).append(SPACE).append(Operator.in).append(SPACE).append(LEFT_PARENTHESIS) + sb.append(field) + .append(SPACE) + .append(Operator.in) + .append(SPACE) + .append(LEFT_PARENTHESIS) .append(query) .append(RIGHT_PARENTHESIS); } diff --git a/app/src/main/java/com/todoroo/andlib/sql/Functions.java b/app/src/main/java/com/todoroo/andlib/sql/Functions.java index 78a2774b0..77da6a46f 100644 --- a/app/src/main/java/com/todoroo/andlib/sql/Functions.java +++ b/app/src/main/java/com/todoroo/andlib/sql/Functions.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.andlib.sql; public final class Functions { @@ -12,9 +11,7 @@ public final class Functions { return new Field("UPPER(" + title.toString() + ")"); } - /** - * @return SQL now (in milliseconds) - */ + /** @return SQL now (in milliseconds) */ public static Field now() { return new Field("(strftime('%s','now')*1000)"); } diff --git a/app/src/main/java/com/todoroo/andlib/sql/Join.java b/app/src/main/java/com/todoroo/andlib/sql/Join.java index 4df5717b4..59929e6a6 100644 --- a/app/src/main/java/com/todoroo/andlib/sql/Join.java +++ b/app/src/main/java/com/todoroo/andlib/sql/Join.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.andlib.sql; import static com.todoroo.andlib.sql.SqlConstants.AND; @@ -34,8 +33,15 @@ public class Join { @Override public String toString() { StringBuilder sb = new StringBuilder(); - sb.append(joinType).append(SPACE).append(JOIN).append(SPACE).append(joinTable).append(SPACE) - .append(ON).append(SPACE).append("("); + sb.append(joinType) + .append(SPACE) + .append(JOIN) + .append(SPACE) + .append(joinTable) + .append(SPACE) + .append(ON) + .append(SPACE) + .append("("); for (int i = 0; i < criterions.length; i++) { sb.append(criterions[i]); if (i < criterions.length - 1) { diff --git a/app/src/main/java/com/todoroo/andlib/sql/JoinType.java b/app/src/main/java/com/todoroo/andlib/sql/JoinType.java index f59d26a27..14078d16b 100644 --- a/app/src/main/java/com/todoroo/andlib/sql/JoinType.java +++ b/app/src/main/java/com/todoroo/andlib/sql/JoinType.java @@ -1,11 +1,11 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.andlib.sql; public enum JoinType { - INNER, LEFT + INNER, + LEFT } diff --git a/app/src/main/java/com/todoroo/andlib/sql/Operator.java b/app/src/main/java/com/todoroo/andlib/sql/Operator.java index 403e834b5..1af320c16 100644 --- a/app/src/main/java/com/todoroo/andlib/sql/Operator.java +++ b/app/src/main/java/com/todoroo/andlib/sql/Operator.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.andlib.sql; public final class Operator { diff --git a/app/src/main/java/com/todoroo/andlib/sql/Order.java b/app/src/main/java/com/todoroo/andlib/sql/Order.java index f35182425..14f0ecd02 100644 --- a/app/src/main/java/com/todoroo/andlib/sql/Order.java +++ b/app/src/main/java/com/todoroo/andlib/sql/Order.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.andlib.sql; import static com.todoroo.andlib.sql.SqlConstants.SPACE; @@ -42,12 +41,10 @@ public class Order { @Override public String toString() { StringBuilder sb = new StringBuilder(); - sb.append(expression.toString()) - .append(SPACE) - .append(orderType.toString()); + sb.append(expression.toString()).append(SPACE).append(orderType.toString()); for (Order secondary : secondaryExpressions) { - sb.append(", ").append(secondary.toString()); //$NON-NLS-1$ + sb.append(", ").append(secondary.toString()); // $NON-NLS-1$ } return sb.toString(); diff --git a/app/src/main/java/com/todoroo/andlib/sql/OrderType.java b/app/src/main/java/com/todoroo/andlib/sql/OrderType.java index 2b126be91..8ede3e3cb 100644 --- a/app/src/main/java/com/todoroo/andlib/sql/OrderType.java +++ b/app/src/main/java/com/todoroo/andlib/sql/OrderType.java @@ -1,11 +1,11 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.andlib.sql; public enum OrderType { - DESC, ASC + DESC, + ASC } diff --git a/app/src/main/java/com/todoroo/andlib/sql/Query.java b/app/src/main/java/com/todoroo/andlib/sql/Query.java index c63fe9e92..356676609 100644 --- a/app/src/main/java/com/todoroo/andlib/sql/Query.java +++ b/app/src/main/java/com/todoroo/andlib/sql/Query.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.andlib.sql; import static com.todoroo.andlib.sql.SqlConstants.ALL; @@ -49,8 +48,8 @@ public final class Query { @Override public boolean equals(Object o) { - return this == o || !(o == null || getClass() != o.getClass()) && this.toString() - .equals(o.toString()); + return this == o + || !(o == null || getClass() != o.getClass()) && this.toString().equals(o.toString()); } @Override diff --git a/app/src/main/java/com/todoroo/andlib/sql/QueryTemplate.java b/app/src/main/java/com/todoroo/andlib/sql/QueryTemplate.java index a7b3b1ba8..97c625c85 100644 --- a/app/src/main/java/com/todoroo/andlib/sql/QueryTemplate.java +++ b/app/src/main/java/com/todoroo/andlib/sql/QueryTemplate.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.andlib.sql; import static com.todoroo.andlib.sql.SqlConstants.COMMA; @@ -16,8 +15,7 @@ import static java.util.Arrays.asList; import java.util.ArrayList; /** - * Query Template returns a bunch of criteria that allows a query to be - * constructed + * Query Template returns a bunch of criteria that allows a query to be constructed * * @author Tim Su */ diff --git a/app/src/main/java/com/todoroo/andlib/sql/SqlConstants.java b/app/src/main/java/com/todoroo/andlib/sql/SqlConstants.java index 851e8af5f..f232f6da3 100644 --- a/app/src/main/java/com/todoroo/andlib/sql/SqlConstants.java +++ b/app/src/main/java/com/todoroo/andlib/sql/SqlConstants.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.andlib.sql; final class SqlConstants { diff --git a/app/src/main/java/com/todoroo/andlib/sql/SqlTable.java b/app/src/main/java/com/todoroo/andlib/sql/SqlTable.java index 01911f4f0..86f6b95e5 100644 --- a/app/src/main/java/com/todoroo/andlib/sql/SqlTable.java +++ b/app/src/main/java/com/todoroo/andlib/sql/SqlTable.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.andlib.sql; public class SqlTable extends DBObject { diff --git a/app/src/main/java/com/todoroo/andlib/sql/UnaryCriterion.java b/app/src/main/java/com/todoroo/andlib/sql/UnaryCriterion.java index 6f39ae928..59732011a 100644 --- a/app/src/main/java/com/todoroo/andlib/sql/UnaryCriterion.java +++ b/app/src/main/java/com/todoroo/andlib/sql/UnaryCriterion.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.andlib.sql; import static com.todoroo.andlib.sql.SqlConstants.SPACE; @@ -23,9 +22,7 @@ public class UnaryCriterion extends Criterion { return new UnaryCriterion(expression, Operator.eq, value); } - /** - * Sanitize the given input for SQL - */ + /** Sanitize the given input for SQL */ public static String sanitize(String input) { return input.replace("'", "''"); } diff --git a/app/src/main/java/com/todoroo/andlib/utility/AndroidUtilities.java b/app/src/main/java/com/todoroo/andlib/utility/AndroidUtilities.java index e8d6c3dcf..41c9176cd 100644 --- a/app/src/main/java/com/todoroo/andlib/utility/AndroidUtilities.java +++ b/app/src/main/java/com/todoroo/andlib/utility/AndroidUtilities.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.andlib.utility; import android.app.Activity; @@ -32,29 +31,26 @@ import timber.log.Timber; */ public class AndroidUtilities { - public static final String SEPARATOR_ESCAPE = "!PIPE!"; //$NON-NLS-1$ - public static final String SERIALIZATION_SEPARATOR = "|"; //$NON-NLS-1$ + public static final String SEPARATOR_ESCAPE = "!PIPE!"; // $NON-NLS-1$ + public static final String SERIALIZATION_SEPARATOR = "|"; // $NON-NLS-1$ // --- 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); - editor.setOnTouchListener((v, event) -> { - editor.setInputType(inputType); - editor.setOnTouchListener(null); - return false; - }); + editor.setOnTouchListener( + (v, event) -> { + editor.setInputType(inputType); + editor.setOnTouchListener(null); + return false; + }); } // --- serialization - /** - * Serializes a content value into a string - */ + /** Serializes a content value into a string */ public static String mapToSerializedString(Map source) { StringBuilder result = new StringBuilder(); for (Entry entry : source.entrySet()) { @@ -63,13 +59,11 @@ public class AndroidUtilities { return result.toString(); } - /** - * add serialized helper - */ - private static void addSerialized(StringBuilder result, - String key, Object value) { - result.append(key.replace(SERIALIZATION_SEPARATOR, SEPARATOR_ESCAPE)).append( - SERIALIZATION_SEPARATOR); + /** add serialized helper */ + private static void addSerialized(StringBuilder result, String key, Object value) { + result + .append(key.replace(SERIALIZATION_SEPARATOR, SEPARATOR_ESCAPE)) + .append(SERIALIZATION_SEPARATOR); if (value instanceof Integer) { result.append('i').append(value); } else if (value instanceof Double) { @@ -77,7 +71,8 @@ public class AndroidUtilities { } else if (value instanceof Long) { result.append('l').append(value); } else if (value instanceof String) { - result.append('s') + result + .append('s') .append(value.toString().replace(SERIALIZATION_SEPARATOR, SEPARATOR_ESCAPE)); } else if (value instanceof Boolean) { result.append('b').append(value); @@ -93,30 +88,33 @@ public class AndroidUtilities { } Map result = new HashMap<>(); - fromSerialized(string, result, (object, key, type, value) -> { - 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; - } - }); + fromSerialized( + string, + result, + (object, key, type, value) -> { + 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; + } + }); return result; } private static void fromSerialized(String string, T object, SerializedPut putter) { - String[] pairs = string.split("\\" + SERIALIZATION_SEPARATOR); //$NON-NLS-1$ + String[] pairs = string.split("\\" + SERIALIZATION_SEPARATOR); // $NON-NLS-1$ for (int i = 0; i < pairs.length; i += 2) { try { String key = pairs[i].replaceAll(SEPARATOR_ESCAPE, SERIALIZATION_SEPARATOR); @@ -134,9 +132,7 @@ public class AndroidUtilities { } } - /** - * Copy a file from one place to another - */ + /** Copy a file from one place to another */ public static void copyFile(File in, File out) throws Exception { FileInputStream fis = new FileInputStream(in); FileOutputStream fos = new FileOutputStream(out); @@ -148,9 +144,7 @@ public class AndroidUtilities { } } - /** - * Copy stream from source to destination - */ + /** Copy stream from source to destination */ private static void copyStream(InputStream source, OutputStream dest) throws IOException { int bytes; byte[] buffer; @@ -218,8 +212,8 @@ public class AndroidUtilities { } /** - * Sleep, ignoring interruption. Before using this method, think carefully - * about why you are ignoring interruptions. + * Sleep, ignoring interruption. Before using this method, think carefully about why you are + * ignoring interruptions. */ public static void sleepDeep(long l) { try { @@ -229,9 +223,7 @@ public class AndroidUtilities { } } - /** - * Capitalize the first character - */ + /** Capitalize the first character */ public static String capitalize(String string) { return string.substring(0, 1).toUpperCase() + string.substring(1); } @@ -240,8 +232,8 @@ public class AndroidUtilities { try { View currentFocus = activity.getCurrentFocus(); if (currentFocus != null) { - InputMethodManager inputMethodManager = (InputMethodManager) activity - .getSystemService(Context.INPUT_METHOD_SERVICE); + InputMethodManager inputMethodManager = + (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(currentFocus.getWindowToken(), 0); } } catch (Exception e) { @@ -255,16 +247,14 @@ public class AndroidUtilities { * @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); + InputMethodManager imm = + (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); for (View v : views) { imm.hideSoftInputFromWindow(v.getWindowToken(), 0); } } - /** - * Returns the final word characters after the last '.' - */ + /** Returns the final word characters after the last '.' */ public static String getFileExtension(String file) { int index = file.lastIndexOf('.'); String extension = ""; diff --git a/app/src/main/java/com/todoroo/andlib/utility/DateUtilities.java b/app/src/main/java/com/todoroo/andlib/utility/DateUtilities.java index f6264bc56..bdaeaa0aa 100644 --- a/app/src/main/java/com/todoroo/andlib/utility/DateUtilities.java +++ b/app/src/main/java/com/todoroo/andlib/utility/DateUtilities.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.andlib.utility; import static org.tasks.date.DateTimeUtils.newDateTime; @@ -16,25 +15,17 @@ import org.tasks.R; import org.tasks.locale.Locale; import org.tasks.time.DateTime; - public class DateUtilities { - /** - * 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; + private static final long abbreviationLimit = DateUtilities.ONE_DAY * 6; private static final String JA = "MMM d\u65E5"; private static final String JA_YEAR = "yy\u5E74 " + JA; @@ -45,8 +36,8 @@ public class DateUtilities { static Boolean is24HourOverride = null; /** - * Add the specified amount of months to the given time.
- * The day of month will stay the same.
+ * 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 interval the amount of months to be added @@ -63,9 +54,7 @@ public class DateUtilities { return result.getMillis(); } - /** - * Returns unixtime for current time - */ + /** Returns unixtime for current time */ public static long now() { return currentTimeMillis(); } @@ -74,9 +63,7 @@ public class DateUtilities { * =========================================================== formatters * ====================================================================== */ - /** - * Returns unixtime one month from now - */ + /** Returns unixtime one month from now */ public static long oneMonthFromNow() { return addCalendarMonthsToUnixtime(currentTimeMillis(), 1); } @@ -138,26 +125,18 @@ public class DateUtilities { case "KE": case "MN": case "US": - return includeYear - ? monthFormat + " d ''yy" - : monthFormat + " d"; + return includeYear ? monthFormat + " d ''yy" : monthFormat + " d"; default: - return includeYear - ? "d " + monthFormat + " ''yy" - : "d " + monthFormat; + return includeYear ? "d " + monthFormat + " ''yy" : "d " + monthFormat; } } - /** - * @return weekday - */ + /** @return weekday */ public static String getWeekday(DateTime date) { return date.toString("EEEE"); } - /** - * @return weekday - */ + /** @return weekday */ public static String getWeekdayShort(DateTime date) { return date.toString("EEE"); } @@ -175,15 +154,16 @@ public class DateUtilities { public static String getRelativeDateStringWithTime(Context context, long timestamp) { String string = DateUtilities.getRelativeDay(context, timestamp, false); if (Task.hasDueTime(timestamp)) { - string = String.format("%s %s", string, //$NON-NLS-1$ - DateUtilities.getTimeString(context, timestamp)); + string = + String.format( + "%s %s", + string, // $NON-NLS-1$ + DateUtilities.getTimeString(context, timestamp)); } return string; } - /** - * @return yesterday, today, tomorrow, or null - */ + /** @return yesterday, today, tomorrow, or null */ public static String getRelativeDay(Context context, long date, boolean abbreviated) { long today = getStartOfDay(currentTimeMillis()); long input = getStartOfDay(date); @@ -201,7 +181,8 @@ public class DateUtilities { } if (today + abbreviationLimit >= input && today - abbreviationLimit <= input) { - return abbreviated ? DateUtilities.getWeekdayShort(newDateTime(date)) + return abbreviated + ? DateUtilities.getWeekdayShort(newDateTime(date)) : DateUtilities.getWeekday(newDateTime(date)); } diff --git a/app/src/main/java/com/todoroo/andlib/utility/DialogUtilities.java b/app/src/main/java/com/todoroo/andlib/utility/DialogUtilities.java index 801ef7469..3f6549c33 100644 --- a/app/src/main/java/com/todoroo/andlib/utility/DialogUtilities.java +++ b/app/src/main/java/com/todoroo/andlib/utility/DialogUtilities.java @@ -1,32 +1,29 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.andlib.utility; - import android.app.Activity; import android.app.Dialog; import timber.log.Timber; public class DialogUtilities { - /** - * Dismiss a dialog off the UI thread - */ + /** Dismiss a dialog off the UI thread */ @Deprecated public static void dismissDialog(Activity activity, final Dialog dialog) { if (dialog == null) { return; } - activity.runOnUiThread(() -> { - try { - dialog.dismiss(); - } catch (Exception e) { - Timber.e(e, e.getMessage()); - } - }); + activity.runOnUiThread( + () -> { + try { + dialog.dismiss(); + } catch (Exception e) { + Timber.e(e, e.getMessage()); + } + }); } } diff --git a/app/src/main/java/com/todoroo/astrid/activity/BeastModePreferences.java b/app/src/main/java/com/todoroo/astrid/activity/BeastModePreferences.java index 081e1a6f5..55609bd9b 100644 --- a/app/src/main/java/com/todoroo/astrid/activity/BeastModePreferences.java +++ b/app/src/main/java/com/todoroo/astrid/activity/BeastModePreferences.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.activity; import static java.util.Arrays.asList; @@ -29,13 +28,18 @@ import org.tasks.preferences.Preferences; import org.tasks.preferences.beast.BeastModeRecyclerAdapter; import org.tasks.ui.MenuColorizer; -public class BeastModePreferences extends ThemedInjectingAppCompatActivity implements - Toolbar.OnMenuItemClickListener { +public class BeastModePreferences extends ThemedInjectingAppCompatActivity + implements Toolbar.OnMenuItemClickListener { - private static final String BEAST_MODE_ORDER_PREF = "beast_mode_order_v3"; //$NON-NLS-1$ + private static final String BEAST_MODE_ORDER_PREF = "beast_mode_order_v3"; // $NON-NLS-1$ private static final String BEAST_MODE_PREF_ITEM_SEPARATOR = ";"; - @BindView(R.id.toolbar) Toolbar toolbar; - @BindView(R.id.recycler_view) RecyclerView recyclerView; + + @BindView(R.id.toolbar) + Toolbar toolbar; + + @BindView(R.id.recycler_view) + RecyclerView recyclerView; + @Inject Preferences preferences; private BeastModeRecyclerAdapter adapter; @@ -53,8 +57,8 @@ public class BeastModePreferences extends ThemedInjectingAppCompatActivity imple preferences.setString(BEAST_MODE_ORDER_PREF, newSetting.toString()); } - public static ArrayList constructOrderedControlList(Preferences preferences, - Context context) { + public static ArrayList constructOrderedControlList( + Preferences preferences, Context context) { String order = preferences.getStringValue(BEAST_MODE_ORDER_PREF); ArrayList list = new ArrayList<>(); String[] itemsArray; diff --git a/app/src/main/java/com/todoroo/astrid/activity/ShareLinkActivity.java b/app/src/main/java/com/todoroo/astrid/activity/ShareLinkActivity.java index 919267164..07327406f 100644 --- a/app/src/main/java/com/todoroo/astrid/activity/ShareLinkActivity.java +++ b/app/src/main/java/com/todoroo/astrid/activity/ShareLinkActivity.java @@ -1,7 +1,4 @@ -/** - * TODO: make this lightweight, don't extend the entire TaskListActivity - */ - +/** TODO: make this lightweight, don't extend the entire TaskListActivity */ package com.todoroo.astrid.activity; import static org.tasks.intents.TaskIntents.getEditTaskStack; @@ -17,8 +14,7 @@ import org.tasks.injection.InjectingAppCompatActivity; /** * @author joshuagross - * - * Create a new task based on incoming links from the "share" menu + *

Create a new task based on incoming links from the "share" menu */ public final class ShareLinkActivity extends InjectingAppCompatActivity { diff --git a/app/src/main/java/com/todoroo/astrid/activity/TaskEditFragment.java b/app/src/main/java/com/todoroo/astrid/activity/TaskEditFragment.java index 35f20f5f2..2b640a396 100755 --- a/app/src/main/java/com/todoroo/astrid/activity/TaskEditFragment.java +++ b/app/src/main/java/com/todoroo/astrid/activity/TaskEditFragment.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.activity; import static org.tasks.date.DateTimeUtils.newDateTime; @@ -53,8 +52,8 @@ import org.tasks.ui.MenuColorizer; import org.tasks.ui.RemoteListFragment; import org.tasks.ui.TaskEditControlFragment; -public final class TaskEditFragment extends InjectingFragment implements - Toolbar.OnMenuItemClickListener { +public final class TaskEditFragment extends InjectingFragment + implements Toolbar.OnMenuItemClickListener { public static final String TAG_TASKEDIT_FRAGMENT = "taskedit_fragment"; private static final String EXTRA_TASK = "extra_task"; @@ -70,9 +69,16 @@ public final class TaskEditFragment extends InjectingFragment implements @Inject Tracker tracker; @Inject TimerPlugin timerPlugin; @Inject LocalBroadcastManager localBroadcastManager; - @BindView(R.id.toolbar) Toolbar toolbar; - @BindView(R.id.comments) LinearLayout comments; - @BindView(R.id.control_sets) LinearLayout controlSets; + + @BindView(R.id.toolbar) + Toolbar toolbar; + + @BindView(R.id.comments) + LinearLayout comments; + + @BindView(R.id.control_sets) + LinearLayout controlSets; + Task model = null; private TaskEditFragmentCallbackHandler callback; @@ -97,8 +103,8 @@ public final class TaskEditFragment extends InjectingFragment implements } @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_task_edit, container, false); ButterKnife.bind(this, view); @@ -106,15 +112,17 @@ public final class TaskEditFragment extends InjectingFragment implements model = arguments.getParcelable(EXTRA_TASK); final boolean backButtonSavesTask = preferences.backButtonSavesTask(); - toolbar.setNavigationIcon(ContextCompat.getDrawable(context, - backButtonSavesTask ? R.drawable.ic_close_24dp : R.drawable.ic_save_24dp)); - toolbar.setNavigationOnClickListener(v -> { - if (backButtonSavesTask) { - discardButtonClick(); - } else { - save(); - } - }); + toolbar.setNavigationIcon( + ContextCompat.getDrawable( + context, backButtonSavesTask ? R.drawable.ic_close_24dp : R.drawable.ic_save_24dp)); + toolbar.setNavigationOnClickListener( + v -> { + if (backButtonSavesTask) { + discardButtonClick(); + } else { + save(); + } + }); toolbar.inflateMenu(R.menu.menu_task_edit_fragment); toolbar.setOnMenuItemClickListener(this); MenuColorizer.colorToolbar(context, toolbar); @@ -127,16 +135,17 @@ public final class TaskEditFragment extends InjectingFragment implements commentsController.reloadView(); FragmentManager fragmentManager = getChildFragmentManager(); - List taskEditControlFragments = taskEditControlSetFragmentManager - .getOrCreateFragments(fragmentManager, model); + List taskEditControlFragments = + taskEditControlSetFragmentManager.getOrCreateFragments(fragmentManager, model); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); for (int i = 0; i < taskEditControlFragments.size(); i++) { TaskEditControlFragment taskEditControlFragment = taskEditControlFragments.get(i); String tag = getString(taskEditControlFragment.controlId()); - fragmentTransaction - .replace(TaskEditControlSetFragmentManager.TASK_EDIT_CONTROL_FRAGMENT_ROWS[i], - taskEditControlFragment, tag); + fragmentTransaction.replace( + TaskEditControlSetFragmentManager.TASK_EDIT_CONTROL_FRAGMENT_ROWS[i], + taskEditControlFragment, + tag); } fragmentTransaction.commit(); @@ -163,29 +172,32 @@ public final class TaskEditFragment extends InjectingFragment implements public Task stopTimer() { timerPlugin.stopTimer(model); String elapsedTime = DateUtils.formatElapsedTime(model.getElapsedSeconds()); - addComment(String.format("%s %s\n%s %s", //$NON-NLS-1$ - getString(R.string.TEA_timer_comment_stopped), - DateUtilities.getTimeString(getActivity(), newDateTime()), - getString(R.string.TEA_timer_comment_spent), - elapsedTime), null); + addComment( + String.format( + "%s %s\n%s %s", // $NON-NLS-1$ + getString(R.string.TEA_timer_comment_stopped), + DateUtilities.getTimeString(getActivity(), newDateTime()), + getString(R.string.TEA_timer_comment_spent), + elapsedTime), + null); return model; } public Task startTimer() { timerPlugin.startTimer(model); - addComment(String.format("%s %s", - getString(R.string.TEA_timer_comment_started), - DateUtilities.getTimeString(getActivity(), newDateTime())), + addComment( + String.format( + "%s %s", + getString(R.string.TEA_timer_comment_started), + DateUtilities.getTimeString(getActivity(), newDateTime())), null); return model; } - /** - * Save task model from values in UI components - */ + /** Save task model from values in UI components */ public void save() { - List fragments = taskEditControlSetFragmentManager - .getFragmentsInPersistOrder(getChildFragmentManager()); + List fragments = + taskEditControlSetFragmentManager.getFragmentsInPersistOrder(getChildFragmentManager()); if (hasChanges(fragments)) { boolean isNewTask = model.isNew(); if (isNewTask) { @@ -201,9 +213,7 @@ public final class TaskEditFragment extends InjectingFragment implements } if (isNewTask) { - ((TaskListActivity) getActivity()) - .getTaskListFragment() - .onTaskCreated(model.getUuid()); + ((TaskListActivity) getActivity()).getTaskListFragment().onTaskCreated(model.getUuid()); } callback.taskEditFinished(); } else { @@ -260,7 +270,8 @@ public final class TaskEditFragment extends InjectingFragment implements public void discardButtonClick() { if (hasChanges( taskEditControlSetFragmentManager.getFragmentsInPersistOrder(getChildFragmentManager()))) { - dialogBuilder.newMessageDialog(R.string.discard_confirmation) + dialogBuilder + .newMessageDialog(R.string.discard_confirmation) .setPositiveButton(R.string.keep_editing, null) .setNegativeButton(R.string.discard, (dialog, which) -> discard()) .show(); @@ -278,12 +289,15 @@ public final class TaskEditFragment extends InjectingFragment implements } private void deleteButtonClick() { - dialogBuilder.newMessageDialog(R.string.DLG_delete_this_task_question) - .setPositiveButton(android.R.string.ok, (dialog, which) -> { - timerPlugin.stopTimer(model); - taskDeleter.markDeleted(model); - callback.taskEditFinished(); - }) + dialogBuilder + .newMessageDialog(R.string.DLG_delete_this_task_question) + .setPositiveButton( + android.R.string.ok, + (dialog, which) -> { + timerPlugin.stopTimer(model); + taskDeleter.markDeleted(model); + callback.taskEditFinished(); + }) .setNegativeButton(android.R.string.cancel, null) .show(); } diff --git a/app/src/main/java/com/todoroo/astrid/activity/TaskListActivity.java b/app/src/main/java/com/todoroo/astrid/activity/TaskListActivity.java index 3e9bf80c9..4ddaebab5 100644 --- a/app/src/main/java/com/todoroo/astrid/activity/TaskListActivity.java +++ b/app/src/main/java/com/todoroo/astrid/activity/TaskListActivity.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.activity; import static com.todoroo.andlib.utility.AndroidUtilities.atLeastLollipop; @@ -73,26 +72,25 @@ import org.tasks.ui.PriorityControlSet; import org.tasks.ui.TaskListViewModel; import timber.log.Timber; -public class TaskListActivity extends InjectingAppCompatActivity implements - OnFilterItemClickedListener, - TaskListFragment.TaskListFragmentCallbackHandler, - PriorityControlSet.OnPriorityChanged, - TimerControlSet.TimerControlSetCallback, - RepeatControlSet.RepeatChangedListener, - DeadlineControlSet.DueDateChangeListener, - TaskEditFragment.TaskEditFragmentCallbackHandler, - CommentBarFragment.CommentBarFragmentCallback, - SortDialog.SortDialogCallback, - RemoteListSelectionHandler { - - /** - * For indicating the new list screen should be launched at fragment setup time - */ - public static final String TOKEN_CREATE_NEW_LIST_NAME = "newListName"; //$NON-NLS-1$ - public static final String OPEN_FILTER = "open_filter"; //$NON-NLS-1$ +public class TaskListActivity extends InjectingAppCompatActivity + implements OnFilterItemClickedListener, + TaskListFragment.TaskListFragmentCallbackHandler, + PriorityControlSet.OnPriorityChanged, + TimerControlSet.TimerControlSetCallback, + RepeatControlSet.RepeatChangedListener, + DeadlineControlSet.DueDateChangeListener, + TaskEditFragment.TaskEditFragmentCallbackHandler, + CommentBarFragment.CommentBarFragmentCallback, + SortDialog.SortDialogCallback, + RemoteListSelectionHandler { + + /** For indicating the new list screen should be launched at fragment setup time */ + public static final String TOKEN_CREATE_NEW_LIST_NAME = "newListName"; // $NON-NLS-1$ + + public static final String OPEN_FILTER = "open_filter"; // $NON-NLS-1$ public static final String LOAD_FILTER = "load_filter"; - public static final String OPEN_TASK = "open_task"; //$NON-NLS-1$ - public static final String OPEN_NEW_TASK = "open_new_task"; //$NON-NLS-1$ + public static final String OPEN_TASK = "open_task"; // $NON-NLS-1$ + public static final String OPEN_NEW_TASK = "open_new_task"; // $NON-NLS-1$ private static final String FRAG_TAG_TASK_LIST = "frag_tag_task_list"; @Inject Preferences preferences; @Inject SubtasksHelper subtasksHelper; @@ -107,9 +105,16 @@ public class TaskListActivity extends InjectingAppCompatActivity implements @Inject TaskDao taskDao; @Inject CaldavDao caldavDao; @Inject LocalBroadcastManager localBroadcastManager; - @BindView(R.id.drawer_layout) DrawerLayout drawerLayout; - @BindView(R.id.master) FrameLayout master; - @BindView(R.id.detail) FrameLayout detail; + + @BindView(R.id.drawer_layout) + DrawerLayout drawerLayout; + + @BindView(R.id.master) + FrameLayout master; + + @BindView(R.id.detail) + FrameLayout detail; + private NavigationDrawerFragment navigationDrawer; private TaskListViewModel viewModel; private int currentNightMode; @@ -117,9 +122,7 @@ public class TaskListActivity extends InjectingAppCompatActivity implements private Filter filter; private ActionMode actionMode = null; - /** - * @see android.app.Activity#onCreate(Bundle) - */ + /** @see android.app.Activity#onCreate(Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -137,12 +140,13 @@ public class TaskListActivity extends InjectingAppCompatActivity implements navigationDrawer = getNavigationDrawerFragment(); navigationDrawer.setUp(drawerLayout); - drawerLayout.addDrawerListener(new DrawerLayout.SimpleDrawerListener() { - @Override - public void onDrawerStateChanged(int newState) { - finishActionMode(); - } - }); + drawerLayout.addDrawerListener( + new DrawerLayout.SimpleDrawerListener() { + @Override + public void onDrawerStateChanged(int newState) { + finishActionMode(); + } + }); handleIntent(); } @@ -162,8 +166,10 @@ public class TaskListActivity extends InjectingAppCompatActivity implements TaskEditFragment taskEditFragment = getTaskEditFragment(); if (taskEditFragment == null) { hideDetailFragment(); - } else if (intent.hasExtra(OPEN_FILTER) || intent.hasExtra(LOAD_FILTER) || intent - .hasExtra(OPEN_TASK) || intent.hasExtra(OPEN_NEW_TASK)) { + } else if (intent.hasExtra(OPEN_FILTER) + || intent.hasExtra(LOAD_FILTER) + || intent.hasExtra(OPEN_TASK) + || intent.hasExtra(OPEN_NEW_TASK)) { taskEditFragment.save(); taskEditFinished(); } else { @@ -176,8 +182,8 @@ public class TaskListActivity extends InjectingAppCompatActivity implements intent.removeExtra(OPEN_FILTER); loadTaskListFragment(filter); } else if (intent.hasExtra(LOAD_FILTER)) { - Filter filter = defaultFilterProvider - .getFilterFromPreference(intent.getStringExtra(LOAD_FILTER)); + Filter filter = + defaultFilterProvider.getFilterFromPreference(intent.getStringExtra(LOAD_FILTER)); intent.removeExtra(LOAD_FILTER); loadTaskListFragment(filter); } else if (taskListFragment == null) { @@ -196,7 +202,8 @@ public class TaskListActivity extends InjectingAppCompatActivity implements private void hideDetailFragment() { if (isDoublePaneLayout()) { - getSupportFragmentManager().beginTransaction() + getSupportFragmentManager() + .beginTransaction() .replace(R.id.detail, new EmptyTaskEditFragment()) .commit(); } else { @@ -218,7 +225,8 @@ public class TaskListActivity extends InjectingAppCompatActivity implements navigationDrawer.setSelected(filter); FragmentManager fragmentManager = getSupportFragmentManager(); - fragmentManager.beginTransaction() + fragmentManager + .beginTransaction() .replace(R.id.master, taskListFragment, FRAG_TAG_TASK_LIST) .commit(); } @@ -253,8 +261,9 @@ public class TaskListActivity extends InjectingAppCompatActivity implements } private NavigationDrawerFragment getNavigationDrawerFragment() { - return (NavigationDrawerFragment) getSupportFragmentManager() - .findFragmentById(NavigationDrawerFragment.FRAGMENT_NAVIGATION_DRAWER); + return (NavigationDrawerFragment) + getSupportFragmentManager() + .findFragmentById(NavigationDrawerFragment.FRAGMENT_NAVIGATION_DRAWER); } @Override @@ -422,13 +431,12 @@ public class TaskListActivity extends InjectingAppCompatActivity implements } public TaskListFragment getTaskListFragment() { - return (TaskListFragment) getSupportFragmentManager() - .findFragmentByTag(FRAG_TAG_TASK_LIST); + return (TaskListFragment) getSupportFragmentManager().findFragmentByTag(FRAG_TAG_TASK_LIST); } public TaskEditFragment getTaskEditFragment() { - return (TaskEditFragment) getSupportFragmentManager() - .findFragmentByTag(TaskEditFragment.TAG_TASKEDIT_FRAGMENT); + return (TaskEditFragment) + getSupportFragmentManager().findFragmentByTag(TaskEditFragment.TAG_TASKEDIT_FRAGMENT); } @Override @@ -457,8 +465,9 @@ public class TaskListActivity extends InjectingAppCompatActivity implements @Override public void taskEditFinished() { - getSupportFragmentManager().popBackStackImmediate(TaskEditFragment.TAG_TASKEDIT_FRAGMENT, - FragmentManager.POP_BACK_STACK_INCLUSIVE); + getSupportFragmentManager() + .popBackStackImmediate( + TaskEditFragment.TAG_TASKEDIT_FRAGMENT, FragmentManager.POP_BACK_STACK_INCLUSIVE); hideDetailFragment(); hideKeyboard(); getTaskListFragment().loadTaskListContent(); @@ -467,8 +476,8 @@ public class TaskListActivity extends InjectingAppCompatActivity implements private void hideKeyboard() { View view = getCurrentFocus(); if (view != null) { - InputMethodManager inputMethodManager = (InputMethodManager) getSystemService( - INPUT_METHOD_SERVICE); + InputMethodManager inputMethodManager = + (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); } } diff --git a/app/src/main/java/com/todoroo/astrid/activity/TaskListFragment.java b/app/src/main/java/com/todoroo/astrid/activity/TaskListFragment.java index 8c34e8c10..ee2d6c810 100644 --- a/app/src/main/java/com/todoroo/astrid/activity/TaskListFragment.java +++ b/app/src/main/java/com/todoroo/astrid/activity/TaskListFragment.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.activity; import static android.support.v4.content.ContextCompat.getColor; @@ -70,17 +69,16 @@ import org.tasks.ui.ProgressDialogAsyncTask; import org.tasks.ui.TaskListViewModel; /** - * Primary activity for the Bente application. Shows a list of upcoming tasks - * and a user's coaches. + * Primary activity for the Bente application. Shows a list of upcoming tasks and a user's coaches. * * @author Tim Su */ -public class TaskListFragment extends InjectingFragment implements - SwipeRefreshLayout.OnRefreshListener, Toolbar.OnMenuItemClickListener { +public class TaskListFragment extends InjectingFragment + implements SwipeRefreshLayout.OnRefreshListener, Toolbar.OnMenuItemClickListener { + public static final String TAGS_METADATA_JOIN = "for_tags"; // $NON-NLS-1$ + public static final String FILE_METADATA_JOIN = "for_actions"; // $NON-NLS-1$ private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234; - public static final String TAGS_METADATA_JOIN = "for_tags"; //$NON-NLS-1$ - public static final String FILE_METADATA_JOIN = "for_actions"; //$NON-NLS-1$ private static final String EXTRA_FILTER = "extra_filter"; private static final String FRAG_TAG_SORT_DIALOG = "frag_tag_sort_dialog"; @@ -102,11 +100,22 @@ public class TaskListFragment extends InjectingFragment implements @Inject ViewHolderFactory viewHolderFactory; @Inject LocalBroadcastManager localBroadcastManager; @Inject Device device; - @BindView(R.id.swipe_layout) SwipeRefreshLayout swipeRefreshLayout; - @BindView(R.id.swipe_layout_empty) SwipeRefreshLayout emptyRefreshLayout; - @BindView(R.id.toolbar) Toolbar toolbar; - @BindView(R.id.task_list_coordinator) CoordinatorLayout coordinatorLayout; - @BindView(R.id.recycler_view) RecyclerView recyclerView; + + @BindView(R.id.swipe_layout) + SwipeRefreshLayout swipeRefreshLayout; + + @BindView(R.id.swipe_layout_empty) + SwipeRefreshLayout emptyRefreshLayout; + + @BindView(R.id.toolbar) + Toolbar toolbar; + + @BindView(R.id.task_list_coordinator) + CoordinatorLayout coordinatorLayout; + + @BindView(R.id.recycler_view) + RecyclerView recyclerView; + private TaskListViewModel taskListViewModel; private TaskAdapter taskAdapter = null; private TaskListRecyclerAdapter recyclerAdapter; @@ -134,10 +143,11 @@ public class TaskListFragment extends InjectingFragment implements protected void setSyncOngoing(final boolean ongoing) { Activity activity = getActivity(); if (activity != null) { - activity.runOnUiThread(() -> { - swipeRefreshLayout.setRefreshing(ongoing); - emptyRefreshLayout.setRefreshing(ongoing); - }); + activity.runOnUiThread( + () -> { + swipeRefreshLayout.setRefreshing(ongoing); + emptyRefreshLayout.setRefreshing(ongoing); + }); } } @@ -164,9 +174,7 @@ public class TaskListFragment extends InjectingFragment implements component.inject(this); } - /** - * Called when loading up the activity - */ + /** Called when loading up the activity */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -193,8 +201,8 @@ public class TaskListFragment extends InjectingFragment implements } @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View parent = inflater.inflate(R.layout.fragment_task_list, container, false); ButterKnife.bind(this, parent); setupRefresh(swipeRefreshLayout); @@ -237,27 +245,32 @@ public class TaskListFragment extends InjectingFragment implements menu.findItem(R.id.menu_voice_add).setVisible(device.voiceInputAvailable()); final MenuItem item = menu.findItem(R.id.menu_search); final SearchView actionView = (SearchView) MenuItemCompat.getActionView(item); - actionView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { - @Override - public boolean onQueryTextSubmit(String query) { - query = query.trim(); - String title = getString(R.string.FLA_search_filter, query); - Filter savedFilter = new Filter(title, - new QueryTemplate().where(Criterion.and( - Task.DELETION_DATE.eq(0), - Criterion.or( - Task.NOTES.like("%" + query + "%"), - Task.TITLE.like("%" + query + "%"))))); - ((TaskListActivity) getActivity()).onFilterItemClicked(savedFilter); - MenuItemCompat.collapseActionView(item); - return true; - } - - @Override - public boolean onQueryTextChange(String query) { - return false; - } - }); + actionView.setOnQueryTextListener( + new SearchView.OnQueryTextListener() { + @Override + public boolean onQueryTextSubmit(String query) { + query = query.trim(); + String title = getString(R.string.FLA_search_filter, query); + Filter savedFilter = + new Filter( + title, + new QueryTemplate() + .where( + Criterion.and( + Task.DELETION_DATE.eq(0), + Criterion.or( + Task.NOTES.like("%" + query + "%"), + Task.TITLE.like("%" + query + "%"))))); + ((TaskListActivity) getActivity()).onFilterItemClicked(savedFilter); + MenuItemCompat.collapseActionView(item); + return true; + } + + @Override + public boolean onQueryTextChange(String query) { + return false; + } + }); } @Override @@ -265,11 +278,11 @@ public class TaskListFragment extends InjectingFragment implements switch (item.getItemId()) { case R.id.menu_voice_add: Intent recognition = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); - recognition.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, - RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); + recognition.putExtra( + RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); recognition.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1); - recognition - .putExtra(RecognizerIntent.EXTRA_PROMPT, getString(R.string.voice_create_prompt)); + recognition.putExtra( + RecognizerIntent.EXTRA_PROMPT, getString(R.string.voice_create_prompt)); startActivityForResult(recognition, TaskListFragment.VOICE_RECOGNITION_REQUEST_CODE); return true; case R.id.menu_sort: @@ -294,7 +307,8 @@ public class TaskListFragment extends InjectingFragment implements startActivityForResult(intent, REQUEST_EDIT_FILTER); return true; case R.id.menu_clear_completed: - dialogBuilder.newMessageDialog(R.string.clear_completed_tasks_confirmation) + dialogBuilder + .newMessageDialog(R.string.clear_completed_tasks_confirmation) .setPositiveButton(android.R.string.ok, (dialog, which) -> clearCompleted()) .setNegativeButton(android.R.string.cancel, null) .show(); @@ -337,22 +351,26 @@ public class TaskListFragment extends InjectingFragment implements public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); - taskListViewModel.getTasks(filter, taskProperties()).observe(getActivity(), list -> { - if (list.isEmpty()) { - swipeRefreshLayout.setVisibility(View.GONE); - emptyRefreshLayout.setVisibility(View.VISIBLE); - } else { - swipeRefreshLayout.setVisibility(View.VISIBLE); - emptyRefreshLayout.setVisibility(View.GONE); - } + taskListViewModel + .getTasks(filter, taskProperties()) + .observe( + getActivity(), + list -> { + if (list.isEmpty()) { + swipeRefreshLayout.setVisibility(View.GONE); + emptyRefreshLayout.setVisibility(View.VISIBLE); + } else { + swipeRefreshLayout.setVisibility(View.VISIBLE); + emptyRefreshLayout.setVisibility(View.GONE); + } - // stash selected items - Bundle saveState = recyclerAdapter.getSaveState(); + // stash selected items + Bundle saveState = recyclerAdapter.getSaveState(); - recyclerAdapter.setList(list); + recyclerAdapter.setList(list); - recyclerAdapter.restoreSaveState(saveState); - }); + recyclerAdapter.restoreSaveState(saveState); + }); ((DefaultItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false); recyclerAdapter.applyToRecyclerView(recyclerView); @@ -369,8 +387,9 @@ public class TaskListFragment extends InjectingFragment implements } public Snackbar makeSnackbar(String text) { - Snackbar snackbar = Snackbar.make(coordinatorLayout, text, 8000) - .setActionTextColor(getColor(context, R.color.snackbar_text_color)); + Snackbar snackbar = + Snackbar.make(coordinatorLayout, text, 8000) + .setActionTextColor(getColor(context, R.color.snackbar_text_color)); snackbar.getView().setBackgroundColor(getColor(context, R.color.snackbar_background)); return snackbar; } @@ -383,8 +402,8 @@ public class TaskListFragment extends InjectingFragment implements } /** - * Called by the RefreshReceiver when the task list receives a refresh - * broadcast. Subclasses should override this. + * Called by the RefreshReceiver when the task list receives a refresh broadcast. Subclasses + * should override this. */ private void refresh() { // TODO: compare indents in diff callback, then animate this @@ -413,9 +432,7 @@ public class TaskListFragment extends InjectingFragment implements return new TaskAdapter(); } - /** - * Fill in the Task List with current items - */ + /** Fill in the Task List with current items */ protected void setTaskAdapter() { if (filter == null) { return; @@ -423,8 +440,16 @@ public class TaskListFragment extends InjectingFragment implements // set up list adapters taskAdapter = createTaskAdapter(); - recyclerAdapter = new TaskListRecyclerAdapter(getActivity(), taskAdapter, viewHolderFactory, - this, taskDeleter, taskDuplicator, tracker, dialogBuilder); + recyclerAdapter = + new TaskListRecyclerAdapter( + getActivity(), + taskAdapter, + viewHolderFactory, + this, + taskDeleter, + taskDuplicator, + tracker, + dialogBuilder); taskAdapter.setHelper(recyclerAdapter.getHelper()); } @@ -443,8 +468,7 @@ public class TaskListFragment extends InjectingFragment implements syncAdapters.syncNow(); } - public void onTaskCreated(String uuid) { - } + public void onTaskCreated(String uuid) {} /* * ====================================================================== @@ -476,8 +500,9 @@ public class TaskListFragment extends InjectingFragment implements List match = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); if (match != null && match.size() > 0 && match.get(0).length() > 0) { String recognizedSpeech = match.get(0); - recognizedSpeech = recognizedSpeech.substring(0, 1).toUpperCase() + - recognizedSpeech.substring(1).toLowerCase(); + recognizedSpeech = + recognizedSpeech.substring(0, 1).toUpperCase() + + recognizedSpeech.substring(1).toLowerCase(); onTaskListItemClicked(addTask(recognizedSpeech)); } @@ -489,8 +514,11 @@ public class TaskListFragment extends InjectingFragment implements if (FilterSettingsActivity.ACTION_FILTER_DELETED.equals(action)) { activity.onFilterItemClicked(null); } else if (FilterSettingsActivity.ACTION_FILTER_RENAMED.equals(action)) { - activity.getIntent().putExtra(TaskListActivity.OPEN_FILTER, - (Filter) data.getParcelableExtra(FilterSettingsActivity.TOKEN_FILTER)); + activity + .getIntent() + .putExtra( + TaskListActivity.OPEN_FILTER, + (Filter) data.getParcelableExtra(FilterSettingsActivity.TOKEN_FILTER)); activity.recreate(); } } @@ -509,13 +537,13 @@ public class TaskListFragment extends InjectingFragment implements } protected boolean hasDraggableOption() { - return BuiltInFilterExposer.isInbox(context, filter) || BuiltInFilterExposer - .isTodayFilter(context, filter); + return BuiltInFilterExposer.isInbox(context, filter) + || BuiltInFilterExposer.isTodayFilter(context, filter); } /** - * Container Activity must implement this interface and we ensure that it - * does during the onAttach() callback + * Container Activity must implement this interface and we ensure that it does during the + * onAttach() callback */ public interface TaskListFragmentCallbackHandler { diff --git a/app/src/main/java/com/todoroo/astrid/adapter/FilterAdapter.java b/app/src/main/java/com/todoroo/astrid/adapter/FilterAdapter.java index c46a575a4..1a232a0b9 100644 --- a/app/src/main/java/com/todoroo/astrid/adapter/FilterAdapter.java +++ b/app/src/main/java/com/todoroo/astrid/adapter/FilterAdapter.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.adapter; import static android.support.v4.content.ContextCompat.getColor; @@ -71,9 +70,14 @@ public class FilterAdapter extends ArrayAdapter { private Filter selected; @Inject - public FilterAdapter(FilterProvider filterProvider, FilterCounter filterCounter, + public FilterAdapter( + FilterProvider filterProvider, + FilterCounter filterCounter, Activity activity, - Theme theme, ThemeCache themeCache, Locale locale, Preferences preferences) { + Theme theme, + ThemeCache themeCache, + Locale locale, + Preferences preferences) { super(activity, 0); this.filterProvider = filterProvider; this.filterCounter = filterCounter; @@ -118,9 +122,7 @@ public class FilterAdapter extends ArrayAdapter { filterCounter.refreshFilterCounts(this::notifyDataSetChanged); } - /** - * Create or reuse a view - */ + /** Create or reuse a view */ private View newView(View convertView, ViewGroup parent, FilterListItem.Type viewType) { if (convertView == null) { ViewHolder viewHolder = new ViewHolder(); @@ -131,11 +133,17 @@ public class FilterAdapter extends ArrayAdapter { if (navigationDrawer) { viewHolder.name.setCheckMarkDrawable(null); } else if (preLollipop()) { - ColorStateList tintList = new ColorStateList(new int[][]{ - new int[]{-android.R.attr.state_checked}, new int[]{android.R.attr.state_checked}}, - new int[]{ - ResourcesCompat.getColor(activity.getResources(), android.R.color.transparent, - null), theme.getThemeAccent().getAccentColor()}); + ColorStateList tintList = + new ColorStateList( + new int[][] { + new int[] {-android.R.attr.state_checked}, + new int[] {android.R.attr.state_checked} + }, + new int[] { + ResourcesCompat.getColor( + activity.getResources(), android.R.color.transparent, null), + theme.getThemeAccent().getAccentColor() + }); Drawable original = ContextCompat.getDrawable(activity, R.drawable.ic_check_black_24dp); Drawable wrapped = DrawableCompat.wrap(original.mutate()); DrawableCompat.setTintList(wrapped, tintList); @@ -264,21 +272,23 @@ public class FilterAdapter extends ArrayAdapter { addSubMenu(R.string.filters, filterProvider.getFilters(), false); if (navigationDrawer) { - add(new NavigationDrawerAction( - activity.getResources().getString(R.string.FLA_new_filter), - R.drawable.ic_add_24dp, - new Intent(activity, CustomFilterActivity.class), - NavigationDrawerFragment.ACTIVITY_REQUEST_NEW_FILTER)); + add( + new NavigationDrawerAction( + activity.getResources().getString(R.string.FLA_new_filter), + R.drawable.ic_add_24dp, + new Intent(activity, CustomFilterActivity.class), + NavigationDrawerFragment.ACTIVITY_REQUEST_NEW_FILTER)); } addSubMenu(R.string.tags, filterProvider.getTags(), false); if (navigationDrawer) { - add(new NavigationDrawerAction( - activity.getResources().getString(R.string.new_tag), - R.drawable.ic_add_24dp, - new Intent(activity, TagSettingsActivity.class), - NavigationDrawerFragment.REQUEST_NEW_LIST)); + add( + new NavigationDrawerAction( + activity.getResources().getString(R.string.new_tag), + R.drawable.ic_add_24dp, + new Intent(activity, TagSettingsActivity.class), + NavigationDrawerFragment.REQUEST_NEW_LIST)); } List googleTaskFilters = filterProvider.getGoogleTaskFilters(); @@ -290,39 +300,43 @@ public class FilterAdapter extends ArrayAdapter { addSubMenu(title, googleTaskFilters, true); if (navigationDrawer) { - add(new NavigationDrawerAction( - activity.getResources().getString(R.string.new_list), - R.drawable.ic_add_24dp, - new Intent(activity, GoogleTaskListSettingsActivity.class), - NavigationDrawerFragment.REQUEST_NEW_GTASK_LIST)); + add( + new NavigationDrawerAction( + activity.getResources().getString(R.string.new_list), + R.drawable.ic_add_24dp, + new Intent(activity, GoogleTaskListSettingsActivity.class), + NavigationDrawerFragment.REQUEST_NEW_GTASK_LIST)); } } - + if (preferences.getBoolean(R.string.p_sync_caldav, false)) { addSubMenu(R.string.CalDAV, filterProvider.getCaldavFilters(), false); if (navigationDrawer) { - add(new NavigationDrawerAction( - activity.getResources().getString(R.string.add_account), - R.drawable.ic_add_24dp, - new Intent(activity, CaldavSettingsActivity.class), - NavigationDrawerFragment.REQUEST_NEW_CALDAV_ACCOUNT)); + add( + new NavigationDrawerAction( + activity.getResources().getString(R.string.add_account), + R.drawable.ic_add_24dp, + new Intent(activity, CaldavSettingsActivity.class), + NavigationDrawerFragment.REQUEST_NEW_CALDAV_ACCOUNT)); } } if (navigationDrawer) { add(new NavigationDrawerSeparator()); - add(new NavigationDrawerAction( - activity.getResources().getString(R.string.TLA_menu_settings), - R.drawable.ic_settings_24dp, - new Intent(activity, BasicPreferences.class), - REQUEST_SETTINGS)); - add(new NavigationDrawerAction( - activity.getResources().getString(R.string.help_and_feedback), - R.drawable.ic_help_24dp, - new Intent(activity, HelpAndFeedbackActivity.class), - 0)); + add( + new NavigationDrawerAction( + activity.getResources().getString(R.string.TLA_menu_settings), + R.drawable.ic_settings_24dp, + new Intent(activity, BasicPreferences.class), + REQUEST_SETTINGS)); + add( + new NavigationDrawerAction( + activity.getResources().getString(R.string.help_and_feedback), + R.drawable.ic_help_24dp, + new Intent(activity, HelpAndFeedbackActivity.class), + 0)); } notifyDataSetChanged(); @@ -343,9 +357,10 @@ public class FilterAdapter extends ArrayAdapter { } viewHolder.icon.setImageResource(filter.icon); - viewHolder.icon.setColorFilter(filter.tint >= 0 - ? themeCache.getThemeColor(filter.tint).getPrimaryColor() - : getColor(activity, R.color.text_primary)); + viewHolder.icon.setColorFilter( + filter.tint >= 0 + ? themeCache.getThemeColor(filter.tint).getPrimaryColor() + : getColor(activity, R.color.text_primary)); String title = filter.listingTitle; if (!title.equals(viewHolder.name.getText())) { diff --git a/app/src/main/java/com/todoroo/astrid/adapter/TaskAdapter.java b/app/src/main/java/com/todoroo/astrid/adapter/TaskAdapter.java index 720079dca..cf4213ebe 100644 --- a/app/src/main/java/com/todoroo/astrid/adapter/TaskAdapter.java +++ b/app/src/main/java/com/todoroo/astrid/adapter/TaskAdapter.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.adapter; import static com.google.common.collect.Lists.newArrayList; @@ -28,19 +27,26 @@ import org.tasks.data.TaskAttachment; */ public class TaskAdapter { - private static final StringProperty TAGS = new StringProperty(null, - "group_concat(nullif(" + TaskListFragment.TAGS_METADATA_JOIN + ".tag_uid, '')" + ", ',')") - .as("tags"); - private static final LongProperty FILE_ID_PROPERTY = TaskAttachment.ID - .cloneAs(TaskListFragment.FILE_METADATA_JOIN, "fileId"); - public static final Property[] PROPERTIES = ObjectArrays.concat( - Task.PROPERTIES, - new Property[]{ - TAGS, // Concatenated list of tags - FILE_ID_PROPERTY // File id - }, Property.class); - private AsyncPagedListDiffer helper; + private static final StringProperty TAGS = + new StringProperty( + null, + "group_concat(nullif(" + + TaskListFragment.TAGS_METADATA_JOIN + + ".tag_uid, '')" + + ", ',')") + .as("tags"); + private static final LongProperty FILE_ID_PROPERTY = + TaskAttachment.ID.cloneAs(TaskListFragment.FILE_METADATA_JOIN, "fileId"); + public static final Property[] PROPERTIES = + ObjectArrays.concat( + Task.PROPERTIES, + new Property[] { + TAGS, // Concatenated list of tags + FILE_ID_PROPERTY // File id + }, + Property.class); private final Set selected = new HashSet<>(); + private AsyncPagedListDiffer helper; private OnCompletedTaskListener onCompletedTaskListener = null; public int getCount() { @@ -89,13 +95,9 @@ public class TaskAdapter { return false; } - public void moved(int from, int to) { + public void moved(int from, int to) {} - } - - public void indented(int position, int delta) { - - } + public void indented(int position, int delta) {} public long getTaskId(int position) { return getTask(position).getId(); diff --git a/app/src/main/java/com/todoroo/astrid/alarms/AlarmService.java b/app/src/main/java/com/todoroo/astrid/alarms/AlarmService.java index 2f01ac34a..482d99c3d 100644 --- a/app/src/main/java/com/todoroo/astrid/alarms/AlarmService.java +++ b/app/src/main/java/com/todoroo/astrid/alarms/AlarmService.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.alarms; import java.util.LinkedHashSet; @@ -91,27 +90,21 @@ public class AlarmService { return alarmDao.getActiveAlarms(taskId); } - /** - * Schedules all alarms - */ + /** Schedules all alarms */ public void scheduleAllAlarms() { for (Alarm alarm : getActiveAlarms()) { scheduleAlarm(alarm); } } - /** - * Schedules alarms for a single task - */ + /** Schedules alarms for a single task */ private void scheduleAlarms(long taskId) { for (Alarm alarm : getActiveAlarmsForTask(taskId)) { scheduleAlarm(alarm); } } - /** - * Schedules alarms for a single task - */ + /** Schedules alarms for a single task */ private void scheduleAlarm(Alarm alarm) { if (alarm == null) { return; diff --git a/app/src/main/java/com/todoroo/astrid/api/AstridApiConstants.java b/app/src/main/java/com/todoroo/astrid/api/AstridApiConstants.java index d2549c41a..d3210970e 100644 --- a/app/src/main/java/com/todoroo/astrid/api/AstridApiConstants.java +++ b/app/src/main/java/com/todoroo/astrid/api/AstridApiConstants.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.api; /** @@ -13,23 +12,15 @@ package com.todoroo.astrid.api; */ public class AstridApiConstants { - /** - * Name of Astrid's publicly readable preference store - */ + /** Name of Astrid's publicly readable preference store */ public static final String PUBLIC_PREFS = "public"; - /** - * Extras name for task id - */ + /** Extras name for task id */ public static final String EXTRAS_TASK_ID = "task_id"; - /** - * Extras name for old task due date - */ + /** Extras name for old task due date */ public static final String EXTRAS_OLD_DUE_DATE = "oldDueDate"; - /** - * Extras name for new task due date - */ + /** Extras name for new task due date */ public static final String EXTRAS_NEW_DUE_DATE = "newDueDate"; } diff --git a/app/src/main/java/com/todoroo/astrid/api/CaldavFilter.java b/app/src/main/java/com/todoroo/astrid/api/CaldavFilter.java index da116ffea..9eb86f799 100644 --- a/app/src/main/java/com/todoroo/astrid/api/CaldavFilter.java +++ b/app/src/main/java/com/todoroo/astrid/api/CaldavFilter.java @@ -15,30 +15,25 @@ import org.tasks.data.CaldavTask; public class CaldavFilter extends Filter { - /** - * Parcelable Creator Object - */ - public static final Creator CREATOR = new Creator() { + /** Parcelable Creator Object */ + public static final Creator CREATOR = + new Creator() { - /** - * {@inheritDoc} - */ - @Override - public CaldavFilter createFromParcel(Parcel source) { - CaldavFilter item = new CaldavFilter(); - item.readFromParcel(source); - return item; - } + /** {@inheritDoc} */ + @Override + public CaldavFilter createFromParcel(Parcel source) { + CaldavFilter item = new CaldavFilter(); + item.readFromParcel(source); + return item; + } - /** - * {@inheritDoc} - */ - @Override - public CaldavFilter[] newArray(int size) { - return new CaldavFilter[size]; - } + /** {@inheritDoc} */ + @Override + public CaldavFilter[] newArray(int size) { + return new CaldavFilter[size]; + } + }; - }; private static final int TAG = R.drawable.ic_cloud_black_24dp; private CaldavAccount account; @@ -56,9 +51,10 @@ public class CaldavFilter extends Filter { private static QueryTemplate queryTemplate(CaldavAccount caldavAccount) { return new QueryTemplate() .join(Join.left(CaldavTask.TABLE, Task.ID.eq(Field.field("caldav_tasks.task")))) - .where(Criterion.and( - TaskDao.TaskCriteria.activeAndVisible(), - Field.field("account").eq(caldavAccount.getUuid()))); + .where( + Criterion.and( + TaskDao.TaskCriteria.activeAndVisible(), + Field.field("account").eq(caldavAccount.getUuid()))); } private static Map getValuesForNewTask(CaldavAccount caldavAccount) { @@ -71,9 +67,7 @@ public class CaldavFilter extends Filter { return account.getUuid(); } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); diff --git a/app/src/main/java/com/todoroo/astrid/api/CustomFilter.java b/app/src/main/java/com/todoroo/astrid/api/CustomFilter.java index 7cf198e91..97fde346e 100644 --- a/app/src/main/java/com/todoroo/astrid/api/CustomFilter.java +++ b/app/src/main/java/com/todoroo/astrid/api/CustomFilter.java @@ -8,32 +8,28 @@ import java.util.Map; public class CustomFilter extends Filter { - /** - * Parcelable Creator Object - */ - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + /** Parcelable Creator Object */ + public static final Parcelable.Creator CREATOR = + new Parcelable.Creator() { - /** - * {@inheritDoc} - */ - @Override - public CustomFilter createFromParcel(Parcel source) { - return new CustomFilter(source); - } + /** {@inheritDoc} */ + @Override + public CustomFilter createFromParcel(Parcel source) { + return new CustomFilter(source); + } + + /** {@inheritDoc} */ + @Override + public CustomFilter[] newArray(int size) { + return new CustomFilter[size]; + } + }; - /** - * {@inheritDoc} - */ - @Override - public CustomFilter[] newArray(int size) { - return new CustomFilter[size]; - } - }; private long id; private String criterion; - public CustomFilter(String listingTitle, String sql, Map values, long id, - String criterion) { + public CustomFilter( + String listingTitle, String sql, Map values, long id, String criterion) { super(listingTitle, sql, values); this.id = id; this.criterion = criterion; @@ -59,9 +55,7 @@ public class CustomFilter extends Filter { return id; } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); diff --git a/app/src/main/java/com/todoroo/astrid/api/CustomFilterCriterion.java b/app/src/main/java/com/todoroo/astrid/api/CustomFilterCriterion.java index cc2a1daff..8c8341719 100644 --- a/app/src/main/java/com/todoroo/astrid/api/CustomFilterCriterion.java +++ b/app/src/main/java/com/todoroo/astrid/api/CustomFilterCriterion.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.api; import android.graphics.Bitmap; @@ -13,59 +12,51 @@ import java.util.HashMap; import java.util.Map; /** - * CustomFilterCriteria allow users to build a custom filter by chaining - * together criteria + * CustomFilterCriteria allow users to build a custom filter by chaining together criteria * * @author Tim Su */ -abstract public class CustomFilterCriterion implements Parcelable { +public abstract class CustomFilterCriterion implements Parcelable { /** - * Values to apply to a task when quick-adding a task from a filter - * created from this criterion. ? will be replaced with the entry value. - * For example, when a user views tasks tagged 'ABC', the - * tasks they create should also be tagged 'ABC'. If set to null, no - * additional values will be stored for a task. + * Values to apply to a task when quick-adding a task from a filter created from this criterion. ? + * will be replaced with the entry value. For example, when a user views tasks tagged 'ABC', the + * tasks they create should also be tagged 'ABC'. If set to null, no additional values will be + * stored for a task. */ public final Map valuesForNewTasks = new HashMap<>(); /** * Criteria Identifier. This identifier allows saved filters to be reloaded. - *

- * e.g "duedate" + * + *

e.g "duedate" */ public String identifier; /** - * Criteria Title. If the title contains ?, this is replaced by the entry - * label string selected. - *

- * e.g "Due: ?" + * Criteria Title. If the title contains ?, this is replaced by the entry label string selected. + * + *

e.g "Due: ?" */ public String text; /** - * Criterion SQL. This query should return task id's. If this contains - * ?, it will be replaced by the entry value - *

- * Examples: + * 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 <= ? - *
  • SELECT task FROM metadata WHERE value = '?' + *
  • SELECT _id FROM tasks WHERE dueDate <= ? + *
  • SELECT task FROM metadata WHERE value = '?' *
*/ public String sql; - /** - * Criteria name. This is displayed when users are selecting a criteria - */ + /** Criteria name. This is displayed when users are selecting a criteria */ public String name; - /** - * Icon for this criteria. Can be null for no bitmap - */ + /** Icon for this criteria. Can be null for no bitmap */ Bitmap icon; // --- parcelable utilities - /** - * Utility method to write to parcel - */ + /** Utility method to write to parcel */ void writeToParcel(Parcel dest) { dest.writeString(identifier); dest.writeString(text); @@ -75,9 +66,7 @@ abstract public class CustomFilterCriterion implements Parcelable { dest.writeString(name); } - /** - * Utility method to read from parcel - */ + /** Utility method to read from parcel */ void readFromParcel(Parcel source) { identifier = source.readString(); text = source.readString(); diff --git a/app/src/main/java/com/todoroo/astrid/api/Filter.java b/app/src/main/java/com/todoroo/astrid/api/Filter.java index 75c2b447f..158d3ecc1 100644 --- a/app/src/main/java/com/todoroo/astrid/api/Filter.java +++ b/app/src/main/java/com/todoroo/astrid/api/Filter.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.api; import android.os.Parcel; @@ -14,57 +13,49 @@ import java.util.HashMap; import java.util.Map; /** - * 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. + * 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 { + /** Parcelable Creator Object */ + public static final Parcelable.Creator CREATOR = + new Parcelable.Creator() { + + /** {@inheritDoc} */ + @Override + public Filter createFromParcel(Parcel source) { + Filter item = new Filter(); + item.readFromParcel(source); + return item; + } + + /** {@inheritDoc} */ + @Override + public Filter[] newArray(int size) { + return new Filter[size]; + } + }; /** - * Parcelable Creator Object - */ - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - - /** - * {@inheritDoc} - */ - @Override - public Filter createFromParcel(Parcel source) { - Filter item = new Filter(); - item.readFromParcel(source); - return item; - } - - /** - * {@inheritDoc} - */ - @Override - public Filter[] newArray(int size) { - return new Filter[size]; - } - }; - /** - * Values to apply to a task when quick-adding a task from this filter. - * For example, when a user views tasks tagged 'ABC', the - * tasks they create should also be tagged 'ABC'. If set to null, no + * Values to apply to a task when quick-adding a task from this filter. For example, when a user + * views tasks tagged 'ABC', the tasks they create should also be tagged 'ABC'. If set to null, no * additional values will be stored for a task. Can use {@link PermaSql} */ - final public Map valuesForNewTasks = new HashMap<>(); + public final Map valuesForNewTasks = new HashMap<>(); /** - * {@link PermaSql} query for this filter. The query will be appended to the select - * statement after "SELECT fields FROM table %s". It is - * recommended that you use a {@link QueryTemplate} to construct your - * query. - *

- * Examples: + * {@link PermaSql} query for this filter. The query will be appended to the select 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 " + + *
  • "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" @@ -72,8 +63,8 @@ public class Filter extends FilterListItem { */ String sqlQuery; /** - * Field for holding a modified sqlQuery based on sqlQuery. Useful for adjusting - * query for sort/subtasks without breaking the equality checking based on sqlQuery. + * Field for holding a modified sqlQuery based on sqlQuery. Useful for adjusting query for + * sort/subtasks without breaking the equality checking based on sqlQuery. */ private String filterOverride; @@ -87,10 +78,9 @@ public class Filter extends FilterListItem { * @param listingTitle Title of this item as displayed on the lists page, e.g. Inbox * @param sqlQuery SQL query for this list (see {@link #sqlQuery} for examples). */ - public Filter(String listingTitle, QueryTemplate sqlQuery, - Map valuesForNewTasks) { - this(listingTitle, sqlQuery == null ? null : sqlQuery.toString(), - valuesForNewTasks); + public Filter( + String listingTitle, QueryTemplate sqlQuery, Map valuesForNewTasks) { + this(listingTitle, sqlQuery == null ? null : sqlQuery.toString(), valuesForNewTasks); } /** @@ -108,9 +98,7 @@ public class Filter extends FilterListItem { } } - /** - * Utility constructor - */ + /** Utility constructor */ Filter() { // do nothing } @@ -132,8 +120,7 @@ public class Filter extends FilterListItem { public int hashCode() { final int prime = 31; int result = 1; - result = prime * result - + ((sqlQuery == null) ? 0 : sqlQuery.hashCode()); + result = prime * result + ((sqlQuery == null) ? 0 : sqlQuery.hashCode()); result = prime * result + ((listingTitle == null) ? 0 : listingTitle.hashCode()); return result; } @@ -172,9 +159,7 @@ public class Filter extends FilterListItem { return Type.ITEM; } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); @@ -197,10 +182,15 @@ public class Filter extends FilterListItem { @Override public String toString() { - return "Filter{" + - "sqlQuery='" + sqlQuery + '\'' + - ", filterOverride='" + filterOverride + '\'' + - ", valuesForNewTasks=" + valuesForNewTasks + - '}'; + return "Filter{" + + "sqlQuery='" + + sqlQuery + + '\'' + + ", filterOverride='" + + filterOverride + + '\'' + + ", valuesForNewTasks=" + + valuesForNewTasks + + '}'; } } diff --git a/app/src/main/java/com/todoroo/astrid/api/FilterListItem.java b/app/src/main/java/com/todoroo/astrid/api/FilterListItem.java index 35a3b5b60..447e3fec2 100644 --- a/app/src/main/java/com/todoroo/astrid/api/FilterListItem.java +++ b/app/src/main/java/com/todoroo/astrid/api/FilterListItem.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.api; import android.content.Intent; @@ -15,12 +14,11 @@ import android.os.Parcelable; * * @author Tim Su */ -abstract public class FilterListItem implements Parcelable { +public abstract class FilterListItem implements Parcelable { - /** - * Title of this item displayed on the Filters page - */ + /** Title of this item displayed on the Filters page */ public String listingTitle = null; + public int icon = 0; public int tint = -1; @@ -31,9 +29,7 @@ abstract public class FilterListItem implements Parcelable { return 0; } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(listingTitle); @@ -45,9 +41,7 @@ abstract public class FilterListItem implements Parcelable { // --- parcelable helpers - /** - * Utility method to read FilterListItem properties from a parcel. - */ + /** Utility method to read FilterListItem properties from a parcel. */ protected void readFromParcel(Parcel source) { listingTitle = source.readString(); icon = source.readInt(); @@ -58,9 +52,7 @@ abstract public class FilterListItem implements Parcelable { @Override public String toString() { - return "FilterListItem{" + - "listingTitle='" + listingTitle + '\'' + - '}'; + return "FilterListItem{" + "listingTitle='" + listingTitle + '\'' + '}'; } public enum Type { diff --git a/app/src/main/java/com/todoroo/astrid/api/GtasksFilter.java b/app/src/main/java/com/todoroo/astrid/api/GtasksFilter.java index 34014e187..677e65609 100644 --- a/app/src/main/java/com/todoroo/astrid/api/GtasksFilter.java +++ b/app/src/main/java/com/todoroo/astrid/api/GtasksFilter.java @@ -16,29 +16,25 @@ import org.tasks.data.GoogleTaskList; public class GtasksFilter extends Filter { - /** - * Parcelable Creator Object - */ - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - - /** - * {@inheritDoc} - */ - @Override - public GtasksFilter createFromParcel(Parcel source) { - GtasksFilter item = new GtasksFilter(); - item.readFromParcel(source); - return item; - } - - /** - * {@inheritDoc} - */ - @Override - public GtasksFilter[] newArray(int size) { - return new GtasksFilter[size]; - } - }; + /** Parcelable Creator Object */ + public static final Parcelable.Creator CREATOR = + new Parcelable.Creator() { + + /** {@inheritDoc} */ + @Override + public GtasksFilter createFromParcel(Parcel source) { + GtasksFilter item = new GtasksFilter(); + item.readFromParcel(source); + return item; + } + + /** {@inheritDoc} */ + @Override + public GtasksFilter[] newArray(int size) { + return new GtasksFilter[size]; + } + }; + private static final int CLOUD = R.drawable.ic_cloud_black_24dp; private GoogleTaskList list; @@ -64,9 +60,10 @@ public class GtasksFilter extends Filter { private static QueryTemplate getQueryTemplate(GoogleTaskList list) { return new QueryTemplate() .join(Join.left(GoogleTask.TABLE, Task.ID.eq(Field.field("google_tasks.task")))) - .where(Criterion.and( - TaskDao.TaskCriteria.activeAndVisible(), - Field.field("list_id").eq(list.getRemoteId()))); + .where( + Criterion.and( + TaskDao.TaskCriteria.activeAndVisible(), + Field.field("list_id").eq(list.getRemoteId()))); } private static Map getValuesForNewTasks(GoogleTaskList list) { @@ -84,9 +81,7 @@ public class GtasksFilter extends Filter { return true; } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); diff --git a/app/src/main/java/com/todoroo/astrid/api/MultipleSelectCriterion.java b/app/src/main/java/com/todoroo/astrid/api/MultipleSelectCriterion.java index 2ce7bc50d..495545f7b 100644 --- a/app/src/main/java/com/todoroo/astrid/api/MultipleSelectCriterion.java +++ b/app/src/main/java/com/todoroo/astrid/api/MultipleSelectCriterion.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.api; import android.graphics.Bitmap; @@ -12,54 +11,47 @@ import android.os.Parcelable; import java.util.Map; /** - * CustomFilterCriteria allow users to build a custom filter by chaining - * together criteria + * CustomFilterCriteria allow users to build a custom filter by chaining together criteria * * @author Tim Su */ public class MultipleSelectCriterion extends CustomFilterCriterion implements Parcelable { - /** - * Parcelable Creator Object - */ - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + /** Parcelable Creator Object */ + public static final Parcelable.Creator CREATOR = + new Parcelable.Creator() { - /** - * {@inheritDoc} - */ - @Override - public MultipleSelectCriterion createFromParcel(Parcel source) { - MultipleSelectCriterion item = new MultipleSelectCriterion(); - item.entryTitles = source.createStringArray(); - item.entryValues = source.createStringArray(); - item.readFromParcel(source); - return item; - } + /** {@inheritDoc} */ + @Override + public MultipleSelectCriterion createFromParcel(Parcel source) { + MultipleSelectCriterion item = new MultipleSelectCriterion(); + item.entryTitles = source.createStringArray(); + item.entryValues = source.createStringArray(); + item.readFromParcel(source); + return item; + } - /** - * {@inheritDoc} - */ - @Override - public MultipleSelectCriterion[] newArray(int size) { - return new MultipleSelectCriterion[size]; - } - - }; - /** - * Array of entries for user to select from - */ + /** {@inheritDoc} */ + @Override + public MultipleSelectCriterion[] newArray(int size) { + return new MultipleSelectCriterion[size]; + } + }; + /** Array of entries for user to select from */ public String[] entryTitles; - /** - * Array of entry values corresponding to entries - */ + /** Array of entry values corresponding to entries */ public String[] entryValues; - /** - * Create a new CustomFilterCriteria object - */ - public MultipleSelectCriterion(String identifier, String title, String sql, - Map valuesForNewTasks, String[] entryTitles, - String[] entryValues, Bitmap icon, String name) { + /** Create a new CustomFilterCriteria object */ + public MultipleSelectCriterion( + String identifier, + String title, + String sql, + Map valuesForNewTasks, + String[] entryTitles, + String[] entryValues, + Bitmap icon, + String name) { this.identifier = identifier; this.text = title; this.sql = sql; @@ -78,22 +70,17 @@ public class MultipleSelectCriterion extends CustomFilterCriterion implements Pa // constructor for inflating from parceling } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public int describeContents() { return 0; } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public void writeToParcel(Parcel dest, int flags) { dest.writeStringArray(entryTitles); dest.writeStringArray(entryValues); super.writeToParcel(dest); } - } diff --git a/app/src/main/java/com/todoroo/astrid/api/PermaSql.java b/app/src/main/java/com/todoroo/astrid/api/PermaSql.java index 36a87338a..a19760e60 100644 --- a/app/src/main/java/com/todoroo/astrid/api/PermaSql.java +++ b/app/src/main/java/com/todoroo/astrid/api/PermaSql.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.api; import static org.tasks.date.DateTimeUtils.newDateTime; @@ -12,9 +11,8 @@ import com.todoroo.andlib.utility.DateUtilities; import org.tasks.time.DateTime; /** - * 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 + * 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 */ @@ -22,77 +20,52 @@ public final class PermaSql { // --- placeholder strings - /** - * value to be replaced with the current time as long - */ - private static final String VALUE_NOW = "NOW()"; //$NON-NLS-1$ - - /** - * 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 - */ - public static final String VALUE_NOON = "NOON()"; //$NON-NLS-1$ + /** 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 */ + public static final String VALUE_NOON = "NOON()"; // $NON-NLS-1$ + /** 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 end of day tomorrow as long */ + public static final String VALUE_EOD_TOMORROW = "EODT()"; // $NON-NLS-1$ + /** 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 end of day next week as long */ + public static final String VALUE_EOD_NEXT_WEEK = "EODW()"; // $NON-NLS-1$ + /** 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 with the current time as long */ + private static final String VALUE_NOW = "NOW()"; // $NON-NLS-1$ + /** value to be replaced by noon yesterday as long */ + private static final String VALUE_NOON_YESTERDAY = "NOONY()"; // $NON-NLS-1$ + /** value to be replaced by noon tomorrow as long */ + private static final String VALUE_NOON_TOMORROW = "NOONT()"; // $NON-NLS-1$ + /** value to be replaced by noon day after tomorrow as long */ + private static final String VALUE_NOON_DAY_AFTER = "NOONTT()"; // $NON-NLS-1$ + /** value to be replaced by noon next week as long */ + private static final String VALUE_NOON_NEXT_WEEK = "NOONW()"; // $NON-NLS-1$ + /** value to be replaced by approximate noon next month as long */ + private static final String VALUE_NOON_NEXT_MONTH = "NOONM()"; // $NON-NLS-1$ - /** - * 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 end of day tomorrow as long - */ - public static final String VALUE_EOD_TOMORROW = "EODT()"; //$NON-NLS-1$ - /** - * 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 end of day next week as long - */ - public static final String VALUE_EOD_NEXT_WEEK = "EODW()"; //$NON-NLS-1$ - /** - * 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 noon yesterday as long - */ - private static final String VALUE_NOON_YESTERDAY = "NOONY()"; //$NON-NLS-1$ - /** - * value to be replaced by noon tomorrow as long - */ - private static final String VALUE_NOON_TOMORROW = "NOONT()"; //$NON-NLS-1$ - /** - * value to be replaced by noon day after tomorrow as long - */ - private static final String VALUE_NOON_DAY_AFTER = "NOONTT()"; //$NON-NLS-1$ - /** - * value to be replaced by noon next week as long - */ - private static final String VALUE_NOON_NEXT_WEEK = "NOONW()"; //$NON-NLS-1$ - /** - * value to be replaced by approximate noon next month as long - */ - private static final String VALUE_NOON_NEXT_MONTH = "NOONM()"; //$NON-NLS-1$ - - /** - * Replace placeholder strings with actual - */ + /** Replace placeholder strings with actual */ public static String replacePlaceholdersForQuery(String value) { 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) || - value.contains(VALUE_EOD_NEXT_WEEK) || value.contains(VALUE_EOD_TOMORROW) || - value.contains(VALUE_EOD_YESTERDAY) || value.contains(VALUE_EOD_NEXT_MONTH)) { + 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) || - value.contains(VALUE_NOON_NEXT_WEEK) || value.contains(VALUE_NOON_TOMORROW) || - value.contains(VALUE_NOON_YESTERDAY) || value.contains(VALUE_NOON_NEXT_MONTH)) { + 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); } return value; @@ -102,14 +75,20 @@ public final class PermaSql { 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) || - value.contains(VALUE_EOD_NEXT_WEEK) || value.contains(VALUE_EOD_TOMORROW) || - value.contains(VALUE_EOD_YESTERDAY) || value.contains(VALUE_EOD_NEXT_MONTH)) { + 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, newDateTime().noon()); } - 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)) { + 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); } return value; @@ -140,5 +119,4 @@ public final class PermaSql { value = value.replace(VALUE_NOON_NEXT_MONTH, Long.toString(time + 30 * DateUtilities.ONE_DAY)); return value; } - } diff --git a/app/src/main/java/com/todoroo/astrid/api/TagFilter.java b/app/src/main/java/com/todoroo/astrid/api/TagFilter.java index ade2f61ca..15e376bab 100644 --- a/app/src/main/java/com/todoroo/astrid/api/TagFilter.java +++ b/app/src/main/java/com/todoroo/astrid/api/TagFilter.java @@ -16,30 +16,25 @@ import org.tasks.data.TagData; public class TagFilter extends Filter { - /** - * Parcelable Creator Object - */ - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + /** Parcelable Creator Object */ + public static final Parcelable.Creator CREATOR = + new Parcelable.Creator() { - /** - * {@inheritDoc} - */ - @Override - public TagFilter createFromParcel(Parcel source) { - TagFilter item = new TagFilter(); - item.readFromParcel(source); - return item; - } + /** {@inheritDoc} */ + @Override + public TagFilter createFromParcel(Parcel source) { + TagFilter item = new TagFilter(); + item.readFromParcel(source); + return item; + } - /** - * {@inheritDoc} - */ - @Override - public TagFilter[] newArray(int size) { - return new TagFilter[size]; - } + /** {@inheritDoc} */ + @Override + public TagFilter[] newArray(int size) { + return new TagFilter[size]; + } + }; - }; private static final int TAG = R.drawable.ic_label_24dp; private String uuid; @@ -57,9 +52,9 @@ public class TagFilter extends Filter { private static QueryTemplate queryTemplate(String uuid) { return new QueryTemplate() .join(Join.inner(Tag.TABLE.as("mtags"), Task.UUID.eq(Field.field("mtags.task_uid")))) - .where(Criterion.and( - Field.field("mtags.tag_uid").eq(uuid), - TaskDao.TaskCriteria.activeAndVisible())); + .where( + Criterion.and( + Field.field("mtags.tag_uid").eq(uuid), TaskDao.TaskCriteria.activeAndVisible())); } private static Map getValuesForNewTask(TagData tagData) { @@ -72,9 +67,7 @@ public class TagFilter extends Filter { return uuid; } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); diff --git a/app/src/main/java/com/todoroo/astrid/api/TaskAction.java b/app/src/main/java/com/todoroo/astrid/api/TaskAction.java index d6dd5ed12..324d5929b 100644 --- a/app/src/main/java/com/todoroo/astrid/api/TaskAction.java +++ b/app/src/main/java/com/todoroo/astrid/api/TaskAction.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.api; import android.app.PendingIntent; @@ -15,19 +14,13 @@ import android.app.PendingIntent; */ public class TaskAction { - /** - * Intent to call when invoking this operation - */ + /** Intent to call when invoking this operation */ public PendingIntent intent; - /** - * Quick action icon - */ + /** Quick action icon */ public int icon; - /** - * Create an EditOperation object - */ + /** Create an EditOperation object */ public TaskAction(PendingIntent intent, int icon) { super(); this.intent = intent; diff --git a/app/src/main/java/com/todoroo/astrid/api/TextInputCriterion.java b/app/src/main/java/com/todoroo/astrid/api/TextInputCriterion.java index 2d43d86b8..cb6a0f4d7 100644 --- a/app/src/main/java/com/todoroo/astrid/api/TextInputCriterion.java +++ b/app/src/main/java/com/todoroo/astrid/api/TextInputCriterion.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.api; import android.graphics.Bitmap; @@ -11,53 +10,46 @@ import android.os.Parcel; import android.os.Parcelable; /** - * CustomFilterCriteria allow users to build a custom filter by chaining - * together criteria + * CustomFilterCriteria allow users to build a custom filter by chaining together criteria * * @author Tim Su */ public class TextInputCriterion extends CustomFilterCriterion implements Parcelable { - /** - * Parcelable Creator Object - */ - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - - /** - * {@inheritDoc} - */ - @Override - public TextInputCriterion createFromParcel(Parcel source) { - TextInputCriterion item = new TextInputCriterion(); - item.prompt = source.readString(); - item.hint = source.readString(); - item.readFromParcel(source); - return item; - } + /** Parcelable Creator Object */ + public static final Parcelable.Creator CREATOR = + new Parcelable.Creator() { - /** - * {@inheritDoc} - */ - @Override - public TextInputCriterion[] newArray(int size) { - return new TextInputCriterion[size]; - } + /** {@inheritDoc} */ + @Override + public TextInputCriterion createFromParcel(Parcel source) { + TextInputCriterion item = new TextInputCriterion(); + item.prompt = source.readString(); + item.hint = source.readString(); + item.readFromParcel(source); + return item; + } - }; - /** - * Text area hint - */ + /** {@inheritDoc} */ + @Override + public TextInputCriterion[] newArray(int size) { + return new TextInputCriterion[size]; + } + }; + /** Text area hint */ public String hint; - /** - * Text area prompt - */ + /** Text area prompt */ private String prompt; - /** - * Create a new CustomFilterCriteria object - */ - public TextInputCriterion(String identifier, String title, String sql, - String prompt, String hint, Bitmap icon, String name) { + /** Create a new CustomFilterCriteria object */ + public TextInputCriterion( + String identifier, + String title, + String sql, + String prompt, + String hint, + Bitmap icon, + String name) { this.identifier = identifier; this.text = title; this.sql = sql; @@ -73,22 +65,17 @@ public class TextInputCriterion extends CustomFilterCriterion implements Parcela // constructor for inflating from parceling } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public int describeContents() { return 0; } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(prompt); dest.writeString(hint); super.writeToParcel(dest); } - } diff --git a/app/src/main/java/com/todoroo/astrid/backup/BackupConstants.java b/app/src/main/java/com/todoroo/astrid/backup/BackupConstants.java index 6482e00df..19e7dcbe8 100755 --- a/app/src/main/java/com/todoroo/astrid/backup/BackupConstants.java +++ b/app/src/main/java/com/todoroo/astrid/backup/BackupConstants.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.backup; /** @@ -17,36 +16,24 @@ public class BackupConstants { // --- general xml - /** - * Tag containing Astrid backup data - */ + /** Tag containing Astrid backup data */ public static final String ASTRID_TAG = "astrid"; - /** - * 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 comment item - */ + /** Tag containing a comment item */ public static final String COMMENT_TAG = "comment"; - /** - * Tag containing a metadata item - */ + /** Tag containing a metadata item */ public static final String METADATA_TAG = "metadata"; - /** - * Tag containing a tagdata item - */ + /** Tag containing a tagdata item */ public static final String TAGDATA_TAG = "tagdata"; // --- general diff --git a/app/src/main/java/com/todoroo/astrid/backup/TasksXmlImporter.java b/app/src/main/java/com/todoroo/astrid/backup/TasksXmlImporter.java index 42409d32d..743bfadb2 100755 --- a/app/src/main/java/com/todoroo/astrid/backup/TasksXmlImporter.java +++ b/app/src/main/java/com/todoroo/astrid/backup/TasksXmlImporter.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.backup; import android.app.Activity; @@ -40,8 +39,8 @@ import timber.log.Timber; public class TasksXmlImporter { - private static final String FORMAT2 = "2"; //$NON-NLS-1$ - private static final String FORMAT3 = "3"; //$NON-NLS-1$ + private static final String FORMAT2 = "2"; // $NON-NLS-1$ + private static final String FORMAT3 = "3"; // $NON-NLS-1$ private final TagDataDao tagDataDao; private final UserActivityDao userActivityDao; private final DialogBuilder dialogBuilder; @@ -61,10 +60,16 @@ public class TasksXmlImporter { private String input; @Inject - public TasksXmlImporter(TagDataDao tagDataDao, UserActivityDao userActivityDao, - DialogBuilder dialogBuilder, TaskDao taskDao, LocationDao locationDao, - LocalBroadcastManager localBroadcastManager, AlarmDao alarmDao, - TagDao tagDao, GoogleTaskDao googleTaskDao) { + public TasksXmlImporter( + TagDataDao tagDataDao, + UserActivityDao userActivityDao, + DialogBuilder dialogBuilder, + TaskDao taskDao, + LocationDao locationDao, + LocalBroadcastManager localBroadcastManager, + AlarmDao alarmDao, + TagDao tagDao, + GoogleTaskDao googleTaskDao) { this.tagDataDao = tagDataDao; this.userActivityDao = userActivityDao; this.dialogBuilder = dialogBuilder; @@ -87,13 +92,15 @@ public class TasksXmlImporter { handler = new Handler(); - new Thread(() -> { - try { - performImport(); - } catch (IOException | XmlPullParserException e) { - Timber.e(e, e.getMessage()); - } - }).start(); + new Thread( + () -> { + try { + performImport(); + } catch (IOException | XmlPullParserException e) { + Timber.e(e, e.getMessage()); + } + }) + .start(); } // --- importers @@ -122,33 +129,36 @@ public class TasksXmlImporter { new Format3TaskImporter(xpp); } else { throw new UnsupportedOperationException( - "Did not know how to import tasks with xml format '" + - format + "'"); + "Did not know how to import tasks with xml format '" + format + "'"); } } } } } finally { localBroadcastManager.broadcastRefresh(); - handler.post(() -> { - if (progressDialog.isShowing()) { - DialogUtilities.dismissDialog(activity, progressDialog); - showSummary(); - } - }); + handler.post( + () -> { + if (progressDialog.isShowing()) { + DialogUtilities.dismissDialog(activity, progressDialog); + showSummary(); + } + }); } } private void showSummary() { Resources r = activity.getResources(); - dialogBuilder.newDialog() + dialogBuilder + .newDialog() .setTitle(R.string.import_summary_title) - .setMessage(activity.getString(R.string.import_summary_message, - input, - r.getQuantityString(R.plurals.Ntasks, taskCount, taskCount), - r.getQuantityString(R.plurals.Ntasks, importCount, importCount), - r.getQuantityString(R.plurals.Ntasks, skipCount, skipCount), - r.getQuantityString(R.plurals.Ntasks, errorCount, errorCount))) + .setMessage( + activity.getString( + R.string.import_summary_message, + input, + r.getQuantityString(R.plurals.Ntasks, taskCount, taskCount), + r.getQuantityString(R.plurals.Ntasks, importCount, importCount), + r.getQuantityString(R.plurals.Ntasks, skipCount, skipCount), + r.getQuantityString(R.plurals.Ntasks, errorCount, errorCount))) .setPositiveButton(android.R.string.ok, (dialog, id) -> dialog.dismiss()) .show(); } @@ -160,8 +170,7 @@ public class TasksXmlImporter { XmlPullParser xpp; Task currentTask; - Format2TaskImporter() { - } + Format2TaskImporter() {} Format2TaskImporter(XmlPullParser xpp) throws XmlPullParserException, IOException { this.xpp = xpp; @@ -206,10 +215,7 @@ public class TasksXmlImporter { } } - /** - * Imports a comment from the XML we're reading. - * taken from EditNoteActivity.addComment() - */ + /** Imports a comment from the XML we're reading. taken from EditNoteActivity.addComment() */ void parseComment() { if (!currentTask.isSaved()) { return; diff --git a/app/src/main/java/com/todoroo/astrid/calls/PhoneStateChangedReceiver.java b/app/src/main/java/com/todoroo/astrid/calls/PhoneStateChangedReceiver.java index 5b08d6a6e..7ac1c6ec9 100644 --- a/app/src/main/java/com/todoroo/astrid/calls/PhoneStateChangedReceiver.java +++ b/app/src/main/java/com/todoroo/astrid/calls/PhoneStateChangedReceiver.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.calls; import static org.tasks.time.DateTimeUtils.currentTimeMillis; @@ -141,13 +140,14 @@ public class PhoneStateChangedReceiver extends InjectingBroadcastReceiver { private Cursor getMissedCalls() { if (permissionChecker.canAccessMissedCallPermissions()) { //noinspection MissingPermission - return 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" - ); + return 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"); } return null; } @@ -172,10 +172,12 @@ public class PhoneStateChangedReceiver extends InjectingBroadcastReceiver { } 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); + 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); try { if (c.moveToFirst()) { @@ -187,10 +189,10 @@ public class PhoneStateChangedReceiver extends InjectingBroadcastReceiver { return -1; } - private void triggerMissedCallNotification(final String name, final String number, - long contactId) { - final String title = context - .getString(R.string.missed_call, TextUtils.isEmpty(name) ? number : name); + private void triggerMissedCallNotification( + final String name, final String number, long contactId) { + final String title = + context.getString(R.string.missed_call, TextUtils.isEmpty(name) ? number : name); Intent missedCallDialog = new Intent(context, MissedCallActivity.class); missedCallDialog.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); @@ -198,17 +200,20 @@ public class PhoneStateChangedReceiver extends InjectingBroadcastReceiver { missedCallDialog.putExtra(MissedCallActivity.EXTRA_NAME, name); missedCallDialog.putExtra(MissedCallActivity.EXTRA_TITLE, title); - NotificationCompat.Builder builder = new NotificationCompat.Builder(context, - NotificationManager.NOTIFICATION_CHANNEL_CALLS) - .setTicker(title) - .setContentTitle(title) - .setContentText(context.getString(R.string.app_name)) - .setWhen(currentTimeMillis()) - .setShowWhen(true) - .setSmallIcon(R.drawable.ic_check_white_24dp) - .setContentIntent(PendingIntent - .getActivity(context, missedCallDialog.hashCode(), missedCallDialog, - PendingIntent.FLAG_UPDATE_CURRENT)); + NotificationCompat.Builder builder = + new NotificationCompat.Builder(context, NotificationManager.NOTIFICATION_CHANNEL_CALLS) + .setTicker(title) + .setContentTitle(title) + .setContentText(context.getString(R.string.app_name)) + .setWhen(currentTimeMillis()) + .setShowWhen(true) + .setSmallIcon(R.drawable.ic_check_white_24dp) + .setContentIntent( + PendingIntent.getActivity( + context, + missedCallDialog.hashCode(), + missedCallDialog, + PendingIntent.FLAG_UPDATE_CURRENT)); Bitmap contactImage = getContactImage(contactId); if (contactImage != null) { @@ -229,12 +234,16 @@ public class PhoneStateChangedReceiver extends InjectingBroadcastReceiver { callLater.putExtra(MissedCallActivity.EXTRA_TITLE, title); callLater.putExtra(MissedCallActivity.EXTRA_CALL_LATER, true); builder - .addAction(R.drawable.ic_phone_white_24dp, context.getString(R.string.MCA_return_call), - PendingIntent.getActivity(context, callNow.hashCode(), callNow, - PendingIntent.FLAG_UPDATE_CURRENT)) - .addAction(R.drawable.ic_add_white_24dp, context.getString(R.string.MCA_add_task), - PendingIntent.getActivity(context, callLater.hashCode(), callLater, - PendingIntent.FLAG_UPDATE_CURRENT)); + .addAction( + R.drawable.ic_phone_white_24dp, + context.getString(R.string.MCA_return_call), + PendingIntent.getActivity( + context, callNow.hashCode(), callNow, PendingIntent.FLAG_UPDATE_CURRENT)) + .addAction( + R.drawable.ic_add_white_24dp, + context.getString(R.string.MCA_add_task), + PendingIntent.getActivity( + context, callLater.hashCode(), callLater, PendingIntent.FLAG_UPDATE_CURRENT)); notificationManager.notify(number.hashCode(), builder, true, false, false); } @@ -243,8 +252,8 @@ public class PhoneStateChangedReceiver extends InjectingBroadcastReceiver { Bitmap b = null; if (contactId >= 0) { Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId); - InputStream input = ContactsContract.Contacts - .openContactPhotoInputStream(context.getContentResolver(), uri); + InputStream input = + ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(), uri); try { b = BitmapFactory.decodeStream(input); } catch (OutOfMemoryError e) { diff --git a/app/src/main/java/com/todoroo/astrid/core/BuiltInFilterExposer.java b/app/src/main/java/com/todoroo/astrid/core/BuiltInFilterExposer.java index f9690874a..d07dd01a9 100644 --- a/app/src/main/java/com/todoroo/astrid/core/BuiltInFilterExposer.java +++ b/app/src/main/java/com/todoroo/astrid/core/BuiltInFilterExposer.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.core; import android.content.Context; @@ -44,11 +43,10 @@ public final class BuiltInFilterExposer { this.preferences = preferences; } - /** - * Build inbox filter - */ + /** Build inbox filter */ public static Filter getMyTasksFilter(Resources r) { - return new Filter(r.getString(R.string.BFE_Active), + return new Filter( + r.getString(R.string.BFE_Active), new QueryTemplate().where(TaskCriteria.activeAndVisible())); } @@ -56,27 +54,36 @@ public final class BuiltInFilterExposer { String todayTitle = AndroidUtilities.capitalize(r.getString(R.string.today)); Map todayValues = new HashMap<>(); todayValues.put(Task.DUE_DATE.name, PermaSql.VALUE_NOON); - return new Filter(todayTitle, - new QueryTemplate().where( - Criterion.and(TaskCriteria.activeAndVisible(), - Task.DUE_DATE.gt(0), - Task.DUE_DATE.lte(PermaSql.VALUE_EOD))), + return new Filter( + todayTitle, + new QueryTemplate() + .where( + Criterion.and( + TaskCriteria.activeAndVisible(), + Task.DUE_DATE.gt(0), + Task.DUE_DATE.lte(PermaSql.VALUE_EOD))), todayValues); } public static Filter getRecentlyModifiedFilter(Resources r) { - return new Filter(r.getString(R.string.BFE_Recent), - new QueryTemplate().where( - TaskCriteria.notDeleted()).orderBy( - Order.desc(Task.MODIFICATION_DATE)).limit(15)); + return new Filter( + r.getString(R.string.BFE_Recent), + new QueryTemplate() + .where(TaskCriteria.notDeleted()) + .orderBy(Order.desc(Task.MODIFICATION_DATE)) + .limit(15)); } public static Filter getUncategorizedFilter(Resources r) { - return new Filter(r.getString(R.string.tag_FEx_untagged), - new QueryTemplate().where(Criterion.and( - Criterion.not(Task.UUID.in(Query.select(Field.field("task_uid")).from(Tag.TABLE))), - TaskCriteria.isActive(), - TaskCriteria.isVisible()))); + return new Filter( + r.getString(R.string.tag_FEx_untagged), + new QueryTemplate() + .where( + Criterion.and( + Criterion.not( + Task.UUID.in(Query.select(Field.field("task_uid")).from(Tag.TABLE))), + TaskCriteria.isActive(), + TaskCriteria.isVisible()))); } public static boolean isInbox(Context context, Filter filter) { diff --git a/app/src/main/java/com/todoroo/astrid/core/CustomFilterActivity.java b/app/src/main/java/com/todoroo/astrid/core/CustomFilterActivity.java index 938bd1b72..7fca6568d 100644 --- a/app/src/main/java/com/todoroo/astrid/core/CustomFilterActivity.java +++ b/app/src/main/java/com/todoroo/astrid/core/CustomFilterActivity.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.core; import static android.text.TextUtils.isEmpty; @@ -58,12 +57,12 @@ import org.tasks.ui.MenuColorizer; * * @author Tim Su */ -public class CustomFilterActivity extends ThemedInjectingAppCompatActivity implements - Toolbar.OnMenuItemClickListener { +public class CustomFilterActivity extends ThemedInjectingAppCompatActivity + implements Toolbar.OnMenuItemClickListener { static final int MENU_GROUP_CONTEXT_TYPE = 1; static final int MENU_GROUP_CONTEXT_DELETE = 2; - private static final String IDENTIFIER_UNIVERSE = "active"; //$NON-NLS-1$ + private static final String IDENTIFIER_UNIVERSE = "active"; // $NON-NLS-1$ private static final int MENU_GROUP_FILTER = 0; // --- hierarchy of filter classes @@ -74,8 +73,13 @@ public class CustomFilterActivity extends ThemedInjectingAppCompatActivity imple // --- activity @Inject FilterCriteriaProvider filterCriteriaProvider; @Inject Locale locale; - @BindView(R.id.tag_name) EditText filterName; - @BindView(R.id.toolbar) Toolbar toolbar; + + @BindView(R.id.tag_name) + EditText filterName; + + @BindView(R.id.toolbar) + Toolbar toolbar; + private ListView listView; private CustomFilterAdapter adapter; @@ -85,9 +89,11 @@ public class CustomFilterActivity extends ThemedInjectingAppCompatActivity imple CriterionInstance item = adapter.getItem(i); // criterion|entry|text|type|sql - values.append(escape(item.criterion.identifier)) + values + .append(escape(item.criterion.identifier)) .append(AndroidUtilities.SERIALIZATION_SEPARATOR); - values.append(escape(item.getValueFromCriterion())) + 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); @@ -102,10 +108,10 @@ public class CustomFilterActivity extends ThemedInjectingAppCompatActivity imple private static String escape(String item) { if (item == null) { - return ""; //$NON-NLS-1$ + return ""; // $NON-NLS-1$ } - return item.replace(AndroidUtilities.SERIALIZATION_SEPARATOR, - AndroidUtilities.SEPARATOR_ESCAPE); + return item.replace( + AndroidUtilities.SERIALIZATION_SEPARATOR, AndroidUtilities.SEPARATOR_ESCAPE); } @Override @@ -141,9 +147,16 @@ public class CustomFilterActivity extends ThemedInjectingAppCompatActivity imple private CriterionInstance getStartingUniverse() { CriterionInstance instance = new CriterionInstance(); - instance.criterion = new MultipleSelectCriterion(IDENTIFIER_UNIVERSE, - getString(R.string.CFA_universe_all), - null, null, null, null, null, null); + instance.criterion = + new MultipleSelectCriterion( + IDENTIFIER_UNIVERSE, + getString(R.string.CFA_universe_all), + null, + null, + null, + null, + null, + null); instance.type = CriterionInstance.TYPE_UNIVERSE; return instance; } @@ -151,21 +164,22 @@ public class CustomFilterActivity extends ThemedInjectingAppCompatActivity imple private void setUpListeners() { findViewById(R.id.add).setOnClickListener(v -> listView.showContextMenu()); - listView.setOnCreateContextMenuListener((menu, v, 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. - */ - return; - } - - int i = 0; - for (CustomFilterCriterion item : filterCriteriaProvider.getAll()) { - menu.add(CustomFilterActivity.MENU_GROUP_FILTER, i, 0, item.name); - i++; - } - }); + listView.setOnCreateContextMenuListener( + (menu, v, 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. + */ + return; + } + + int i = 0; + for (CustomFilterCriterion item : filterCriteriaProvider.getAll()) { + menu.add(CustomFilterActivity.MENU_GROUP_FILTER, i, 0, item.name); + i++; + } + }); } // --- listeners and action events @@ -226,31 +240,30 @@ public class CustomFilterActivity extends ThemedInjectingAppCompatActivity imple sql.append(Task.ID).append(" IN (").append(subSql).append(") "); } - if (instance.criterion.valuesForNewTasks != null && - instance.type == CriterionInstance.TYPE_INTERSECT) { + if (instance.criterion.valuesForNewTasks != null + && instance.type == CriterionInstance.TYPE_INTERSECT) { for (Entry entry : instance.criterion.valuesForNewTasks.entrySet()) { - values.put(entry.getKey().replace("?", value), - entry.getValue().toString().replace("?", value)); + values.put( + entry.getKey().replace("?", value), entry.getValue().toString().replace("?", value)); } } } org.tasks.data.Filter storeObject = persist(title, sql.toString(), values); - Filter filter = new CustomFilter(title, sql.toString(), values, storeObject.getId(), - storeObject.getCriterion()); + Filter filter = + new CustomFilter( + title, sql.toString(), values, storeObject.getId(), storeObject.getCriterion()); setResult(RESULT_OK, new Intent().putExtra(TaskListActivity.OPEN_FILTER, filter)); finish(); } - /** - * Recalculate all sizes - */ + /** Recalculate all sizes */ void updateList() { int max = 0, last = -1; - StringBuilder sql = new StringBuilder( - Query.select(new CountProperty()).from(Task.TABLE).toString()). - append(" WHERE "); + StringBuilder sql = + new StringBuilder(Query.select(new CountProperty()).from(Task.TABLE).toString()) + .append(" WHERE "); for (int i = 0; i < adapter.getCount(); i++) { CriterionInstance instance = adapter.getItem(i); @@ -320,7 +333,8 @@ public class CustomFilterActivity extends ThemedInjectingAppCompatActivity imple if (filterName.getText().toString().trim().isEmpty() && adapter.getCount() <= 1) { finish(); } else { - dialogBuilder.newMessageDialog(R.string.discard_changes) + dialogBuilder + .newMessageDialog(R.string.discard_changes) .setPositiveButton(R.string.keep_editing, null) .setNegativeButton(R.string.discard, (dialog, which) -> finish()) .show(); @@ -334,10 +348,12 @@ public class CustomFilterActivity extends ThemedInjectingAppCompatActivity imple CustomFilterCriterion criterion = filterCriteriaProvider.getAll().get(item.getItemId()); final CriterionInstance instance = new CriterionInstance(); instance.criterion = criterion; - adapter.showOptionsFor(instance, () -> { - adapter.add(instance); - updateList(); - }); + adapter.showOptionsFor( + instance, + () -> { + adapter.add(instance); + updateList(); + }); return true; } @@ -386,37 +402,29 @@ public class CustomFilterActivity extends ThemedInjectingAppCompatActivity imple 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 filter count - */ - int start; public int end; + /** statistics for filter count */ + int start; + int max; public String getTitleFromCriterion() { if (criterion instanceof MultipleSelectCriterion) { - if (selectedIndex >= 0 && ((MultipleSelectCriterion) criterion).entryTitles != null && - selectedIndex < ((MultipleSelectCriterion) criterion).entryTitles.length) { + if (selectedIndex >= 0 + && ((MultipleSelectCriterion) criterion).entryTitles != null + && selectedIndex < ((MultipleSelectCriterion) criterion).entryTitles.length) { String title = ((MultipleSelectCriterion) criterion).entryTitles[selectedIndex]; return criterion.text.replace("?", title); } @@ -427,7 +435,7 @@ public class CustomFilterActivity extends ThemedInjectingAppCompatActivity imple } return criterion.text.replace("?", selectedText); } - throw new UnsupportedOperationException("Unknown criterion type"); //$NON-NLS-1$ + throw new UnsupportedOperationException("Unknown criterion type"); // $NON-NLS-1$ } String getValueFromCriterion() { @@ -435,15 +443,16 @@ public class CustomFilterActivity extends ThemedInjectingAppCompatActivity imple return null; } if (criterion instanceof MultipleSelectCriterion) { - if (selectedIndex >= 0 && ((MultipleSelectCriterion) criterion).entryValues != null && - selectedIndex < ((MultipleSelectCriterion) criterion).entryValues.length) { + 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) { return selectedText; } - throw new UnsupportedOperationException("Unknown criterion type"); //$NON-NLS-1$ + throw new UnsupportedOperationException("Unknown criterion type"); // $NON-NLS-1$ } } } diff --git a/app/src/main/java/com/todoroo/astrid/core/CustomFilterAdapter.java b/app/src/main/java/com/todoroo/astrid/core/CustomFilterAdapter.java index 75e29fe26..f9916d87e 100644 --- a/app/src/main/java/com/todoroo/astrid/core/CustomFilterAdapter.java +++ b/app/src/main/java/com/todoroo/astrid/core/CustomFilterAdapter.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.core; import android.content.DialogInterface; @@ -38,28 +37,34 @@ class CustomFilterAdapter extends ArrayAdapter { private final DialogBuilder dialogBuilder; private final LayoutInflater inflater; private final Locale locale; - private final View.OnClickListener filterClickListener = new View.OnClickListener() { - @Override - public void onClick(View v) { - ViewHolder viewHolder = (ViewHolder) v.getTag(); - if (viewHolder == null) { - return; - } - if (viewHolder.item.type == CriterionInstance.TYPE_UNIVERSE) { - return; - } - - showOptionsFor(viewHolder.item, () -> { - activity.updateList(); - notifyDataSetInvalidated(); - }); - } - }; + private final View.OnClickListener filterClickListener = + new View.OnClickListener() { + @Override + public void onClick(View v) { + ViewHolder viewHolder = (ViewHolder) v.getTag(); + if (viewHolder == null) { + return; + } + if (viewHolder.item.type == CriterionInstance.TYPE_UNIVERSE) { + return; + } + + showOptionsFor( + viewHolder.item, + () -> { + activity.updateList(); + notifyDataSetInvalidated(); + }); + } + }; // --- view event handling - public CustomFilterAdapter(CustomFilterActivity activity, DialogBuilder dialogBuilder, - List objects, Locale locale) { + public CustomFilterAdapter( + CustomFilterActivity activity, + DialogBuilder dialogBuilder, + List objects, + Locale locale) { super(activity, 0, objects); this.activity = activity; this.dialogBuilder = dialogBuilder; @@ -78,43 +83,50 @@ class CustomFilterAdapter extends ArrayAdapter { menu.setHeaderTitle(viewHolder.name.getText()); - MenuItem item = menu - .add(CustomFilterActivity.MENU_GROUP_CONTEXT_TYPE, CriterionInstance.TYPE_INTERSECT, index, - activity.getString(R.string.CFA_context_chain, - activity.getString(R.string.CFA_type_intersect))); + MenuItem item = + menu.add( + CustomFilterActivity.MENU_GROUP_CONTEXT_TYPE, + CriterionInstance.TYPE_INTERSECT, + index, + activity.getString( + R.string.CFA_context_chain, activity.getString(R.string.CFA_type_intersect))); item.setChecked(viewHolder.item.type == CriterionInstance.TYPE_INTERSECT); - item = menu.add(CustomFilterActivity.MENU_GROUP_CONTEXT_TYPE, CriterionInstance.TYPE_ADD, index, - activity.getString(R.string.CFA_context_chain, - activity.getString(R.string.CFA_type_add))); + item = + menu.add( + CustomFilterActivity.MENU_GROUP_CONTEXT_TYPE, + CriterionInstance.TYPE_ADD, + index, + activity.getString( + R.string.CFA_context_chain, activity.getString(R.string.CFA_type_add))); item.setChecked(viewHolder.item.type == CriterionInstance.TYPE_ADD); - item = menu - .add(CustomFilterActivity.MENU_GROUP_CONTEXT_TYPE, CriterionInstance.TYPE_SUBTRACT, index, - activity.getString(R.string.CFA_context_chain, - activity.getString(R.string.CFA_type_subtract))); + item = + menu.add( + CustomFilterActivity.MENU_GROUP_CONTEXT_TYPE, + CriterionInstance.TYPE_SUBTRACT, + index, + activity.getString( + R.string.CFA_context_chain, activity.getString(R.string.CFA_type_subtract))); item.setChecked(viewHolder.item.type == CriterionInstance.TYPE_SUBTRACT); menu.setGroupCheckable(CustomFilterActivity.MENU_GROUP_CONTEXT_TYPE, true, true); - menu.add(CustomFilterActivity.MENU_GROUP_CONTEXT_DELETE, 0, index, - R.string.CFA_context_delete); + menu.add(CustomFilterActivity.MENU_GROUP_CONTEXT_DELETE, 0, index, R.string.CFA_context_delete); } - /** - * Show options menu for the given criterioninstance - */ + /** Show options menu for the given criterioninstance */ public void showOptionsFor(final CriterionInstance item, final Runnable onComplete) { - AlertDialogBuilder dialog = dialogBuilder.newDialog() - .setTitle(item.criterion.name); + AlertDialogBuilder dialog = dialogBuilder.newDialog().setTitle(item.criterion.name); if (item.criterion instanceof MultipleSelectCriterion) { MultipleSelectCriterion multiSelectCriterion = (MultipleSelectCriterion) item.criterion; final String[] titles = multiSelectCriterion.entryTitles; - DialogInterface.OnClickListener listener = (click, which) -> { - item.selectedIndex = which; - if (onComplete != null) { - onComplete.run(); - } - }; + DialogInterface.OnClickListener listener = + (click, which) -> { + item.selectedIndex = which; + if (onComplete != null) { + onComplete.run(); + } + }; dialog.setItems(titles, listener); } else if (item.criterion instanceof TextInputCriterion) { TextInputCriterion textInCriterion = (TextInputCriterion) item.criterion; @@ -123,16 +135,20 @@ class CustomFilterAdapter extends ArrayAdapter { final EditText editText = new EditText(activity); editText.setText(item.selectedText); editText.setHint(textInCriterion.hint); - frameLayout.addView(editText, new FrameLayout.LayoutParams( - FrameLayout.LayoutParams.MATCH_PARENT, - FrameLayout.LayoutParams.WRAP_CONTENT)); - dialog.setView(frameLayout). - setPositiveButton(android.R.string.ok, (dialogInterface, which) -> { - item.selectedText = editText.getText().toString(); - if (onComplete != null) { - onComplete.run(); - } - }); + frameLayout.addView( + editText, + new FrameLayout.LayoutParams( + FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT)); + dialog + .setView(frameLayout) + .setPositiveButton( + android.R.string.ok, + (dialogInterface, which) -> { + item.selectedText = editText.getText().toString(); + if (onComplete != null) { + onComplete.run(); + } + }); } dialog.show().setOwnerActivity(activity); @@ -169,8 +185,8 @@ class CustomFilterAdapter extends ArrayAdapter { String title = item.getTitleFromCriterion(); - viewHolder.type.setVisibility(item.type == CriterionInstance.TYPE_UNIVERSE ? - View.GONE : View.VISIBLE); + 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); @@ -196,6 +212,4 @@ class CustomFilterAdapter extends ArrayAdapter { TextView name; TextView filterCount; } - - } diff --git a/app/src/main/java/com/todoroo/astrid/core/CustomFilterExposer.java b/app/src/main/java/com/todoroo/astrid/core/CustomFilterExposer.java index fb4ab8f2a..7725b5900 100644 --- a/app/src/main/java/com/todoroo/astrid/core/CustomFilterExposer.java +++ b/app/src/main/java/com/todoroo/astrid/core/CustomFilterExposer.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.core; import static com.google.common.collect.Lists.newArrayList; @@ -53,8 +52,8 @@ public final class CustomFilterExposer { sql = sql.replace("tasks.userId=0", "1"); // TODO: replace dirty hack for missing column - CustomFilter customFilter = new CustomFilter(title, sql, values, savedFilter.getId(), - savedFilter.getCriterion()); + CustomFilter customFilter = + new CustomFilter(title, sql, values, savedFilter.getId(), savedFilter.getCriterion()); customFilter.icon = filter; return customFilter; } diff --git a/app/src/main/java/com/todoroo/astrid/core/DefaultsPreferences.java b/app/src/main/java/com/todoroo/astrid/core/DefaultsPreferences.java index 5bd64657c..fdcecb59f 100644 --- a/app/src/main/java/com/todoroo/astrid/core/DefaultsPreferences.java +++ b/app/src/main/java/com/todoroo/astrid/core/DefaultsPreferences.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.core; import static org.tasks.PermissionUtil.verifyPermissions; @@ -32,8 +31,8 @@ import org.tasks.preferences.PermissionRequestor; import org.tasks.preferences.Preferences; import org.tasks.sync.SyncAdapters; -public class DefaultsPreferences extends InjectingPreferenceActivity implements - RemoteListSelectionHandler { +public class DefaultsPreferences extends InjectingPreferenceActivity + implements RemoteListSelectionHandler { private static final String FRAG_TAG_REMOTE_LIST_SELECTION = "frag_tag_remote_list_selection"; @@ -55,23 +54,27 @@ public class DefaultsPreferences extends InjectingPreferenceActivity implements addPreferencesFromResource(R.xml.preferences_defaults); defaultCalendarPref = findPreference(getString(R.string.gcal_p_default)); - defaultCalendarPref.setOnPreferenceClickListener(preference -> { - if (permissionRequester.requestCalendarPermissions()) { - startCalendarSelectionActivity(); - } - return false; - }); + defaultCalendarPref.setOnPreferenceClickListener( + preference -> { + if (permissionRequester.requestCalendarPermissions()) { + startCalendarSelectionActivity(); + } + return false; + }); String defaultCalendarName = getDefaultCalendarName(); - defaultCalendarPref.setSummary(defaultCalendarName == null - ? getString(R.string.dont_add_to_calendar) - : defaultCalendarName); + defaultCalendarPref.setSummary( + defaultCalendarName == null + ? getString(R.string.dont_add_to_calendar) + : defaultCalendarName); if (syncAdapters.isSyncEnabled()) { - findPreference(R.string.p_default_remote_list).setOnPreferenceClickListener(preference -> { - newRemoteListNativePicker(defaultFilterProvider.getDefaultRemoteList()) - .show(getFragmentManager(), FRAG_TAG_REMOTE_LIST_SELECTION); - return false; - }); + findPreference(R.string.p_default_remote_list) + .setOnPreferenceClickListener( + preference -> { + newRemoteListNativePicker(defaultFilterProvider.getDefaultRemoteList()) + .show(getFragmentManager(), FRAG_TAG_REMOTE_LIST_SELECTION); + return false; + }); updateRemoteListSummary(); } else { remove(R.string.p_default_remote_list); @@ -85,14 +88,14 @@ public class DefaultsPreferences extends InjectingPreferenceActivity implements } private String getDefaultCalendarName() { - AndroidCalendar calendar = calendarProvider - .getCalendar(preferences.getStringValue(R.string.gcal_p_default)); + AndroidCalendar calendar = + calendarProvider.getCalendar(preferences.getStringValue(R.string.gcal_p_default)); return calendar == null ? null : calendar.getName(); } @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, - @NonNull int[] grantResults) { + public void onRequestPermissionsResult( + int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == PermissionRequestor.REQUEST_CALENDAR) { if (verifyPermissions(grantResults)) { startCalendarSelectionActivity(); @@ -105,7 +108,8 @@ public class DefaultsPreferences extends InjectingPreferenceActivity implements @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CALENDAR_SELECTION && resultCode == RESULT_OK) { - preferences.setString(R.string.gcal_p_default, + preferences.setString( + R.string.gcal_p_default, data.getStringExtra(CalendarSelectionActivity.EXTRA_CALENDAR_ID)); defaultCalendarPref.setSummary( data.getStringExtra(CalendarSelectionActivity.EXTRA_CALENDAR_NAME)); @@ -129,9 +133,9 @@ public class DefaultsPreferences extends InjectingPreferenceActivity implements private void updateRemoteListSummary() { Filter defaultFilter = defaultFilterProvider.getDefaultRemoteList(); - findPreference(R.string.p_default_remote_list).setSummary(defaultFilter == null - ? getString(R.string.dont_sync) - : defaultFilter.listingTitle); + findPreference(R.string.p_default_remote_list) + .setSummary( + defaultFilter == null ? getString(R.string.dont_sync) : defaultFilter.listingTitle); } @Override diff --git a/app/src/main/java/com/todoroo/astrid/core/LinkActionExposer.java b/app/src/main/java/com/todoroo/astrid/core/LinkActionExposer.java index 619b037a3..483dcf221 100644 --- a/app/src/main/java/com/todoroo/astrid/core/LinkActionExposer.java +++ b/app/src/main/java/com/todoroo/astrid/core/LinkActionExposer.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.core; import android.app.PendingIntent; @@ -40,8 +39,7 @@ public class LinkActionExposer { Linkify.addLinks(titleSpan, Linkify.ALL); URLSpan[] urlSpans = titleSpan.getSpans(0, titleSpan.length(), URLSpan.class); - if (urlSpans.length == 0 && !hasNotes && - !hasAttachments) { + if (urlSpans.length == 0 && !hasNotes && !hasAttachments) { return null; } @@ -69,8 +67,8 @@ public class LinkActionExposer { return null; } - private static TaskAction createLinkAction(Context context, long id, String url, String text, - PackageManager pm) { + private static TaskAction createLinkAction( + Context context, long id, String url, String text, PackageManager pm) { Intent itemIntent = new Intent(Intent.ACTION_VIEW); itemIntent.setData(Uri.parse(url)); List resolveInfoList = pm.queryIntentActivities(itemIntent, 0); diff --git a/app/src/main/java/com/todoroo/astrid/core/OldTaskPreferences.java b/app/src/main/java/com/todoroo/astrid/core/OldTaskPreferences.java index 76c6f312c..a57df6f73 100644 --- a/app/src/main/java/com/todoroo/astrid/core/OldTaskPreferences.java +++ b/app/src/main/java/com/todoroo/astrid/core/OldTaskPreferences.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.core; import android.os.Bundle; @@ -35,109 +34,129 @@ public class OldTaskPreferences extends InjectingPreferenceActivity { addPreferencesFromResource(R.xml.preferences_oldtasks); findPreference(getString(R.string.EPr_manage_purge_deleted)) - .setOnPreferenceClickListener(preference -> { - purgeDeletedTasks(); - return false; - }); + .setOnPreferenceClickListener( + preference -> { + purgeDeletedTasks(); + return false; + }); findPreference(getString(R.string.EPr_manage_delete_completed_gcal)) - .setOnPreferenceClickListener(preference -> { - deleteCompletedEvents(); - return false; - }); + .setOnPreferenceClickListener( + preference -> { + deleteCompletedEvents(); + return false; + }); findPreference(getString(R.string.EPr_manage_delete_all_gcal)) - .setOnPreferenceClickListener(preference -> { - deleteAllCalendarEvents(); - return false; - }); + .setOnPreferenceClickListener( + preference -> { + deleteAllCalendarEvents(); + return false; + }); findPreference(getString(R.string.EPr_reset_preferences)) - .setOnPreferenceClickListener(preference -> { - resetPreferences(); - return false; - }); + .setOnPreferenceClickListener( + preference -> { + resetPreferences(); + return false; + }); findPreference(getString(R.string.EPr_delete_task_data)) - .setOnPreferenceClickListener(preference -> { - deleteTaskData(); - return false; - }); + .setOnPreferenceClickListener( + preference -> { + deleteTaskData(); + return false; + }); } private void purgeDeletedTasks() { - dialogBuilder.newMessageDialog(R.string.EPr_manage_purge_deleted_message) - .setPositiveButton(android.R.string.ok, - (dialog, which) -> new ProgressDialogAsyncTask(OldTaskPreferences.this, dialogBuilder) { - @Override - protected Integer doInBackground(Void... params) { - return taskDeleter.purgeDeleted(); - } - - @Override - protected int getResultResource() { - return R.string.EPr_manage_purge_deleted_status; - } - }.execute()) + dialogBuilder + .newMessageDialog(R.string.EPr_manage_purge_deleted_message) + .setPositiveButton( + android.R.string.ok, + (dialog, which) -> + new ProgressDialogAsyncTask(OldTaskPreferences.this, dialogBuilder) { + @Override + protected Integer doInBackground(Void... params) { + return taskDeleter.purgeDeleted(); + } + + @Override + protected int getResultResource() { + return R.string.EPr_manage_purge_deleted_status; + } + }.execute()) .setNegativeButton(android.R.string.cancel, null) .show(); } private void deleteCompletedEvents() { - dialogBuilder.newMessageDialog(R.string.EPr_manage_delete_completed_gcal_message) - .setPositiveButton(android.R.string.ok, - (dialog, which) -> new ProgressDialogAsyncTask(OldTaskPreferences.this, dialogBuilder) { - - @Override - protected Integer doInBackground(Void... params) { - calendarEventProvider.deleteEvents(taskDao.getCompletedCalendarEvents()); - return taskDao.clearCompletedCalendarEvents(); - } - - @Override - protected int getResultResource() { - return R.string.EPr_manage_delete_completed_gcal_status; - } - }.execute()) + dialogBuilder + .newMessageDialog(R.string.EPr_manage_delete_completed_gcal_message) + .setPositiveButton( + android.R.string.ok, + (dialog, which) -> + new ProgressDialogAsyncTask(OldTaskPreferences.this, dialogBuilder) { + + @Override + protected Integer doInBackground(Void... params) { + calendarEventProvider.deleteEvents(taskDao.getCompletedCalendarEvents()); + return taskDao.clearCompletedCalendarEvents(); + } + + @Override + protected int getResultResource() { + return R.string.EPr_manage_delete_completed_gcal_status; + } + }.execute()) .setNegativeButton(android.R.string.cancel, null) .show(); } private void deleteAllCalendarEvents() { - dialogBuilder.newMessageDialog(R.string.EPr_manage_delete_all_gcal_message) - .setPositiveButton(android.R.string.ok, - (dialog, which) -> new ProgressDialogAsyncTask(OldTaskPreferences.this, dialogBuilder) { - @Override - protected Integer doInBackground(Void... params) { - calendarEventProvider.deleteEvents(taskDao.getAllCalendarEvents()); - return taskDao.clearAllCalendarEvents(); - } - - @Override - protected int getResultResource() { - return R.string.EPr_manage_delete_all_gcal_status; - } - }.execute()) + dialogBuilder + .newMessageDialog(R.string.EPr_manage_delete_all_gcal_message) + .setPositiveButton( + android.R.string.ok, + (dialog, which) -> + new ProgressDialogAsyncTask(OldTaskPreferences.this, dialogBuilder) { + @Override + protected Integer doInBackground(Void... params) { + calendarEventProvider.deleteEvents(taskDao.getAllCalendarEvents()); + return taskDao.clearAllCalendarEvents(); + } + + @Override + protected int getResultResource() { + return R.string.EPr_manage_delete_all_gcal_status; + } + }.execute()) .setNegativeButton(android.R.string.cancel, null) .show(); } private void resetPreferences() { - dialogBuilder.newMessageDialog(R.string.EPr_reset_preferences_warning) - .setPositiveButton(R.string.EPr_reset_preferences, (dialog, which) -> { - preferences.reset(); - System.exit(0); - }) + dialogBuilder + .newMessageDialog(R.string.EPr_reset_preferences_warning) + .setPositiveButton( + R.string.EPr_reset_preferences, + (dialog, which) -> { + preferences.reset(); + System.exit(0); + }) .setNegativeButton(android.R.string.cancel, null) .show(); } private void deleteTaskData() { - dialogBuilder.newMessageDialog(R.string.EPr_delete_task_data_warning) - .setPositiveButton(R.string.EPr_delete_task_data, (dialog, which) -> { - deleteDatabase(database.getName()); - System.exit(0); - }) + dialogBuilder + .newMessageDialog(R.string.EPr_delete_task_data_warning) + .setPositiveButton( + R.string.EPr_delete_task_data, + (dialog, which) -> { + deleteDatabase(database.getName()); + System.exit(0); + }) .setNegativeButton(android.R.string.cancel, null) .show(); } diff --git a/app/src/main/java/com/todoroo/astrid/core/SortHelper.java b/app/src/main/java/com/todoroo/astrid/core/SortHelper.java index 961adc811..946ece1c0 100644 --- a/app/src/main/java/com/todoroo/astrid/core/SortHelper.java +++ b/app/src/main/java/com/todoroo/astrid/core/SortHelper.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.core; import static com.todoroo.astrid.dao.TaskDao.TaskCriteria.isVisible; @@ -32,11 +31,9 @@ public class SortHelper { private static final Order ORDER_TITLE = Order.asc(Functions.upper(Task.TITLE)); - /** - * Takes a SQL query, and if there isn't already an order, creates an order. - */ - public static String adjustQueryForFlagsAndSort(Preferences preferences, String originalSql, - int sort) { + /** Takes a SQL query, and if there isn't already an order, creates an order. */ + public static String adjustQueryForFlagsAndSort( + Preferences preferences, String originalSql, int sort) { // sort if (originalSql == null) { originalSql = ""; @@ -52,17 +49,19 @@ public class SortHelper { // flags if (preferences.getBoolean(R.string.p_show_completed_tasks, false)) { - originalSql = originalSql.replace(Task.COMPLETION_DATE.eq(0).toString(), - Criterion.all.toString()); + originalSql = + originalSql.replace(Task.COMPLETION_DATE.eq(0).toString(), Criterion.all.toString()); } else { - originalSql = originalSql.replace(Task.COMPLETION_DATE.eq(0).toString(), - Criterion - .or(Task.COMPLETION_DATE.lte(0), Task.COMPLETION_DATE.gt(DateUtilities.now() - 60000)) - .toString()); + originalSql = + originalSql.replace( + Task.COMPLETION_DATE.eq(0).toString(), + Criterion.or( + Task.COMPLETION_DATE.lte(0), + Task.COMPLETION_DATE.gt(DateUtilities.now() - 60000)) + .toString()); } if (preferences.getBoolean(R.string.p_show_hidden_tasks, false)) { - originalSql = originalSql.replace(isVisible().toString(), - Criterion.all.toString()); + originalSql = originalSql.replace(isVisible().toString(), Criterion.all.toString()); } return originalSql; @@ -75,22 +74,31 @@ public class SortHelper { order = ORDER_TITLE; break; case SORT_DUE: - order = Order.asc( - "(CASE WHEN (dueDate=0) THEN (strftime('%s','now')*1000)*2 ELSE (CASE WHEN (dueDate / 60000) > 0 THEN dueDate ELSE (dueDate + 43140000) END) END)+importance"); + order = + Order.asc( + "(CASE WHEN (dueDate=0) THEN (strftime('%s','now')*1000)*2 ELSE (CASE WHEN (dueDate / 60000) > 0 THEN dueDate ELSE (dueDate + 43140000) END) END)+importance"); break; case SORT_IMPORTANCE: - order = Order.asc( - "importance*(strftime('%s','now')*1000)+(CASE WHEN (dueDate=0) THEN (strftime('%s','now')*1000) ELSE dueDate END)"); + order = + Order.asc( + "importance*(strftime('%s','now')*1000)+(CASE WHEN (dueDate=0) THEN (strftime('%s','now')*1000) ELSE dueDate END)"); break; case SORT_MODIFIED: order = Order.desc(Task.MODIFICATION_DATE); break; case SORT_WIDGET: default: - order = Order.asc("(CASE WHEN (dueDate=0) " + // if no due date - "THEN (strftime('%s','now')*1000)*2 " + // then now * 2 - "ELSE (" + adjustedDueDateFunction() + ") END) " + // else due time - "+ 172800000 * importance"); // add 2 days * importance + order = + Order.asc( + "(CASE WHEN (dueDate=0) " + + // if no due date + "THEN (strftime('%s','now')*1000)*2 " + + // then now * 2 + "ELSE (" + + adjustedDueDateFunction() + + ") END) " + + // else due time + "+ 172800000 * importance"); // add 2 days * importance } if (sortType != SORT_ALPHA) { order.addSecondaryExpression(ORDER_TITLE); diff --git a/app/src/main/java/com/todoroo/astrid/dao/Database.java b/app/src/main/java/com/todoroo/astrid/dao/Database.java index d21c67174..75518d138 100644 --- a/app/src/main/java/com/todoroo/astrid/dao/Database.java +++ b/app/src/main/java/com/todoroo/astrid/dao/Database.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.dao; import android.arch.persistence.db.SupportSQLiteDatabase; @@ -46,23 +45,24 @@ import timber.log.Timber; * @author Tim Su */ @android.arch.persistence.room.Database( - entities = { - Notification.class, - TagData.class, - UserActivity.class, - TaskAttachment.class, - TaskListMetadata.class, - Task.class, - Alarm.class, - Location.class, - Tag.class, - GoogleTask.class, - Filter.class, - GoogleTaskList.class, - CaldavAccount.class, - CaldavTask.class - }, - version = 57) + entities = { + Notification.class, + TagData.class, + UserActivity.class, + TaskAttachment.class, + TaskListMetadata.class, + Task.class, + Alarm.class, + Location.class, + Tag.class, + GoogleTask.class, + Filter.class, + GoogleTaskList.class, + CaldavAccount.class, + CaldavTask.class + }, + version = 57 +) public abstract class Database extends RoomDatabase { public static final String NAME = "database"; @@ -115,10 +115,10 @@ public abstract class Database extends RoomDatabase { } /** - * Open the database for writing. Must be closed afterwards. If user is - * out of disk space, database may be opened for reading instead + * Open the database for writing. Must be closed afterwards. If user is out of disk space, + * database may be opened for reading instead */ - public synchronized final void openForWriting() { + public final synchronized void openForWriting() { if (database != null && !database.isReadOnly() && database.isOpen()) { return; } @@ -132,21 +132,17 @@ public abstract class Database extends RoomDatabase { } } - /** - * Open the database for reading. Must be closed afterwards - */ - public synchronized final void openForReading() { + /** Open the database for reading. Must be closed afterwards */ + public final synchronized void openForReading() { if (database != null && database.isOpen()) { return; } database = getOpenHelper().getReadableDatabase(); } - /** - * Close the database if it has been opened previously - */ + /** Close the database if it has been opened previously */ @Override - public synchronized final void close() { + public final synchronized void close() { if (database != null) { try { database.close(); @@ -157,9 +153,7 @@ public abstract class Database extends RoomDatabase { database = null; } - /** - * @return sql database. opens database if not yet open - */ + /** @return sql database. opens database if not yet open */ private synchronized SupportSQLiteDatabase getDatabase() { if (database == null) { openForWriting(); @@ -167,9 +161,7 @@ public abstract class Database extends RoomDatabase { return database; } - /** - * @return human-readable database name for debugging - */ + /** @return human-readable database name for debugging */ @Override public String toString() { return "DB:" + getName(); @@ -181,4 +173,3 @@ public abstract class Database extends RoomDatabase { return getDatabase().query(sql, null); } } - diff --git a/app/src/main/java/com/todoroo/astrid/dao/TaskDao.java b/app/src/main/java/com/todoroo/astrid/dao/TaskDao.java index 77b821746..de6ca6720 100644 --- a/app/src/main/java/com/todoroo/astrid/dao/TaskDao.java +++ b/app/src/main/java/com/todoroo/astrid/dao/TaskDao.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.dao; import static com.todoroo.andlib.utility.DateUtilities.now; @@ -54,7 +53,8 @@ public abstract class TaskDao { return needsRefresh(now()); } - @android.arch.persistence.room.Query("SELECT * FROM tasks WHERE completed = 0 AND deleted = 0 AND (hideUntil > :now OR dueDate > :now)") + @android.arch.persistence.room.Query( + "SELECT * FROM tasks WHERE completed = 0 AND deleted = 0 AND (hideUntil > :now OR dueDate > :now)") abstract List needsRefresh(long now); @android.arch.persistence.room.Query("SELECT * FROM tasks WHERE _id = :id LIMIT 1") @@ -66,7 +66,8 @@ public abstract class TaskDao { @android.arch.persistence.room.Query("SELECT COUNT(1) FROM tasks WHERE timerStart > 0") public abstract int activeTimers(); - @android.arch.persistence.room.Query("SELECT tasks.* FROM tasks INNER JOIN notification ON tasks._id = notification.task") + @android.arch.persistence.room.Query( + "SELECT tasks.* FROM tasks INNER JOIN notification ON tasks._id = notification.task") public abstract List activeNotifications(); @android.arch.persistence.room.Query("SELECT * FROM tasks WHERE remoteId = :remoteId") @@ -75,34 +76,40 @@ public abstract class TaskDao { @android.arch.persistence.room.Query("SELECT * FROM tasks WHERE completed = 0 AND deleted = 0") abstract List getActiveTasks(); - @android.arch.persistence.room.Query("SELECT * FROM tasks WHERE hideUntil < (strftime('%s','now')*1000)") + @android.arch.persistence.room.Query( + "SELECT * FROM tasks WHERE hideUntil < (strftime('%s','now')*1000)") abstract List getVisibleTasks(); - @android.arch.persistence.room.Query("SELECT * FROM tasks WHERE remoteId IN (:remoteIds) " + - "AND recurrence NOT NULL AND LENGTH(recurrence) > 0") + @android.arch.persistence.room.Query( + "SELECT * FROM tasks WHERE remoteId IN (:remoteIds) " + + "AND recurrence NOT NULL AND LENGTH(recurrence) > 0") public abstract List getRecurringTasks(List remoteIds); - @android.arch.persistence.room.Query("UPDATE tasks SET completed = :completionDate " + - "WHERE remoteId = :remoteId") + @android.arch.persistence.room.Query( + "UPDATE tasks SET completed = :completionDate " + "WHERE remoteId = :remoteId") public abstract void setCompletionDate(String remoteId, long completionDate); - @android.arch.persistence.room.Query("UPDATE tasks SET snoozeTime = :millis WHERE _id in (:taskIds)") + @android.arch.persistence.room.Query( + "UPDATE tasks SET snoozeTime = :millis WHERE _id in (:taskIds)") public abstract void snooze(List taskIds, long millis); - @android.arch.persistence.room.Query("SELECT tasks.* FROM tasks " + - "LEFT JOIN google_tasks ON tasks._id = google_tasks.task " + - "WHERE tasks.modified > google_tasks.last_sync " + - "OR google_tasks.remote_id = ''") + @android.arch.persistence.room.Query( + "SELECT tasks.* FROM tasks " + + "LEFT JOIN google_tasks ON tasks._id = google_tasks.task " + + "WHERE tasks.modified > google_tasks.last_sync " + + "OR google_tasks.remote_id = ''") public abstract List getGoogleTasksToPush(); - @android.arch.persistence.room.Query("SELECT tasks.* FROM tasks " + - "LEFT JOIN caldav_tasks ON tasks._id = caldav_tasks.task " + - "WHERE caldav_tasks.account = :uid " + - "AND tasks.modified > caldav_tasks.last_sync") + @android.arch.persistence.room.Query( + "SELECT tasks.* FROM tasks " + + "LEFT JOIN caldav_tasks ON tasks._id = caldav_tasks.task " + + "WHERE caldav_tasks.account = :uid " + + "AND tasks.modified > caldav_tasks.last_sync") public abstract List getCaldavTasksToPush(String uid); - @android.arch.persistence.room.Query("SELECT * FROM TASKS " + - "WHERE completed = 0 AND deleted = 0 AND (notificationFlags > 0 OR notifications > 0)") + @android.arch.persistence.room.Query( + "SELECT * FROM TASKS " + + "WHERE completed = 0 AND deleted = 0 AND (notificationFlags > 0 OR notifications > 0)") public abstract List getTasksWithReminders(); // --- SQL clause generators @@ -110,20 +117,22 @@ public abstract class TaskDao { @android.arch.persistence.room.Query("SELECT * FROM tasks") public abstract List getAll(); - @android.arch.persistence.room.Query("SELECT calendarUri FROM tasks " + - "WHERE calendarUri NOT NULL AND calendarUri != ''") + @android.arch.persistence.room.Query( + "SELECT calendarUri FROM tasks " + "WHERE calendarUri NOT NULL AND calendarUri != ''") public abstract List getAllCalendarEvents(); - @android.arch.persistence.room.Query("UPDATE tasks SET calendarUri = '' " + - "WHERE calendarUri NOT NULL AND calendarUri != ''") + @android.arch.persistence.room.Query( + "UPDATE tasks SET calendarUri = '' " + "WHERE calendarUri NOT NULL AND calendarUri != ''") public abstract int clearAllCalendarEvents(); - @android.arch.persistence.room.Query("SELECT calendarUri FROM tasks " + - "WHERE completed > 0 AND calendarUri NOT NULL AND calendarUri != ''") + @android.arch.persistence.room.Query( + "SELECT calendarUri FROM tasks " + + "WHERE completed > 0 AND calendarUri NOT NULL AND calendarUri != ''") public abstract List getCompletedCalendarEvents(); - @android.arch.persistence.room.Query("UPDATE tasks SET calendarUri = '' " + - "WHERE completed > 0 AND calendarUri NOT NULL AND calendarUri != ''") + @android.arch.persistence.room.Query( + "UPDATE tasks SET calendarUri = '' " + + "WHERE completed > 0 AND calendarUri NOT NULL AND calendarUri != ''") public abstract int clearCompletedCalendarEvents(); @android.arch.persistence.room.Query("SELECT * FROM tasks WHERE deleted > 0") @@ -132,15 +141,17 @@ public abstract class TaskDao { @android.arch.persistence.room.Query("DELETE FROM tasks WHERE _id = :id") public abstract int deleteById(long id); - @android.arch.persistence.room.Query("SELECT tasks.* FROM tasks INNER JOIN google_tasks ON google_tasks.task = tasks._id WHERE google_tasks.list_id = :googleTaskList") + @android.arch.persistence.room.Query( + "SELECT tasks.* FROM tasks INNER JOIN google_tasks ON google_tasks.task = tasks._id WHERE google_tasks.list_id = :googleTaskList") public abstract List getGoogleTasks(String googleTaskList); - @android.arch.persistence.room.Query("SELECT tasks.* FROM tasks INNER JOIN caldav_tasks ON caldav_tasks.task = tasks._id WHERE caldav_tasks.account = :caldavAccount") + @android.arch.persistence.room.Query( + "SELECT tasks.* FROM tasks INNER JOIN caldav_tasks ON caldav_tasks.task = tasks._id WHERE caldav_tasks.account = :caldavAccount") public abstract List getCaldavTasks(String caldavAccount); /** - * Saves the given task to the database.getDatabase(). Task must already - * exist. Returns true on success. + * Saves the given task to the database.getDatabase(). Task must already exist. Returns true on + * success. */ public void save(Task task) { save(task, fetch(task.getId())); @@ -185,16 +196,14 @@ public abstract class TaskDao { return false; } - @android.arch.persistence.room.Query("SELECT * FROM tasks " + - "WHERE completed = 0 AND deleted = 0 AND hideUntil < (strftime('%s','now')*1000) " + - "ORDER BY (CASE WHEN (dueDate=0) THEN (strftime('%s','now')*1000)*2 ELSE ((CASE WHEN (dueDate / 60000) > 0 THEN dueDate ELSE (dueDate + 43140000) END)) END) + 172800000 * importance ASC " - + - "LIMIT 100") + @android.arch.persistence.room.Query( + "SELECT * FROM tasks " + + "WHERE completed = 0 AND deleted = 0 AND hideUntil < (strftime('%s','now')*1000) " + + "ORDER BY (CASE WHEN (dueDate=0) THEN (strftime('%s','now')*1000)*2 ELSE ((CASE WHEN (dueDate / 60000) > 0 THEN dueDate ELSE (dueDate + 43140000) END)) END) + 172800000 * importance ASC " + + "LIMIT 100") public abstract List getAstrid2TaskProviderTasks(); - /** - * Mark the given task as completed and save it. - */ + /** Mark the given task as completed and save it. */ public void setComplete(Task item, boolean completed) { if (completed) { item.setCompletionDate(now()); @@ -232,8 +241,9 @@ public abstract class TaskDao { } public Cursor getCursor(String queryTemplate) { - Query query = Query.select(Task.PROPERTIES) - .withQueryTemplate(PermaSql.replacePlaceholdersForQuery(queryTemplate)); + Query query = + Query.select(Task.PROPERTIES) + .withQueryTemplate(PermaSql.replacePlaceholdersForQuery(queryTemplate)); String queryString = query.from(Task.TABLE).toString(); if (BuildConfig.DEBUG) { Timber.v(queryString); @@ -241,23 +251,20 @@ public abstract class TaskDao { return database.rawQuery(queryString); } - public LimitOffsetDataSource getLimitOffsetDataSource(String queryTemplate, - Property... properties) { - String query = Query - .select(properties) - .withQueryTemplate(PermaSql.replacePlaceholdersForQuery(queryTemplate)) - .from(Task.TABLE).toString(); + public LimitOffsetDataSource getLimitOffsetDataSource( + String queryTemplate, Property... properties) { + String query = + Query.select(properties) + .withQueryTemplate(PermaSql.replacePlaceholdersForQuery(queryTemplate)) + .from(Task.TABLE) + .toString(); return new LimitOffsetDataSource(database, query); } - /** - * Generates SQL clauses - */ + /** Generates SQL clauses */ public static class TaskCriteria { - /** - * @return tasks that were not deleted - */ + /** @return tasks that were not deleted */ public static Criterion notDeleted() { return Task.DELETION_DATE.eq(0); } @@ -266,29 +273,22 @@ public abstract class TaskDao { return Task.COMPLETION_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), + 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 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()); } } } - diff --git a/app/src/main/java/com/todoroo/astrid/data/SyncFlags.java b/app/src/main/java/com/todoroo/astrid/data/SyncFlags.java index 1b4a56458..0182e2d1b 100644 --- a/app/src/main/java/com/todoroo/astrid/data/SyncFlags.java +++ b/app/src/main/java/com/todoroo/astrid/data/SyncFlags.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.data; public class SyncFlags { @@ -11,5 +10,4 @@ public class SyncFlags { public static final String GTASKS_SUPPRESS_SYNC = "gtasks_suppress_sync"; public static final String FORCE_SYNC = "force_sync"; - } diff --git a/app/src/main/java/com/todoroo/astrid/data/Task.java b/app/src/main/java/com/todoroo/astrid/data/Task.java index d59331397..39d7c70aa 100644 --- a/app/src/main/java/com/todoroo/astrid/data/Task.java +++ b/app/src/main/java/com/todoroo/astrid/data/Task.java @@ -1,12 +1,10 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.data; - import static org.tasks.date.DateTimeUtils.newDateTime; import android.arch.persistence.room.ColumnInfo; @@ -39,113 +37,89 @@ import timber.log.Timber; * * @author Tim Su */ -@Entity(tableName = "tasks", - indices = @Index(name = "t_rid", value = "remoteId", unique = true)) +@Entity(tableName = "tasks", indices = @Index(name = "t_rid", value = "remoteId", unique = true)) public class Task implements Parcelable { // --- table and uri - /** - * table for this model - */ + /** table for this model */ public static final Table TABLE = new Table("tasks"); public static final long NO_ID = 0; // --- properties - public static final LongProperty ID = new LongProperty( - TABLE, "_id"); - public static final StringProperty TITLE = new StringProperty( - TABLE, "title"); - public static final IntegerProperty IMPORTANCE = new IntegerProperty( - TABLE, "importance"); - public static final LongProperty DUE_DATE = new LongProperty( - TABLE, "dueDate"); - public static final LongProperty HIDE_UNTIL = new LongProperty( - TABLE, "hideUntil"); - public static final LongProperty MODIFICATION_DATE = new LongProperty( - TABLE, "modified"); - public static final LongProperty COMPLETION_DATE = new LongProperty( - TABLE, "completed"); - public static final LongProperty DELETION_DATE = new LongProperty( - TABLE, "deleted"); - public static final StringProperty NOTES = new StringProperty( - TABLE, "notes"); - public static final LongProperty TIMER_START = new LongProperty( - TABLE, "timerStart"); - /** - * constant value for no uuid - */ - public static final String NO_UUID = "0"; //$NON-NLS-1$ - public static final StringProperty UUID = new StringProperty( - TABLE, "remoteId"); - /** - * List of all properties for this model - */ - public static final Property[] PROPERTIES = new Property[]{ - new StringProperty(TABLE, "calendarUri"), - COMPLETION_DATE, - new LongProperty(TABLE, "created"), - DELETION_DATE, - DUE_DATE, - new IntegerProperty(TABLE, "elapsedSeconds"), - new IntegerProperty(TABLE, "estimatedSeconds"), - HIDE_UNTIL, - ID, - IMPORTANCE, - MODIFICATION_DATE, - NOTES, - new StringProperty(TABLE, "recurrence"), - new IntegerProperty(TABLE, "notificationFlags"), - new LongProperty(TABLE, "lastNotified"), - new LongProperty(TABLE, "notifications"), - new LongProperty(TABLE, "snoozeTime"), - new LongProperty(TABLE, "repeatUntil"), - TIMER_START, - TITLE, - UUID - }; - /** - * whether to send a reminder at deadline - */ + public static final LongProperty ID = new LongProperty(TABLE, "_id"); + public static final StringProperty TITLE = new StringProperty(TABLE, "title"); + public static final IntegerProperty IMPORTANCE = new IntegerProperty(TABLE, "importance"); + public static final LongProperty DUE_DATE = new LongProperty(TABLE, "dueDate"); + public static final LongProperty HIDE_UNTIL = new LongProperty(TABLE, "hideUntil"); + public static final LongProperty MODIFICATION_DATE = new LongProperty(TABLE, "modified"); + public static final LongProperty COMPLETION_DATE = new LongProperty(TABLE, "completed"); + public static final LongProperty DELETION_DATE = new LongProperty(TABLE, "deleted"); + public static final StringProperty NOTES = new StringProperty(TABLE, "notes"); + public static final LongProperty TIMER_START = new LongProperty(TABLE, "timerStart"); + /** constant value for no uuid */ + public static final String NO_UUID = "0"; // $NON-NLS-1$ + + public static final StringProperty UUID = new StringProperty(TABLE, "remoteId"); + /** List of all properties for this model */ + public static final Property[] PROPERTIES = + new Property[] { + new StringProperty(TABLE, "calendarUri"), + COMPLETION_DATE, + new LongProperty(TABLE, "created"), + DELETION_DATE, + DUE_DATE, + new IntegerProperty(TABLE, "elapsedSeconds"), + new IntegerProperty(TABLE, "estimatedSeconds"), + HIDE_UNTIL, + ID, + IMPORTANCE, + MODIFICATION_DATE, + NOTES, + new StringProperty(TABLE, "recurrence"), + new IntegerProperty(TABLE, "notificationFlags"), + new LongProperty(TABLE, "lastNotified"), + new LongProperty(TABLE, "notifications"), + new LongProperty(TABLE, "snoozeTime"), + new LongProperty(TABLE, "repeatUntil"), + TIMER_START, + TITLE, + UUID + }; + /** 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; + public static final int IMPORTANCE_DO_OR_DIE = 0; public static final int IMPORTANCE_MUST_DO = 1; public static final int IMPORTANCE_SHOULD_DO = 2; public static final int IMPORTANCE_NONE = 3; - public static final Creator CREATOR = new Creator() { - @Override - public Task createFromParcel(Parcel source) { - return new Task(source); - } - - @Override - public Task[] newArray(int size) { - return new Task[size]; - } - }; - /** - * urgency array index -> significance - */ + public static final Creator CREATOR = + new Creator() { + @Override + public Task createFromParcel(Parcel source) { + return new Task(source); + } + + @Override + public Task[] newArray(int size) { + return new Task[size]; + } + }; + /** urgency array index -> significance */ public static final int URGENCY_NONE = 0; + 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; public static final int HIDE_UNTIL_WEEK_BEFORE = 3; @@ -164,110 +138,85 @@ public class Task implements Parcelable { static final int URGENCY_NEXT_MONTH = 6; // --- importance settings (note: importance > 3 are supported via plugin) - /** - * ID - */ + /** ID */ @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "_id") public transient Long id = NO_ID; - /** - * Name of Task - */ + /** Name of Task */ @ColumnInfo(name = "title") public String title = ""; - /** - * Importance of Task (see importance flags) - */ + /** Importance of Task (see importance flags) */ @ColumnInfo(name = "importance") public Integer importance = IMPORTANCE_NONE; - /** - * Unixtime Task is due, 0 if not set - */ + /** Unixtime Task is due, 0 if not set */ @ColumnInfo(name = "dueDate") public Long dueDate = 0L; - /** - * Unixtime Task should be hidden until, 0 if not set - */ + /** Unixtime Task should be hidden until, 0 if not set */ @ColumnInfo(name = "hideUntil") public Long hideUntil = 0L; - /** - * Unixtime Task was created - */ + /** Unixtime Task was created */ @ColumnInfo(name = "created") public Long created = 0L; - /** - * Unixtime Task was last touched - */ + /** Unixtime Task was last touched */ @ColumnInfo(name = "modified") public Long modified = 0L; - /** - * Unixtime Task was completed. 0 means active - */ + /** Unixtime Task was completed. 0 means active */ @ColumnInfo(name = "completed") public Long completed = 0L; // --- data access boilerplate - /** - * Unixtime Task was deleted. 0 means not deleted - */ + /** Unixtime Task was deleted. 0 means not deleted */ @ColumnInfo(name = "deleted") public Long deleted = 0L; + @ColumnInfo(name = "notes") public String notes = ""; + @ColumnInfo(name = "estimatedSeconds") public Integer estimatedSeconds = 0; + @ColumnInfo(name = "elapsedSeconds") public Integer elapsedSeconds = 0; + @ColumnInfo(name = "timerStart") public Long timerStart = 0L; - /** - * Flags for when to send reminders - */ + /** Flags for when to send reminders */ @ColumnInfo(name = "notificationFlags") public Integer notificationFlags = 0; // --- parcelable helpers - /** - * Reminder period, in milliseconds. 0 means disabled - */ + /** Reminder period, in milliseconds. 0 means disabled */ @ColumnInfo(name = "notifications") public Long notifications = 0L; // --- data access methods - /** - * Unixtime the last reminder was triggered - */ + /** Unixtime the last reminder was triggered */ @ColumnInfo(name = "lastNotified") public Long lastNotified = 0L; - /** - * Unixtime snooze is set (0 -> no snooze) - */ + /** Unixtime snooze is set (0 -> no snooze) */ @ColumnInfo(name = "snoozeTime") public Long snoozeTime = 0L; + @ColumnInfo(name = "recurrence") public String recurrence = ""; + @ColumnInfo(name = "repeatUntil") public Long repeatUntil = 0L; + @ColumnInfo(name = "calendarUri") public String calendarUri = ""; // --- due and hide until date management - /** - * Remote id - */ + /** Remote id */ @ColumnInfo(name = "remoteId") public String remoteId = NO_UUID; - @Ignore - private transient int indent; - @Ignore - private transient String tags; - @Ignore - private transient boolean hasFiles; - @Ignore - private transient HashMap transitoryData = null; - public Task() { - } + @Ignore private transient int indent; + @Ignore private transient String tags; + @Ignore private transient boolean hasFiles; + @Ignore private transient HashMap transitoryData = null; + + public Task() {} @Ignore public Task(Cursor _cursor) { @@ -443,8 +392,8 @@ public class Task implements Parcelable { } /** - * Creates due date for this task. If this due date has no time associated, - * we move it to the last millisecond of the day. + * 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 @@ -488,19 +437,18 @@ public class Task implements Parcelable { DateTime dueDate = newDateTime(date).withMillisOfSecond(0); if (setting != URGENCY_SPECIFIC_DAY_TIME) { - dueDate = dueDate - .withHourOfDay(12) - .withMinuteOfHour(0) - .withSecondOfMinute(0); // Seconds == 0 means no due time + dueDate = + dueDate + .withHourOfDay(12) + .withMinuteOfHour(0) + .withSecondOfMinute(0); // Seconds == 0 means no due time } else { dueDate = dueDate.withSecondOfMinute(1); // Seconds > 0 means due time exists } return dueDate.getMillis(); } - /** - * Checks whether provided due date has a due time or only a date - */ + /** Checks whether provided due date has a due time or only a date */ public static boolean hasDueTime(long dueDate) { return dueDate > 0 && (dueDate % 60000 > 0); } @@ -535,23 +483,17 @@ public class Task implements Parcelable { remoteId = uuid; } - /** - * Checks whether task is done. Requires COMPLETION_DATE - */ + /** Checks whether task is done. Requires COMPLETION_DATE */ public boolean isCompleted() { return completed > 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() { return deleted > 0; } - /** - * Checks whether task is hidden. Requires HIDDEN_UNTIL - */ + /** Checks whether task is hidden. Requires HIDDEN_UNTIL */ public boolean isHidden() { return hideUntil > DateUtilities.now(); } @@ -560,9 +502,7 @@ public class Task implements Parcelable { return hideUntil > 0; } - /** - * Checks whether task is done. Requires DUE_DATE - */ + /** Checks whether task is done. Requires DUE_DATE */ public boolean hasDueDate() { return dueDate > 0; } @@ -603,19 +543,14 @@ public class Task implements Parcelable { DateTime hideUntil = newDateTime(date).withMillisOfSecond(0); // get rid of millis if (setting != HIDE_UNTIL_SPECIFIC_DAY_TIME && setting != HIDE_UNTIL_DUE_TIME) { - hideUntil = hideUntil - .withHourOfDay(0) - .withMinuteOfHour(0) - .withSecondOfMinute(0); + hideUntil = hideUntil.withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0); } else { hideUntil = hideUntil.withSecondOfMinute(1); } return hideUntil.getMillis(); } - /** - * Checks whether this due date has a due time or only a date - */ + /** Checks whether this due date has a due time or only a date */ public boolean hasDueTime() { return hasDueDate() && hasDueTime(getDueDate()); } @@ -633,7 +568,7 @@ public class Task implements Parcelable { } public String sanitizedRecurrence() { - return getRecurrenceWithoutFrom().replaceAll("BYDAY=;", ""); //$NON-NLS-1$//$NON-NLS-2$ + return getRecurrenceWithoutFrom().replaceAll("BYDAY=;", ""); // $NON-NLS-1$//$NON-NLS-2$ } public String getRecurrenceWithoutFrom() { @@ -837,17 +772,13 @@ public class Task implements Parcelable { return getId() == NO_ID; } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public int describeContents() { return 0; } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(calendarUri); @@ -877,30 +808,57 @@ public class Task implements Parcelable { @Override public String toString() { - return "Task{" + - "id=" + id + - ", title='" + title + '\'' + - ", importance=" + importance + - ", dueDate=" + dueDate + - ", transitoryData=" + transitoryData + - ", hideUntil=" + hideUntil + - ", created=" + created + - ", modified=" + modified + - ", completed=" + completed + - ", deleted=" + deleted + - ", notes='" + notes + '\'' + - ", estimatedSeconds=" + estimatedSeconds + - ", elapsedSeconds=" + elapsedSeconds + - ", timerStart=" + timerStart + - ", notificationFlags=" + notificationFlags + - ", notifications=" + notifications + - ", lastNotified=" + lastNotified + - ", snoozeTime=" + snoozeTime + - ", recurrence='" + recurrence + '\'' + - ", repeatUntil=" + repeatUntil + - ", calendarUri='" + calendarUri + '\'' + - ", remoteId='" + remoteId + '\'' + - '}'; + return "Task{" + + "id=" + + id + + ", title='" + + title + + '\'' + + ", importance=" + + importance + + ", dueDate=" + + dueDate + + ", transitoryData=" + + transitoryData + + ", hideUntil=" + + hideUntil + + ", created=" + + created + + ", modified=" + + modified + + ", completed=" + + completed + + ", deleted=" + + deleted + + ", notes='" + + notes + + '\'' + + ", estimatedSeconds=" + + estimatedSeconds + + ", elapsedSeconds=" + + elapsedSeconds + + ", timerStart=" + + timerStart + + ", notificationFlags=" + + notificationFlags + + ", notifications=" + + notifications + + ", lastNotified=" + + lastNotified + + ", snoozeTime=" + + snoozeTime + + ", recurrence='" + + recurrence + + '\'' + + ", repeatUntil=" + + repeatUntil + + ", calendarUri='" + + calendarUri + + '\'' + + ", remoteId='" + + remoteId + + '\'' + + '}'; } public int getIndent() { @@ -949,19 +907,23 @@ public class Task implements Parcelable { if (notes != null ? !notes.equals(task.notes) : task.notes != null) { return false; } - if (estimatedSeconds != null ? !estimatedSeconds.equals(task.estimatedSeconds) + if (estimatedSeconds != null + ? !estimatedSeconds.equals(task.estimatedSeconds) : task.estimatedSeconds != null) { return false; } - if (elapsedSeconds != null ? !elapsedSeconds.equals(task.elapsedSeconds) + if (elapsedSeconds != null + ? !elapsedSeconds.equals(task.elapsedSeconds) : task.elapsedSeconds != null) { return false; } - if (notificationFlags != null ? !notificationFlags.equals(task.notificationFlags) + if (notificationFlags != null + ? !notificationFlags.equals(task.notificationFlags) : task.notificationFlags != null) { return false; } - if (notifications != null ? !notifications.equals(task.notifications) + if (notifications != null + ? !notifications.equals(task.notifications) : task.notifications != null) { return false; } @@ -1011,7 +973,8 @@ public class Task implements Parcelable { if (title != null ? !title.equals(original.title) : original.title != null) { return false; } - if (importance != null ? !importance.equals(original.importance) + if (importance != null + ? !importance.equals(original.importance) : original.importance != null) { return false; } @@ -1027,11 +990,13 @@ public class Task implements Parcelable { if (notes != null ? !notes.equals(original.notes) : original.notes != null) { return false; } - if (recurrence != null ? !recurrence.equals(original.recurrence) + if (recurrence != null + ? !recurrence.equals(original.recurrence) : original.recurrence != null) { return false; } - return repeatUntil != null ? repeatUntil.equals(original.repeatUntil) + return repeatUntil != null + ? repeatUntil.equals(original.repeatUntil) : original.repeatUntil == null; } @@ -1139,26 +1104,31 @@ public class Task implements Parcelable { if (notes != null ? !notes.equals(task.notes) : task.notes != null) { return false; } - if (estimatedSeconds != null ? !estimatedSeconds.equals(task.estimatedSeconds) + if (estimatedSeconds != null + ? !estimatedSeconds.equals(task.estimatedSeconds) : task.estimatedSeconds != null) { return false; } - if (elapsedSeconds != null ? !elapsedSeconds.equals(task.elapsedSeconds) + if (elapsedSeconds != null + ? !elapsedSeconds.equals(task.elapsedSeconds) : task.elapsedSeconds != null) { return false; } if (timerStart != null ? !timerStart.equals(task.timerStart) : task.timerStart != null) { return false; } - if (notificationFlags != null ? !notificationFlags.equals(task.notificationFlags) + if (notificationFlags != null + ? !notificationFlags.equals(task.notificationFlags) : task.notificationFlags != null) { return false; } - if (notifications != null ? !notifications.equals(task.notifications) + if (notifications != null + ? !notifications.equals(task.notifications) : task.notifications != null) { return false; } - if (lastNotified != null ? !lastNotified.equals(task.lastNotified) + if (lastNotified != null + ? !lastNotified.equals(task.lastNotified) : task.lastNotified != null) { return false; } diff --git a/app/src/main/java/com/todoroo/astrid/files/AACRecordingActivity.java b/app/src/main/java/com/todoroo/astrid/files/AACRecordingActivity.java index 204fc526c..6cf442e37 100644 --- a/app/src/main/java/com/todoroo/astrid/files/AACRecordingActivity.java +++ b/app/src/main/java/com/todoroo/astrid/files/AACRecordingActivity.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.files; import static org.tasks.PermissionUtil.verifyPermissions; @@ -21,10 +20,10 @@ import org.tasks.preferences.ActivityPermissionRequestor; import org.tasks.preferences.PermissionRequestor; import org.tasks.themes.Theme; -public class AACRecordingActivity extends InjectingAppCompatActivity implements - RecordAudioDialog.RecordAudioDialogCallback { +public class AACRecordingActivity extends InjectingAppCompatActivity + implements RecordAudioDialog.RecordAudioDialogCallback { - public static final String RESULT_OUTFILE = "outfile"; //$NON-NLS-1$ + public static final String RESULT_OUTFILE = "outfile"; // $NON-NLS-1$ private static final String FRAG_TAG_RECORD_AUDIO = "frag_tag_record_audio"; @Inject ActivityPermissionRequestor permissionRequestor; @Inject Theme theme; @@ -41,8 +40,8 @@ public class AACRecordingActivity extends InjectingAppCompatActivity implements private void showDialog() { FragmentManager supportFragmentManager = getSupportFragmentManager(); - RecordAudioDialog dialog = (RecordAudioDialog) supportFragmentManager - .findFragmentByTag(FRAG_TAG_RECORD_AUDIO); + RecordAudioDialog dialog = + (RecordAudioDialog) supportFragmentManager.findFragmentByTag(FRAG_TAG_RECORD_AUDIO); if (dialog == null) { dialog = newRecordAudioDialog(); dialog.show(supportFragmentManager, FRAG_TAG_RECORD_AUDIO); @@ -55,8 +54,8 @@ public class AACRecordingActivity extends InjectingAppCompatActivity implements } @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, - @NonNull int[] grantResults) { + public void onRequestPermissionsResult( + int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == PermissionRequestor.REQUEST_MIC) { if (verifyPermissions(grantResults)) { showDialog(); diff --git a/app/src/main/java/com/todoroo/astrid/files/FilesAction.java b/app/src/main/java/com/todoroo/astrid/files/FilesAction.java index 35c8604f5..28067aaf2 100644 --- a/app/src/main/java/com/todoroo/astrid/files/FilesAction.java +++ b/app/src/main/java/com/todoroo/astrid/files/FilesAction.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.files; import com.todoroo.astrid.api.TaskAction; diff --git a/app/src/main/java/com/todoroo/astrid/files/FilesControlSet.java b/app/src/main/java/com/todoroo/astrid/files/FilesControlSet.java index 0810f7950..386e3cac8 100644 --- a/app/src/main/java/com/todoroo/astrid/files/FilesControlSet.java +++ b/app/src/main/java/com/todoroo/astrid/files/FilesControlSet.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.files; import android.annotation.SuppressLint; @@ -53,8 +52,11 @@ public class FilesControlSet extends TaskEditControlFragment { @Inject DialogBuilder dialogBuilder; @Inject @ForActivity Context context; - @BindView(R.id.attachment_container) LinearLayout attachmentContainer; - @BindView(R.id.add_attachment) TextView addAttachment; + @BindView(R.id.attachment_container) + LinearLayout attachmentContainer; + + @BindView(R.id.add_attachment) + TextView addAttachment; private String taskUuid; @@ -73,8 +75,8 @@ public class FilesControlSet extends TaskEditControlFragment { @Nullable @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = super.onCreateView(inflater, container, savedInstanceState); taskUuid = task.getUuid(); @@ -90,8 +92,8 @@ public class FilesControlSet extends TaskEditControlFragment { @OnClick(R.id.add_attachment) void addAttachment(View view) { - startActivityForResult(new Intent(context, AddAttachmentActivity.class), - REQUEST_ADD_ATTACHMENT); + startActivityForResult( + new Intent(context, AddAttachmentActivity.class), REQUEST_ADD_ATTACHMENT); } @Override @@ -110,9 +112,7 @@ public class FilesControlSet extends TaskEditControlFragment { } @Override - public void apply(Task task) { - - } + public void apply(Task task) {} @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { @@ -129,8 +129,8 @@ public class FilesControlSet extends TaskEditControlFragment { } private void addAttachment(TaskAttachment taskAttachment) { - View fileRow = getActivity().getLayoutInflater() - .inflate(R.layout.file_row, attachmentContainer, false); + View fileRow = + getActivity().getLayoutInflater().inflate(R.layout.file_row, attachmentContainer, false); fileRow.setTag(taskAttachment); attachmentContainer.addView(fileRow); addAttachment(taskAttachment, fileRow); @@ -143,17 +143,21 @@ public class FilesControlSet extends TaskEditControlFragment { nameView.setOnClickListener(v -> showFile(taskAttachment)); View clearFile = fileRow.findViewById(R.id.clear); clearFile.setOnClickListener( - v -> dialogBuilder.newMessageDialog(R.string.premium_remove_file_confirm) - .setPositiveButton(android.R.string.ok, (dialog, which) -> { - taskAttachmentDao.delete(taskAttachment); - if (!Strings.isNullOrEmpty(taskAttachment.getPath())) { - File f = new File(taskAttachment.getPath()); - f.delete(); - } - attachmentContainer.removeView(fileRow); - }) - .setNegativeButton(android.R.string.cancel, null) - .show()); + v -> + dialogBuilder + .newMessageDialog(R.string.premium_remove_file_confirm) + .setPositiveButton( + android.R.string.ok, + (dialog, which) -> { + taskAttachmentDao.delete(taskAttachment); + if (!Strings.isNullOrEmpty(taskAttachment.getPath())) { + File f = new File(taskAttachment.getPath()); + f.delete(); + } + attachmentContainer.removeView(fileRow); + }) + .setNegativeButton(android.R.string.cancel, null) + .show()); } private void validateFiles(List files) { @@ -162,7 +166,7 @@ public class FilesControlSet extends TaskEditControlFragment { if (!Strings.isNullOrEmpty(m.getPath())) { File f = new File(m.getPath()); if (!f.exists()) { - m.setPath(""); //$NON-NLS-1$ + m.setPath(""); // $NON-NLS-1$ // No local file and no url -- delete the metadata taskAttachmentDao.delete(m); files.remove(i); @@ -183,16 +187,19 @@ public class FilesControlSet extends TaskEditControlFragment { @SuppressLint("NewApi") private void showFile(final TaskAttachment m) { - final String fileType = !Strings.isNullOrEmpty(m.getContentType()) ? m.getContentType() - : TaskAttachment.FILE_TYPE_OTHER; + final String fileType = + !Strings.isNullOrEmpty(m.getContentType()) + ? m.getContentType() + : TaskAttachment.FILE_TYPE_OTHER; final String filePath = m.getPath(); if (fileType.startsWith(TaskAttachment.FILE_TYPE_AUDIO)) { play(m.getPath(), () -> showFromIntent(filePath, fileType)); } else if (fileType.startsWith(TaskAttachment.FILE_TYPE_IMAGE)) { try { - Intent intent = FileHelper - .getReadableActionView(context, filePath, TaskAttachment.FILE_TYPE_IMAGE + "*"); + Intent intent = + FileHelper.getReadableActionView( + context, filePath, TaskAttachment.FILE_TYPE_IMAGE + "*"); getActivity().startActivity(intent); } catch (ActivityNotFoundException e) { Timber.e(e, e.getMessage()); @@ -228,8 +235,8 @@ public class FilesControlSet extends TaskEditControlFragment { } private void createNewFileAttachment(String path, String fileName, String fileType) { - TaskAttachment attachment = TaskAttachment - .createNewAttachment(taskUuid, path, fileName, fileType); + TaskAttachment attachment = + TaskAttachment.createNewAttachment(taskUuid, path, fileName, fileType); taskAttachmentDao.createNew(attachment); addAttachment(attachment); } diff --git a/app/src/main/java/com/todoroo/astrid/gcal/CalendarAlarmReceiver.java b/app/src/main/java/com/todoroo/astrid/gcal/CalendarAlarmReceiver.java index cde6b571b..f70f128df 100644 --- a/app/src/main/java/com/todoroo/astrid/gcal/CalendarAlarmReceiver.java +++ b/app/src/main/java/com/todoroo/astrid/gcal/CalendarAlarmReceiver.java @@ -53,8 +53,8 @@ public class CalendarAlarmReceiver extends InjectingBroadcastReceiver { } long eventId = Long.parseLong(uriString.substring(pathIndex)); if (eventId > 0) { - boolean fromPostpone = CalendarNotificationIntentService.URI_PREFIX_POSTPONE - .equals(data.getScheme()); + boolean fromPostpone = + CalendarNotificationIntentService.URI_PREFIX_POSTPONE.equals(data.getScheme()); showCalReminder(context, eventId, fromPostpone); } } catch (IllegalArgumentException e) { diff --git a/app/src/main/java/com/todoroo/astrid/gcal/CalendarReminderActivity.java b/app/src/main/java/com/todoroo/astrid/gcal/CalendarReminderActivity.java index 2221fe6a3..69b009c28 100644 --- a/app/src/main/java/com/todoroo/astrid/gcal/CalendarReminderActivity.java +++ b/app/src/main/java/com/todoroo/astrid/gcal/CalendarReminderActivity.java @@ -35,27 +35,31 @@ public class CalendarReminderActivity extends ThemedInjectingAppCompatActivity { private final OnClickListener dismissListener = v -> finish(); @Inject Preferences preferences; @Inject DialogBuilder dialogBuilder; - private final OnClickListener ignoreListener = new OnClickListener() { - @Override - public void onClick(final View v) { - // Check for number of ignore presses - int ignorePresses = preferences.getInt(PREF_IGNORE_PRESSES, 0); - ignorePresses++; - if (ignorePresses == IGNORE_PROMPT_COUNT) { - dialogBuilder.newMessageDialog(R.string.CRA_ignore_body) - .setPositiveButton(R.string.CRA_ignore_all, (dialog, which) -> { - preferences.setBoolean(R.string.p_calendar_reminders, false); - dismissListener.onClick(v); - }) - .setNegativeButton(R.string.CRA_ignore_this, - (dialog, which) -> dismissListener.onClick(v)) - .show(); - } else { - dismissListener.onClick(v); - } - preferences.setInt(PREF_IGNORE_PRESSES, ignorePresses); - } - }; + private final OnClickListener ignoreListener = + new OnClickListener() { + @Override + public void onClick(final View v) { + // Check for number of ignore presses + int ignorePresses = preferences.getInt(PREF_IGNORE_PRESSES, 0); + ignorePresses++; + if (ignorePresses == IGNORE_PROMPT_COUNT) { + dialogBuilder + .newMessageDialog(R.string.CRA_ignore_body) + .setPositiveButton( + R.string.CRA_ignore_all, + (dialog, which) -> { + preferences.setBoolean(R.string.p_calendar_reminders, false); + dismissListener.onClick(v); + }) + .setNegativeButton( + R.string.CRA_ignore_this, (dialog, which) -> dismissListener.onClick(v)) + .show(); + } else { + dismissListener.onClick(v); + } + preferences.setInt(PREF_IGNORE_PRESSES, ignorePresses); + } + }; @Inject AlarmManager alarmManager; @Inject ThemeAccent themeAccent; private String eventName; @@ -78,8 +82,8 @@ public class CalendarReminderActivity extends ThemedInjectingAppCompatActivity { fromPostpone = intent.getBooleanExtra(TOKEN_FROM_POSTPONE, false); eventId = intent.getLongExtra(TOKEN_EVENT_ID, -1); eventName = intent.getStringExtra(TOKEN_EVENT_NAME); - endTime = intent - .getLongExtra(TOKEN_EVENT_END_TIME, DateUtilities.now() + DateUtilities.ONE_HOUR); + endTime = + intent.getLongExtra(TOKEN_EVENT_END_TIME, DateUtilities.now() + DateUtilities.ONE_HOUR); createListButton = findViewById(R.id.create_list); postponeButton = findViewById(R.id.postpone); @@ -98,8 +102,7 @@ public class CalendarReminderActivity extends ThemedInjectingAppCompatActivity { } private void setupUi() { - ((TextView) findViewById(R.id.reminder_title)) - .setText(getString(R.string.CRA_title)); + ((TextView) findViewById(R.id.reminder_title)).setText(getString(R.string.CRA_title)); TextView dialogView = findViewById(R.id.reminder_message); String speechText; @@ -122,11 +125,13 @@ public class CalendarReminderActivity extends ThemedInjectingAppCompatActivity { ignoreButton.setOnClickListener(ignoreListener); dismissButton.setOnClickListener(dismissListener); - ignoreSettingsButton.setOnClickListener(v -> { - Intent editPreferences = new Intent(CalendarReminderActivity.this, BasicPreferences.class); - startActivity(editPreferences); - dismissListener.onClick(v); - }); + ignoreSettingsButton.setOnClickListener( + v -> { + Intent editPreferences = + new Intent(CalendarReminderActivity.this, BasicPreferences.class); + startActivity(editPreferences); + dismissListener.onClick(v); + }); if (!fromPostpone) { postponeButton.setOnClickListener(v -> postpone()); @@ -149,8 +154,9 @@ public class CalendarReminderActivity extends ThemedInjectingAppCompatActivity { eventAlarm.setData( Uri.parse(CalendarNotificationIntentService.URI_PREFIX_POSTPONE + "://" + eventId)); - PendingIntent pendingIntent = PendingIntent.getBroadcast(this, - CalendarAlarmReceiver.REQUEST_CODE_CAL_REMINDER, eventAlarm, 0); + PendingIntent pendingIntent = + PendingIntent.getBroadcast( + this, CalendarAlarmReceiver.REQUEST_CODE_CAL_REMINDER, eventAlarm, 0); alarmManager.cancel(pendingIntent); @@ -158,5 +164,4 @@ public class CalendarReminderActivity extends ThemedInjectingAppCompatActivity { alarmManager.wakeup(alarmTime, pendingIntent); dismissButton.performClick(); } - } diff --git a/app/src/main/java/com/todoroo/astrid/gcal/GCalHelper.java b/app/src/main/java/com/todoroo/astrid/gcal/GCalHelper.java index 824f3a224..04c8935fe 100644 --- a/app/src/main/java/com/todoroo/astrid/gcal/GCalHelper.java +++ b/app/src/main/java/com/todoroo/astrid/gcal/GCalHelper.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.gcal; import android.content.ContentResolver; @@ -28,9 +27,7 @@ import timber.log.Timber; 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; private final TaskDao taskDao; @@ -40,8 +37,12 @@ public class GCalHelper { private final ContentResolver cr; @Inject - public GCalHelper(@ForApplication Context context, TaskDao taskDao, Preferences preferences, - PermissionChecker permissionChecker, CalendarEventProvider calendarEventProvider) { + public GCalHelper( + @ForApplication Context context, + TaskDao taskDao, + Preferences preferences, + PermissionChecker permissionChecker, + CalendarEventProvider calendarEventProvider) { this.taskDao = taskDao; this.preferences = preferences; this.permissionChecker = permissionChecker; @@ -99,8 +100,9 @@ public class GCalHelper { values.put(CalendarContract.Events.TITLE, task.getTitle()); values.put(CalendarContract.Events.DESCRIPTION, task.getNotes()); values.put(CalendarContract.Events.HAS_ALARM, 0); - boolean valuesContainCalendarId = (values.containsKey(CalendarContract.Events.CALENDAR_ID) && - !TextUtils.isEmpty(values.getAsString(CalendarContract.Events.CALENDAR_ID))); + boolean valuesContainCalendarId = + (values.containsKey(CalendarContract.Events.CALENDAR_ID) + && !TextUtils.isEmpty(values.getAsString(CalendarContract.Events.CALENDAR_ID))); if (!valuesContainCalendarId) { String calendarId = preferences.getDefaultCalendar(); if (!TextUtils.isEmpty(calendarId)) { diff --git a/app/src/main/java/com/todoroo/astrid/gtasks/GtasksFilterExposer.java b/app/src/main/java/com/todoroo/astrid/gtasks/GtasksFilterExposer.java index 3fa0f30ce..730e34fcd 100644 --- a/app/src/main/java/com/todoroo/astrid/gtasks/GtasksFilterExposer.java +++ b/app/src/main/java/com/todoroo/astrid/gtasks/GtasksFilterExposer.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.gtasks; import static com.google.common.collect.Lists.newArrayList; diff --git a/app/src/main/java/com/todoroo/astrid/gtasks/GtasksListService.java b/app/src/main/java/com/todoroo/astrid/gtasks/GtasksListService.java index 85c45ffb0..cd2ad990c 100644 --- a/app/src/main/java/com/todoroo/astrid/gtasks/GtasksListService.java +++ b/app/src/main/java/com/todoroo/astrid/gtasks/GtasksListService.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.gtasks; import static com.google.common.collect.Lists.newArrayList; @@ -32,9 +31,12 @@ public class GtasksListService { private final TaskDao taskDao; @Inject - public GtasksListService(GoogleTaskListDao googleTaskListDao, - TaskDeleter taskDeleter, LocalBroadcastManager localBroadcastManager, - GoogleTaskDao googleTaskDao, TaskDao taskDao) { + public GtasksListService( + GoogleTaskListDao googleTaskListDao, + TaskDeleter taskDeleter, + LocalBroadcastManager localBroadcastManager, + GoogleTaskDao googleTaskDao, + TaskDao taskDao) { this.googleTaskListDao = googleTaskListDao; this.taskDeleter = taskDeleter; this.localBroadcastManager = localBroadcastManager; @@ -113,8 +115,9 @@ public class GtasksListService { long lastUpdate = remoteList.getUpdated().getValue(); if (lastSync < lastUpdate) { listsToUpdate.add(localList); - Timber.d("%s out of date [local=%s] [remote=%s]", listName, printTimestamp(lastSync), - printTimestamp(lastUpdate)); + Timber.d( + "%s out of date [local=%s] [remote=%s]", + listName, printTimestamp(lastSync), printTimestamp(lastUpdate)); } else { Timber.d("%s up to date", listName); } diff --git a/app/src/main/java/com/todoroo/astrid/gtasks/GtasksPreferenceService.java b/app/src/main/java/com/todoroo/astrid/gtasks/GtasksPreferenceService.java index e599efecf..4d6f4a22b 100644 --- a/app/src/main/java/com/todoroo/astrid/gtasks/GtasksPreferenceService.java +++ b/app/src/main/java/com/todoroo/astrid/gtasks/GtasksPreferenceService.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.gtasks; import com.todoroo.andlib.utility.DateUtilities; @@ -17,10 +16,10 @@ import org.tasks.preferences.Preferences; */ public class GtasksPreferenceService { - private static final String IDENTIFIER = "gtasks"; //$NON-NLS-1$ - public static final String PREF_USER_NAME = IDENTIFIER + "_user"; //$NON-NLS-1$ - private static final String PREF_LAST_SYNC = "_last_sync"; //$NON-NLS-1$ - private static final String PREF_ONGOING = "_ongoing"; //$NON-NLS-1$ + private static final String IDENTIFIER = "gtasks"; // $NON-NLS-1$ + public static final String PREF_USER_NAME = IDENTIFIER + "_user"; // $NON-NLS-1$ + private static final String PREF_LAST_SYNC = "_last_sync"; // $NON-NLS-1$ + private static final String PREF_ONGOING = "_ongoing"; // $NON-NLS-1$ private final Preferences preferences; @Inject @@ -36,44 +35,32 @@ public class GtasksPreferenceService { preferences.setString(PREF_USER_NAME, userName); } - /** - * @return Last Successful Sync Date, or 0 - */ + /** @return Last Successful Sync Date, or 0 */ public long getLastSyncDate() { return preferences.getLong(IDENTIFIER + PREF_LAST_SYNC, 0); } - /** - * @return Last Error, or null if no last error - */ + /** @return Last Error, or null if no last error */ public boolean isOngoing() { return preferences.getBoolean(IDENTIFIER + PREF_ONGOING, false); } - /** - * Deletes Last Successful Sync Date - */ + /** Deletes Last Successful Sync Date */ public void clearLastSyncDate() { preferences.clear(IDENTIFIER + PREF_LAST_SYNC); } - /** - * Set Ongoing - */ + /** Set Ongoing */ public void stopOngoing() { preferences.setBoolean(IDENTIFIER + PREF_ONGOING, false); } - /** - * Set Last Successful Sync Date - */ + /** Set Last Successful Sync Date */ public void recordSuccessfulSync() { preferences.setLong(IDENTIFIER + PREF_LAST_SYNC, DateUtilities.now() + 1000); } - /** - * Set Last Attempted Sync Date - */ + /** Set Last Attempted Sync Date */ public void recordSyncStart() { preferences.setBoolean(IDENTIFIER + PREF_ONGOING, true); } diff --git a/app/src/main/java/com/todoroo/astrid/gtasks/GtasksSubtaskListFragment.java b/app/src/main/java/com/todoroo/astrid/gtasks/GtasksSubtaskListFragment.java index f8113e88c..62e7a7d52 100644 --- a/app/src/main/java/com/todoroo/astrid/gtasks/GtasksSubtaskListFragment.java +++ b/app/src/main/java/com/todoroo/astrid/gtasks/GtasksSubtaskListFragment.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.gtasks; import android.app.Activity; @@ -25,8 +24,8 @@ public class GtasksSubtaskListFragment extends GtasksListFragment { @Inject OrderedMetadataListFragmentHelper helper; - public static TaskListFragment newGtasksSubtaskListFragment(GtasksFilter filter, - GoogleTaskList list) { + public static TaskListFragment newGtasksSubtaskListFragment( + GtasksFilter filter, GoogleTaskList list) { GtasksSubtaskListFragment fragment = new GtasksSubtaskListFragment(); fragment.filter = filter; fragment.list = list; diff --git a/app/src/main/java/com/todoroo/astrid/gtasks/GtasksTaskListUpdater.java b/app/src/main/java/com/todoroo/astrid/gtasks/GtasksTaskListUpdater.java index 01ba95f31..1ea91b25a 100644 --- a/app/src/main/java/com/todoroo/astrid/gtasks/GtasksTaskListUpdater.java +++ b/app/src/main/java/com/todoroo/astrid/gtasks/GtasksTaskListUpdater.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.gtasks; import com.todoroo.astrid.api.Filter; @@ -28,14 +27,10 @@ import timber.log.Timber; @ApplicationScope public class GtasksTaskListUpdater { - /** - * 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<>(); private final GtasksSyncService gtasksSyncService; @@ -70,12 +65,15 @@ public class GtasksTaskListUpdater { // --- used during synchronization public void correctOrderAndIndentForList(String listId) { - orderAndIndentHelper(listId, new AtomicLong(0L), Task.NO_ID, 0, - new HashSet<>()); + orderAndIndentHelper(listId, new AtomicLong(0L), Task.NO_ID, 0, new HashSet<>()); } - private void orderAndIndentHelper(final String listId, final AtomicLong order, final long parent, - final int indentLevel, final Set alreadyChecked) { + private void orderAndIndentHelper( + final String listId, + final AtomicLong order, + final long parent, + final int indentLevel, + final Set alreadyChecked) { for (GoogleTask curr : googleTaskDao.byRemoteOrder(listId, parent)) { if (!alreadyChecked.contains(curr.getTask())) { curr.setIndent(indentLevel); @@ -92,43 +90,43 @@ public class GtasksTaskListUpdater { final AtomicLong previousTask = new AtomicLong(Task.NO_ID); final AtomicInteger previousIndent = new AtomicInteger(-1); - iterateThroughList(list, (taskId, metadata) -> { - int indent = metadata.getIndent(); - - try { - long parent, sibling; - if (indent > previousIndent.get()) { - parent = previousTask.get(); - sibling = Task.NO_ID; - } 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++) { - sibling = parents.get(sibling); + iterateThroughList( + list, + (taskId, metadata) -> { + int indent = metadata.getIndent(); + + try { + long parent, sibling; + if (indent > previousIndent.get()) { + parent = previousTask.get(); + sibling = Task.NO_ID; + } 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++) { + sibling = parents.get(sibling); + } + if (parents.containsKey(sibling)) { + parent = parents.get(sibling); + } else { + parent = Task.NO_ID; + } + } + parents.put(taskId, parent); + siblings.put(taskId, sibling); + } catch (Exception e) { + Timber.e(e, e.getMessage()); } - if (parents.containsKey(sibling)) { - parent = parents.get(sibling); - } else { - parent = Task.NO_ID; - } - } - parents.put(taskId, parent); - siblings.put(taskId, sibling); - } catch (Exception e) { - Timber.e(e, e.getMessage()); - } - previousTask.set(taskId); - previousIndent.set(indent); - }); + previousTask.set(taskId); + previousIndent.set(indent); + }); } - /** - * Indent a task and all its children - */ + /** Indent a task and all its children */ public void indent(final GoogleTaskList list, final long targetTaskId, final int delta) { if (list == null) { return; @@ -141,47 +139,49 @@ public class GtasksTaskListUpdater { final AtomicLong previousTask = new AtomicLong(Task.NO_ID); final AtomicLong globalOrder = new AtomicLong(-1); - iterateThroughList(list, (taskId, googleTask) -> { - int indent = googleTask.getIndent(); - - long order = globalOrder.incrementAndGet(); - googleTask.setOrder(order); - - if (targetTaskId == taskId) { - // if indenting is warranted, indent me and my children - if (indent + delta <= previousIndent.get() + 1 && indent + delta >= 0) { - targetTaskIndent.set(indent); - googleTask.setIndent(indent + delta); - - long newParent = computeNewParent(list, taskId, indent + delta - 1); - if (newParent == taskId) { - googleTask.setParent(Task.NO_ID); + iterateThroughList( + list, + (taskId, googleTask) -> { + int indent = googleTask.getIndent(); + + long order = globalOrder.incrementAndGet(); + googleTask.setOrder(order); + + if (targetTaskId == taskId) { + // if indenting is warranted, indent me and my children + if (indent + delta <= previousIndent.get() + 1 && indent + delta >= 0) { + targetTaskIndent.set(indent); + googleTask.setIndent(indent + delta); + + long newParent = computeNewParent(list, taskId, indent + delta - 1); + if (newParent == taskId) { + googleTask.setParent(Task.NO_ID); + } else { + googleTask.setParent(newParent); + } + saveAndUpdateModifiedDate(googleTask); + } + } else if (targetTaskIndent.get() > -1) { + // found first task that is not beneath target + if (indent <= targetTaskIndent.get()) { + targetTaskIndent.set(-1); + } else { + googleTask.setIndent(indent + delta); + saveAndUpdateModifiedDate(googleTask); + } } else { - googleTask.setParent(newParent); + previousIndent.set(indent); + previousTask.set(taskId); } - saveAndUpdateModifiedDate(googleTask); - } - } else if (targetTaskIndent.get() > -1) { - // found first task that is not beneath target - if (indent <= targetTaskIndent.get()) { - targetTaskIndent.set(-1); - } else { - googleTask.setIndent(indent + delta); - saveAndUpdateModifiedDate(googleTask); - } - } else { - previousIndent.set(indent); - previousTask.set(taskId); - } - saveAndUpdateModifiedDate(googleTask); - }); + saveAndUpdateModifiedDate(googleTask); + }); onMovedOrIndented(getTaskMetadata(targetTaskId)); } /** - * Helper function to iterate through a list and compute a new parent for the target task - * based on the target parent's indent + * Helper function to iterate through a list and compute a new parent for the target task based on + * the target parent's indent */ private long computeNewParent(GoogleTaskList list, long targetTaskId, int targetParentIndent) { final AtomicInteger desiredParentIndent = new AtomicInteger(targetParentIndent); @@ -189,16 +189,18 @@ public class GtasksTaskListUpdater { final AtomicLong lastPotentialParent = new AtomicLong(Task.NO_ID); final AtomicBoolean computedParent = new AtomicBoolean(false); - iterateThroughList(list, (taskId, googleTask) -> { - if (targetTask.get() == taskId) { - computedParent.set(true); - } + iterateThroughList( + list, + (taskId, googleTask) -> { + if (targetTask.get() == taskId) { + computedParent.set(true); + } - int indent = googleTask.getIndent(); - if (!computedParent.get() && indent == desiredParentIndent.get()) { - lastPotentialParent.set(taskId); - } - }); + int indent = googleTask.getIndent(); + if (!computedParent.get() && indent == desiredParentIndent.get()) { + lastPotentialParent.set(taskId); + } + }); if (lastPotentialParent.get() == Task.NO_ID) { return Task.NO_ID; @@ -207,11 +209,10 @@ public class GtasksTaskListUpdater { } /** - * Move a task and all its children to the position right above - * taskIdToMoveto. Will change the indent level to match taskIdToMoveTo. + * Move a task and all its children to the position right above taskIdToMoveto. Will change the + * indent level to match taskIdToMoveTo. */ - void moveTo(GoogleTaskList list, final long targetTaskId, - final long moveBeforeTaskId) { + void moveTo(GoogleTaskList list, final long targetTaskId, final long moveBeforeTaskId) { if (list == null) { return; } @@ -229,8 +230,7 @@ public class GtasksTaskListUpdater { if (sibling != null && !ancestorOf(target, sibling)) { int index = sibling.parent.children.indexOf(sibling); - if (target.parent == sibling.parent && - target.parent.children.indexOf(target) < index) { + if (target.parent == sibling.parent && target.parent.children.indexOf(target) < index) { index--; } @@ -257,8 +257,8 @@ public class GtasksTaskListUpdater { return ancestorOf(ancestor, descendant.parent); } - private void traverseTreeAndWriteValues(GoogleTaskList list, Node node, AtomicLong order, - int indent) { + private void traverseTreeAndWriteValues( + GoogleTaskList list, Node node, AtomicLong order, int indent) { if (node.taskId != Task.NO_ID) { GoogleTask googleTask = getTaskMetadata(node.taskId); if (googleTask == null) { @@ -300,33 +300,35 @@ public class GtasksTaskListUpdater { final AtomicInteger previoustIndent = new AtomicInteger(-1); final AtomicReference currentNode = new AtomicReference<>(root); - iterateThroughList(list, (taskId, googleTask) -> { - int indent = googleTask.getIndent(); - - int previousIndentValue = previoustIndent.get(); - 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 - 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++) { - node = node.parent; - if (node == null) { - node = root; - break; + iterateThroughList( + list, + (taskId, googleTask) -> { + int indent = googleTask.getIndent(); + + int previousIndentValue = previoustIndent.get(); + 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 + 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++) { + node = node.parent; + if (node == null) { + node = root; + break; + } + } + currentNode.set(new Node(taskId, node)); + node.children.add(currentNode.get()); } - } - currentNode.set(new Node(taskId, node)); - node.children.add(currentNode.get()); - } - previoustIndent.set(indent); - }); + previoustIndent.set(indent); + }); return root; } @@ -334,11 +336,8 @@ public class GtasksTaskListUpdater { googleTaskDao.update(googleTask); } - /** - * Apply an operation only to the children of the task - */ - void applyToChildren(GoogleTaskList list, long targetTaskId, - OrderedListNodeVisitor visitor) { + /** Apply an operation only to the children of the task */ + void applyToChildren(GoogleTaskList list, long targetTaskId, OrderedListNodeVisitor visitor) { Node root = buildTreeModel(list); Node target = findNode(root, targetTaskId); @@ -359,9 +358,7 @@ public class GtasksTaskListUpdater { // --- task cascading operations - /** - * Removes a task from the order hierarchy and un-indent children - */ + /** Removes a task from the order hierarchy and un-indent children */ void onDeleteTask(GoogleTaskList list, final long targetTaskId) { if (list == null) { return; @@ -404,4 +401,3 @@ public class GtasksTaskListUpdater { } } } - diff --git a/app/src/main/java/com/todoroo/astrid/gtasks/OrderedMetadataListFragmentHelper.java b/app/src/main/java/com/todoroo/astrid/gtasks/OrderedMetadataListFragmentHelper.java index 81c793391..0daf5d75d 100644 --- a/app/src/main/java/com/todoroo/astrid/gtasks/OrderedMetadataListFragmentHelper.java +++ b/app/src/main/java/com/todoroo/astrid/gtasks/OrderedMetadataListFragmentHelper.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.gtasks; import android.text.TextUtils; @@ -36,8 +35,8 @@ class OrderedMetadataListFragmentHelper { private GoogleTaskList list; @Inject - OrderedMetadataListFragmentHelper(TaskDao taskDao, GtasksTaskListUpdater updater, - GoogleTaskDao googleTaskDao) { + OrderedMetadataListFragmentHelper( + TaskDao taskDao, GtasksTaskListUpdater updater, GoogleTaskDao googleTaskDao) { this.taskDao = taskDao; this.updater = updater; this.googleTaskDao = googleTaskDao; @@ -79,18 +78,21 @@ class OrderedMetadataListFragmentHelper { final ArrayList chained = new ArrayList<>(); final int parentIndent = item.getIndent(); - updater.applyToChildren(list, itemId, node -> { - Task childTask = taskDao.fetch(node.taskId); - if (!TextUtils.isEmpty(childTask.getRecurrence())) { - GoogleTask googleTask = updater.getTaskMetadata(node.taskId); - googleTask.setIndent(parentIndent); - googleTaskDao.update(googleTask); - } - childTask.setCompletionDate(completionDate); - taskDao.save(childTask); - - chained.add(node.taskId); - }); + updater.applyToChildren( + list, + itemId, + node -> { + Task childTask = taskDao.fetch(node.taskId); + if (!TextUtils.isEmpty(childTask.getRecurrence())) { + GoogleTask googleTask = updater.getTaskMetadata(node.taskId); + googleTask.setIndent(parentIndent); + googleTaskDao.update(googleTask); + } + childTask.setCompletionDate(completionDate); + taskDao.save(childTask); + + chained.add(node.taskId); + }); if (chained.size() > 0) { chainedCompletions.put(itemId, chained); @@ -129,7 +131,8 @@ class OrderedMetadataListFragmentHelper { public void moved(int from, int to) { long targetTaskId = taskAdapter.getTaskId(from); if (targetTaskId <= 0) { - return; // This can happen with gestures on empty parts of the list (e.g. extra space below tasks) + return; // This can happen with gestures on empty parts of the list (e.g. extra space below + // tasks) } try { @@ -148,7 +151,8 @@ class OrderedMetadataListFragmentHelper { public void indented(int which, int delta) { long targetTaskId = taskAdapter.getTaskId(which); if (targetTaskId <= 0) { - return; // This can happen with gestures on empty parts of the list (e.g. extra space below tasks) + return; // This can happen with gestures on empty parts of the list (e.g. extra space below + // tasks) } try { updater.indent(list, targetTaskId, delta); diff --git a/app/src/main/java/com/todoroo/astrid/gtasks/api/GtasksApiUtilities.java b/app/src/main/java/com/todoroo/astrid/gtasks/api/GtasksApiUtilities.java index 2e988789b..cbd566c81 100644 --- a/app/src/main/java/com/todoroo/astrid/gtasks/api/GtasksApiUtilities.java +++ b/app/src/main/java/com/todoroo/astrid/gtasks/api/GtasksApiUtilities.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.gtasks.api; import com.google.api.client.util.DateTime; @@ -28,10 +27,10 @@ public class GtasksApiUtilities { } /** - * Google deals only in dates for due times, so on the server side they normalize to utc time - * and then truncate h:m:s to 0. This can lead to a loss of date information for - * us, so we adjust here by doing the normalizing/truncating ourselves and - * then correcting the date we get back in a similar way. + * Google deals only in dates for due times, so on the server side they normalize to utc time and + * then truncate h:m:s to 0. This can lead to a loss of date information for us, so we adjust here + * by doing the normalizing/truncating ourselves and then correcting the date we get back in a + * similar way. */ public static DateTime unixTimeToGtasksDueDate(long time) { if (time < 0) { @@ -45,13 +44,13 @@ public class GtasksApiUtilities { return new DateTime(date, TimeZone.getTimeZone("GMT")); } - //Adjust for google's rounding + // Adjust for google's rounding public static long gtasksDueTimeToUnixTime(DateTime gtasksDueTime) { if (gtasksDueTime == null) { return 0; } try { - long utcTime = gtasksDueTime.getValue(); //DateTime.parseRfc3339(gtasksDueTime).value; + long utcTime = gtasksDueTime.getValue(); // DateTime.parseRfc3339(gtasksDueTime).value; Date date = new Date(utcTime); Date returnDate = new Date(date.getTime() + date.getTimezoneOffset() * 60000); return returnDate.getTime(); diff --git a/app/src/main/java/com/todoroo/astrid/gtasks/api/GtasksInvoker.java b/app/src/main/java/com/todoroo/astrid/gtasks/api/GtasksInvoker.java index 2682eddbd..c70d259be 100644 --- a/app/src/main/java/com/todoroo/astrid/gtasks/api/GtasksInvoker.java +++ b/app/src/main/java/com/todoroo/astrid/gtasks/api/GtasksInvoker.java @@ -25,8 +25,8 @@ import org.tasks.injection.ForApplication; import timber.log.Timber; /** - * Wrapper around the official Google Tasks API to simplify common operations. In the case - * of an exception, each request is tried twice in case of a timeout. + * Wrapper around the official Google Tasks API to simplify common operations. In the case of an + * exception, each request is tried twice in case of a timeout. * * @author Sam Bosley */ @@ -38,15 +38,18 @@ public class GtasksInvoker { private final Tasks service; @Inject - public GtasksInvoker(@ForApplication Context context, GtasksPreferenceService preferenceService, + public GtasksInvoker( + @ForApplication Context context, + GtasksPreferenceService preferenceService, PlayServices playServices) { - credential = GoogleAccountCredential - .usingOAuth2(context, Collections.singletonList(TasksScopes.TASKS)); + credential = + GoogleAccountCredential.usingOAuth2(context, Collections.singletonList(TasksScopes.TASKS)); this.playServices = playServices; setUserName(preferenceService.getUserName()); - service = new Tasks.Builder(new NetHttpTransport(), new JacksonFactory(), credential) - .setApplicationName(String.format("Tasks/%s", BuildConfig.VERSION_NAME)) - .build(); + service = + new Tasks.Builder(new NetHttpTransport(), new JacksonFactory(), credential) + .setApplicationName(String.format("Tasks/%s", BuildConfig.VERSION_NAME)) + .build(); } public void setUserName(String username) { @@ -54,80 +57,64 @@ public class GtasksInvoker { } public TaskLists allGtaskLists(String pageToken) throws IOException { - return execute(service - .tasklists() - .list() - .setPageToken(pageToken)); + return execute(service.tasklists().list().setPageToken(pageToken)); } - public com.google.api.services.tasks.model.Tasks getAllGtasksFromListId(String listId, - boolean includeDeleted, boolean includeHidden, long lastSyncDate, String pageToken) + public com.google.api.services.tasks.model.Tasks getAllGtasksFromListId( + String listId, + boolean includeDeleted, + boolean includeHidden, + long lastSyncDate, + String pageToken) throws IOException { - return execute(service - .tasks() - .list(listId) - .setShowDeleted(includeDeleted) - .setShowHidden(includeHidden) - .setPageToken(pageToken) - .setUpdatedMin( - GtasksApiUtilities.unixTimeToGtasksCompletionTime(lastSyncDate).toStringRfc3339())); + return execute( + service + .tasks() + .list(listId) + .setShowDeleted(includeDeleted) + .setShowHidden(includeHidden) + .setPageToken(pageToken) + .setUpdatedMin( + GtasksApiUtilities.unixTimeToGtasksCompletionTime(lastSyncDate).toStringRfc3339())); } public Task createGtask(String listId, Task task, String parent, String priorSiblingId) throws IOException { Timber.d("createGtask: %s", prettyPrint(task)); - return execute(service - .tasks() - .insert(listId, task) - .setParent(parent) - .setPrevious(priorSiblingId)); + return execute( + service.tasks().insert(listId, task).setParent(parent).setPrevious(priorSiblingId)); } public void updateGtask(String listId, Task task) throws IOException { Timber.d("updateGtask: %s", prettyPrint(task)); - execute(service - .tasks() - .update(listId, task.getId(), task)); + execute(service.tasks().update(listId, task.getId(), task)); } public Task moveGtask(String listId, String taskId, String parentId, String previousId) throws IOException { - return execute(service - .tasks() - .move(listId, taskId) - .setParent(parentId) - .setPrevious(previousId)); + return execute( + service.tasks().move(listId, taskId).setParent(parentId).setPrevious(previousId)); } public void deleteGtaskList(String listId) throws IOException { - execute(service - .tasklists() - .delete(listId)); + execute(service.tasklists().delete(listId)); } public TaskList renameGtaskList(String listId, String title) throws IOException { - return execute(service - .tasklists() - .patch(listId, new TaskList().setTitle(title))); + return execute(service.tasklists().patch(listId, new TaskList().setTitle(title))); } public TaskList createGtaskList(String title) throws IOException { - return execute(service - .tasklists() - .insert(new TaskList().setTitle(title))); + return execute(service.tasklists().insert(new TaskList().setTitle(title))); } public void clearCompleted(String listId) throws IOException { - execute(service - .tasks() - .clear(listId)); + execute(service.tasks().clear(listId)); } public void deleteGtask(String listId, String taskId) throws IOException { try { - execute(service - .tasks() - .delete(listId, taskId)); + execute(service.tasks().delete(listId, taskId)); } catch (HttpNotFoundException ignored) { } diff --git a/app/src/main/java/com/todoroo/astrid/gtasks/api/MoveRequest.java b/app/src/main/java/com/todoroo/astrid/gtasks/api/MoveRequest.java index cb587f1b1..fb1f83d58 100644 --- a/app/src/main/java/com/todoroo/astrid/gtasks/api/MoveRequest.java +++ b/app/src/main/java/com/todoroo/astrid/gtasks/api/MoveRequest.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.gtasks.api; import com.google.api.services.tasks.model.Task; @@ -23,7 +22,11 @@ public class MoveRequest { private String parentId; private String priorSiblingId; - public MoveRequest(GtasksInvoker service, String taskId, String destinationList, String parentId, + public MoveRequest( + GtasksInvoker service, + String taskId, + String destinationList, + String parentId, String priorSiblingId) { this.service = service; this.taskId = taskId; diff --git a/app/src/main/java/com/todoroo/astrid/gtasks/auth/GtasksLoginActivity.java b/app/src/main/java/com/todoroo/astrid/gtasks/auth/GtasksLoginActivity.java index 70375f27c..385cd19ed 100644 --- a/app/src/main/java/com/todoroo/astrid/gtasks/auth/GtasksLoginActivity.java +++ b/app/src/main/java/com/todoroo/astrid/gtasks/auth/GtasksLoginActivity.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.gtasks.auth; import android.app.ProgressDialog; @@ -22,8 +21,8 @@ import org.tasks.injection.ActivityComponent; import org.tasks.injection.InjectingAppCompatActivity; /** - * This activity allows users to sign in or log in to Google Tasks - * through the Android account manager + * This activity allows users to sign in or log in to Google Tasks through the Android account + * manager * * @author Sam Bosley */ @@ -46,8 +45,9 @@ public class GtasksLoginActivity extends InjectingAppCompatActivity { if (existingUsername != null && accountManager.hasAccount(existingUsername)) { getAuthToken(existingUsername); } else { - Intent chooseAccountIntent = android.accounts.AccountManager.newChooseAccountIntent( - null, null, new String[]{"com.google"}, false, null, null, null, null); + Intent chooseAccountIntent = + android.accounts.AccountManager.newChooseAccountIntent( + null, null, new String[] {"com.google"}, false, null, null, null, null); startActivityForResult(chooseAccountIntent, RC_CHOOSE_ACCOUNT); } } @@ -65,23 +65,26 @@ public class GtasksLoginActivity extends InjectingAppCompatActivity { } private void getAuthToken(String a, final ProgressDialog pd) { - playServices.getAuthToken(this, a, new AuthResultHandler() { - @Override - public void authenticationSuccessful(String accountName) { - gtasksPreferenceService.setUserName(accountName); - gtasksInvoker.setUserName(accountName); - setResult(RESULT_OK); - finish(); - DialogUtilities.dismissDialog(GtasksLoginActivity.this, pd); - } + playServices.getAuthToken( + this, + a, + new AuthResultHandler() { + @Override + public void authenticationSuccessful(String accountName) { + gtasksPreferenceService.setUserName(accountName); + gtasksInvoker.setUserName(accountName); + setResult(RESULT_OK); + finish(); + DialogUtilities.dismissDialog(GtasksLoginActivity.this, pd); + } - @Override - public void authenticationFailed(final String message) { - runOnUiThread( - () -> Toast.makeText(GtasksLoginActivity.this, message, Toast.LENGTH_LONG).show()); - DialogUtilities.dismissDialog(GtasksLoginActivity.this, pd); - } - }); + @Override + public void authenticationFailed(final String message) { + runOnUiThread( + () -> Toast.makeText(GtasksLoginActivity.this, message, Toast.LENGTH_LONG).show()); + DialogUtilities.dismissDialog(GtasksLoginActivity.this, pd); + } + }); } @Override @@ -95,7 +98,7 @@ public class GtasksLoginActivity extends InjectingAppCompatActivity { pd.show(); getAuthToken(accountName, pd); } else { - //User didn't give permission--cancel + // User didn't give permission--cancel finish(); } } diff --git a/app/src/main/java/com/todoroo/astrid/gtasks/sync/GtasksSyncService.java b/app/src/main/java/com/todoroo/astrid/gtasks/sync/GtasksSyncService.java index d0a8abb38..bfdaa1cc3 100644 --- a/app/src/main/java/com/todoroo/astrid/gtasks/sync/GtasksSyncService.java +++ b/app/src/main/java/com/todoroo/astrid/gtasks/sync/GtasksSyncService.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.gtasks.sync; import android.text.TextUtils; @@ -35,16 +34,19 @@ public class GtasksSyncService { private final TaskDao taskDao; private final GtasksPreferenceService gtasksPreferenceService; private final GtasksInvoker gtasksInvoker; - private final LinkedBlockingQueue operationQueue = new LinkedBlockingQueue<>(); + private final LinkedBlockingQueue operationQueue = + new LinkedBlockingQueue<>(); private final GtaskSyncAdapterHelper gtaskSyncAdapterHelper; private final Tracker tracker; private final GoogleTaskDao googleTaskDao; @Inject - public GtasksSyncService(TaskDao taskDao, + public GtasksSyncService( + TaskDao taskDao, GtasksPreferenceService gtasksPreferenceService, GtasksInvoker gtasksInvoker, - GtaskSyncAdapterHelper gtaskSyncAdapterHelper, Tracker tracker, + GtaskSyncAdapterHelper gtaskSyncAdapterHelper, + Tracker tracker, GoogleTaskDao googleTaskDao) { this.taskDao = taskDao; this.gtasksPreferenceService = gtasksPreferenceService; @@ -68,7 +70,7 @@ public class GtasksSyncService { return; } if (gtasksPreferenceService - .isOngoing()) //Don't try and sync changes that occur during a normal sync + .isOngoing()) // Don't try and sync changes that occur during a normal sync { return; } @@ -97,20 +99,21 @@ public class GtasksSyncService { } } - public void iterateThroughList(String listId, - final GtasksTaskListUpdater.OrderedListIterator iterator, long startAtOrder, + public void iterateThroughList( + String listId, + final GtasksTaskListUpdater.OrderedListIterator iterator, + long startAtOrder, boolean reverse) { - List tasks = reverse - ? googleTaskDao.getTasksFromReverse(listId, startAtOrder) - : googleTaskDao.getTasksFrom(listId, startAtOrder); + List tasks = + reverse + ? googleTaskDao.getTasksFromReverse(listId, startAtOrder) + : googleTaskDao.getTasksFrom(listId, startAtOrder); for (GoogleTask entry : tasks) { iterator.processTask(entry.getTask(), entry); } } - /** - * Gets the remote id string of the parent task - */ + /** Gets the remote id string of the parent task */ public String getRemoteParentId(GoogleTask googleTask) { String parent = null; long parentId = googleTask.getParent(); @@ -124,27 +127,26 @@ public class GtasksSyncService { return parent; } - /** - * Gets the remote id string of the previous sibling task - */ + /** Gets the remote id string of the previous sibling task */ public String getRemoteSiblingId(String listId, GoogleTask gtasksMetadata) { final AtomicInteger indentToMatch = new AtomicInteger(gtasksMetadata.getIndent()); final AtomicLong parentToMatch = new AtomicLong(gtasksMetadata.getParent()); final AtomicReference sibling = new AtomicReference<>(); - GtasksTaskListUpdater.OrderedListIterator iterator = (taskId, googleTask) -> { - Task t = taskDao.fetch(taskId); - if (t == null || t.isDeleted()) { - return; - } - int currIndent = googleTask.getIndent(); - long currParent = googleTask.getParent(); - - if (currIndent == indentToMatch.get() && currParent == parentToMatch.get()) { - if (sibling.get() == null) { - sibling.set(googleTask.getRemoteId()); - } - } - }; + GtasksTaskListUpdater.OrderedListIterator iterator = + (taskId, googleTask) -> { + Task t = taskDao.fetch(taskId); + if (t == null || t.isDeleted()) { + return; + } + int currIndent = googleTask.getIndent(); + long currParent = googleTask.getParent(); + + if (currIndent == indentToMatch.get() && currParent == parentToMatch.get()) { + if (sibling.get() == null) { + sibling.set(googleTask.getRemoteId()); + } + } + }; iterateThroughList(listId, iterator, gtasksMetadata.getOrder(), true); return sibling.get(); diff --git a/app/src/main/java/com/todoroo/astrid/gtasks/sync/GtasksTaskContainer.java b/app/src/main/java/com/todoroo/astrid/gtasks/sync/GtasksTaskContainer.java index 3e2697429..86cbcf922 100644 --- a/app/src/main/java/com/todoroo/astrid/gtasks/sync/GtasksTaskContainer.java +++ b/app/src/main/java/com/todoroo/astrid/gtasks/sync/GtasksTaskContainer.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.gtasks.sync; import static org.tasks.gtasks.GoogleTaskSynchronizer.mergeDates; @@ -19,12 +18,13 @@ public class GtasksTaskContainer { public final Task task; public final ArrayList metadata; - private final long updateTime; public final GoogleTask gtaskMetadata; + private final long updateTime; public GtasksTaskContainer( com.google.api.services.tasks.model.Task remoteTask, - Task localTask, String listId, + Task localTask, + String listId, GoogleTask metadata) { task = localTask; this.metadata = new ArrayList<>(); diff --git a/app/src/main/java/com/todoroo/astrid/helper/UUIDHelper.java b/app/src/main/java/com/todoroo/astrid/helper/UUIDHelper.java index d4c65f0d2..2b5922f9b 100644 --- a/app/src/main/java/com/todoroo/astrid/helper/UUIDHelper.java +++ b/app/src/main/java/com/todoroo/astrid/helper/UUIDHelper.java @@ -6,9 +6,7 @@ public class UUIDHelper { private static final long MIN_UUID = 100000000; - /** - * @return a pair consisting of the newly generated uuid and the corresponding proof text - */ + /** @return a pair consisting of the newly generated uuid and the corresponding proof text */ public static String newUUID() { long uuid; do { diff --git a/app/src/main/java/com/todoroo/astrid/notes/CommentsController.java b/app/src/main/java/com/todoroo/astrid/notes/CommentsController.java index 6a9f92164..1670e2b20 100644 --- a/app/src/main/java/com/todoroo/astrid/notes/CommentsController.java +++ b/app/src/main/java/com/todoroo/astrid/notes/CommentsController.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.notes; import static android.support.v4.content.ContextCompat.getColor; @@ -46,32 +45,35 @@ public class CommentsController { private ViewGroup commentsContainer; @Inject - public CommentsController(UserActivityDao userActivityDao, Activity activity, - Preferences preferences) { + public CommentsController( + UserActivityDao userActivityDao, Activity activity, Preferences preferences) { this.userActivityDao = userActivityDao; this.activity = activity; this.preferences = preferences; } - private static void setupImagePopupForCommentView(View view, ImageView commentPictureView, - final Uri updateBitmap, - final Activity activity) { + private static void setupImagePopupForCommentView( + View view, ImageView commentPictureView, final Uri updateBitmap, final Activity activity) { if (updateBitmap != null) { commentPictureView.setVisibility(View.VISIBLE); String path = getPathFromUri(activity, updateBitmap); commentPictureView.setImageBitmap( - sampleBitmap(path, commentPictureView.getLayoutParams().width, + sampleBitmap( + path, + commentPictureView.getLayoutParams().width, commentPictureView.getLayoutParams().height)); - view.setOnClickListener(v -> { - File file = new File(updateBitmap.getPath()); - Uri uri = FileProvider - .getUriForFile(activity, Constants.FILE_PROVIDER_AUTHORITY, file.getAbsoluteFile()); - Intent intent = new Intent(Intent.ACTION_VIEW); - intent.setDataAndType(uri, "image/*"); - FileHelper.grantReadPermissions(activity, intent, uri); - activity.startActivity(intent); - }); + view.setOnClickListener( + v -> { + File file = new File(updateBitmap.getPath()); + Uri uri = + FileProvider.getUriForFile( + activity, Constants.FILE_PROVIDER_AUTHORITY, file.getAbsoluteFile()); + Intent intent = new Intent(Intent.ACTION_VIEW); + intent.setDataAndType(uri, "image/*"); + FileHelper.grantReadPermissions(activity, intent, uri); + activity.startActivity(intent); + }); } else { commentPictureView.setVisibility(View.GONE); } @@ -102,25 +104,24 @@ public class CommentsController { loadMore.setText(R.string.TEA_load_more); loadMore.setTextColor(getColor(activity, R.color.text_secondary)); loadMore.setBackgroundColor(Color.alpha(0)); - loadMore.setOnClickListener(v -> { - // Perform action on click - commentItems += 10; - reloadView(); - }); + loadMore.setOnClickListener( + v -> { + // Perform action on click + commentItems += 10; + reloadView(); + }); commentsContainer.addView(loadMore); } } private View getUpdateNotes(UserActivity userActivity, ViewGroup parent) { - View convertView = activity.getLayoutInflater() - .inflate(R.layout.comment_adapter_row, parent, false); + View convertView = + activity.getLayoutInflater().inflate(R.layout.comment_adapter_row, parent, false); bindView(convertView, userActivity); return convertView; } - /** - * Helper method to set the contents and visibility of each field - */ + /** Helper method to set the contents and visibility of each field */ private void bindView(View view, UserActivity item) { // name final TextView nameView = view.findViewById(R.id.title); diff --git a/app/src/main/java/com/todoroo/astrid/notes/NotesAction.java b/app/src/main/java/com/todoroo/astrid/notes/NotesAction.java index ca8fee16e..24d9bf5fe 100644 --- a/app/src/main/java/com/todoroo/astrid/notes/NotesAction.java +++ b/app/src/main/java/com/todoroo/astrid/notes/NotesAction.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.notes; import com.todoroo.astrid.api.TaskAction; diff --git a/app/src/main/java/com/todoroo/astrid/provider/Astrid2TaskProvider.java b/app/src/main/java/com/todoroo/astrid/provider/Astrid2TaskProvider.java index b9e1af6ff..4fed860d6 100644 --- a/app/src/main/java/com/todoroo/astrid/provider/Astrid2TaskProvider.java +++ b/app/src/main/java/com/todoroo/astrid/provider/Astrid2TaskProvider.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.provider; import android.content.ContentValues; @@ -31,11 +30,10 @@ import org.tasks.ui.CheckBoxes; import timber.log.Timber; /** - * This is the legacy Astrid task provider. While it will continue to be - * supported, note that it does not expose all of the information in - * Astrid, nor does it support many editing operations. + * This is the legacy Astrid task provider. While it will continue to be supported, note that it + * does not expose all of the information in Astrid, nor does it support many editing operations. * - * See the individual methods for a description of what is returned. + *

    See the individual methods for a description of what is returned. * * @author Tim Su */ @@ -47,21 +45,28 @@ public class Astrid2TaskProvider extends InjectingContentProvider { private static final UriMatcher URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH); - private final static String NAME = "name"; - private final static String IMPORTANCE_COLOR = "importance_color"; - private final static String IDENTIFIER = "identifier"; - private final static String PREFERRED_DUE_DATE = "preferredDueDate"; - private final static String DEFINITE_DUE_DATE = "definiteDueDate"; - private final static String IMPORTANCE = "importance"; - private final static String ID = "id"; - - private final static String TAGS_ID = "tags_id"; - - private static final String[] TASK_FIELD_LIST = new String[]{NAME, IMPORTANCE_COLOR, - PREFERRED_DUE_DATE, DEFINITE_DUE_DATE, - IMPORTANCE, IDENTIFIER, TAGS_ID}; - - private static final String[] TAGS_FIELD_LIST = new String[]{ID, NAME}; + private static final String NAME = "name"; + private static final String IMPORTANCE_COLOR = "importance_color"; + private static final String IDENTIFIER = "identifier"; + private static final String PREFERRED_DUE_DATE = "preferredDueDate"; + private static final String DEFINITE_DUE_DATE = "definiteDueDate"; + private static final String IMPORTANCE = "importance"; + private static final String ID = "id"; + + private static final String TAGS_ID = "tags_id"; + + private static final String[] TASK_FIELD_LIST = + new String[] { + NAME, + IMPORTANCE_COLOR, + PREFERRED_DUE_DATE, + DEFINITE_DUE_DATE, + IMPORTANCE, + IDENTIFIER, + TAGS_ID + }; + + private static final String[] TAGS_FIELD_LIST = new String[] {ID, NAME}; private static final int URI_TASKS = 0; private static final int URI_TAGS = 1; @@ -113,8 +118,7 @@ public class Astrid2TaskProvider extends InjectingContentProvider { } /** - * Note: tag id is no longer a real column, so we pass in a UID - * generated from the tag string. + * Note: tag id is no longer a real column, so we pass in a UID generated from the tag string. * * @return two-column cursor: tag id (string) and tag name */ @@ -150,14 +154,15 @@ public class Astrid2TaskProvider extends InjectingContentProvider { /** * Cursor with the following columns + * *

      - *
    1. task title, string - *
    2. task importance color, int android RGB color - *
    3. task due date (was: preferred due date), long millis since epoch - *
    4. task due date (was: absolute due date), long millis since epoch - *
    5. task importance, integer from 0 to 3 (0 => most important) - *
    6. task id, long - *
    7. task tags, string tags separated by | + *
    8. task title, string + *
    9. task importance color, int android RGB color + *
    10. task due date (was: preferred due date), long millis since epoch + *
    11. task due date (was: absolute due date), long millis since epoch + *
    12. task importance, integer from 0 to 3 (0 => most important) + *
    13. task id, long + *
    14. task tags, string tags separated by | *
    * * @return cursor as described above @@ -184,8 +189,12 @@ public class Astrid2TaskProvider extends InjectingContentProvider { } @Override - public Cursor query(@NonNull Uri uri, String[] projection, String selection, - String[] selectionArgs, String sortOrder) { + public Cursor query( + @NonNull Uri uri, + String[] projection, + String selection, + String[] selectionArgs, + String sortOrder) { switch (URI_MATCHER.match(uri)) { case URI_TASKS: return getTasks(); @@ -197,8 +206,8 @@ public class Astrid2TaskProvider extends InjectingContentProvider { } @Override - public int update(@NonNull Uri uri, ContentValues values, String selection, - String[] selectionArgs) { + public int update( + @NonNull Uri uri, ContentValues values, String selection, String[] selectionArgs) { throw new UnsupportedOperationException("not supported"); } diff --git a/app/src/main/java/com/todoroo/astrid/reminders/ReminderPreferences.java b/app/src/main/java/com/todoroo/astrid/reminders/ReminderPreferences.java index 6ede10eb8..81d06cf97 100644 --- a/app/src/main/java/com/todoroo/astrid/reminders/ReminderPreferences.java +++ b/app/src/main/java/com/todoroo/astrid/reminders/ReminderPreferences.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.reminders; import static com.todoroo.andlib.utility.AndroidUtilities.atLeastJellybean; @@ -71,15 +70,14 @@ public class ReminderPreferences extends InjectingPreferenceActivity { R.string.p_rmd_quietStart, R.string.p_rmd_quietEnd, R.string.p_rmd_persistent); - resetGeofencesOnChange( - R.string.p_geofence_radius, - R.string.p_geofence_responsiveness); + resetGeofencesOnChange(R.string.p_geofence_radius, R.string.p_geofence_responsiveness); - fieldMissedCalls = (CheckBoxPreference) findPreference( - getString(R.string.p_field_missed_calls)); + fieldMissedCalls = + (CheckBoxPreference) findPreference(getString(R.string.p_field_missed_calls)); fieldMissedCalls.setOnPreferenceChangeListener( - (preference, newValue) -> newValue != null && (!(boolean) newValue || permissionRequestor - .requestMissedCallPermissions())); + (preference, newValue) -> + newValue != null + && (!(boolean) newValue || permissionRequestor.requestMissedCallPermissions())); fieldMissedCalls.setChecked( fieldMissedCalls.isChecked() && permissionChecker.canAccessMissedCallPermissions()); @@ -94,40 +92,44 @@ public class ReminderPreferences extends InjectingPreferenceActivity { .setOnPreferenceClickListener(this::openBatteryOptimizationSettings); findPreference(R.string.p_bundle_notifications) - .setOnPreferenceChangeListener((preference, o) -> { - NotificationSchedulerIntentService.enqueueWork(this, true); - return true; - }); + .setOnPreferenceChangeListener( + (preference, o) -> { + NotificationSchedulerIntentService.enqueueWork(this, true); + return true; + }); findPreference(R.string.p_badges_enabled) - .setOnPreferenceChangeListener((preference, newValue) -> { - if (newValue != null) { - boolean enabled = (boolean) newValue; - badger.setEnabled(enabled); - if (enabled) { - showRestartDialog(); - } - return true; - } - return false; - }); + .setOnPreferenceChangeListener( + (preference, newValue) -> { + if (newValue != null) { + boolean enabled = (boolean) newValue; + badger.setEnabled(enabled); + if (enabled) { + showRestartDialog(); + } + return true; + } + return false; + }); Preference badgePreference = findPreference(getString(R.string.p_badge_list)); Filter filter = defaultFilterProvider.getBadgeFilter(); badgePreference.setSummary(filter.listingTitle); - badgePreference.setOnPreferenceClickListener(preference -> { - Intent intent = new Intent(ReminderPreferences.this, FilterSelectionActivity.class); - intent.putExtra(FilterSelectionActivity.EXTRA_FILTER, defaultFilterProvider.getBadgeFilter()); - intent.putExtra(FilterSelectionActivity.EXTRA_RETURN_FILTER, true); - startActivityForResult(intent, REQUEST_BADGE_LIST); - return true; - }); + badgePreference.setOnPreferenceClickListener( + preference -> { + Intent intent = new Intent(ReminderPreferences.this, FilterSelectionActivity.class); + intent.putExtra( + FilterSelectionActivity.EXTRA_FILTER, defaultFilterProvider.getBadgeFilter()); + intent.putExtra(FilterSelectionActivity.EXTRA_RETURN_FILTER, true); + startActivityForResult(intent, REQUEST_BADGE_LIST); + return true; + }); requires(device.supportsLocationServices(), R.string.geolocation_reminders); requires(atLeastOreo(), R.string.notification_channel_settings); requires(atLeastMarshmallow(), R.string.battery_optimization_settings); - requires(preOreo(), R.string.p_rmd_ringtone, R.string.p_rmd_vibrate, - R.string.p_led_notification); + requires( + preOreo(), R.string.p_rmd_ringtone, R.string.p_rmd_vibrate, R.string.p_led_notification); requires(atLeastJellybean(), R.string.p_bundle_notifications); } @@ -149,25 +151,29 @@ public class ReminderPreferences extends InjectingPreferenceActivity { private void rescheduleNotificationsOnChange(int... resIds) { for (int resId : resIds) { - findPreference(getString(resId)).setOnPreferenceChangeListener((preference, newValue) -> { - NotificationSchedulerIntentService.enqueueWork(this, false); - return true; - }); + findPreference(getString(resId)) + .setOnPreferenceChangeListener( + (preference, newValue) -> { + NotificationSchedulerIntentService.enqueueWork(this, false); + return true; + }); } } private void resetGeofencesOnChange(int... resIds) { for (int resId : resIds) { - findPreference(getString(resId)).setOnPreferenceChangeListener((preference, newValue) -> { - GeofenceSchedulingIntentService.enqueueWork(this); - return true; - }); + findPreference(getString(resId)) + .setOnPreferenceChangeListener( + (preference, newValue) -> { + GeofenceSchedulingIntentService.enqueueWork(this); + return true; + }); } } @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, - @NonNull int[] grantResults) { + public void onRequestPermissionsResult( + int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == PermissionRequestor.REQUEST_CONTACTS) { if (verifyPermissions(grantResults)) { fieldMissedCalls.setChecked(true); @@ -178,33 +184,40 @@ public class ReminderPreferences extends InjectingPreferenceActivity { } private void initializeTimePreference(final TimePreference preference, final int requestCode) { - preference.setOnPreferenceClickListener(ignored -> { - final DateTime current = new DateTime().withMillisOfDay(preference.getMillisOfDay()); - Intent intent = new Intent(ReminderPreferences.this, TimePickerActivity.class); - intent.putExtra(TimePickerActivity.EXTRA_TIMESTAMP, current.getMillis()); - startActivityForResult(intent, requestCode); - return true; - }); + preference.setOnPreferenceClickListener( + ignored -> { + final DateTime current = new DateTime().withMillisOfDay(preference.getMillisOfDay()); + Intent intent = new Intent(ReminderPreferences.this, TimePickerActivity.class); + intent.putExtra(TimePickerActivity.EXTRA_TIMESTAMP, current.getMillis()); + startActivityForResult(intent, requestCode); + return true; + }); } private void initializeRingtonePreference() { - Preference.OnPreferenceChangeListener ringtoneChangedListener = (preference, value) -> { - if ("".equals(value)) { - preference.setSummary(R.string.silent); - } else { - Ringtone ringtone = RingtoneManager.getRingtone(ReminderPreferences.this, value == null - ? Settings.System.DEFAULT_NOTIFICATION_URI : Uri.parse((String) value)); - preference.setSummary(ringtone == null ? "" : ringtone.getTitle(ReminderPreferences.this)); - } - return true; - }; + Preference.OnPreferenceChangeListener ringtoneChangedListener = + (preference, value) -> { + if ("".equals(value)) { + preference.setSummary(R.string.silent); + } else { + Ringtone ringtone = + RingtoneManager.getRingtone( + ReminderPreferences.this, + value == null + ? Settings.System.DEFAULT_NOTIFICATION_URI + : Uri.parse((String) value)); + preference.setSummary( + ringtone == null ? "" : ringtone.getTitle(ReminderPreferences.this)); + } + return true; + }; String ringtoneKey = getString(R.string.p_rmd_ringtone); Preference ringtonePreference = findPreference(ringtoneKey); ringtonePreference.setOnPreferenceChangeListener(ringtoneChangedListener); - ringtoneChangedListener - .onPreferenceChange(ringtonePreference, PreferenceManager.getDefaultSharedPreferences(this) - .getString(ringtoneKey, null)); + ringtoneChangedListener.onPreferenceChange( + ringtonePreference, + PreferenceManager.getDefaultSharedPreferences(this).getString(ringtoneKey, null)); } @Override diff --git a/app/src/main/java/com/todoroo/astrid/reminders/ReminderService.java b/app/src/main/java/com/todoroo/astrid/reminders/ReminderService.java index 35a12d7b8..b183b3a8e 100644 --- a/app/src/main/java/com/todoroo/astrid/reminders/ReminderService.java +++ b/app/src/main/java/com/todoroo/astrid/reminders/ReminderService.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.reminders; import com.todoroo.andlib.utility.DateUtilities; @@ -21,25 +20,15 @@ import org.tasks.time.DateTime; @ApplicationScope public final class ReminderService { - /** - * 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; private static final long NO_ALARM = Long.MAX_VALUE; @@ -129,8 +118,7 @@ public final class ReminderService { if (task.hasDueDate() && task.isNotifyAfterDeadline()) { DateTime overdueDate = new DateTime(task.getDueDate()).plusDays(1); if (!task.hasDueTime()) { - overdueDate = overdueDate - .withMillisOfDay(preferences.getDefaultDueTime()); + overdueDate = overdueDate.withMillisOfDay(preferences.getDefaultDueTime()); } DateTime lastReminder = new DateTime(task.getReminderLast()); @@ -139,8 +127,7 @@ public final class ReminderService { return overdueDate.getMillis(); } - overdueDate = lastReminder - .withMillisOfDay(overdueDate.getMillisOfDay()); + overdueDate = lastReminder.withMillisOfDay(overdueDate.getMillisOfDay()); return overdueDate.isAfter(lastReminder) ? overdueDate.getMillis() @@ -151,13 +138,12 @@ 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. + * + *

    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. */ private long calculateNextDueDateReminder(Task task) { if (task.hasDueDate() && task.isNotifyAtDeadline()) { @@ -169,9 +155,8 @@ public final class ReminderService { if (task.hasDueTime()) { dueDateAlarm = dueDate; } else { - dueDateAlarm = new DateTime(dueDate) - .withMillisOfDay(preferences.getDefaultDueTime()) - .getMillis(); + dueDateAlarm = + new DateTime(dueDate).withMillisOfDay(preferences.getDefaultDueTime()).getMillis(); } return lastReminder < dueDateAlarm ? dueDateAlarm : NO_ALARM; @@ -181,10 +166,9 @@ 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. + * + *

    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. */ private long calculateNextRandomReminder(Task task) { long reminderPeriod = task.getReminderPeriod(); @@ -198,8 +182,8 @@ public final class ReminderService { when += (long) (reminderPeriod * (0.85f + 0.3f * random.nextFloat())); if (when < DateUtilities.now()) { - when = DateUtilities.now() + (long) ((0.5f + - 6 * random.nextFloat()) * DateUtilities.ONE_HOUR); + when = + DateUtilities.now() + (long) ((0.5f + 6 * random.nextFloat()) * DateUtilities.ONE_HOUR); } return when; diff --git a/app/src/main/java/com/todoroo/astrid/repeats/RepeatControlSet.java b/app/src/main/java/com/todoroo/astrid/repeats/RepeatControlSet.java index 38d1dd0d2..c2e1fc6a8 100644 --- a/app/src/main/java/com/todoroo/astrid/repeats/RepeatControlSet.java +++ b/app/src/main/java/com/todoroo/astrid/repeats/RepeatControlSet.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.repeats; import static android.support.v4.content.ContextCompat.getColor; @@ -81,9 +80,16 @@ public class RepeatControlSet extends TaskEditControlFragment @Inject Theme theme; @Inject Tracker tracker; @Inject RepeatRuleToString repeatRuleToString; - @BindView(R.id.display_row_edit) TextView displayView; - @BindView(R.id.repeatType) Spinner typeSpinner; - @BindView(R.id.repeatTypeContainer) LinearLayout repeatTypeContainer; + + @BindView(R.id.display_row_edit) + TextView displayView; + + @BindView(R.id.repeatType) + Spinner typeSpinner; + + @BindView(R.id.repeatTypeContainer) + LinearLayout repeatTypeContainer; + private RRule rrule; private HiddenTopArrayAdapter typeAdapter; private long dueDate; @@ -116,8 +122,8 @@ public class RepeatControlSet extends TaskEditControlFragment @Nullable @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = super.onCreateView(inflater, container, savedInstanceState); if (savedInstanceState == null) { repeatAfterCompletion = task.repeatAfterCompletion(); @@ -148,23 +154,25 @@ public class RepeatControlSet extends TaskEditControlFragment repeatTypes.add(""); repeatTypes.addAll(Arrays.asList(getResources().getStringArray(R.array.repeat_type))); - typeAdapter = new HiddenTopArrayAdapter(context, 0, repeatTypes) { - @NonNull - @Override - public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { - int selectedItemPosition = position; - if (parent instanceof AdapterView) { - selectedItemPosition = ((AdapterView) parent).getSelectedItemPosition(); - } - TextView tv = (TextView) inflater - .inflate(android.R.layout.simple_spinner_item, parent, false); - tv.setPadding(0, 0, 0, 0); - tv.setText(repeatTypes.get(selectedItemPosition)); - return tv; - } - }; - Drawable drawable = DrawableCompat - .wrap(ContextCompat.getDrawable(context, R.drawable.textfield_underline_black)); + typeAdapter = + new HiddenTopArrayAdapter(context, 0, repeatTypes) { + @NonNull + @Override + public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { + int selectedItemPosition = position; + if (parent instanceof AdapterView) { + selectedItemPosition = ((AdapterView) parent).getSelectedItemPosition(); + } + TextView tv = + (TextView) inflater.inflate(android.R.layout.simple_spinner_item, parent, false); + tv.setPadding(0, 0, 0, 0); + tv.setText(repeatTypes.get(selectedItemPosition)); + return tv; + } + }; + Drawable drawable = + DrawableCompat.wrap( + ContextCompat.getDrawable(context, R.drawable.textfield_underline_black)); drawable.mutate(); DrawableCompat.setTint(drawable, getColor(context, R.color.text_primary)); typeSpinner.setBackgroundDrawable(drawable); @@ -208,21 +216,21 @@ public class RepeatControlSet extends TaskEditControlFragment return false; } Frequency frequency = rrule.getFreq(); - return (frequency == WEEKLY || frequency == MONTHLY) && !rrule.getByDay().isEmpty() || - frequency == HOURLY || - frequency == MINUTELY || - rrule.getUntil() != null || - rrule.getInterval() != 1 || - rrule.getCount() != 0; + return (frequency == WEEKLY || frequency == MONTHLY) && !rrule.getByDay().isEmpty() + || frequency == HOURLY + || frequency == MINUTELY + || rrule.getUntil() != null + || rrule.getInterval() != 1 + || rrule.getCount() != 0; } @OnClick(R.id.display_row_edit) void openPopup(View view) { boolean customPicked = isCustomValue(); - List repeatOptions = newArrayList( - context.getResources().getStringArray(R.array.repeat_options)); - SingleCheckedArrayAdapter adapter = new SingleCheckedArrayAdapter(context, repeatOptions, - theme.getThemeAccent()); + List repeatOptions = + newArrayList(context.getResources().getStringArray(R.array.repeat_options)); + SingleCheckedArrayAdapter adapter = + new SingleCheckedArrayAdapter(context, repeatOptions, theme.getThemeAccent()); int selected = 0; if (customPicked) { adapter.insert(repeatRuleToString.toString(rrule), 0); @@ -245,49 +253,53 @@ public class RepeatControlSet extends TaskEditControlFragment break; } } - dialogBuilder.newDialog() - .setSingleChoiceItems(adapter, selected, (dialogInterface, i) -> { - if (customPicked) { - if (i == 0) { - dialogInterface.dismiss(); - return; - } - i--; - } - if (i == 0) { - rrule = null; - } else if (i == 5) { - newCustomRecurrenceDialog(this, rrule, dueDate) - .show(getFragmentManager(), FRAG_TAG_CUSTOM_RECURRENCE); - dialogInterface.dismiss(); - return; - } else { - rrule = new RRule(); - rrule.setInterval(1); - repeatAfterCompletion = false; - - switch (i) { - case 1: - rrule.setFreq(DAILY); - break; - case 2: - rrule.setFreq(WEEKLY); - break; - case 3: - rrule.setFreq(MONTHLY); - break; - case 4: - rrule.setFreq(YEARLY); - break; - } + dialogBuilder + .newDialog() + .setSingleChoiceItems( + adapter, + selected, + (dialogInterface, i) -> { + if (customPicked) { + if (i == 0) { + dialogInterface.dismiss(); + return; + } + i--; + } + if (i == 0) { + rrule = null; + } else if (i == 5) { + newCustomRecurrenceDialog(this, rrule, dueDate) + .show(getFragmentManager(), FRAG_TAG_CUSTOM_RECURRENCE); + dialogInterface.dismiss(); + return; + } else { + rrule = new RRule(); + rrule.setInterval(1); + repeatAfterCompletion = false; - tracker.reportEvent(Tracking.Events.RECURRENCE_PRESET, rrule.toIcal()); - } + switch (i) { + case 1: + rrule.setFreq(DAILY); + break; + case 2: + rrule.setFreq(WEEKLY); + break; + case 3: + rrule.setFreq(MONTHLY); + break; + case 4: + rrule.setFreq(YEARLY); + break; + } - callback.repeatChanged(rrule != null); - refreshDisplayView(); - dialogInterface.dismiss(); - }) + tracker.reportEvent(Tracking.Events.RECURRENCE_PRESET, rrule.toIcal()); + } + + callback.repeatChanged(rrule != null); + refreshDisplayView(); + dialogInterface.dismiss(); + }) .setOnCancelListener(d -> refreshDisplayView()) .show(); } @@ -309,9 +321,9 @@ public class RepeatControlSet extends TaskEditControlFragment @Override public boolean hasChanges(Task original) { - return !getRecurrenceValue().equals(original.getRecurrence()) || - original.getRepeatUntil() != (rrule == null ? 0 - : DateTime.from(rrule.getUntil()).getMillis()); + return !getRecurrenceValue().equals(original.getRecurrence()) + || original.getRepeatUntil() + != (rrule == null ? 0 : DateTime.from(rrule.getUntil()).getMillis()); } @Override @@ -333,7 +345,7 @@ public class RepeatControlSet extends TaskEditControlFragment copy.setUntil(null); String result = copy.toIcal(); if (repeatAfterCompletion && !TextUtils.isEmpty(result)) { - result += ";FROM=COMPLETION"; //$NON-NLS-1$ + result += ";FROM=COMPLETION"; // $NON-NLS-1$ } return result; diff --git a/app/src/main/java/com/todoroo/astrid/repeats/RepeatTaskHelper.java b/app/src/main/java/com/todoroo/astrid/repeats/RepeatTaskHelper.java index dbcf5e0d0..5408e7577 100644 --- a/app/src/main/java/com/todoroo/astrid/repeats/RepeatTaskHelper.java +++ b/app/src/main/java/com/todoroo/astrid/repeats/RepeatTaskHelper.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.repeats; import static org.tasks.date.DateTimeUtils.newDate; @@ -35,16 +34,19 @@ import timber.log.Timber; public class RepeatTaskHelper { - private static final Comparator weekdayCompare = (object1, object2) -> - object1.wday.javaDayNum - object2.wday.javaDayNum; + private static final Comparator weekdayCompare = + (object1, object2) -> object1.wday.javaDayNum - object2.wday.javaDayNum; private final GCalHelper gcalHelper; private final TaskDao taskDao; private final LocalBroadcastManager localBroadcastManager; private final AlarmService alarmService; @Inject - public RepeatTaskHelper(GCalHelper gcalHelper, AlarmService alarmService, - TaskDao taskDao, LocalBroadcastManager localBroadcastManager) { + public RepeatTaskHelper( + GCalHelper gcalHelper, + AlarmService alarmService, + TaskDao taskDao, + LocalBroadcastManager localBroadcastManager) { this.gcalHelper = gcalHelper; this.taskDao = taskDao; this.localBroadcastManager = localBroadcastManager; @@ -52,13 +54,11 @@ public class RepeatTaskHelper { } private static boolean repeatFinished(long newDueDate, long repeatUntil) { - return repeatUntil > 0 && newDateTime(newDueDate).startOfDay() - .isAfter(newDateTime(repeatUntil).startOfDay()); + return repeatUntil > 0 + && newDateTime(newDueDate).startOfDay().isAfter(newDateTime(repeatUntil).startOfDay()); } - /** - * Compute next due date - */ + /** Compute next due date */ static long computeNextDueDate(Task task, String recurrence, boolean repeatAfterCompletion) throws ParseException { RRule rrule = initRRule(recurrence); @@ -69,7 +69,8 @@ public class RepeatTaskHelper { if (rrule.getFreq() == Frequency.HOURLY || rrule.getFreq() == Frequency.MINUTELY) { return handleSubdayRepeat(original, rrule); - } else if (rrule.getFreq() == Frequency.WEEKLY && rrule.getByDay().size() > 0 + } else if (rrule.getFreq() == Frequency.WEEKLY + && rrule.getByDay().size() > 0 && repeatAfterCompletion) { return handleWeeklyRepeatAfterComplete(rrule, original, task.hasDueTime()); } else if (rrule.getFreq() == Frequency.MONTHLY && rrule.getByDay().isEmpty()) { @@ -79,8 +80,8 @@ public class RepeatTaskHelper { } } - private static long handleWeeklyRepeatAfterComplete(RRule rrule, DateTime original, - boolean hasDueTime) { + private static long handleWeeklyRepeatAfterComplete( + RRule rrule, DateTime original, boolean hasDueTime) { List byDay = rrule.getByDay(); long newDate = original.getMillis(); newDate += DateUtilities.ONE_WEEK * (rrule.getInterval() - 1); @@ -101,15 +102,13 @@ public class RepeatTaskHelper { } } - private static long handleMonthlyRepeat(DateTime original, DateValue startDateAsDV, - boolean hasDueTime, RRule rrule) { + private static long handleMonthlyRepeat( + DateTime original, DateValue startDateAsDV, boolean hasDueTime, RRule rrule) { if (original.isLastDayOfMonth()) { int interval = rrule.getInterval(); DateTime newDateTime = original.plusMonths(interval); - long time = newDateTime - .withDayOfMonth(newDateTime.getNumberOfDaysInMonth()) - .getMillis(); + long time = newDateTime.withDayOfMonth(newDateTime.getNumberOfDaysInMonth()).getMillis(); if (hasDueTime) { return Task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, time); } else { @@ -132,8 +131,9 @@ public class RepeatTaskHelper { private static long invokeRecurrence(RRule rrule, DateTime original, DateValue startDateAsDV) { long newDueDate = -1; - RecurrenceIterator iterator = RecurrenceIteratorFactory.createRecurrenceIterator(rrule, - startDateAsDV, TimeZone.getDefault()); + RecurrenceIterator iterator = + RecurrenceIteratorFactory.createRecurrenceIterator( + rrule, startDateAsDV, TimeZone.getDefault()); DateValue nextDate; for (int i = 0; i < 10; i++) { // ten tries then we give up @@ -156,32 +156,34 @@ public class RepeatTaskHelper { return newDueDate; } - /** - * Compute long due date from DateValue - */ + /** Compute long due date from DateValue */ private static long buildNewDueDate(DateTime original, DateValue nextDate) { long newDueDate; if (nextDate instanceof DateTimeValueImpl) { DateTimeValueImpl newDateTime = (DateTimeValueImpl) nextDate; - DateTime date = newDateUtc(newDateTime.year(), newDateTime.month(), - newDateTime.day(), newDateTime.hour(), - newDateTime.minute(), newDateTime.second()) - .toLocal(); + DateTime date = + newDateUtc( + newDateTime.year(), + newDateTime.month(), + newDateTime.day(), + newDateTime.hour(), + newDateTime.minute(), + newDateTime.second()) + .toLocal(); // time may be inaccurate due to DST, force time to be same - date = date - .withHourOfDay(original.getHourOfDay()) - .withMinuteOfHour(original.getMinuteOfHour()); + date = + date.withHourOfDay(original.getHourOfDay()).withMinuteOfHour(original.getMinuteOfHour()); newDueDate = Task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, date.getMillis()); } else { - newDueDate = Task.createDueDate(Task.URGENCY_SPECIFIC_DAY, - newDate(nextDate.year(), nextDate.month(), nextDate.day()).getMillis()); + newDueDate = + Task.createDueDate( + Task.URGENCY_SPECIFIC_DAY, + newDate(nextDate.year(), nextDate.month(), nextDate.day()).getMillis()); } return newDueDate; } - /** - * Initialize RRule instance - */ + /** Initialize RRule instance */ private static RRule initRRule(String recurrence) throws ParseException { RRule rrule = new RRule(recurrence); @@ -194,20 +196,19 @@ public class RepeatTaskHelper { return rrule; } - /** - * Set up repeat start date - */ - private static DateTime setUpStartDate(Task task, boolean repeatAfterCompletion, - Frequency frequency) { + /** Set up repeat start date */ + private static DateTime setUpStartDate( + Task task, boolean repeatAfterCompletion, Frequency frequency) { if (repeatAfterCompletion) { DateTime startDate = task.isCompleted() ? newDateTime(task.getCompletionDate()) : newDateTime(); if (task.hasDueTime() && frequency != Frequency.HOURLY && frequency != Frequency.MINUTELY) { DateTime dueDate = newDateTime(task.getDueDate()); - startDate = startDate - .withHourOfDay(dueDate.getHourOfDay()) - .withMinuteOfHour(dueDate.getMinuteOfHour()) - .withSecondOfMinute(dueDate.getSecondOfMinute()); + startDate = + startDate + .withHourOfDay(dueDate.getHourOfDay()) + .withMinuteOfHour(dueDate.getMinuteOfHour()) + .withSecondOfMinute(dueDate.getSecondOfMinute()); } return startDate; } else { @@ -217,12 +218,16 @@ public class RepeatTaskHelper { private static DateValue setUpStartDateAsDV(Task task, DateTime startDate) { if (task.hasDueTime()) { - return new DateTimeValueImpl(startDate.getYear(), - startDate.getMonthOfYear(), startDate.getDayOfMonth(), - startDate.getHourOfDay(), startDate.getMinuteOfHour(), startDate.getSecondOfMinute()); + return new DateTimeValueImpl( + startDate.getYear(), + startDate.getMonthOfYear(), + startDate.getDayOfMonth(), + startDate.getHourOfDay(), + startDate.getMinuteOfHour(), + startDate.getSecondOfMinute()); } else { - return new DateValueImpl(startDate.getYear(), - startDate.getMonthOfYear(), startDate.getDayOfMonth()); + return new DateValueImpl( + startDate.getYear(), startDate.getMonthOfYear(), startDate.getDayOfMonth()); } } @@ -236,7 +241,8 @@ public class RepeatTaskHelper { millis = DateUtilities.ONE_MINUTE; break; default: - throw new RuntimeException("Error handing subday repeat: " + rrule.getFreq()); //$NON-NLS-1$ + throw new RuntimeException( + "Error handing subday repeat: " + rrule.getFreq()); // $NON-NLS-1$ } long newDueDate = startDate.getMillis() + millis * rrule.getInterval(); return Task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, newDueDate); @@ -288,5 +294,4 @@ public class RepeatTaskHelper { localBroadcastManager.broadcastRepeat(task.getId(), oldDueDate, newDueDate); } } - } diff --git a/app/src/main/java/com/todoroo/astrid/service/StartupService.java b/app/src/main/java/com/todoroo/astrid/service/StartupService.java index 15b5925fc..b9e2f86ae 100644 --- a/app/src/main/java/com/todoroo/astrid/service/StartupService.java +++ b/app/src/main/java/com/todoroo/astrid/service/StartupService.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.service; import android.content.Context; @@ -59,11 +58,17 @@ public class StartupService { private final GoogleTaskListDao googleTaskListDao; @Inject - public StartupService(Database database, Preferences preferences, Tracker tracker, - TagDataDao tagDataDao, TagService tagService, + public StartupService( + Database database, + Preferences preferences, + Tracker tracker, + TagDataDao tagDataDao, + TagService tagService, LocalBroadcastManager localBroadcastManager, - @ForApplication Context context, TagDao tagDao, - FilterDao filterDao, DefaultFilterProvider defaultFilterProvider, + @ForApplication Context context, + TagDao tagDao, + FilterDao filterDao, + DefaultFilterProvider defaultFilterProvider, GoogleTaskListDao googleTaskListDao) { this.database = database; this.preferences = preferences; @@ -78,9 +83,7 @@ public class StartupService { this.googleTaskListDao = googleTaskListDao; } - /** - * Called when this application is started up - */ + /** Called when this application is started up */ public synchronized void onStartupApplication() { try { database.openForWriting(); @@ -132,8 +135,7 @@ public class StartupService { // preserve pre-marshmallow default backup location if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { if (!preferences.isStringValueSet(R.string.p_backup_dir)) { - String directory = String.format("%s/astrid", - Environment.getExternalStorageDirectory()); + String directory = String.format("%s/astrid", Environment.getExternalStorageDirectory()); File file = new File(directory); if (file.exists() && file.isDirectory()) { preferences.setString(R.string.p_backup_dir, directory); @@ -146,8 +148,8 @@ public class StartupService { } private void removeDuplicateTags() { - ListMultimap tagsByUuid = Multimaps - .index(tagService.getTagList(), TagData::getRemoteId); + ListMultimap tagsByUuid = + Multimaps.index(tagService.getTagList(), TagData::getRemoteId); for (String uuid : tagsByUuid.keySet()) { removeDuplicateTagData(tagsByUuid.get(uuid)); removeDuplicateTagMetadata(uuid); diff --git a/app/src/main/java/com/todoroo/astrid/service/SyncV2Service.java b/app/src/main/java/com/todoroo/astrid/service/SyncV2Service.java index d74e5cbc0..8f62ee46e 100644 --- a/app/src/main/java/com/todoroo/astrid/service/SyncV2Service.java +++ b/app/src/main/java/com/todoroo/astrid/service/SyncV2Service.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.service; import com.todoroo.astrid.gtasks.sync.GtasksSyncService; @@ -14,8 +13,8 @@ import org.tasks.gtasks.GtaskSyncAdapterHelper; import org.tasks.sync.SyncExecutor; /** - * SyncV2Service is a simplified synchronization interface for supporting - * next-generation sync interfaces such as Google Tasks and Astrid.com + * SyncV2Service is a simplified synchronization interface for supporting next-generation sync + * interfaces such as Google Tasks and Astrid.com * * @author Tim Su */ @@ -31,7 +30,9 @@ public class SyncV2Service { private final GtasksSyncService gtasksSyncService; @Inject - public SyncV2Service(SyncExecutor syncExecutor, GtaskSyncAdapterHelper gtaskSyncAdapterHelper, + public SyncV2Service( + SyncExecutor syncExecutor, + GtaskSyncAdapterHelper gtaskSyncAdapterHelper, GtasksSyncService gtasksSyncService) { this.syncExecutor = syncExecutor; this.gtaskSyncAdapterHelper = gtaskSyncAdapterHelper; @@ -40,14 +41,16 @@ public class SyncV2Service { public void clearCompleted(final GoogleTaskList list, final SyncResultCallback callback) { if (gtaskSyncAdapterHelper.isEnabled()) { - syncExecutor.execute(callback, () -> { - callback.started(); - try { - gtasksSyncService.clearCompleted(list.getRemoteId()); - } finally { - callback.finished(); - } - }); + syncExecutor.execute( + callback, + () -> { + callback.started(); + try { + gtasksSyncService.clearCompleted(list.getRemoteId()); + } finally { + callback.finished(); + } + }); } } } diff --git a/app/src/main/java/com/todoroo/astrid/service/TaskCreator.java b/app/src/main/java/com/todoroo/astrid/service/TaskCreator.java index f741dfdc1..736c04f87 100644 --- a/app/src/main/java/com/todoroo/astrid/service/TaskCreator.java +++ b/app/src/main/java/com/todoroo/astrid/service/TaskCreator.java @@ -47,10 +47,17 @@ public class TaskCreator { private final TagService tagService; @Inject - public TaskCreator(GCalHelper gcalHelper, Preferences preferences, TagDataDao tagDataDao, - TaskDao taskDao, TagService tagService, TagDao tagDao, - GoogleTaskDao googleTaskDao, Tracker tracker, - DefaultFilterProvider defaultFilterProvider, CaldavDao caldavDao) { + public TaskCreator( + GCalHelper gcalHelper, + Preferences preferences, + TagDataDao tagDataDao, + TaskDao taskDao, + TagService tagService, + TagDao tagDao, + GoogleTaskDao googleTaskDao, + Tracker tracker, + DefaultFilterProvider defaultFilterProvider, + CaldavDao caldavDao) { this.gcalHelper = gcalHelper; this.preferences = preferences; this.tagDataDao = tagDataDao; @@ -64,9 +71,9 @@ public class TaskCreator { } private static void setDefaultReminders(Preferences preferences, Task task) { - task.setReminderPeriod(DateUtilities.ONE_HOUR * - preferences.getIntegerFromString(R.string.p_rmd_default_random_hours, - 0)); + task.setReminderPeriod( + DateUtilities.ONE_HOUR + * preferences.getIntegerFromString(R.string.p_rmd_default_random_hours, 0)); task.setReminderFlags(preferences.getDefaultReminders() | preferences.getDefaultRingMode()); } @@ -77,9 +84,10 @@ public class TaskCreator { taskDao.createNew(task); boolean gcalCreateEventEnabled = - preferences.isDefaultCalendarSet() && task.hasDueDate(); //$NON-NLS-1$ - if (!TextUtils.isEmpty(task.getTitle()) && gcalCreateEventEnabled && TextUtils - .isEmpty(task.getCalendarURI())) { + preferences.isDefaultCalendarSet() && task.hasDueDate(); // $NON-NLS-1$ + if (!TextUtils.isEmpty(task.getTitle()) + && gcalCreateEventEnabled + && TextUtils.isEmpty(task.getCalendarURI())) { Uri calendarUri = gcalHelper.createTaskEvent(task, new ContentValues()); task.setCalendarUri(calendarUri.toString()); } @@ -94,8 +102,8 @@ public class TaskCreator { } else { Filter remoteList = defaultFilterProvider.getDefaultRemoteList(); if (remoteList != null && remoteList instanceof GtasksFilter) { - googleTaskDao - .insert(new GoogleTask(task.getId(), ((GtasksFilter) remoteList).getRemoteId())); + googleTaskDao.insert( + new GoogleTask(task.getId(), ((GtasksFilter) remoteList).getRemoteId())); } } @@ -104,8 +112,8 @@ public class TaskCreator { } /** - * Create task from the given content values, saving it. This version - * doesn't need to start with a base task model. + * Create task from the given content values, saving it. This version doesn't need to start with a + * base task model. */ public Task createWithValues(Map values, String title) { Task task = new Task(); @@ -117,12 +125,15 @@ public class TaskCreator { task.setUuid(UUIDHelper.newUUID()); - task.setImportance(preferences - .getIntegerFromString(R.string.p_default_importance_key, Task.IMPORTANCE_SHOULD_DO)); - task.setDueDate(Task.createDueDate( - preferences.getIntegerFromString(R.string.p_default_urgency_key, Task.URGENCY_NONE), 0)); - int setting = preferences.getIntegerFromString(R.string.p_default_hideUntil_key, - Task.HIDE_UNTIL_NONE); + task.setImportance( + preferences.getIntegerFromString( + R.string.p_default_importance_key, Task.IMPORTANCE_SHOULD_DO)); + task.setDueDate( + Task.createDueDate( + preferences.getIntegerFromString(R.string.p_default_urgency_key, Task.URGENCY_NONE), + 0)); + int setting = + preferences.getIntegerFromString(R.string.p_default_hideUntil_key, Task.HIDE_UNTIL_NONE); task.setHideUntil(task.createHideUntil(setting, 0)); setDefaultReminders(preferences, task); diff --git a/app/src/main/java/com/todoroo/astrid/service/TaskDeleter.java b/app/src/main/java/com/todoroo/astrid/service/TaskDeleter.java index 6bd57b166..6351cc573 100644 --- a/app/src/main/java/com/todoroo/astrid/service/TaskDeleter.java +++ b/app/src/main/java/com/todoroo/astrid/service/TaskDeleter.java @@ -29,9 +29,14 @@ public class TaskDeleter { private final CaldavDao caldavDao; @Inject - public TaskDeleter(TaskDao taskDao, CalendarEventProvider calendarEventProvider, - AlarmDao alarmDao, LocationDao locationDao, TagDao tagDao, - GoogleTaskDao googleTaskDao, CaldavDao caldavDao) { + public TaskDeleter( + TaskDao taskDao, + CalendarEventProvider calendarEventProvider, + AlarmDao alarmDao, + LocationDao locationDao, + TagDao tagDao, + GoogleTaskDao googleTaskDao, + CaldavDao caldavDao) { this.taskDao = taskDao; this.calendarEventProvider = calendarEventProvider; this.alarmDao = alarmDao; @@ -75,9 +80,11 @@ public class TaskDeleter { public int clearCompleted(Filter filter) { List completed = new ArrayList<>(); - String query = filter.getSqlQuery() - .replace(isVisible().toString(), all.toString()) - .replace(notCompleted().toString(), all.toString()); + String query = + filter + .getSqlQuery() + .replace(isVisible().toString(), all.toString()) + .replace(notCompleted().toString(), all.toString()); for (Task task : taskDao.fetchFiltered(query)) { if (task.isCompleted()) { completed.add(task); diff --git a/app/src/main/java/com/todoroo/astrid/service/TaskDuplicator.java b/app/src/main/java/com/todoroo/astrid/service/TaskDuplicator.java index 54f5fc11d..fbcfc3dcf 100644 --- a/app/src/main/java/com/todoroo/astrid/service/TaskDuplicator.java +++ b/app/src/main/java/com/todoroo/astrid/service/TaskDuplicator.java @@ -26,9 +26,12 @@ public class TaskDuplicator { private final LocalBroadcastManager localBroadcastManager; @Inject - public TaskDuplicator(GCalHelper gcalHelper, TaskDao taskDao, + public TaskDuplicator( + GCalHelper gcalHelper, + TaskDao taskDao, LocalBroadcastManager localBroadcastManager, - TagDao tagDao, GoogleTaskDao googleTaskDao) { + TagDao tagDao, + GoogleTaskDao googleTaskDao) { this.gcalHelper = gcalHelper; this.taskDao = taskDao; this.localBroadcastManager = localBroadcastManager; @@ -62,8 +65,9 @@ public class TaskDuplicator { taskDao.createNew(clone); - tagDao.insert(transform(tags, - tag -> new Tag(clone.getId(), clone.getUuid(), tag.getName(), tag.getTagUid()))); + tagDao.insert( + transform( + tags, tag -> new Tag(clone.getId(), clone.getUuid(), tag.getName(), tag.getTagUid()))); if (googleTask != null) { googleTaskDao.insert(new GoogleTask(clone.getId(), googleTask.getListId())); diff --git a/app/src/main/java/com/todoroo/astrid/subtasks/AstridOrderedListFragmentHelper.java b/app/src/main/java/com/todoroo/astrid/subtasks/AstridOrderedListFragmentHelper.java index 94f11fae3..b0fdeefd6 100644 --- a/app/src/main/java/com/todoroo/astrid/subtasks/AstridOrderedListFragmentHelper.java +++ b/app/src/main/java/com/todoroo/astrid/subtasks/AstridOrderedListFragmentHelper.java @@ -65,11 +65,13 @@ class AstridOrderedListFragmentHelper { } final ArrayList chained = new ArrayList<>(); - updater.applyToDescendants(itemId, node -> { - String uuid = node.uuid; - taskDao.setCompletionDate(uuid, completionDate); - chained.add(node.uuid); - }); + updater.applyToDescendants( + itemId, + node -> { + String uuid = node.uuid; + taskDao.setCompletionDate(uuid, completionDate); + chained.add(node.uuid); + }); if (chained.size() > 0) { // move recurring items to item parent @@ -129,12 +131,13 @@ class AstridOrderedListFragmentHelper { public void moved(int from, int to) { String targetTaskId = taskAdapter.getItemUuid(from); if (!Task.isValidUuid(targetTaskId)) { - return; // This can happen with gestures on empty parts of the list (e.g. extra space below tasks) + return; // This can happen with gestures on empty parts of the list (e.g. extra space below + // tasks) } try { if (to >= taskAdapter.getCount()) { - updater.moveTo(list, fragment.getFilter(), targetTaskId, "-1"); //$NON-NLS-1$ + updater.moveTo(list, fragment.getFilter(), targetTaskId, "-1"); // $NON-NLS-1$ } else { String destinationTaskId = taskAdapter.getItemUuid(to); updater.moveTo(list, fragment.getFilter(), targetTaskId, destinationTaskId); @@ -148,7 +151,8 @@ class AstridOrderedListFragmentHelper { public void indented(int which, int delta) { String targetTaskId = taskAdapter.getItemUuid(which); if (!Task.isValidUuid(targetTaskId)) { - return; // This can happen with gestures on empty parts of the list (e.g. extra space below tasks) + return; // This can happen with gestures on empty parts of the list (e.g. extra space below + // tasks) } try { updater.indent(list, fragment.getFilter(), targetTaskId, delta); diff --git a/app/src/main/java/com/todoroo/astrid/subtasks/SubtasksFilterUpdater.java b/app/src/main/java/com/todoroo/astrid/subtasks/SubtasksFilterUpdater.java index 354045c46..92a626713 100644 --- a/app/src/main/java/com/todoroo/astrid/subtasks/SubtasksFilterUpdater.java +++ b/app/src/main/java/com/todoroo/astrid/subtasks/SubtasksFilterUpdater.java @@ -18,8 +18,8 @@ import timber.log.Timber; public class SubtasksFilterUpdater { - static final String ACTIVE_TASKS_ORDER = "active_tasks_order"; //$NON-NLS-1$ - static final String TODAY_TASKS_ORDER = "today_tasks_order"; //$NON-NLS-1$ + static final String ACTIVE_TASKS_ORDER = "active_tasks_order"; // $NON-NLS-1$ + static final String TODAY_TASKS_ORDER = "today_tasks_order"; // $NON-NLS-1$ private final TaskListMetadataDao taskListMetadataDao; private final TaskDao taskDao; @@ -35,19 +35,19 @@ public class SubtasksFilterUpdater { static String buildOrderString(String[] ids) { StringBuilder builder = new StringBuilder(); if (ids.length == 0) { - return "(1)"; //$NON-NLS-1$ + return "(1)"; // $NON-NLS-1$ } for (int i = ids.length - 1; i >= 0; i--) { builder.append(Task.UUID.eq(ids[i]).toString()); if (i > 0) { - builder.append(", "); //$NON-NLS-1$ + builder.append(", "); // $NON-NLS-1$ } } return builder.toString(); } static Node buildTreeModel(String serializedTree, JSONTreeModelBuilder callback) { - Node root = new Node("-1", null, -1); //$NON-NLS-1$ + Node root = new Node("-1", null, -1); // $NON-NLS-1$ try { JSONArray tree = new JSONArray(serializedTree); recursivelyBuildChildren(root, tree, callback); @@ -57,8 +57,8 @@ public class SubtasksFilterUpdater { return root; } - private static void recursivelyBuildChildren(Node node, JSONArray children, - JSONTreeModelBuilder callback) throws JSONException { + private static void recursivelyBuildChildren( + Node node, JSONArray children, JSONTreeModelBuilder callback) throws JSONException { for (int i = 1; i < children.length(); i++) { JSONArray subarray = children.optJSONArray(i); String uuid; @@ -105,12 +105,12 @@ public class SubtasksFilterUpdater { private String getSerializedTree(TaskListMetadata list) { if (list == null) { - return "[]"; //$NON-NLS-1$ + return "[]"; // $NON-NLS-1$ } String order = list.getTaskIds(); - if (TextUtils.isEmpty(order) || "null".equals(order)) //$NON-NLS-1$ + if (TextUtils.isEmpty(order) || "null".equals(order)) // $NON-NLS-1$ { - order = "[]"; //$NON-NLS-1$ + order = "[]"; // $NON-NLS-1$ } return order; @@ -133,9 +133,10 @@ public class SubtasksFilterUpdater { query = query.replaceAll("ORDER BY .*", ""); query = query + String.format("ORDER BY %s", getOrderString()); - query = query.replace( - TaskDao.TaskCriteria.activeAndVisible().toString(), - TaskDao.TaskCriteria.notDeleted().toString()); + query = + query.replace( + TaskDao.TaskCriteria.activeAndVisible().toString(), + TaskDao.TaskCriteria.notDeleted().toString()); filter.setFilterQueryOverride(query); } @@ -162,11 +163,12 @@ public class SubtasksFilterUpdater { currentIds.add(id); } Set idsInQuery = new HashSet<>(); - String sql = filter.getSqlQuery().replaceAll("ORDER BY .*", ""); //$NON-NLS-1$//$NON-NLS-2$ - sql = sql + " ORDER BY created"; //$NON-NLS-1$ - sql = sql.replace( - TaskDao.TaskCriteria.activeAndVisible().toString(), - TaskDao.TaskCriteria.notDeleted().toString()); + String sql = filter.getSqlQuery().replaceAll("ORDER BY .*", ""); // $NON-NLS-1$//$NON-NLS-2$ + sql = sql + " ORDER BY created"; // $NON-NLS-1$ + sql = + sql.replace( + TaskDao.TaskCriteria.activeAndVisible().toString(), + TaskDao.TaskCriteria.notDeleted().toString()); List tasks = taskDao.fetchFiltered(sql); for (Task task : tasks) { String id = task.getUuid(); @@ -322,7 +324,7 @@ public class SubtasksFilterUpdater { return; } - if ("-1".equals(beforeTaskId)) { //$NON-NLS-1$ + if ("-1".equals(beforeTaskId)) { // $NON-NLS-1$ moveToEndOfList(list, filter, target); return; } diff --git a/app/src/main/java/com/todoroo/astrid/subtasks/SubtasksHelper.java b/app/src/main/java/com/todoroo/astrid/subtasks/SubtasksHelper.java index b49861320..ddc2319a1 100644 --- a/app/src/main/java/com/todoroo/astrid/subtasks/SubtasksHelper.java +++ b/app/src/main/java/com/todoroo/astrid/subtasks/SubtasksHelper.java @@ -32,8 +32,12 @@ public class SubtasksHelper { private final TaskListMetadataDao taskListMetadataDao; @Inject - public SubtasksHelper(@ForApplication Context context, Preferences preferences, TaskDao taskDao, - TagDataDao tagDataDao, TaskListMetadataDao taskListMetadataDao) { + public SubtasksHelper( + @ForApplication Context context, + Preferences preferences, + TaskDao taskDao, + TagDataDao tagDataDao, + TaskListMetadataDao taskListMetadataDao) { this.context = context; this.preferences = preferences; this.taskDao = taskDao; @@ -44,8 +48,8 @@ public class SubtasksHelper { @Deprecated private static List getIdList(String serializedTree) { ArrayList ids = new ArrayList<>(); - String[] digitsOnly = serializedTree - .split("[\\[\\],\\s]"); // Split on [ ] , or whitespace chars + String[] digitsOnly = + serializedTree.split("[\\[\\],\\s]"); // Split on [ ] , or whitespace chars for (String idString : digitsOnly) { try { if (!TextUtils.isEmpty(idString)) { @@ -69,13 +73,11 @@ public class SubtasksHelper { return ids.toArray(new String[ids.size()]); } - /** - * Takes a subtasks string containing local ids and remaps it to one containing UUIDs - */ + /** Takes a subtasks string containing local ids and remaps it to one containing UUIDs */ static String convertTreeToRemoteIds(TaskDao taskDao, String localTree) { List localIds = getIdList(localTree); Map idMap = getIdMap(taskDao, localIds); - idMap.put(-1L, "-1"); //$NON-NLS-1$ + idMap.put(-1L, "-1"); // $NON-NLS-1$ Node tree = SubtasksFilterUpdater.buildTreeModel(localTree, null); remapLocalTreeToRemote(tree, idMap); @@ -100,15 +102,18 @@ public class SubtasksHelper { } private static void remapLocalTreeToRemote(Node root, Map idMap) { - remapTree(root, idMap, uuid -> { - Long localId = -1L; - try { - localId = Long.parseLong(uuid); - } catch (NumberFormatException e) { - Timber.e(e, e.getMessage()); - } - return localId; - }); + remapTree( + root, + idMap, + uuid -> { + Long localId = -1L; + try { + localId = Long.parseLong(uuid); + } catch (NumberFormatException e) { + Timber.e(e, e.getMessage()); + } + return localId; + }); } private static Map getIdMap(TaskDao taskDao, List keys) { @@ -121,11 +126,11 @@ public class SubtasksHelper { } public boolean shouldUseSubtasksFragmentForFilter(Filter filter) { - return preferences.getBoolean(R.string.p_manual_sort, false) && - filter != null && - (filter.supportsSubtasks() || - BuiltInFilterExposer.isInbox(context, filter) || - BuiltInFilterExposer.isTodayFilter(context, filter)); + return preferences.getBoolean(R.string.p_manual_sort, false) + && filter != null + && (filter.supportsSubtasks() + || BuiltInFilterExposer.isInbox(context, filter) + || BuiltInFilterExposer.isTodayFilter(context, filter)); } public String applySubtasksToWidgetFilter(Filter filter, String query) { @@ -146,8 +151,8 @@ public class SubtasksHelper { query = query.replaceAll("ORDER BY .*", ""); query = query + String.format(" ORDER BY %s", getOrderString(tagData, tlm)); - query = query - .replace(TaskDao.TaskCriteria.isVisible().toString(), Criterion.all.toString()); + query = + query.replace(TaskDao.TaskCriteria.isVisible().toString(), Criterion.all.toString()); } filter.setFilterQueryOverride(query); @@ -162,7 +167,7 @@ public class SubtasksHelper { } else if (tagData != null) { serialized = convertTreeToRemoteIds(taskDao, tagData.getTagOrdering()); } else { - serialized = "[]"; //$NON-NLS-1$ + serialized = "[]"; // $NON-NLS-1$ } return SubtasksFilterUpdater.buildOrderString(getStringIdArray(serialized)); diff --git a/app/src/main/java/com/todoroo/astrid/subtasks/SubtasksListFragment.java b/app/src/main/java/com/todoroo/astrid/subtasks/SubtasksListFragment.java index 699cbcc9c..e733fb3fe 100644 --- a/app/src/main/java/com/todoroo/astrid/subtasks/SubtasksListFragment.java +++ b/app/src/main/java/com/todoroo/astrid/subtasks/SubtasksListFragment.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.subtasks; import android.app.Activity; @@ -73,7 +72,7 @@ public class SubtasksListFragment extends TaskListFragment { if (taskListMetadata == null) { String defaultOrder = preferences.getStringValue(prefId); if (TextUtils.isEmpty(defaultOrder)) { - defaultOrder = "[]"; //$NON-NLS-1$ + defaultOrder = "[]"; // $NON-NLS-1$ } defaultOrder = SubtasksHelper.convertTreeToRemoteIds(taskDao, defaultOrder); taskListMetadata = new TaskListMetadata(); diff --git a/app/src/main/java/com/todoroo/astrid/subtasks/SubtasksTagListFragment.java b/app/src/main/java/com/todoroo/astrid/subtasks/SubtasksTagListFragment.java index 5edfd8b3f..cdd67a900 100644 --- a/app/src/main/java/com/todoroo/astrid/subtasks/SubtasksTagListFragment.java +++ b/app/src/main/java/com/todoroo/astrid/subtasks/SubtasksTagListFragment.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.subtasks; import android.app.Activity; @@ -40,8 +39,8 @@ public class SubtasksTagListFragment extends TagListFragment { @Override public void setTaskAdapter() { String tdId = tagData.getRemoteId(); - TaskListMetadata taskListMetadata = taskListMetadataDao - .fetchByTagOrFilter(tagData.getRemoteId()); + TaskListMetadata taskListMetadata = + taskListMetadataDao.fetchByTagOrFilter(tagData.getRemoteId()); if (taskListMetadata == null && !Task.isUuidEmpty(tdId)) { taskListMetadata = new TaskListMetadata(); taskListMetadata.setTagUuid(tdId); diff --git a/app/src/main/java/com/todoroo/astrid/sync/SyncResultCallback.java b/app/src/main/java/com/todoroo/astrid/sync/SyncResultCallback.java index f061465ef..b8cc433c5 100644 --- a/app/src/main/java/com/todoroo/astrid/sync/SyncResultCallback.java +++ b/app/src/main/java/com/todoroo/astrid/sync/SyncResultCallback.java @@ -1,20 +1,15 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.sync; public interface SyncResultCallback { - /** - * Provider started sync - */ + /** Provider started sync */ void started(); - /** - * Provider finished sync - */ + /** Provider finished sync */ void finished(); } diff --git a/app/src/main/java/com/todoroo/astrid/tags/TagFilterExposer.java b/app/src/main/java/com/todoroo/astrid/tags/TagFilterExposer.java index 14af36b25..aaa54670e 100644 --- a/app/src/main/java/com/todoroo/astrid/tags/TagFilterExposer.java +++ b/app/src/main/java/com/todoroo/astrid/tags/TagFilterExposer.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.tags; import com.google.common.base.Strings; @@ -28,9 +27,7 @@ public class TagFilterExposer { this.tagService = tagService; } - /** - * Create filter from new tag object - */ + /** Create filter from new tag object */ private static TagFilter filterFromTag(TagData tag) { if (tag == null || Strings.isNullOrEmpty(tag.getName())) { return null; diff --git a/app/src/main/java/com/todoroo/astrid/tags/TagService.java b/app/src/main/java/com/todoroo/astrid/tags/TagService.java index e2241a8eb..84d92435b 100644 --- a/app/src/main/java/com/todoroo/astrid/tags/TagService.java +++ b/app/src/main/java/com/todoroo/astrid/tags/TagService.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.tags; import static com.google.common.collect.Lists.newArrayList; @@ -59,9 +58,7 @@ public final class TagService { return newArrayList(transform(uuids, this::tagFromUUID)); } - /** - * Return all tags (including metadata tags and TagData tags) in an array list - */ + /** Return all tags (including metadata tags and TagData tags) in an array list */ public List getTagList() { final List tagList = new ArrayList<>(); for (TagData tagData : tagDataDao.tagDataOrderedByName()) { @@ -77,8 +74,8 @@ 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 + * If a tag already exists in the database that case insensitively matches the given tag, return + * that. Otherwise, return the argument */ public String getTagWithCase(String tag) { TagData tagData = tagDataDao.getTagByName(tag); diff --git a/app/src/main/java/com/todoroo/astrid/tags/TagsControlSet.java b/app/src/main/java/com/todoroo/astrid/tags/TagsControlSet.java index 9b1814106..02e3bf1cd 100644 --- a/app/src/main/java/com/todoroo/astrid/tags/TagsControlSet.java +++ b/app/src/main/java/com/todoroo/astrid/tags/TagsControlSet.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.tags; import static com.google.common.base.Predicates.notNull; @@ -78,18 +77,22 @@ public final class TagsControlSet extends TaskEditControlFragment { private static final String EXTRA_NEW_TAGS = "extra_new_tags"; private static final String EXTRA_ORIGINAL_TAGS = "extra_original_tags"; private static final String EXTRA_SELECTED_TAGS = "extra_selected_tags"; - private final Ordering orderByName = new Ordering() { - @Override - public int compare(TagData left, TagData right) { - return left.getName().compareTo(right.getName()); - } - }; + private final Ordering orderByName = + new Ordering() { + @Override + public int compare(TagData left, TagData right) { + return left.getName().compareTo(right.getName()); + } + }; @Inject TagDao tagDao; @Inject TagDataDao tagDataDao; @Inject TagService tagService; @Inject DialogBuilder dialogBuilder; @Inject ThemeCache themeCache; - @BindView(R.id.display_row_edit) TextView tagsDisplay; + + @BindView(R.id.display_row_edit) + TextView tagsDisplay; + private LinearLayout newTagLayout; private ListView tagListView; private View dialogView; @@ -101,16 +104,23 @@ public final class TagsControlSet extends TaskEditControlFragment { private Function tagToString(final float maxLength) { return tagData -> { String tagName = tagData.getName(); - tagName = tagName - .substring(0, Math.min(tagName.length(), (int) maxLength)) - .replace(' ', NO_BREAK_SPACE); + tagName = + tagName + .substring(0, Math.min(tagName.length(), (int) maxLength)) + .replace(' ', NO_BREAK_SPACE); SpannableString string = new SpannableString(NO_BREAK_SPACE + tagName + NO_BREAK_SPACE); int themeIndex = tagData.getColor(); ThemeColor color = themeIndex >= 0 ? themeCache.getThemeColor(themeIndex) : themeCache.getUntaggedColor(); - string.setSpan(new BackgroundColorSpan(color.getPrimaryColor()), 0, string.length(), + string.setSpan( + new BackgroundColorSpan(color.getPrimaryColor()), + 0, + string.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); - string.setSpan(new ForegroundColorSpan(color.getActionBarTint()), 0, string.length(), + string.setSpan( + new ForegroundColorSpan(color.getActionBarTint()), + 0, + string.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); return string; }; @@ -131,8 +141,8 @@ public final class TagsControlSet extends TaskEditControlFragment { @Nullable @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = super.onCreateView(inflater, container, savedInstanceState); ArrayList newTags; if (savedInstanceState != null) { @@ -140,9 +150,11 @@ public final class TagsControlSet extends TaskEditControlFragment { originalTags = savedInstanceState.getParcelableArrayList(EXTRA_ORIGINAL_TAGS); newTags = savedInstanceState.getStringArrayList(EXTRA_NEW_TAGS); } else { - originalTags = new ArrayList<>(task.isNew() - ? transform(task.getTags(), tagDataDao::getTagByName) - : tagService.getTagDataForTask(task.getId())); + originalTags = + new ArrayList<>( + task.isNew() + ? transform(task.getTags(), tagDataDao::getTagByName) + : tagService.getTagDataForTask(task.getId())); selectedTags = new ArrayList<>(originalTags); newTags = new ArrayList<>(); } @@ -151,16 +163,16 @@ public final class TagsControlSet extends TaskEditControlFragment { newTagLayout = dialogView.findViewById(R.id.newTags); tagListView = dialogView.findViewById(R.id.existingTags); tagListView.setAdapter( - new ArrayAdapter(getActivity(), R.layout.simple_list_item_multiple_choice_themed, - allTags) { + new ArrayAdapter( + getActivity(), R.layout.simple_list_item_multiple_choice_themed, allTags) { @NonNull @SuppressLint("NewApi") @Override public View getView(int position, View convertView, @NonNull ViewGroup parent) { CheckedTextView view = (CheckedTextView) super.getView(position, convertView, parent); TagData tagData = allTags.get(position); - ThemeColor themeColor = themeCache - .getThemeColor(tagData.getColor() >= 0 ? tagData.getColor() : 19); + ThemeColor themeColor = + themeCache.getThemeColor(tagData.getColor() >= 0 ? tagData.getColor() : 19); view.setText(tagData.getName()); Drawable original = ContextCompat.getDrawable(getContext(), R.drawable.ic_label_24dp); Drawable wrapped = DrawableCompat.wrap(original.mutate()); @@ -215,7 +227,8 @@ public final class TagsControlSet extends TaskEditControlFragment { } private AlertDialog buildDialog() { - return dialogBuilder.newDialog() + return dialogBuilder + .newDialog() .setView(dialogView) .setOnDismissListener(dialogInterface -> refreshDisplayView()) .create(); @@ -274,9 +287,7 @@ public final class TagsControlSet extends TaskEditControlFragment { return tags; } - /** - * Adds a tag to the tag field - */ + /** Adds a tag to the tag field */ private void addTag(String tagName) { LayoutInflater inflater = getActivity().getLayoutInflater(); @@ -294,62 +305,61 @@ public final class TagsControlSet extends TaskEditControlFragment { tagItem = inflater.inflate(R.layout.tag_edit_row, null); newTagLayout.addView(tagItem); if (tagName == null) { - tagName = ""; //$NON-NLS-1$ + tagName = ""; // $NON-NLS-1$ } - final AutoCompleteTextView textView = tagItem. - findViewById(R.id.text1); + final AutoCompleteTextView textView = tagItem.findViewById(R.id.text1); textView.setText(tagName); - textView.addTextChangedListener(new TextWatcher() { - @Override - public void afterTextChanged(Editable s) { - // - } - - @Override - public void beforeTextChanged(CharSequence s, int start, int count, - int after) { - // - } + textView.addTextChangedListener( + new TextWatcher() { + @Override + public void afterTextChanged(Editable s) { + // + } - @Override - public void onTextChanged(CharSequence s, int start, int before, - int count) { - if (count > 0 && newTagLayout.getChildAt(newTagLayout.getChildCount() - 1) == - tagItem) { - addTag(""); //$NON-NLS-1$ - } - } - }); + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + // + } - textView.setOnEditorActionListener((arg0, actionId, arg2) -> { - if (actionId != EditorInfo.IME_NULL) { - return false; - } - if (getLastTextView().getText().length() != 0) { - addTag(""); //$NON-NLS-1$ - } - return true; - }); + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + if (count > 0 && newTagLayout.getChildAt(newTagLayout.getChildCount() - 1) == tagItem) { + addTag(""); // $NON-NLS-1$ + } + } + }); - tagItem.findViewById(R.id.button1).setOnClickListener(v -> { - TextView lastView = getLastTextView(); - if (lastView == textView && textView.getText().length() == 0) { - return; - } + textView.setOnEditorActionListener( + (arg0, actionId, arg2) -> { + if (actionId != EditorInfo.IME_NULL) { + return false; + } + if (getLastTextView().getText().length() != 0) { + addTag(""); // $NON-NLS-1$ + } + return true; + }); - if (newTagLayout.getChildCount() > 1) { - newTagLayout.removeView(tagItem); - } else { - textView.setText(""); //$NON-NLS-1$ - } - }); + tagItem + .findViewById(R.id.button1) + .setOnClickListener( + v -> { + TextView lastView = getLastTextView(); + if (lastView == textView && textView.getText().length() == 0) { + return; + } + + if (newTagLayout.getChildCount() > 1) { + newTagLayout.removeView(tagItem); + } else { + textView.setText(""); // $NON-NLS-1$ + } + }); } - /** - * Get tags container last text view. might be null - */ + /** Get tags container last text view. might be null */ private TextView getLastTextView() { if (newTagLayout.getChildCount() == 0) { return null; diff --git a/app/src/main/java/com/todoroo/astrid/timers/TimerControlSet.java b/app/src/main/java/com/todoroo/astrid/timers/TimerControlSet.java index 21e79f7a9..7eba46672 100644 --- a/app/src/main/java/com/todoroo/astrid/timers/TimerControlSet.java +++ b/app/src/main/java/com/todoroo/astrid/timers/TimerControlSet.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc - *

    - * See the file "LICENSE" for the full license governing this code. + * + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.timers; import android.app.Activity; @@ -48,9 +47,16 @@ public class TimerControlSet extends TaskEditControlFragment { @Inject DialogBuilder dialogBuilder; @Inject @ForActivity Context context; @Inject Theme theme; - @BindView(R.id.display_row_edit) TextView displayEdit; - @BindView(R.id.timer) Chronometer chronometer; - @BindView(R.id.timer_button) ImageView timerButton; + + @BindView(R.id.display_row_edit) + TextView displayEdit; + + @BindView(R.id.timer) + Chronometer chronometer; + + @BindView(R.id.timer_button) + ImageView timerButton; + private TimeDurationControlSet estimated; private TimeDurationControlSet elapsed; private long timerStarted; @@ -60,8 +66,8 @@ public class TimerControlSet extends TaskEditControlFragment { @Nullable @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = super.onCreateView(inflater, container, savedInstanceState); int elapsedSeconds; int estimatedSeconds; @@ -114,7 +120,8 @@ public class TimerControlSet extends TaskEditControlFragment { } private AlertDialog buildDialog() { - return dialogBuilder.newDialog() + return dialogBuilder + .newDialog() .setView(dialogView) .setPositiveButton(android.R.string.ok, (dialog12, which) -> refreshDisplayView()) .setOnCancelListener(dialog1 -> refreshDisplayView()) @@ -154,8 +161,8 @@ public class TimerControlSet extends TaskEditControlFragment { @Override public boolean hasChanges(Task original) { - return elapsed.getTimeDurationInSeconds() != original.getElapsedSeconds() || - estimated.getTimeDurationInSeconds() != original.getEstimatedSeconds(); + return elapsed.getTimeDurationInSeconds() != original.getElapsedSeconds() + || estimated.getTimeDurationInSeconds() != original.getEstimatedSeconds(); } @Override @@ -184,7 +191,7 @@ public class TimerControlSet extends TaskEditControlFragment { String toDisplay; if (!TextUtils.isEmpty(est) && !TextUtils.isEmpty(elap)) { - toDisplay = est + ", " + elap; //$NON-NLS-1$ + toDisplay = est + ", " + elap; // $NON-NLS-1$ } else if (!TextUtils.isEmpty(est)) { toDisplay = est; } else if (!TextUtils.isEmpty(elap)) { @@ -197,9 +204,8 @@ public class TimerControlSet extends TaskEditControlFragment { } private void updateChronometer() { - timerButton.setImageResource(timerActive() - ? R.drawable.ic_pause_24dp - : R.drawable.ic_play_arrow_24dp); + timerButton.setImageResource( + timerActive() ? R.drawable.ic_pause_24dp : R.drawable.ic_play_arrow_24dp); long elapsed = this.elapsed.getTimeDurationInSeconds() * 1000L; if (timerActive()) { @@ -207,11 +213,11 @@ public class TimerControlSet extends TaskEditControlFragment { elapsed += DateUtilities.now() - timerStarted; chronometer.setBase(SystemClock.elapsedRealtime() - elapsed); if (elapsed > DateUtilities.ONE_DAY) { - chronometer.setOnChronometerTickListener(cArg -> { - long t = SystemClock.elapsedRealtime() - cArg.getBase(); - cArg.setText(DateFormat.format("d'd' h:mm", t)); //$NON-NLS-1$ - }); - + chronometer.setOnChronometerTickListener( + cArg -> { + long t = SystemClock.elapsedRealtime() - cArg.getBase(); + cArg.setText(DateFormat.format("d'd' h:mm", t)); // $NON-NLS-1$ + }); } chronometer.start(); } else { diff --git a/app/src/main/java/com/todoroo/astrid/timers/TimerFilterExposer.java b/app/src/main/java/com/todoroo/astrid/timers/TimerFilterExposer.java index 099eea836..6ba6b0097 100644 --- a/app/src/main/java/com/todoroo/astrid/timers/TimerFilterExposer.java +++ b/app/src/main/java/com/todoroo/astrid/timers/TimerFilterExposer.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.timers; import static com.google.common.collect.Lists.newArrayList; @@ -38,8 +37,9 @@ public final class TimerFilterExposer { public static Filter createFilter(Context context) { Resources r = context.getResources(); - Filter filter = new Filter(r.getString(R.string.TFE_workingOn), - new QueryTemplate().where(Task.TIMER_START.gt(0))); + Filter filter = + new Filter( + r.getString(R.string.TFE_workingOn), new QueryTemplate().where(Task.TIMER_START.gt(0))); filter.icon = R.drawable.ic_timer_24dp; return filter; } diff --git a/app/src/main/java/com/todoroo/astrid/timers/TimerPlugin.java b/app/src/main/java/com/todoroo/astrid/timers/TimerPlugin.java index 652498cfd..63a1fa525 100644 --- a/app/src/main/java/com/todoroo/astrid/timers/TimerPlugin.java +++ b/app/src/main/java/com/todoroo/astrid/timers/TimerPlugin.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.timers; import static org.tasks.time.DateTimeUtils.currentTimeMillis; @@ -34,8 +33,11 @@ public class TimerPlugin { private final TaskDao taskDao; @Inject - public TimerPlugin(@ForApplication Context context, NotificationManager notificationManager, - Tracker tracker, TaskDao taskDao) { + public TimerPlugin( + @ForApplication Context context, + NotificationManager notificationManager, + Tracker tracker, + TaskDao taskDao) { this.context = context; this.notificationManager = notificationManager; this.tracker = tracker; @@ -86,22 +88,23 @@ public class TimerPlugin { Filter filter = TimerFilterExposer.createFilter(context); Intent notifyIntent = TaskIntents.getTaskListIntent(context, filter); notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); - PendingIntent pendingIntent = PendingIntent.getActivity(context, - Constants.NOTIFICATION_TIMER, notifyIntent, 0); + PendingIntent pendingIntent = + PendingIntent.getActivity(context, Constants.NOTIFICATION_TIMER, notifyIntent, 0); Resources r = context.getResources(); String appName = r.getString(R.string.app_name); - String text = r.getString(R.string.TPl_notification, - r.getQuantityString(R.plurals.Ntasks, count, count)); - NotificationCompat.Builder builder = new NotificationCompat.Builder(context, - NotificationManager.NOTIFICATION_CHANNEL_TIMERS) - .setContentIntent(pendingIntent) - .setContentTitle(appName) - .setContentText(text) - .setWhen(currentTimeMillis()) - .setSmallIcon(R.drawable.ic_timer_white_24dp) - .setAutoCancel(false) - .setOngoing(true); + String text = + r.getString( + R.string.TPl_notification, r.getQuantityString(R.plurals.Ntasks, count, count)); + NotificationCompat.Builder builder = + new NotificationCompat.Builder(context, NotificationManager.NOTIFICATION_CHANNEL_TIMERS) + .setContentIntent(pendingIntent) + .setContentTitle(appName) + .setContentText(text) + .setWhen(currentTimeMillis()) + .setSmallIcon(R.drawable.ic_timer_white_24dp) + .setAutoCancel(false) + .setOngoing(true); notificationManager.notify(Constants.NOTIFICATION_TIMER, builder, false, false, false); } } diff --git a/app/src/main/java/com/todoroo/astrid/ui/CheckableImageView.java b/app/src/main/java/com/todoroo/astrid/ui/CheckableImageView.java index d95d8accb..f18d30185 100644 --- a/app/src/main/java/com/todoroo/astrid/ui/CheckableImageView.java +++ b/app/src/main/java/com/todoroo/astrid/ui/CheckableImageView.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.ui; import android.content.Context; @@ -14,9 +13,7 @@ import android.widget.Checkable; public class CheckableImageView extends AppCompatImageView implements Checkable { - private static final int[] CHECKED_STATE_SET = { - android.R.attr.state_checked - }; + private static final int[] CHECKED_STATE_SET = {android.R.attr.state_checked}; private boolean mChecked; private boolean mBroadcasting; @@ -42,7 +39,7 @@ public class CheckableImageView extends AppCompatImageView implements Checkable } /** - *

    Changes the checked state of this button.

    + * Changes the checked state of this button. * * @param checked true to check the button, false to uncheck it */ diff --git a/app/src/main/java/com/todoroo/astrid/ui/EditTitleControlSet.java b/app/src/main/java/com/todoroo/astrid/ui/EditTitleControlSet.java index b79670cf3..f3545ffe0 100644 --- a/app/src/main/java/com/todoroo/astrid/ui/EditTitleControlSet.java +++ b/app/src/main/java/com/todoroo/astrid/ui/EditTitleControlSet.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.ui; import android.content.Context; @@ -46,8 +45,11 @@ public class EditTitleControlSet extends TaskEditControlFragment { @Inject TaskDao taskDao; @Inject CheckBoxes checkBoxes; - @BindView(R.id.title) EditText editText; - @BindView(R.id.completeBox) CheckableImageView completeBox; + @BindView(R.id.title) + EditText editText; + + @BindView(R.id.completeBox) + CheckableImageView completeBox; private boolean showKeyboard; private boolean isComplete; @@ -62,8 +64,8 @@ public class EditTitleControlSet extends TaskEditControlFragment { @Nullable @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(getLayout(), null); ButterKnife.bind(this, view); if (savedInstanceState == null) { @@ -108,8 +110,8 @@ public class EditTitleControlSet extends TaskEditControlFragment { if (showKeyboard) { editText.requestFocus(); - InputMethodManager imm = (InputMethodManager) getActivity() - .getSystemService(Context.INPUT_METHOD_SERVICE); + InputMethodManager imm = + (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT); } } @@ -164,16 +166,14 @@ public class EditTitleControlSet extends TaskEditControlFragment { @Override public boolean hasChanges(Task original) { - return !title.equals(original.getTitle()) || - isComplete != original.isCompleted() || - (original.isNew() && !Strings.isNullOrEmpty(title)); + return !title.equals(original.getTitle()) + || isComplete != original.isCompleted() + || (original.isNew() && !Strings.isNullOrEmpty(title)); } @Override public void apply(Task task) { - task.setTitle(Strings.isNullOrEmpty(title) - ? getString(R.string.no_title) - : title); + task.setTitle(Strings.isNullOrEmpty(title) ? getString(R.string.no_title) : title); if (isComplete != task.isCompleted()) { taskDao.setComplete(task, isComplete); } diff --git a/app/src/main/java/com/todoroo/astrid/ui/HideUntilControlSet.java b/app/src/main/java/com/todoroo/astrid/ui/HideUntilControlSet.java index 8af44ec84..38c326899 100644 --- a/app/src/main/java/com/todoroo/astrid/ui/HideUntilControlSet.java +++ b/app/src/main/java/com/todoroo/astrid/ui/HideUntilControlSet.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.ui; import static android.support.v4.content.ContextCompat.getColor; @@ -66,9 +65,13 @@ public class HideUntilControlSet extends TaskEditControlFragment implements OnIt @Inject @ForActivity Context context; @Inject ThemeBase themeBase; @Inject Preferences preferences; - //private final CheckBox enabled; - @BindView(R.id.hideUntil) Spinner spinner; - @BindView(R.id.clear) ImageView clearButton; + // private final CheckBox enabled; + @BindView(R.id.hideUntil) + Spinner spinner; + + @BindView(R.id.clear) + ImageView clearButton; + private ArrayAdapter adapter; private int previousSetting = Task.HIDE_UNTIL_NONE; private int selection; @@ -85,47 +88,49 @@ public class HideUntilControlSet extends TaskEditControlFragment implements OnIt @Nullable @Override - public View onCreateView(final LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = super.onCreateView(inflater, container, savedInstanceState); - adapter = new HiddenTopArrayAdapter(context, - android.R.layout.simple_spinner_item, spinnerItems) { - @NonNull - @Override - public View getView(int position, View convertView, @NonNull ViewGroup parent) { - int selectedItemPosition = position; - if (parent instanceof AdapterView) { - selectedItemPosition = ((AdapterView) parent).getSelectedItemPosition(); - } - TextView tv = (TextView) inflater - .inflate(android.R.layout.simple_spinner_item, parent, false); - tv.setPadding(0, 0, 0, 0); - HideUntilValue value = getItem(selectedItemPosition); - if (value.setting == Task.HIDE_UNTIL_NONE) { - clearButton.setVisibility(View.GONE); - tv.setText(value.label); - tv.setTextColor(getColor(context, R.color.text_tertiary)); - } else { - String display = value.label; - if (value.setting != Task.HIDE_UNTIL_SPECIFIC_DAY - && value.setting != Task.HIDE_UNTIL_SPECIFIC_DAY_TIME) { - display = display.toLowerCase(); + adapter = + new HiddenTopArrayAdapter( + context, android.R.layout.simple_spinner_item, spinnerItems) { + @NonNull + @Override + public View getView(int position, View convertView, @NonNull ViewGroup parent) { + int selectedItemPosition = position; + if (parent instanceof AdapterView) { + selectedItemPosition = ((AdapterView) parent).getSelectedItemPosition(); + } + TextView tv = + (TextView) inflater.inflate(android.R.layout.simple_spinner_item, parent, false); + tv.setPadding(0, 0, 0, 0); + HideUntilValue value = getItem(selectedItemPosition); + if (value.setting == Task.HIDE_UNTIL_NONE) { + clearButton.setVisibility(View.GONE); + tv.setText(value.label); + tv.setTextColor(getColor(context, R.color.text_tertiary)); + } else { + String display = value.label; + if (value.setting != Task.HIDE_UNTIL_SPECIFIC_DAY + && value.setting != Task.HIDE_UNTIL_SPECIFIC_DAY_TIME) { + display = display.toLowerCase(); + } + tv.setText(getString(R.string.TEA_hideUntil_display, display)); + tv.setTextColor(getColor(context, R.color.text_primary)); + } + return tv; } - tv.setText(getString(R.string.TEA_hideUntil_display, display)); - tv.setTextColor(getColor(context, R.color.text_primary)); - } - return tv; - } - }; + }; if (savedInstanceState == null) { long dueDate = task.getDueDate(); long hideUntil = task.getHideUntil(); - DateTime dueDay = newDateTime(dueDate) - .withHourOfDay(0) - .withMinuteOfHour(0) - .withSecondOfMinute(0) - .withMillisOfSecond(0); + DateTime dueDay = + newDateTime(dueDate) + .withHourOfDay(0) + .withMinuteOfHour(0) + .withSecondOfMinute(0) + .withMillisOfSecond(0); // For the hide until due case, we need the time component long dueTime = dueDate / 1000L * 1000L; @@ -134,8 +139,8 @@ public class HideUntilControlSet extends TaskEditControlFragment implements OnIt selection = 0; hideUntil = 0; if (task.isNew()) { - int defaultHideUntil = preferences.getIntegerFromString(R.string.p_default_hideUntil_key, - HIDE_UNTIL_NONE); + int defaultHideUntil = + preferences.getIntegerFromString(R.string.p_default_hideUntil_key, HIDE_UNTIL_NONE); switch (defaultHideUntil) { case HIDE_UNTIL_DUE: selection = 1; @@ -231,19 +236,21 @@ public class HideUntilControlSet extends TaskEditControlFragment implements OnIt spinnerItems.clear(); // set up base values String[] labels = getResources().getStringArray(R.array.TEA_hideUntil); - spinnerItems.addAll(new ArrayList<>(asList( - new HideUntilValue(labels[0], Task.HIDE_UNTIL_DUE), - new HideUntilValue(labels[1], Task.HIDE_UNTIL_DUE_TIME), - new HideUntilValue(labels[2], Task.HIDE_UNTIL_DAY_BEFORE), - new HideUntilValue(labels[3], Task.HIDE_UNTIL_WEEK_BEFORE), - new HideUntilValue(labels[4], Task.HIDE_UNTIL_SPECIFIC_DAY, -1)))); + spinnerItems.addAll( + new ArrayList<>( + asList( + new HideUntilValue(labels[0], Task.HIDE_UNTIL_DUE), + new HideUntilValue(labels[1], Task.HIDE_UNTIL_DUE_TIME), + new HideUntilValue(labels[2], Task.HIDE_UNTIL_DAY_BEFORE), + new HideUntilValue(labels[3], Task.HIDE_UNTIL_WEEK_BEFORE), + new HideUntilValue(labels[4], Task.HIDE_UNTIL_SPECIFIC_DAY, -1)))); if (specificDate > 0) { spinnerItems.add(0, getHideUntilValue(specificDate)); existingDate = specificDate; } else { - spinnerItems.add(0, - new HideUntilValue(getString(R.string.TEA_hideUntil_label), Task.HIDE_UNTIL_NONE)); + spinnerItems.add( + 0, new HideUntilValue(getString(R.string.TEA_hideUntil_label), Task.HIDE_UNTIL_NONE)); existingDate = EXISTING_TIME_UNSET; } adapter.notifyDataSetChanged(); @@ -251,13 +258,18 @@ public class HideUntilControlSet extends TaskEditControlFragment implements OnIt private HideUntilValue getHideUntilValue(long timestamp) { DateTime hideUntilAsDate = newDateTime(timestamp); - if (hideUntilAsDate.getHourOfDay() == 0 && hideUntilAsDate.getMinuteOfHour() == 0 + if (hideUntilAsDate.getHourOfDay() == 0 + && hideUntilAsDate.getMinuteOfHour() == 0 && hideUntilAsDate.getSecondOfMinute() == 0) { - return new HideUntilValue(DateUtilities.getDateString(newDateTime(timestamp)), - Task.HIDE_UNTIL_SPECIFIC_DAY, timestamp); + return new HideUntilValue( + DateUtilities.getDateString(newDateTime(timestamp)), + Task.HIDE_UNTIL_SPECIFIC_DAY, + timestamp); } else { - return new HideUntilValue(DateUtilities.getDateStringWithTime(context, timestamp), - Task.HIDE_UNTIL_SPECIFIC_DAY_TIME, timestamp); + return new HideUntilValue( + DateUtilities.getDateStringWithTime(context, timestamp), + Task.HIDE_UNTIL_SPECIFIC_DAY_TIME, + timestamp); } } @@ -298,9 +310,8 @@ public class HideUntilControlSet extends TaskEditControlFragment implements OnIt private void refreshDisplayView() { selectedValue = adapter.getItem(selection); - clearButton.setVisibility(selectedValue.setting == Task.HIDE_UNTIL_NONE - ? View.GONE - : View.VISIBLE); + clearButton.setVisibility( + selectedValue.setting == Task.HIDE_UNTIL_NONE ? View.GONE : View.VISIBLE); } // --- setting up values diff --git a/app/src/main/java/com/todoroo/astrid/ui/MultilineCheckboxPreference.java b/app/src/main/java/com/todoroo/astrid/ui/MultilineCheckboxPreference.java index e314abcd2..4feff88d5 100644 --- a/app/src/main/java/com/todoroo/astrid/ui/MultilineCheckboxPreference.java +++ b/app/src/main/java/com/todoroo/astrid/ui/MultilineCheckboxPreference.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.ui; import android.content.Context; diff --git a/app/src/main/java/com/todoroo/astrid/ui/MultilineHelper.java b/app/src/main/java/com/todoroo/astrid/ui/MultilineHelper.java index 2b7b6c97f..b91257e67 100644 --- a/app/src/main/java/com/todoroo/astrid/ui/MultilineHelper.java +++ b/app/src/main/java/com/todoroo/astrid/ui/MultilineHelper.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.ui; import android.view.View; diff --git a/app/src/main/java/com/todoroo/astrid/ui/MultilineListPreference.java b/app/src/main/java/com/todoroo/astrid/ui/MultilineListPreference.java index 21776b282..c2c220723 100644 --- a/app/src/main/java/com/todoroo/astrid/ui/MultilineListPreference.java +++ b/app/src/main/java/com/todoroo/astrid/ui/MultilineListPreference.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.ui; import android.content.Context; diff --git a/app/src/main/java/com/todoroo/astrid/ui/MultilinePreference.java b/app/src/main/java/com/todoroo/astrid/ui/MultilinePreference.java index 86c469547..b73b637ff 100644 --- a/app/src/main/java/com/todoroo/astrid/ui/MultilinePreference.java +++ b/app/src/main/java/com/todoroo/astrid/ui/MultilinePreference.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.ui; import android.content.Context; diff --git a/app/src/main/java/com/todoroo/astrid/ui/NNumberPickerDialog.java b/app/src/main/java/com/todoroo/astrid/ui/NNumberPickerDialog.java index aaeb88ff9..381a16437 100644 --- a/app/src/main/java/com/todoroo/astrid/ui/NNumberPickerDialog.java +++ b/app/src/main/java/com/todoroo/astrid/ui/NNumberPickerDialog.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.ui; import android.content.Context; @@ -20,9 +19,7 @@ import java.util.LinkedList; import java.util.List; import org.tasks.R; -/** - * Dialog box with an arbitrary number of number pickers - */ +/** Dialog box with an arbitrary number of number pickers */ class NNumberPickerDialog extends AlertDialog implements OnClickListener { private final List pickers = new LinkedList<>(); @@ -37,31 +34,36 @@ class NNumberPickerDialog extends AlertDialog implements OnClickListener { * @param incrementBy picker increment by array * @param start picker range start array * @param end picker range end array - * @param separators text separating the spinners. whole array, or individual elements can be - * null + * @param separators text separating the spinners. whole array, or individual elements can be null */ - public NNumberPickerDialog(Context context, OnNNumberPickedListener callBack, - String title, int[] initialValue, int[] incrementBy, int[] start, - int[] end, String[] separators) { + public NNumberPickerDialog( + Context context, + OnNNumberPickedListener callBack, + String title, + int[] initialValue, + int[] incrementBy, + int[] start, + int[] end, + String[] separators) { super(context); mCallback = callBack; setButton(DialogInterface.BUTTON_POSITIVE, context.getText(android.R.string.ok), this); - setButton(DialogInterface.BUTTON_NEGATIVE, context.getText(android.R.string.cancel), + setButton( + DialogInterface.BUTTON_NEGATIVE, + context.getText(android.R.string.cancel), (OnClickListener) null); - LayoutInflater inflater = (LayoutInflater) context - .getSystemService(Context.LAYOUT_INFLATER_SERVICE); + LayoutInflater inflater = + (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.n_number_picker_dialog, null); setView(view); LinearLayout container = (LinearLayout) view; setTitle(title); - LayoutParams npLayout = new LayoutParams(LayoutParams.WRAP_CONTENT, - LayoutParams.MATCH_PARENT); + LayoutParams npLayout = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); npLayout.gravity = 1; - LayoutParams sepLayout = new LayoutParams(LayoutParams.WRAP_CONTENT, - LayoutParams.MATCH_PARENT); + LayoutParams sepLayout = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); for (int i = 0; i < incrementBy.length; i++) { NumberPicker np = new NumberPicker(context, null); np.setIncrementBy(incrementBy[i]); diff --git a/app/src/main/java/com/todoroo/astrid/ui/NumberPicker.java b/app/src/main/java/com/todoroo/astrid/ui/NumberPicker.java index 64c4d9c7a..f63374fd6 100644 --- a/app/src/main/java/com/todoroo/astrid/ui/NumberPicker.java +++ b/app/src/main/java/com/todoroo/astrid/ui/NumberPicker.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.ui; import android.content.Context; @@ -27,11 +26,11 @@ import com.todoroo.andlib.utility.AndroidUtilities; import org.tasks.R; import timber.log.Timber; -public class NumberPicker extends LinearLayout implements OnClickListener, - OnFocusChangeListener, OnLongClickListener { +public class NumberPicker extends LinearLayout + implements OnClickListener, OnFocusChangeListener, OnLongClickListener { - private static final char[] DIGIT_CHARACTERS = new char[]{'0', '1', '2', - '3', '4', '5', '6', '7', '8', '9'}; + private static final char[] DIGIT_CHARACTERS = + new char[] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; private final Handler mHandler; private final EditText mText; private final InputFilter mNumberInputFilter; @@ -45,19 +44,20 @@ public class NumberPicker extends LinearLayout implements OnClickListener, private Formatter mFormatter; private boolean mIncrement; private boolean mDecrement; - private final Runnable mRunnable = new Runnable() { - @Override - public void run() { - long speed = 60; - if (mIncrement) { - changeCurrent(mCurrent + incrementBy); - mHandler.postDelayed(this, speed); - } else if (mDecrement) { - changeCurrent(mCurrent - incrementBy); - mHandler.postDelayed(this, speed); - } - } - }; + private final Runnable mRunnable = + new Runnable() { + @Override + public void run() { + long speed = 60; + if (mIncrement) { + changeCurrent(mCurrent + incrementBy); + mHandler.postDelayed(this, speed); + } else if (mDecrement) { + changeCurrent(mCurrent - incrementBy); + mHandler.postDelayed(this, speed); + } + } + }; public NumberPicker(Context context) { this(context, null); @@ -66,8 +66,8 @@ public class NumberPicker extends LinearLayout implements OnClickListener, public NumberPicker(Context context, AttributeSet attrs) { super(context, attrs); setOrientation(VERTICAL); - LayoutInflater inflater = (LayoutInflater) context - .getSystemService(Context.LAYOUT_INFLATER_SERVICE); + LayoutInflater inflater = + (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(getLayout(), this, true); mHandler = new Handler(); InputFilter inputFilter = new NumberPickerInputFilter(); @@ -83,26 +83,54 @@ public class NumberPicker extends LinearLayout implements OnClickListener, mText = findViewById(R.id.timepicker_input); mText.setOnFocusChangeListener(this); - mText.setFilters(new InputFilter[]{inputFilter}); + mText.setFilters(new InputFilter[] {inputFilter}); // disable keyboard until user requests it AndroidUtilities.suppressVirtualKeyboard(mText); - Animation slideUpOutAnimation = new TranslateAnimation( - Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, - Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -100); + Animation slideUpOutAnimation = + new TranslateAnimation( + Animation.RELATIVE_TO_SELF, + 0, + Animation.RELATIVE_TO_SELF, + 0, + Animation.RELATIVE_TO_SELF, + 0, + Animation.RELATIVE_TO_SELF, + -100); slideUpOutAnimation.setDuration(200); - Animation slideUpInAnimation = new TranslateAnimation( - Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, - Animation.RELATIVE_TO_SELF, 100, Animation.RELATIVE_TO_SELF, 0); + Animation slideUpInAnimation = + new TranslateAnimation( + Animation.RELATIVE_TO_SELF, + 0, + Animation.RELATIVE_TO_SELF, + 0, + Animation.RELATIVE_TO_SELF, + 100, + Animation.RELATIVE_TO_SELF, + 0); slideUpInAnimation.setDuration(200); - Animation slideDownOutAnimation = new TranslateAnimation( - Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, - Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 100); + Animation slideDownOutAnimation = + new TranslateAnimation( + Animation.RELATIVE_TO_SELF, + 0, + Animation.RELATIVE_TO_SELF, + 0, + Animation.RELATIVE_TO_SELF, + 0, + Animation.RELATIVE_TO_SELF, + 100); slideDownOutAnimation.setDuration(200); - Animation slideDownInAnimation = new TranslateAnimation( - Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, - Animation.RELATIVE_TO_SELF, -100, Animation.RELATIVE_TO_SELF, 0); + Animation slideDownInAnimation = + new TranslateAnimation( + Animation.RELATIVE_TO_SELF, + 0, + Animation.RELATIVE_TO_SELF, + 0, + Animation.RELATIVE_TO_SELF, + -100, + Animation.RELATIVE_TO_SELF, + 0); slideDownInAnimation.setDuration(200); if (!isEnabled()) { @@ -120,7 +148,7 @@ public class NumberPicker extends LinearLayout implements OnClickListener, /** * @return The number of allowable digits that can be typed in (-1 for unlimited) e.g. return 2 if - * you don't want to allow 00002 even if 2 is in range. + * you don't want to allow 00002 even if 2 is in range. */ private int getMaxDigits() { return -1; @@ -144,8 +172,8 @@ public class NumberPicker extends LinearLayout implements OnClickListener, } /** - * Set the range of numbers allowed for the number picker. The current value - * will be automatically set to the start. + * Set the range of numbers allowed for the number picker. The current value will be automatically + * set to the start. * * @param start the start of the range (inclusive) * @param end the end of the range (inclusive) @@ -175,8 +203,7 @@ public class NumberPicker extends LinearLayout implements OnClickListener, } private String formatNumber(int value) { - return (mFormatter != null) ? mFormatter.toString(value) : String - .valueOf(value); + return (mFormatter != null) ? mFormatter.toString(value) : String.valueOf(value); } private void changeCurrent(int current) { @@ -198,7 +225,6 @@ public class NumberPicker extends LinearLayout implements OnClickListener, } else { return current; } - } private void updateView() { @@ -245,8 +271,8 @@ public class NumberPicker extends LinearLayout implements OnClickListener, } /** - * We start the long click here but rely on the {@link NumberPickerButton} - * to inform us when the long click has ended. + * We start the long click here but rely on the {@link NumberPickerButton} to inform us when the + * long click has ended. */ @Override public boolean onLongClick(View v) { @@ -284,9 +310,7 @@ public class NumberPicker extends LinearLayout implements OnClickListener, } } - /** - * @return the current value. - */ + /** @return the current value. */ public int getCurrent() { String str = String.valueOf(((TextView) mText).getText()); validateCurrentView(str, true); @@ -300,9 +324,7 @@ public class NumberPicker extends LinearLayout implements OnClickListener, public interface OnChangedListener { - /** - * return new value - */ + /** return new value */ int onChanged(int newVal); } @@ -314,10 +336,9 @@ public class NumberPicker extends LinearLayout implements OnClickListener, private class NumberPickerInputFilter implements InputFilter { @Override - public CharSequence filter(CharSequence source, int start, int end, - Spanned dest, int dstart, int dend) { - return mNumberInputFilter.filter(source, start, end, dest, - dstart, dend); + public CharSequence filter( + CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { + return mNumberInputFilter.filter(source, start, end, dest, dstart, dend); } } @@ -329,17 +350,18 @@ public class NumberPicker extends LinearLayout implements OnClickListener, } @Override - public CharSequence filter(CharSequence source, int start, int end, - Spanned dest, int dstart, int dend) { + public CharSequence filter( + CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { - CharSequence filtered = super.filter(source, start, end, dest, - dstart, dend); + CharSequence filtered = super.filter(source, start, end, dest, dstart, dend); if (filtered == null) { filtered = source.subSequence(start, end); } - String result = String.valueOf(dest.subSequence(0, dstart)) - + filtered + dest.subSequence(dend, dest.length()); + String result = + String.valueOf(dest.subSequence(0, dstart)) + + filtered + + dest.subSequence(dend, dest.length()); if ("".equals(result)) { return result; diff --git a/app/src/main/java/com/todoroo/astrid/ui/NumberPickerButton.java b/app/src/main/java/com/todoroo/astrid/ui/NumberPickerButton.java index d1fa9abd4..2f1b4795e 100644 --- a/app/src/main/java/com/todoroo/astrid/ui/NumberPickerButton.java +++ b/app/src/main/java/com/todoroo/astrid/ui/NumberPickerButton.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.ui; import android.content.Context; @@ -13,15 +12,12 @@ import android.view.KeyEvent; import android.view.MotionEvent; import org.tasks.R; -/** - * This class exists purely to cancel long click events. - */ +/** This class exists purely to cancel long click events. */ public class NumberPickerButton extends AppCompatImageButton { private NumberPicker mNumberPicker; - public NumberPickerButton(Context context, AttributeSet attrs, - int defStyle) { + public NumberPickerButton(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @@ -51,8 +47,7 @@ public class NumberPickerButton extends AppCompatImageButton { @Override public boolean onKeyUp(int keyCode, KeyEvent event) { - if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER) - || (keyCode == KeyEvent.KEYCODE_ENTER)) { + if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER) || (keyCode == KeyEvent.KEYCODE_ENTER)) { cancelLongpress(); } return super.onKeyUp(keyCode, event); diff --git a/app/src/main/java/com/todoroo/astrid/ui/RandomReminderControlSet.java b/app/src/main/java/com/todoroo/astrid/ui/RandomReminderControlSet.java index 640a53760..965739c9c 100644 --- a/app/src/main/java/com/todoroo/astrid/ui/RandomReminderControlSet.java +++ b/app/src/main/java/com/todoroo/astrid/ui/RandomReminderControlSet.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.ui; import android.content.Context; @@ -28,23 +27,24 @@ class RandomReminderControlSet { Spinner periodSpinner = parentView.findViewById(R.id.reminder_random_interval); periodSpinner.setVisibility(View.VISIBLE); // create adapter - ArrayAdapter adapter = new ArrayAdapter<>( - context, android.R.layout.simple_spinner_item, - context.getResources().getStringArray(R.array.TEA_reminder_random)); + ArrayAdapter adapter = + new ArrayAdapter<>( + context, + android.R.layout.simple_spinner_item, + context.getResources().getStringArray(R.array.TEA_reminder_random)); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); periodSpinner.setAdapter(adapter); - periodSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - selectedIndex = position; - } - - @Override - public void onNothingSelected(AdapterView parent) { + periodSpinner.setOnItemSelectedListener( + new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + selectedIndex = position; + } - } - }); + @Override + public void onNothingSelected(AdapterView parent) {} + }); // create hour array String[] hourStrings = context.getResources().getStringArray(R.array.TEA_reminder_random_hours); diff --git a/app/src/main/java/com/todoroo/astrid/ui/ReminderControlSet.java b/app/src/main/java/com/todoroo/astrid/ui/ReminderControlSet.java index fa2db900c..871d74813 100644 --- a/app/src/main/java/com/todoroo/astrid/ui/ReminderControlSet.java +++ b/app/src/main/java/com/todoroo/astrid/ui/ReminderControlSet.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.ui; import static com.google.common.collect.Lists.newArrayList; @@ -81,9 +80,16 @@ public class ReminderControlSet extends TaskEditControlFragment { @Inject Device device; @Inject Preferences preferences; @Inject @ForActivity Context context; - @BindView(R.id.alert_container) LinearLayout alertContainer; - @BindView(R.id.reminder_alarm) Spinner mode; - @BindView(R.id.alarms_add_spinner) Spinner addSpinner; + + @BindView(R.id.alert_container) + LinearLayout alertContainer; + + @BindView(R.id.reminder_alarm) + Spinner mode; + + @BindView(R.id.alarms_add_spinner) + Spinner addSpinner; + private long taskId; private int flags; private long randomReminder; @@ -100,15 +106,15 @@ public class ReminderControlSet extends TaskEditControlFragment { @Nullable @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = super.onCreateView(inflater, container, savedInstanceState); - remindAdapter = new HiddenTopArrayAdapter(context, android.R.layout.simple_spinner_item, - spinnerOptions); + remindAdapter = + new HiddenTopArrayAdapter(context, android.R.layout.simple_spinner_item, spinnerOptions); String[] modes = getResources().getStringArray(R.array.reminder_ring_modes); - ArrayAdapter modeAdapter = new ArrayAdapter<>(context, - android.R.layout.simple_spinner_item, modes); + ArrayAdapter modeAdapter = + new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, modes); modeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mode.setAdapter(modeAdapter); @@ -210,10 +216,10 @@ public class ReminderControlSet extends TaskEditControlFragment { @Override public boolean hasChanges(Task original) { - return getFlags() != original.getReminderFlags() || - getRandomReminderPeriod() != original.getReminderPeriod() || - !newHashSet(currentAlarms()).equals(alarms) || - !newHashSet(geofenceService.getGeofences(taskId)).equals(locations); + return getFlags() != original.getReminderFlags() + || getRandomReminderPeriod() != original.getReminderPeriod() + || !newHashSet(currentAlarms()).equals(alarms) + || !newHashSet(geofenceService.getGeofences(taskId)).equals(locations); } @Override @@ -256,8 +262,8 @@ public class ReminderControlSet extends TaskEditControlFragment { } @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, - @NonNull int[] grantResults) { + public void onRequestPermissionsResult( + int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == PermissionRequestor.REQUEST_LOCATION) { if (verifyPermissions(grantResults)) { pickLocation(); @@ -309,8 +315,8 @@ public class ReminderControlSet extends TaskEditControlFragment { private void addNewAlarm() { Intent intent = new Intent(getActivity(), DateAndTimePickerActivity.class); - intent.putExtra(DateAndTimePickerActivity.EXTRA_TIMESTAMP, - newDateTime().startOfDay().getMillis()); + intent.putExtra( + DateAndTimePickerActivity.EXTRA_TIMESTAMP, newDateTime().startOfDay().getMillis()); startActivityForResult(intent, REQUEST_NEW_ALARM); } @@ -324,13 +330,16 @@ public class ReminderControlSet extends TaskEditControlFragment { private void addAlarmRow(final View alertItem, String text, final View.OnClickListener onRemove) { TextView display = alertItem.findViewById(R.id.alarm_string); display.setText(text); - alertItem.findViewById(R.id.clear).setOnClickListener(v -> { - alertContainer.removeView(alertItem); - if (onRemove != null) { - onRemove.onClick(v); - } - updateSpinner(); - }); + alertItem + .findViewById(R.id.clear) + .setOnClickListener( + v -> { + alertContainer.removeView(alertItem); + if (onRemove != null) { + onRemove.onClick(v); + } + updateSpinner(); + }); updateSpinner(); } @@ -365,8 +374,8 @@ public class ReminderControlSet extends TaskEditControlFragment { } private void addRandomReminder(long reminderPeriod) { - View alarmRow = addAlarmRow(getString(R.string.randomly_once) + " ", - v -> randomControlSet = null); + View alarmRow = + addAlarmRow(getString(R.string.randomly_once) + " ", v -> randomControlSet = null); randomControlSet = new RandomReminderControlSet(context, alarmRow, reminderPeriod); } diff --git a/app/src/main/java/com/todoroo/astrid/ui/TimeDurationControlSet.java b/app/src/main/java/com/todoroo/astrid/ui/TimeDurationControlSet.java index dff69f904..66522bc33 100644 --- a/app/src/main/java/com/todoroo/astrid/ui/TimeDurationControlSet.java +++ b/app/src/main/java/com/todoroo/astrid/ui/TimeDurationControlSet.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.ui; import android.content.Context; @@ -24,8 +23,7 @@ public class TimeDurationControlSet implements OnNNumberPickedListener, View.OnC private int[] initialValues = null; private NNumberPickerDialog dialog = null; - public TimeDurationControlSet(Context context, View view, - int timeButtonId, Theme theme) { + public TimeDurationControlSet(Context context, View view, int timeButtonId, Theme theme) { this.context = context; this.theme = theme; @@ -53,43 +51,46 @@ public class TimeDurationControlSet implements OnNNumberPickedListener, View.OnC timeButton.setText(DateUtils.formatElapsedTime(timeDuration)); int hours = timeDuration / 3600; int minutes = timeDuration / 60 - 60 * hours; - initialValues = new int[]{hours, minutes}; + initialValues = new int[] {hours, minutes}; } - /** - * Called when NumberPicker activity is completed - */ + /** Called when NumberPicker activity is completed */ @Override public void onNumbersPicked(int[] values) { setTimeDuration(values[0] * 3600 + values[1] * 60); } - /** - * Called when time button is clicked - */ + /** Called when time button is clicked */ @Override public void onClick(View v) { if (dialog == null) { - dialog = new NNumberPickerDialog(theme.getThemedDialog(context), this, - context.getResources().getString(R.string.DLG_hour_minutes), - new int[]{0, 0}, new int[]{1, 5}, new int[]{0, 0}, - new int[]{999, 59}, new String[]{":", null}); + dialog = + new NNumberPickerDialog( + theme.getThemedDialog(context), + this, + context.getResources().getString(R.string.DLG_hour_minutes), + new int[] {0, 0}, + new int[] {1, 5}, + new int[] {0, 0}, + new int[] {999, 59}, + new String[] {":", null}); final NumberPicker hourPicker = dialog.getPicker(0); final NumberPicker minutePicker = dialog.getPicker(1); minutePicker.setFormatter(value -> String.format("%02d", value)); - minutePicker.setOnChangeListener(newVal -> { - if (newVal < 0) { - if (hourPicker.getCurrent() == 0) { - return 0; - } - hourPicker.setCurrent(hourPicker.getCurrent() - 1); - return 60 + newVal; - } else if (newVal > 59) { - hourPicker.setCurrent(hourPicker.getCurrent() + 1); - return newVal % 60; - } - return newVal; - }); + minutePicker.setOnChangeListener( + newVal -> { + if (newVal < 0) { + if (hourPicker.getCurrent() == 0) { + return 0; + } + hourPicker.setCurrent(hourPicker.getCurrent() - 1); + return 60 + newVal; + } else if (newVal > 59) { + hourPicker.setCurrent(hourPicker.getCurrent() + 1); + return newVal % 60; + } + return newVal; + }); } if (initialValues != null) { @@ -99,6 +100,4 @@ public class TimeDurationControlSet implements OnNNumberPickedListener, View.OnC theme.applyToContext(dialog.getContext()); dialog.show(); } - - } diff --git a/app/src/main/java/com/todoroo/astrid/utility/Constants.java b/app/src/main/java/com/todoroo/astrid/utility/Constants.java index ec7d1c102..e5a8928b4 100644 --- a/app/src/main/java/com/todoroo/astrid/utility/Constants.java +++ b/app/src/main/java/com/todoroo/astrid/utility/Constants.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.utility; import org.tasks.BuildConfig; @@ -12,9 +11,8 @@ public final class Constants { public static final String FILE_PROVIDER_AUTHORITY = BuildConfig.APPLICATION_ID + ".provider"; - /** - * Notification Manager id for timing - */ + /** Notification Manager id for timing */ public static final int NOTIFICATION_TIMER = -2; + public static final int NOTIFICATION_SYNC_ERROR = -3; } diff --git a/app/src/main/java/com/todoroo/astrid/utility/Flags.java b/app/src/main/java/com/todoroo/astrid/utility/Flags.java index 73b5038c6..fb7f96b1e 100644 --- a/app/src/main/java/com/todoroo/astrid/utility/Flags.java +++ b/app/src/main/java/com/todoroo/astrid/utility/Flags.java @@ -1,21 +1,17 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.utility; public class Flags { - /** - * If set, indicates tags changed during task save - */ + /** If set, indicates tags changed during task save */ public static final int TAGS_CHANGED = 1 << 1; - /** - * If set, indicates that TaskListFragmentPager should not intercept touch events - */ + /** If set, indicates that TaskListFragmentPager should not intercept touch events */ public static final int TLFP_NO_INTERCEPT_TOUCH = 1 << 7; + private static int state = 0; public static boolean checkAndClear(int flag) { @@ -31,5 +27,4 @@ public class Flags { public static void set(int flag) { state |= flag; } - } diff --git a/app/src/main/java/com/todoroo/astrid/utility/TitleParser.java b/app/src/main/java/com/todoroo/astrid/utility/TitleParser.java index 984f8b12f..46d48e6f8 100644 --- a/app/src/main/java/com/todoroo/astrid/utility/TitleParser.java +++ b/app/src/main/java/com/todoroo/astrid/utility/TitleParser.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package com.todoroo.astrid.utility; import android.text.TextUtils; @@ -26,7 +25,9 @@ public class TitleParser { public static void parse(TagService tagService, Task task, ArrayList tags) { repeatHelper(task); - listHelper(tagService, task, + listHelper( + tagService, + task, tags); // Don't need to know if tags affected things since we don't show alerts for them dayHelper(task); priorityHelper(task); @@ -76,36 +77,44 @@ public class TitleParser { task.setTitle(inputText.trim()); } - //helper method for priorityHelper. converts the string to a Task Importance + // helper method for priorityHelper. converts the string to a Task Importance private static int strToPriority(String priorityStr) { if (priorityStr != null) { priorityStr.toLowerCase().trim(); } int priority = Task.IMPORTANCE_DO_OR_DIE; - if ("0".equals(priorityStr) || "!0".equals(priorityStr) || "least".equals(priorityStr) + if ("0".equals(priorityStr) + || "!0".equals(priorityStr) + || "least".equals(priorityStr) || "lowest".equals(priorityStr)) { priority = Task.IMPORTANCE_NONE; } - if ("!".equals(priorityStr) || "!1".equals(priorityStr) || "bang".equals(priorityStr) || "1" - .equals(priorityStr) || "low".equals(priorityStr)) { + if ("!".equals(priorityStr) + || "!1".equals(priorityStr) + || "bang".equals(priorityStr) + || "1".equals(priorityStr) + || "low".equals(priorityStr)) { priority = Task.IMPORTANCE_SHOULD_DO; } - if ("!!".equals(priorityStr) || "!2".equals(priorityStr) || "bang bang".equals(priorityStr) - || "2".equals(priorityStr) || "high".equals(priorityStr)) { + if ("!!".equals(priorityStr) + || "!2".equals(priorityStr) + || "bang bang".equals(priorityStr) + || "2".equals(priorityStr) + || "high".equals(priorityStr)) { priority = Task.IMPORTANCE_MUST_DO; } return priority; } - //priorityHelper parses the string and sets the Task's importance + // priorityHelper parses the string and sets the Task's importance private static void priorityHelper(Task task) { String inputText = task.getTitle(); String[] importanceStrings = { - "()((^|[^\\w!])!+|(^|[^\\w!])!\\d)($|[^\\w!])", - "()(?i)((\\s?bang){1,})$", - "(?i)(\\spriority\\s?(\\d)$)", - "(?i)(\\sbang\\s?(\\d)$)", - "(?i)()(\\shigh(est)?|\\slow(est)?|\\stop|\\sleast) ?priority$" + "()((^|[^\\w!])!+|(^|[^\\w!])!\\d)($|[^\\w!])", + "()(?i)((\\s?bang){1,})$", + "(?i)(\\spriority\\s?(\\d)$)", + "(?i)(\\sbang\\s?(\\d)$)", + "(?i)()(\\shigh(est)?|\\slow(est)?|\\stop|\\sleast) ?priority$" }; for (String importanceString : importanceStrings) { Pattern importancePattern = Pattern.compile(importanceString); @@ -124,7 +133,7 @@ public class TitleParser { task.setTitle(inputText.trim()); } - //helper for dayHelper. Converts am/pm to an int 0/1. + // helper for dayHelper. Converts am/pm to an int 0/1. private static int ampmToNumber(String amPmString) { int time = Calendar.PM; if (amPmString == null) { @@ -158,24 +167,24 @@ public class TitleParser { return s; } - //---------------------DATE-------------------------- - //Handles setting the task's date. - //Day of week (e.g. Monday, Tuesday,..) is overridden by a set date (e.g. October 23 2013). - //Vague times (e.g. breakfast, night) are overridden by a set time (9 am, at 10, 17:00) + // ---------------------DATE-------------------------- + // Handles setting the task's date. + // Day of week (e.g. Monday, Tuesday,..) is overridden by a set date (e.g. October 23 2013). + // Vague times (e.g. breakfast, night) are overridden by a set time (9 am, at 10, 17:00) private static void dayHelper(Task task) { String inputText = task.getTitle(); Calendar cal = null; Boolean containsSpecificTime = false; String[] daysOfWeek = { - "(?i)(\\(|\\b)today(\\)|\\b)", - "(?i)(\\(|\\b)tomorrow(\\)|\\b)", - "(?i)(\\(|\\b)mon(day(\\)|\\b)|(\\)|\\.))", - "(?i)(\\(|\\b)tue(sday(\\)|\\b)|(\\)|\\.))", - "(?i)(\\(|\\b)wed(nesday(\\)|\\b)|(\\)|\\.))", - "(?i)(\\(|\\b)thu(rsday(\\)|\\b)|(\\)|\\.))", - "(?i)(\\(|\\b)fri(day(\\)|\\b)|(\\)|\\.))", - "(?i)(\\(|\\b)sat(urday(\\)|\\b)|(\\)|\\.))", - "(?i)(\\(|\\b)sun(day(\\)|\\b)|(\\)|\\.))" + "(?i)(\\(|\\b)today(\\)|\\b)", + "(?i)(\\(|\\b)tomorrow(\\)|\\b)", + "(?i)(\\(|\\b)mon(day(\\)|\\b)|(\\)|\\.))", + "(?i)(\\(|\\b)tue(sday(\\)|\\b)|(\\)|\\.))", + "(?i)(\\(|\\b)wed(nesday(\\)|\\b)|(\\)|\\.))", + "(?i)(\\(|\\b)thu(rsday(\\)|\\b)|(\\)|\\.))", + "(?i)(\\(|\\b)fri(day(\\)|\\b)|(\\)|\\.))", + "(?i)(\\(|\\b)sat(urday(\\)|\\b)|(\\)|\\.))", + "(?i)(\\(|\\b)sun(day(\\)|\\b)|(\\)|\\.))" }; for (String date : daysOfWeek) { @@ -185,27 +194,27 @@ public class TitleParser { String toParse = stripParens(m.group(0)); cal = AstridChronic.parse(toParse).getBeginCalendar(); inputText = removeIfParenthetical(m, inputText); - //then put it into task + // then put it into task } } String[] dates = { - "(?i)(\\(|\\b)(jan(\\.|uary))(\\s(3[0-1]|[0-2]?[0-9])),?( (\\d{4}|\\d{2}))?(\\)|\\b)", - "(?i)(\\(|\\b)(feb(\\.|ruary))(\\s(3[0-1]|[0-2]?[0-9])),?( (\\d{4}|\\d{2}))?(\\)|\\b)", - "(?i)(\\(|\\b)(mar(\\.|ch))(\\s(3[0-1]|[0-2]?[0-9])),?( (\\d{4}|\\d{2}))?(\\)|\\b)", - "(?i)(\\(|\\b)(apr(\\.|il))(\\s(3[0-1]|[0-2]?[0-9])),?( (\\d{4}|\\d{2}))?(\\)|\\b)", - "(?i)(\\(|\\b)(may())(\\s(3[0-1]|[0-2]?[0-9])),?( (\\d{4}|\\d{2}))?(\\)|\\b)", - "(?i)(\\(|\\b)(jun(\\.|e))(\\s(3[0-1]|[0-2]?[0-9])),?( (\\d{4}|\\d{2}))?(\\)|\\b)", - "(?i)(\\(|\\b)(jul(\\.|y))(\\s(3[0-1]|[0-2]?[0-9])),?( (\\d{4}|\\d{2}))?(\\)|\\b)", - "(?i)(\\(|\\b)(aug(\\.|ust))(\\s(3[0-1]|[0-2]?[0-9])),?( (\\d{4}|\\d{2}))?(\\)|\\b)", - "(?i)(\\(|\\b)(sep(\\.|tember))(\\s(3[0-1]|[0-2]?[0-9])),?( (\\d{4}|\\d{2}))?(\\)|\\b)", - "(?i)(\\(|\\b)(oct(\\.|ober))(\\s(3[0-1]|[0-2]?[0-9])),?( (\\d{4}|\\d{2}))?(\\)|\\b)", - "(?i)(\\(|\\b)(nov(\\.|ember))(\\s(3[0-1]|[0-2]?[0-9])),?( (\\d{4}|\\d{2}))?(\\)|\\b)", - "(?i)(\\(|\\b)(dec(\\.|ember))(\\s(3[0-1]|[0-2]?[0-9])),?( (\\d{4}|\\d{2}))?(\\)|\\b)" + "(?i)(\\(|\\b)(jan(\\.|uary))(\\s(3[0-1]|[0-2]?[0-9])),?( (\\d{4}|\\d{2}))?(\\)|\\b)", + "(?i)(\\(|\\b)(feb(\\.|ruary))(\\s(3[0-1]|[0-2]?[0-9])),?( (\\d{4}|\\d{2}))?(\\)|\\b)", + "(?i)(\\(|\\b)(mar(\\.|ch))(\\s(3[0-1]|[0-2]?[0-9])),?( (\\d{4}|\\d{2}))?(\\)|\\b)", + "(?i)(\\(|\\b)(apr(\\.|il))(\\s(3[0-1]|[0-2]?[0-9])),?( (\\d{4}|\\d{2}))?(\\)|\\b)", + "(?i)(\\(|\\b)(may())(\\s(3[0-1]|[0-2]?[0-9])),?( (\\d{4}|\\d{2}))?(\\)|\\b)", + "(?i)(\\(|\\b)(jun(\\.|e))(\\s(3[0-1]|[0-2]?[0-9])),?( (\\d{4}|\\d{2}))?(\\)|\\b)", + "(?i)(\\(|\\b)(jul(\\.|y))(\\s(3[0-1]|[0-2]?[0-9])),?( (\\d{4}|\\d{2}))?(\\)|\\b)", + "(?i)(\\(|\\b)(aug(\\.|ust))(\\s(3[0-1]|[0-2]?[0-9])),?( (\\d{4}|\\d{2}))?(\\)|\\b)", + "(?i)(\\(|\\b)(sep(\\.|tember))(\\s(3[0-1]|[0-2]?[0-9])),?( (\\d{4}|\\d{2}))?(\\)|\\b)", + "(?i)(\\(|\\b)(oct(\\.|ober))(\\s(3[0-1]|[0-2]?[0-9])),?( (\\d{4}|\\d{2}))?(\\)|\\b)", + "(?i)(\\(|\\b)(nov(\\.|ember))(\\s(3[0-1]|[0-2]?[0-9])),?( (\\d{4}|\\d{2}))?(\\)|\\b)", + "(?i)(\\(|\\b)(dec(\\.|ember))(\\s(3[0-1]|[0-2]?[0-9])),?( (\\d{4}|\\d{2}))?(\\)|\\b)" }; // m.group(2) = "month" - //m.group(5) = "day" + // m.group(5) = "day" for (String date : dates) { Pattern pattern = Pattern.compile(date); Matcher m = pattern.matcher(inputText); @@ -219,7 +228,7 @@ public class TitleParser { if (m.group(6) != null) { dateCal.set(Calendar.YEAR, Integer.parseInt(m.group(6).trim())); } else if (today.get(Calendar.MONTH) - dateCal.get(Calendar.MONTH) - > 1) { //if more than a month in the past + > 1) { // if more than a month in the past dateCal.set(Calendar.YEAR, dateCal.get(Calendar.YEAR) + 1); } if (cal == null) { @@ -234,8 +243,9 @@ public class TitleParser { } // for dates in the format MM/DD - Pattern p = Pattern.compile( - "(?i)(\\(|\\b)(1[0-2]|0?[1-9])(\\/|-)(3[0-1]|[0-2]?[0-9])(\\/|-)?(\\d{4}|\\d{2})?(\\)|\\b)"); + Pattern p = + Pattern.compile( + "(?i)(\\(|\\b)(1[0-2]|0?[1-9])(\\/|-)(3[0-1]|[0-2]?[0-9])(\\/|-)?(\\d{4}|\\d{2})?(\\)|\\b)"); Matcher match = p.matcher(inputText); if (match.find()) { Calendar dCal = Calendar.getInstance(); @@ -293,18 +303,18 @@ public class TitleParser { } String[] times = { - //[time] am/pm - "(?i)(\\b)([01]?\\d):?([0-5]\\d)? ?([ap]\\.?m?\\.?)\\b", - //army time - "(?i)\\b(([0-2]?[0-9]):([0-5][0-9]))(\\b)", - //[int] o'clock - "(?i)\\b(([01]?\\d)() ?o'? ?clock) ?([ap]\\.?m\\.?)?\\b", - //at [int] - "(?i)(\\bat) ([01]?\\d)()($|\\D($|\\D))" - - //m.group(2) holds the hour - //m.group(3) holds the minutes - //m.group(4) holds am/pm + // [time] am/pm + "(?i)(\\b)([01]?\\d):?([0-5]\\d)? ?([ap]\\.?m?\\.?)\\b", + // army time + "(?i)\\b(([0-2]?[0-9]):([0-5][0-9]))(\\b)", + // [int] o'clock + "(?i)\\b(([01]?\\d)() ?o'? ?clock) ?([ap]\\.?m\\.?)?\\b", + // at [int] + "(?i)(\\bat) ([01]?\\d)()($|\\D($|\\D))" + + // m.group(2) holds the hour + // m.group(3) holds the minutes + // m.group(4) holds am/pm }; for (String time : times) { @@ -326,15 +336,17 @@ public class TitleParser { timeCal.set(Calendar.AM_PM, ampmToNumber(m.group(4))); } - //sets it to the next occurrence of that hour if no am/pm is provided. doesn't include military time - if (Integer.parseInt(m.group(2)) <= 12 && (m.group(4) == null || (m.group(4).trim()) - .equals(""))) { + // sets it to the next occurrence of that hour if no am/pm is provided. doesn't include + // military time + if (Integer.parseInt(m.group(2)) <= 12 + && (m.group(4) == null || (m.group(4).trim()).equals(""))) { while (timeCal.getTime().getTime() < today.getTime().getTime()) { timeCal.set(Calendar.HOUR_OF_DAY, timeCal.get(Calendar.HOUR_OF_DAY) + 12); } - } else { //if am/pm is provided and the time is in the past, set it to the next day. Military time included. - if (timeCal.get(Calendar.HOUR) != 0 && (timeCal.getTime().getTime() < today.getTime() - .getTime())) { + } else { // if am/pm is provided and the time is in the past, set it to the next day. + // Military time included. + if (timeCal.get(Calendar.HOUR) != 0 + && (timeCal.getTime().getTime() < today.getTime().getTime())) { timeCal.set(Calendar.DAY_OF_MONTH, timeCal.get(Calendar.DAY_OF_MONTH) + 1); } if (timeCal.get(Calendar.HOUR) == 0) { @@ -355,7 +367,7 @@ public class TitleParser { } if (cal - != null) { //if at least one of the above has been called, write to task. else do nothing. + != null) { // if at least one of the above has been called, write to task. else do nothing. if (!TextUtils.isEmpty(inputText)) { task.setTitle(inputText); } @@ -367,9 +379,9 @@ public class TitleParser { } } } - //---------------------DATE-------------------------- + // ---------------------DATE-------------------------- - //Parses through the text and sets the frequency of the task. + // Parses through the text and sets the frequency of the task. private static void repeatHelper(Task task) { String inputText = task.getTitle(); HashMap repeatTimes = new HashMap<>(); @@ -379,13 +391,13 @@ public class TitleParser { repeatTimes.put("(?i)\\bevery ?\\w{0,6} ?evenings?\\b", Frequency.DAILY); repeatTimes.put("(?i)\\bevery ?\\w{0,6} ?afternoons?\\b", Frequency.DAILY); repeatTimes.put("(?i)\\bevery \\w{0,6} ?weeks?\\b", Frequency.WEEKLY); - repeatTimes.put("(?i)\\bevery \\w{0,6} ?(mon|tues|wednes|thurs|fri|satur|sun)days?\\b", - Frequency.WEEKLY); + repeatTimes.put( + "(?i)\\bevery \\w{0,6} ?(mon|tues|wednes|thurs|fri|satur|sun)days?\\b", Frequency.WEEKLY); repeatTimes.put("(?i)\\bevery \\w{0,6} ?months?\\b", Frequency.MONTHLY); repeatTimes.put("(?i)\\bevery \\w{0,6} ?years?\\b", Frequency.YEARLY); HashMap repeatTimesIntervalOne = new HashMap<>(); - //pre-determined intervals of 1 + // pre-determined intervals of 1 repeatTimesIntervalOne.put("(?i)\\bdaily\\b", Frequency.DAILY); repeatTimesIntervalOne.put("(?i)\\beveryday\\b", Frequency.DAILY); repeatTimesIntervalOne.put("(?i)\\bweekly\\b", Frequency.WEEKLY); @@ -421,13 +433,14 @@ public class TitleParser { } } - //helper method for repeatHelper. + // helper method for repeatHelper. private static int findInterval(String inputText) { HashMap wordsToNum = new HashMap<>(); - String[] words = new String[]{ - "one", "two", "three", "four", "five", "six", - "seven", "eight", "nine", "ten", "eleven", "twelve" - }; + String[] words = + new String[] { + "one", "two", "three", "four", "five", "six", + "seven", "eight", "nine", "ten", "eleven", "twelve" + }; for (int i = 0; i < words.length; i++) { wordsToNum.put(words[i], i + 1); wordsToNum.put(Integer.toString(i + 1), i + 1); @@ -453,7 +466,7 @@ public class TitleParser { return interval; } - //helper method for DayHelper. Resets the time on the calendar to 00:00:00 am + // helper method for DayHelper. Resets the time on the calendar to 00:00:00 am private static void setCalendarToDefaultTime(Calendar cal) { cal.set(Calendar.HOUR, 0); cal.set(Calendar.HOUR_OF_DAY, 0); @@ -461,6 +474,4 @@ public class TitleParser { cal.set(Calendar.SECOND, 0); cal.set(Calendar.AM_PM, Calendar.AM); } - } - diff --git a/app/src/main/java/com/todoroo/astrid/voice/VoiceOutputAssistant.java b/app/src/main/java/com/todoroo/astrid/voice/VoiceOutputAssistant.java index 140827fac..65729b7b3 100644 --- a/app/src/main/java/com/todoroo/astrid/voice/VoiceOutputAssistant.java +++ b/app/src/main/java/com/todoroo/astrid/voice/VoiceOutputAssistant.java @@ -1,7 +1,4 @@ -/** - * - */ - +/** */ package com.todoroo.astrid.voice; import android.content.Context; @@ -15,9 +12,7 @@ import javax.inject.Inject; import org.tasks.injection.ForApplication; import timber.log.Timber; -/** - * @author Arne Jans - */ +/** @author Arne Jans */ public class VoiceOutputAssistant implements OnInitListener { private final Context context; @@ -46,15 +41,16 @@ public class VoiceOutputAssistant implements OnInitListener { if (mTts != null && isTTSInitialized) { final String id = UUID.randomUUID().toString(); Timber.d("%s: %s (%s)", mTts, textToSpeak, id); - mTts.setOnUtteranceCompletedListener(utteranceId -> { - Timber.d("%s: onUtteranceCompleted", utteranceId); - if (utteranceId.equals(id)) { - shutdown(); - } - }); + mTts.setOnUtteranceCompletedListener( + utteranceId -> { + Timber.d("%s: onUtteranceCompleted", utteranceId); + if (utteranceId.equals(id)) { + shutdown(); + } + }); HashMap params = new HashMap<>(); - params.put(TextToSpeech.Engine.KEY_PARAM_STREAM, - String.valueOf(AudioManager.STREAM_NOTIFICATION)); + params.put( + TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_NOTIFICATION)); params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, id); mTts.speak(textToSpeak, TextToSpeech.QUEUE_ADD, params); } else { diff --git a/app/src/main/java/net/dinglisch/android/tasker/TaskerPlugin.java b/app/src/main/java/net/dinglisch/android/tasker/TaskerPlugin.java index 03dd97dc5..829649322 100644 --- a/app/src/main/java/net/dinglisch/android/tasker/TaskerPlugin.java +++ b/app/src/main/java/net/dinglisch/android/tasker/TaskerPlugin.java @@ -1,5 +1,5 @@ -//package com.yourcompany.yourcondition; -//package com.yourcompany.yoursetting; +// package com.yourcompany.yourcondition; +// package com.yourcompany.yoursetting; package net.dinglisch.android.tasker; @@ -32,7 +32,8 @@ package net.dinglisch.android.tasker; // added Host.addHintTimeoutMS() // v1.7 20160619 -// null check for getCallingActivity() in hostSupportsOnFireVariableReplacement( Activity editActivity ) +// null check for getCallingActivity() in hostSupportsOnFireVariableReplacement( Activity +// editActivity ) // v1.8 20161002 // added hostSupportsKeyEncoding(), setKeyEncoding() and Host.getKeysWithEncoding() @@ -46,21 +47,18 @@ import android.util.Log; public class TaskerPlugin { - /** - * @see Setting#hostSupportsOnFireVariableReplacement(Bundle) - */ - private final static int EXTRA_HOST_CAPABILITY_SETTING_FIRE_VARIABLE_REPLACEMENT = 8; - private final static String TAG = "TaskerPlugin"; - private final static String BASE_KEY = "net.dinglisch.android.tasker"; - private final static String EXTRAS_PREFIX = BASE_KEY + ".extras."; - private final static int FIRST_ON_FIRE_VARIABLES_TASKER_VERSION = 80; - /** - * Host capabilities, passed to plugin with edit intents - */ - private final static String EXTRA_HOST_CAPABILITIES = EXTRAS_PREFIX + "HOST_CAPABILITIES"; + /** @see Setting#hostSupportsOnFireVariableReplacement(Bundle) */ + private static final int EXTRA_HOST_CAPABILITY_SETTING_FIRE_VARIABLE_REPLACEMENT = 8; + + private static final String TAG = "TaskerPlugin"; + private static final String BASE_KEY = "net.dinglisch.android.tasker"; + private static final String EXTRAS_PREFIX = BASE_KEY + ".extras."; + private static final int FIRST_ON_FIRE_VARIABLES_TASKER_VERSION = 80; + /** Host capabilities, passed to plugin with edit intents */ + private static final String EXTRA_HOST_CAPABILITIES = EXTRAS_PREFIX + "HOST_CAPABILITIES"; - private static Object getBundleValueSafe(Bundle b, String key, Class expectedClass, - String funcName) { + private static Object getBundleValueSafe( + Bundle b, String key, Class expectedClass, String funcName) { Object value = null; if (b != null) { @@ -69,8 +67,14 @@ public class TaskerPlugin { if (obj == null) { Log.w(TAG, funcName + ": " + key + ": null value"); } else if (obj.getClass() != expectedClass) { - Log.w(TAG, - funcName + ": " + key + ": expected " + expectedClass.getClass().getName() + ", got " + Log.w( + TAG, + funcName + + ": " + + key + + ": expected " + + expectedClass.getClass().getName() + + ", got " + obj.getClass().getName()); } else { value = obj; @@ -83,12 +87,11 @@ public class TaskerPlugin { // ----------------------------- SETTING PLUGIN ONLY --------------------------------- // private static boolean hostSupports(Bundle extrasFromHost, int capabilityFlag) { - Integer flags = (Integer) getBundleValueSafe(extrasFromHost, EXTRA_HOST_CAPABILITIES, - Integer.class, "hostSupports"); - return - (flags != null) && - ((flags & capabilityFlag) > 0) - ; + Integer flags = + (Integer) + getBundleValueSafe( + extrasFromHost, EXTRA_HOST_CAPABILITIES, Integer.class, "hostSupports"); + return (flags != null) && ((flags & capabilityFlag) > 0); } // ---------------------------------- HELPER FUNCTIONS -------------------------------- // @@ -111,8 +114,8 @@ public class TaskerPlugin { return code; } - private static void addStringArrayToBundleAsString(String[] toAdd, Bundle bundle, String key, - String callerName) { + private static void addStringArrayToBundleAsString( + String[] toAdd, Bundle bundle, String key, String callerName) { StringBuilder builder = new StringBuilder(); @@ -148,19 +151,17 @@ public class TaskerPlugin { public static class Setting { - /** - * @see #setVariableReplaceKeys(Bundle, String[]) - */ - private final static String BUNDLE_KEY_VARIABLE_REPLACE_STRINGS = + /** @see #setVariableReplaceKeys(Bundle, String[]) */ + private static final String BUNDLE_KEY_VARIABLE_REPLACE_STRINGS = EXTRAS_PREFIX + "VARIABLE_REPLACE_KEYS"; /** * Used by: plugin EditActivity. * - * Indicates to plugin that host will replace variables in specified bundle keys. + *

    Indicates to plugin that host will replace variables in specified bundle keys. * - * Replacement takes place every time the setting is fired, before the bundle is - * passed to the plugin FireReceiver. + *

    Replacement takes place every time the setting is fired, before the bundle is passed to + * the plugin FireReceiver. * * @param extrasFromHost intent extras from the intent received by the edit activity * @see #setVariableReplaceKeys(Bundle, String[]) @@ -172,36 +173,35 @@ public class TaskerPlugin { /** * Used by: plugin EditActivity. * - * Description as above. + *

    Description as above. * - * This version also includes backwards compatibility with pre 4.2 Tasker versions. - * At some point this function will be deprecated. + *

    This version also includes backwards compatibility with pre 4.2 Tasker versions. At some + * point this function will be deprecated. * * @param editActivity the plugin edit activity, needed to test calling Tasker version * @see #setVariableReplaceKeys(Bundle, String[]) */ - public static boolean hostSupportsOnFireVariableReplacement(Activity editActivity) { - boolean supportedFlag = hostSupportsOnFireVariableReplacement( - editActivity.getIntent().getExtras()); + boolean supportedFlag = + hostSupportsOnFireVariableReplacement(editActivity.getIntent().getExtras()); if (!supportedFlag) { ComponentName callingActivity = editActivity.getCallingActivity(); if (callingActivity == null) { - Log.w(TAG, + Log.w( + TAG, "hostSupportsOnFireVariableReplacement: null callingActivity, defaulting to false"); } else { String callerPackage = callingActivity.getPackageName(); // Tasker only supporteed this from 1.0.10 supportedFlag = - (callerPackage.startsWith(BASE_KEY)) && - (getPackageVersionCode(editActivity.getPackageManager(), callerPackage) - > FIRST_ON_FIRE_VARIABLES_TASKER_VERSION) - ; + (callerPackage.startsWith(BASE_KEY)) + && (getPackageVersionCode(editActivity.getPackageManager(), callerPackage) + > FIRST_ON_FIRE_VARIABLES_TASKER_VERSION); } } @@ -211,7 +211,7 @@ public class TaskerPlugin { /** * Used by: plugin EditActivity * - * Indicates to host which bundle keys should be replaced. + *

    Indicates to host which bundle keys should be replaced. * * @param resultBundleToHost the bundle being returned to the host * @param listOfKeyNames which bundle keys to replace variables in when setting fires @@ -220,9 +220,10 @@ public class TaskerPlugin { */ public static void setVariableReplaceKeys(Bundle resultBundleToHost, String[] listOfKeyNames) { addStringArrayToBundleAsString( - listOfKeyNames, resultBundleToHost, BUNDLE_KEY_VARIABLE_REPLACE_STRINGS, - "setVariableReplaceKeys" - ); + listOfKeyNames, + resultBundleToHost, + BUNDLE_KEY_VARIABLE_REPLACE_STRINGS, + "setVariableReplaceKeys"); } } } diff --git a/app/src/main/java/org/tasks/ErrorReportingSingleThreadExecutor.java b/app/src/main/java/org/tasks/ErrorReportingSingleThreadExecutor.java index 878e71fc3..0b03d3b67 100644 --- a/app/src/main/java/org/tasks/ErrorReportingSingleThreadExecutor.java +++ b/app/src/main/java/org/tasks/ErrorReportingSingleThreadExecutor.java @@ -8,18 +8,19 @@ import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import org.tasks.analytics.Tracker; -public class ErrorReportingSingleThreadExecutor implements Executor, - Thread.UncaughtExceptionHandler { +public class ErrorReportingSingleThreadExecutor + implements Executor, Thread.UncaughtExceptionHandler { private final ExecutorService executorService; private final Tracker tracker; public ErrorReportingSingleThreadExecutor(String nameFormat, Tracker tracker) { - executorService = newSingleThreadExecutor( - new ThreadFactoryBuilder() - .setNameFormat(String.format("%s-%%d", nameFormat)) - .setUncaughtExceptionHandler(this) - .build()); + executorService = + newSingleThreadExecutor( + new ThreadFactoryBuilder() + .setNameFormat(String.format("%s-%%d", nameFormat)) + .setUncaughtExceptionHandler(this) + .build()); this.tracker = tracker; } diff --git a/app/src/main/java/org/tasks/LocalBroadcastManager.java b/app/src/main/java/org/tasks/LocalBroadcastManager.java index 9cb28c519..9b9cb0ffd 100644 --- a/app/src/main/java/org/tasks/LocalBroadcastManager.java +++ b/app/src/main/java/org/tasks/LocalBroadcastManager.java @@ -47,9 +47,9 @@ public class LocalBroadcastManager { /** * Action name for broadcast intent notifying that task was created from repeating template - *

  • EXTRAS_TASK_ID id of the task - *
  • EXTRAS_OLD_DUE_DATE task old due date (could be 0) - *
  • EXTRAS_NEW_DUE_DATE task new due date (will not be 0) + *
  • EXTRAS_TASK_ID id of the task + *
  • EXTRAS_OLD_DUE_DATE task old due date (could be 0) + *
  • EXTRAS_NEW_DUE_DATE task new due date (will not be 0) */ public void broadcastRepeat(long id, long oldDueDate, long newDueDate) { Intent intent = new Intent(REPEAT); diff --git a/app/src/main/java/org/tasks/Notifier.java b/app/src/main/java/org/tasks/Notifier.java index e9ac00927..04dfbbd4f 100644 --- a/app/src/main/java/org/tasks/Notifier.java +++ b/app/src/main/java/org/tasks/Notifier.java @@ -41,10 +41,15 @@ public class Notifier { private final CheckBoxes checkBoxes; @Inject - public Notifier(@ForApplication Context context, TaskDao taskDao, - NotificationManager notificationManager, TelephonyManager telephonyManager, - AudioManager audioManager, VoiceOutputAssistant voiceOutputAssistant, - Preferences preferences, CheckBoxes checkBoxes) { + public Notifier( + @ForApplication Context context, + TaskDao taskDao, + NotificationManager notificationManager, + TelephonyManager telephonyManager, + AudioManager audioManager, + VoiceOutputAssistant voiceOutputAssistant, + Preferences preferences, + CheckBoxes checkBoxes) { this.context = context; this.taskDao = taskDao; this.notificationManager = notificationManager; @@ -65,42 +70,37 @@ public class Notifier { Intent intent = new Intent(context, TaskListActivity.class); intent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_MULTIPLE_TASK); intent.putExtra(TaskListActivity.OPEN_FILTER, filter); - PendingIntent pendingIntent = PendingIntent - .getActivity(context, filter.listingTitle.hashCode(), intent, - PendingIntent.FLAG_UPDATE_CURRENT); - - String summaryTitle = context.getResources() - .getQuantityString(R.plurals.task_count, count, count); - NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle() - .setBigContentTitle(summaryTitle); + PendingIntent pendingIntent = + PendingIntent.getActivity( + context, filter.listingTitle.hashCode(), intent, PendingIntent.FLAG_UPDATE_CURRENT); + + String summaryTitle = + context.getResources().getQuantityString(R.plurals.task_count, count, count); + NotificationCompat.InboxStyle style = + new NotificationCompat.InboxStyle().setBigContentTitle(summaryTitle); int maxPriority = 3; for (Task task : tasks) { style.addLine(task.getTitle()); maxPriority = Math.min(maxPriority, task.getImportance()); } - NotificationCompat.Builder builder = new NotificationCompat.Builder(context, - NotificationManager.NOTIFICATION_CHANNEL_TASKER) - .setSmallIcon(R.drawable.ic_done_all_white_24dp) - .setCategory(NotificationCompat.CATEGORY_REMINDER) - .setTicker(summaryTitle) - .setContentTitle(summaryTitle) - .setContentText(filter.listingTitle) - .setContentIntent(pendingIntent) - .setAutoCancel(true) - .setWhen(currentTimeMillis()) - .setShowWhen(true) - .setColor(checkBoxes.getPriorityColor(maxPriority)) - .setGroupSummary(true) - .setGroup(filter.listingTitle) - .setStyle(style); - - notificationManager.notify( - filter.listingTitle.hashCode(), - builder, - true, - false, - false); + NotificationCompat.Builder builder = + new NotificationCompat.Builder(context, NotificationManager.NOTIFICATION_CHANNEL_TASKER) + .setSmallIcon(R.drawable.ic_done_all_white_24dp) + .setCategory(NotificationCompat.CATEGORY_REMINDER) + .setTicker(summaryTitle) + .setContentTitle(summaryTitle) + .setContentText(filter.listingTitle) + .setContentIntent(pendingIntent) + .setAutoCancel(true) + .setWhen(currentTimeMillis()) + .setShowWhen(true) + .setColor(checkBoxes.getPriorityColor(maxPriority)) + .setGroupSummary(true) + .setGroup(filter.listingTitle) + .setStyle(style); + + notificationManager.notify(filter.listingTitle.hashCode(), builder, true, false, false); } public void triggerTaskNotification(long id, int type) { @@ -115,8 +115,8 @@ public class Notifier { triggerNotifications(transform(entries, NotificationQueueEntry::toNotification), true); } - private void triggerNotifications(List entries, - boolean alert) { + private void triggerNotifications( + List entries, boolean alert) { List notifications = new ArrayList<>(); boolean ringFiveTimes = false; boolean ringNonstop = false; @@ -144,11 +144,11 @@ public class Notifier { notificationManager.notifyTasks(notifications, alert, ringNonstop, ringFiveTimes); - if (alert && - preferences.getBoolean(R.string.p_voiceRemindersEnabled, false) && - !ringNonstop && - !audioManager.notificationsMuted() && - telephonyManager.callStateIdle()) { + if (alert + && preferences.getBoolean(R.string.p_voiceRemindersEnabled, false) + && !ringNonstop + && !audioManager.notificationsMuted() + && telephonyManager.callStateIdle()) { for (org.tasks.notifications.Notification notification : notifications) { AndroidUtilities.sleepDeep(2000); voiceOutputAssistant.speak( diff --git a/app/src/main/java/org/tasks/activities/AddAttachmentActivity.java b/app/src/main/java/org/tasks/activities/AddAttachmentActivity.java index c332551a3..cf7f58d8d 100644 --- a/app/src/main/java/org/tasks/activities/AddAttachmentActivity.java +++ b/app/src/main/java/org/tasks/activities/AddAttachmentActivity.java @@ -28,8 +28,8 @@ import org.tasks.injection.InjectingAppCompatActivity; import org.tasks.preferences.Preferences; import timber.log.Timber; -public class AddAttachmentActivity extends InjectingAppCompatActivity implements - DialogInterface.OnCancelListener, AddAttachmentDialog.AddAttachmentCallback { +public class AddAttachmentActivity extends InjectingAppCompatActivity + implements DialogInterface.OnCancelListener, AddAttachmentDialog.AddAttachmentCallback { public static final String EXTRA_PATH = "extra_path"; public static final String EXTRA_TYPE = "extra_type"; @@ -45,8 +45,8 @@ public class AddAttachmentActivity extends InjectingAppCompatActivity implements super.onCreate(savedInstanceState); FragmentManager fragmentManager = getSupportFragmentManager(); - AddAttachmentDialog dialog = (AddAttachmentDialog) fragmentManager - .findFragmentByTag(FRAG_TAG_ATTACHMENT_DIALOG); + AddAttachmentDialog dialog = + (AddAttachmentDialog) fragmentManager.findFragmentByTag(FRAG_TAG_ATTACHMENT_DIALOG); if (dialog == null) { dialog = new AddAttachmentDialog(); dialog.show(fragmentManager, FRAG_TAG_ATTACHMENT_DIALOG); @@ -107,8 +107,8 @@ public class AddAttachmentActivity extends InjectingAppCompatActivity implements } else if (requestCode == REQUEST_CODE_RECORD) { if (resultCode == RESULT_OK) { final String recordedAudioPath = data.getStringExtra(AACRecordingActivity.RESULT_OUTFILE); - final String extension = recordedAudioPath - .substring(recordedAudioPath.lastIndexOf('.') + 1); + final String extension = + recordedAudioPath.substring(recordedAudioPath.lastIndexOf('.') + 1); Intent intent = new Intent(); intent.putExtra(EXTRA_PATH, recordedAudioPath); intent.putExtra(EXTRA_TYPE, TaskAttachment.FILE_TYPE_AUDIO + extension); diff --git a/app/src/main/java/org/tasks/activities/CalendarSelectionActivity.java b/app/src/main/java/org/tasks/activities/CalendarSelectionActivity.java index 483bac0e2..b27695e8d 100644 --- a/app/src/main/java/org/tasks/activities/CalendarSelectionActivity.java +++ b/app/src/main/java/org/tasks/activities/CalendarSelectionActivity.java @@ -14,12 +14,13 @@ import org.tasks.injection.ThemedInjectingAppCompatActivity; import org.tasks.preferences.ActivityPermissionRequestor; import org.tasks.preferences.PermissionRequestor; -public class CalendarSelectionActivity extends ThemedInjectingAppCompatActivity implements - CalendarSelectionDialog.CalendarSelectionHandler { +public class CalendarSelectionActivity extends ThemedInjectingAppCompatActivity + implements CalendarSelectionDialog.CalendarSelectionHandler { public static final String EXTRA_CALENDAR_ID = "extra_calendar_id"; public static final String EXTRA_CALENDAR_NAME = "extra_calendar_name"; - private static final String FRAG_TAG_CALENDAR_PREFERENCE_SELECTION = "frag_tag_calendar_preference_selection"; + private static final String FRAG_TAG_CALENDAR_PREFERENCE_SELECTION = + "frag_tag_calendar_preference_selection"; @Inject ActivityPermissionRequestor permissionRequestor; @Override @@ -33,8 +34,9 @@ public class CalendarSelectionActivity extends ThemedInjectingAppCompatActivity private void showDialog() { FragmentManager fragmentManager = getSupportFragmentManager(); - CalendarSelectionDialog fragmentByTag = (CalendarSelectionDialog) fragmentManager - .findFragmentByTag(FRAG_TAG_CALENDAR_PREFERENCE_SELECTION); + CalendarSelectionDialog fragmentByTag = + (CalendarSelectionDialog) + fragmentManager.findFragmentByTag(FRAG_TAG_CALENDAR_PREFERENCE_SELECTION); if (fragmentByTag == null) { Intent intent = getIntent(); fragmentByTag = newCalendarSelectionDialog(intent.getStringExtra(EXTRA_CALENDAR_NAME)); @@ -63,8 +65,8 @@ public class CalendarSelectionActivity extends ThemedInjectingAppCompatActivity } @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, - @NonNull int[] grantResults) { + public void onRequestPermissionsResult( + int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == PermissionRequestor.REQUEST_CALENDAR) { if (verifyPermissions(grantResults)) { showDialog(); diff --git a/app/src/main/java/org/tasks/activities/CalendarSelectionDialog.java b/app/src/main/java/org/tasks/activities/CalendarSelectionDialog.java index e86698215..a5517d3ba 100644 --- a/app/src/main/java/org/tasks/activities/CalendarSelectionDialog.java +++ b/app/src/main/java/org/tasks/activities/CalendarSelectionDialog.java @@ -57,23 +57,26 @@ public class CalendarSelectionDialog extends InjectingDialogFragment { } else { calendars.add(0, new AndroidCalendar(null, getString(R.string.dont_add_to_calendar), -1)); List calendarNames = transform(calendars, AndroidCalendar::getName); - adapter = new SingleCheckedArrayAdapter(getActivity(), calendarNames, - theme.getThemeAccent()) { - @Override - protected int getDrawable(int position) { - return R.drawable.ic_event_24dp; - } - - @Override - protected int getDrawableColor(int position) { - return calendars.get(position).getColor(); - } - }; + adapter = + new SingleCheckedArrayAdapter(getActivity(), calendarNames, theme.getThemeAccent()) { + @Override + protected int getDrawable(int position) { + return R.drawable.ic_event_24dp; + } + + @Override + protected int getDrawableColor(int position) { + return calendars.get(position).getColor(); + } + }; selectedIndex = Strings.isNullOrEmpty(selected) ? 0 : calendarNames.indexOf(selected); } - return dialogBuilder.newDialog() - .setSingleChoiceItems(adapter, selectedIndex, + return dialogBuilder + .newDialog() + .setSingleChoiceItems( + adapter, + selectedIndex, (dialog, which) -> handler.selectedCalendar(calendars.get(which))) .setOnDismissListener(dialogInterface -> handler.cancel()) .show(); diff --git a/app/src/main/java/org/tasks/activities/CameraActivity.java b/app/src/main/java/org/tasks/activities/CameraActivity.java index c7163c05f..9c169d0ac 100644 --- a/app/src/main/java/org/tasks/activities/CameraActivity.java +++ b/app/src/main/java/org/tasks/activities/CameraActivity.java @@ -50,8 +50,8 @@ public class CameraActivity extends InjectingAppCompatActivity { if (atLeastLollipop()) { intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); } else { - List resolveInfoList = getPackageManager() - .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); + List resolveInfoList = + getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo resolveInfo : resolveInfoList) { grantUriPermission( resolveInfo.activityInfo.packageName, diff --git a/app/src/main/java/org/tasks/activities/ColorPickerActivity.java b/app/src/main/java/org/tasks/activities/ColorPickerActivity.java index 17657c18d..22fb36239 100644 --- a/app/src/main/java/org/tasks/activities/ColorPickerActivity.java +++ b/app/src/main/java/org/tasks/activities/ColorPickerActivity.java @@ -15,8 +15,8 @@ import org.tasks.injection.ThemedInjectingAppCompatActivity; import org.tasks.themes.Theme; import org.tasks.themes.ThemeCache; -public class ColorPickerActivity extends ThemedInjectingAppCompatActivity implements - ColorPickerDialog.ThemePickerCallback, PurchaseHelperCallback { +public class ColorPickerActivity extends ThemedInjectingAppCompatActivity + implements ColorPickerDialog.ThemePickerCallback, PurchaseHelperCallback { public static final String EXTRA_PALETTE = "extra_palette"; public static final String EXTRA_SHOW_NONE = "extra_show_none"; @@ -40,9 +40,10 @@ public class ColorPickerActivity extends ThemedInjectingAppCompatActivity implem Intent intent = getIntent(); palette = (ColorPalette) intent.getSerializableExtra(EXTRA_PALETTE); boolean showNone = intent.getBooleanExtra(EXTRA_SHOW_NONE, false); - int selected = intent.hasExtra(EXTRA_THEME_INDEX) - ? intent.getIntExtra(EXTRA_THEME_INDEX, -1) - : getCurrentSelection(palette); + int selected = + intent.hasExtra(EXTRA_THEME_INDEX) + ? intent.getIntExtra(EXTRA_THEME_INDEX, -1) + : getCurrentSelection(palette); newColorPickerDialog(getItems(palette), showNone, selected) .show(getSupportFragmentManager(), FRAG_TAG_COLOR_PICKER); } @@ -78,9 +79,12 @@ public class ColorPickerActivity extends ThemedInjectingAppCompatActivity implem @Override public void initiateThemePurchase() { - purchaseHelper - .purchase(this, getString(R.string.sku_themes), getString(R.string.p_purchased_themes), - REQUEST_PURCHASE, this); + purchaseHelper.purchase( + this, + getString(R.string.sku_themes), + getString(R.string.p_purchased_themes), + REQUEST_PURCHASE, + this); } @Override @@ -115,5 +119,10 @@ public class ColorPickerActivity extends ThemedInjectingAppCompatActivity implem } } - public enum ColorPalette {THEMES, COLORS, ACCENTS, WIDGET_BACKGROUND} + public enum ColorPalette { + THEMES, + COLORS, + ACCENTS, + WIDGET_BACKGROUND + } } diff --git a/app/src/main/java/org/tasks/activities/DateAndTimePickerActivity.java b/app/src/main/java/org/tasks/activities/DateAndTimePickerActivity.java index bd7aa0407..f0f5335a3 100644 --- a/app/src/main/java/org/tasks/activities/DateAndTimePickerActivity.java +++ b/app/src/main/java/org/tasks/activities/DateAndTimePickerActivity.java @@ -19,9 +19,10 @@ import org.tasks.themes.ThemeAccent; import org.tasks.themes.ThemeBase; import org.tasks.time.DateTime; -public class DateAndTimePickerActivity extends InjectingAppCompatActivity implements - DatePickerDialog.OnDateSetListener, DialogInterface.OnCancelListener, - NativeDatePickerDialog.NativeDatePickerDialogCallback { +public class DateAndTimePickerActivity extends InjectingAppCompatActivity + implements DatePickerDialog.OnDateSetListener, + DialogInterface.OnCancelListener, + NativeDatePickerDialog.NativeDatePickerDialogCallback { public static final String EXTRA_TIMESTAMP = "extra_timestamp"; private static final String FRAG_TAG_DATE_PICKER = "frag_tag_date_picker"; @@ -49,16 +50,15 @@ public class DateAndTimePickerActivity extends InjectingAppCompatActivity implem FragmentManager fragmentManager = getFragmentManager(); if (preferences.getBoolean(R.string.p_use_native_datetime_pickers, false)) { if (fragmentManager.findFragmentByTag(FRAG_TAG_DATE_PICKER) == null) { - newNativeDatePickerDialog(initial) - .show(fragmentManager, FRAG_TAG_DATE_PICKER); + newNativeDatePickerDialog(initial).show(fragmentManager, FRAG_TAG_DATE_PICKER); } } else { - MyDatePickerDialog datePickerDialog = (MyDatePickerDialog) fragmentManager - .findFragmentByTag(FRAG_TAG_DATE_PICKER); + MyDatePickerDialog datePickerDialog = + (MyDatePickerDialog) fragmentManager.findFragmentByTag(FRAG_TAG_DATE_PICKER); if (datePickerDialog == null) { datePickerDialog = new MyDatePickerDialog(); - datePickerDialog.initialize(null, initial.getYear(), initial.getMonthOfYear() - 1, - initial.getDayOfMonth()); + datePickerDialog.initialize( + null, initial.getYear(), initial.getMonthOfYear() - 1, initial.getDayOfMonth()); datePickerDialog.setThemeDark(themeBase.isDarkTheme(this)); datePickerDialog.setAccentColor(themeAccent.getAccentColor()); int firstDayOfWeek = preferences.getFirstDayOfWeek(); @@ -106,9 +106,8 @@ public class DateAndTimePickerActivity extends InjectingAppCompatActivity implem private void dateSet(int year, int month, int day) { dateSelected = true; - final long timestamp = new DateTime(year, month + 1, day) - .withMillisOfDay(initial.getMillisOfDay()) - .getMillis(); + final long timestamp = + new DateTime(year, month + 1, day).withMillisOfDay(initial.getMillisOfDay()).getMillis(); Intent intent = new Intent(this, TimePickerActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT); intent.putExtra(TimePickerActivity.EXTRA_TIMESTAMP, timestamp); diff --git a/app/src/main/java/org/tasks/activities/DatePickerActivity.java b/app/src/main/java/org/tasks/activities/DatePickerActivity.java index b99431542..11984ad8f 100644 --- a/app/src/main/java/org/tasks/activities/DatePickerActivity.java +++ b/app/src/main/java/org/tasks/activities/DatePickerActivity.java @@ -18,8 +18,9 @@ import org.tasks.themes.ThemeAccent; import org.tasks.themes.ThemeBase; import org.tasks.time.DateTime; -public class DatePickerActivity extends InjectingAppCompatActivity implements - DatePickerDialog.OnDateSetListener, NativeDatePickerDialog.NativeDatePickerDialogCallback { +public class DatePickerActivity extends InjectingAppCompatActivity + implements DatePickerDialog.OnDateSetListener, + NativeDatePickerDialog.NativeDatePickerDialogCallback { public static final String EXTRA_TIMESTAMP = "extra_timestamp"; private static final String FRAG_TAG_DATE_PICKER = "frag_tag_date_picker"; @@ -38,16 +39,15 @@ public class DatePickerActivity extends InjectingAppCompatActivity implements if (preferences.getBoolean(R.string.p_use_native_datetime_pickers, false)) { if (fragmentManager.findFragmentByTag(FRAG_TAG_DATE_PICKER) == null) { - newNativeDatePickerDialog(initial) - .show(fragmentManager, FRAG_TAG_DATE_PICKER); + newNativeDatePickerDialog(initial).show(fragmentManager, FRAG_TAG_DATE_PICKER); } } else { - MyDatePickerDialog dialog = (MyDatePickerDialog) fragmentManager - .findFragmentByTag(FRAG_TAG_DATE_PICKER); + MyDatePickerDialog dialog = + (MyDatePickerDialog) fragmentManager.findFragmentByTag(FRAG_TAG_DATE_PICKER); if (dialog == null) { dialog = new MyDatePickerDialog(); - dialog.initialize(null, initial.getYear(), initial.getMonthOfYear() - 1, - initial.getDayOfMonth()); + dialog.initialize( + null, initial.getYear(), initial.getMonthOfYear() - 1, initial.getDayOfMonth()); dialog.setVersion(DatePickerDialog.Version.VERSION_2); dialog.setThemeDark(themeBase.isDarkTheme(this)); dialog.setAccentColor(themeAccent.getAccentColor()); @@ -68,8 +68,8 @@ public class DatePickerActivity extends InjectingAppCompatActivity implements } @Override - public void onDateSet(DatePickerDialog view, final int year, final int monthOfYear, - final int dayOfMonth) { + public void onDateSet( + DatePickerDialog view, final int year, final int monthOfYear, final int dayOfMonth) { dateSet(year, monthOfYear, dayOfMonth); } diff --git a/app/src/main/java/org/tasks/activities/FilterSelectionActivity.java b/app/src/main/java/org/tasks/activities/FilterSelectionActivity.java index 85aa82ad7..df3d73193 100644 --- a/app/src/main/java/org/tasks/activities/FilterSelectionActivity.java +++ b/app/src/main/java/org/tasks/activities/FilterSelectionActivity.java @@ -31,22 +31,27 @@ public class FilterSelectionActivity extends InjectingAppCompatActivity { filterAdapter.populateList(); - dialogBuilder.newDialog() - .setSingleChoiceItems(filterAdapter, filterAdapter.indexOf(selected), (dialog, which) -> { - final Filter selectedFilter = (Filter) filterAdapter.getItem(which); - Intent data = new Intent(); - if (returnFilter) { - data.putExtra(EXTRA_FILTER, selectedFilter); - } - data.putExtra(EXTRA_FILTER_NAME, selectedFilter.listingTitle); - data.putExtra(EXTRA_FILTER_SQL, selectedFilter.getSqlQuery()); - if (selectedFilter.valuesForNewTasks != null) { - data.putExtra(EXTRA_FILTER_VALUES, - AndroidUtilities.mapToSerializedString(selectedFilter.valuesForNewTasks)); - } - setResult(RESULT_OK, data); - dialog.dismiss(); - }) + dialogBuilder + .newDialog() + .setSingleChoiceItems( + filterAdapter, + filterAdapter.indexOf(selected), + (dialog, which) -> { + final Filter selectedFilter = (Filter) filterAdapter.getItem(which); + Intent data = new Intent(); + if (returnFilter) { + data.putExtra(EXTRA_FILTER, selectedFilter); + } + data.putExtra(EXTRA_FILTER_NAME, selectedFilter.listingTitle); + data.putExtra(EXTRA_FILTER_SQL, selectedFilter.getSqlQuery()); + if (selectedFilter.valuesForNewTasks != null) { + data.putExtra( + EXTRA_FILTER_VALUES, + AndroidUtilities.mapToSerializedString(selectedFilter.valuesForNewTasks)); + } + setResult(RESULT_OK, data); + dialog.dismiss(); + }) .setOnDismissListener(dialog -> finish()) .show(); } diff --git a/app/src/main/java/org/tasks/activities/FilterSettingsActivity.java b/app/src/main/java/org/tasks/activities/FilterSettingsActivity.java index 09b62ab01..68d0977fa 100644 --- a/app/src/main/java/org/tasks/activities/FilterSettingsActivity.java +++ b/app/src/main/java/org/tasks/activities/FilterSettingsActivity.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package org.tasks.activities; import static android.text.TextUtils.isEmpty; @@ -30,8 +29,8 @@ import org.tasks.injection.ThemedInjectingAppCompatActivity; import org.tasks.preferences.Preferences; import org.tasks.ui.MenuColorizer; -public class FilterSettingsActivity extends ThemedInjectingAppCompatActivity implements - Toolbar.OnMenuItemClickListener { +public class FilterSettingsActivity extends ThemedInjectingAppCompatActivity + implements Toolbar.OnMenuItemClickListener { public static final String TOKEN_FILTER = "token_filter"; @@ -40,9 +39,16 @@ public class FilterSettingsActivity extends ThemedInjectingAppCompatActivity imp @Inject FilterDao filterDao; @Inject DialogBuilder dialogBuilder; @Inject Preferences preferences; - @BindView(R.id.name) TextInputEditText name; - @BindView(R.id.name_layout) TextInputLayout nameLayout; - @BindView(R.id.toolbar) Toolbar toolbar; + + @BindView(R.id.name) + TextInputEditText name; + + @BindView(R.id.name_layout) + TextInputLayout nameLayout; + + @BindView(R.id.toolbar) + Toolbar toolbar; + private CustomFilter filter; @Override @@ -55,16 +61,18 @@ public class FilterSettingsActivity extends ThemedInjectingAppCompatActivity imp filter = getIntent().getParcelableExtra(TOKEN_FILTER); final boolean backButtonSavesTask = preferences.backButtonSavesTask(); - toolbar.setNavigationIcon(ContextCompat.getDrawable(this, - backButtonSavesTask ? R.drawable.ic_close_24dp : R.drawable.ic_save_24dp)); + toolbar.setNavigationIcon( + ContextCompat.getDrawable( + this, backButtonSavesTask ? R.drawable.ic_close_24dp : R.drawable.ic_save_24dp)); toolbar.setTitle(filter.listingTitle); - toolbar.setNavigationOnClickListener(v -> { - if (backButtonSavesTask) { - discard(); - } else { - save(); - } - }); + toolbar.setNavigationOnClickListener( + v -> { + if (backButtonSavesTask) { + discard(); + } else { + save(); + } + }); toolbar.inflateMenu(R.menu.menu_tag_settings); toolbar.setOnMenuItemClickListener(this); MenuColorizer.colorToolbar(this, toolbar); @@ -118,12 +126,16 @@ public class FilterSettingsActivity extends ThemedInjectingAppCompatActivity imp } private void deleteTag() { - dialogBuilder.newMessageDialog(R.string.delete_tag_confirmation, filter.listingTitle) - .setPositiveButton(R.string.delete, (dialog, which) -> { - filterDao.delete(filter.getId()); - setResult(RESULT_OK, new Intent(ACTION_FILTER_DELETED).putExtra(TOKEN_FILTER, filter)); - finish(); - }) + dialogBuilder + .newMessageDialog(R.string.delete_tag_confirmation, filter.listingTitle) + .setPositiveButton( + R.string.delete, + (dialog, which) -> { + filterDao.delete(filter.getId()); + setResult( + RESULT_OK, new Intent(ACTION_FILTER_DELETED).putExtra(TOKEN_FILTER, filter)); + finish(); + }) .setNegativeButton(android.R.string.cancel, null) .show(); } @@ -133,7 +145,8 @@ public class FilterSettingsActivity extends ThemedInjectingAppCompatActivity imp if (filter.listingTitle.equals(tagName)) { finish(); } else { - dialogBuilder.newMessageDialog(R.string.discard_changes) + dialogBuilder + .newMessageDialog(R.string.discard_changes) .setPositiveButton(R.string.keep_editing, null) .setNegativeButton(R.string.discard, (dialog, which) -> finish()) .show(); diff --git a/app/src/main/java/org/tasks/activities/GoogleTaskListSettingsActivity.java b/app/src/main/java/org/tasks/activities/GoogleTaskListSettingsActivity.java index a4ae7bad6..9ca458e28 100644 --- a/app/src/main/java/org/tasks/activities/GoogleTaskListSettingsActivity.java +++ b/app/src/main/java/org/tasks/activities/GoogleTaskListSettingsActivity.java @@ -41,8 +41,10 @@ import org.tasks.themes.ThemeColor; import org.tasks.ui.MenuColorizer; public class GoogleTaskListSettingsActivity extends ThemedInjectingAppCompatActivity - implements Toolbar.OnMenuItemClickListener, CreateListDialog.CreateListDialogCallback, - DeleteListDialog.DeleteListDialogCallback, RenameListDialog.RenameListDialogCallback { + implements Toolbar.OnMenuItemClickListener, + CreateListDialog.CreateListDialogCallback, + DeleteListDialog.DeleteListDialogCallback, + RenameListDialog.RenameListDialogCallback { public static final String EXTRA_STORE_DATA = "extra_store_data"; public static final String ACTION_DELETED = "action_deleted"; @@ -59,9 +61,16 @@ public class GoogleTaskListSettingsActivity extends ThemedInjectingAppCompatActi @Inject Tracker tracker; @Inject ThemeCache themeCache; @Inject ThemeColor themeColor; - @BindView(R.id.name) TextInputEditText name; - @BindView(R.id.color) TextInputEditText color; - @BindView(R.id.toolbar) Toolbar toolbar; + + @BindView(R.id.name) + TextInputEditText name; + + @BindView(R.id.color) + TextInputEditText color; + + @BindView(R.id.toolbar) + Toolbar toolbar; + private boolean isNewList; private GoogleTaskList gtasksList; private int selectedTheme; @@ -87,15 +96,17 @@ public class GoogleTaskListSettingsActivity extends ThemedInjectingAppCompatActi final boolean backButtonSavesTask = preferences.backButtonSavesTask(); toolbar.setTitle(isNewList ? getString(R.string.new_list) : gtasksList.getTitle()); - toolbar.setNavigationIcon(ContextCompat.getDrawable(this, - backButtonSavesTask ? R.drawable.ic_close_24dp : R.drawable.ic_save_24dp)); - toolbar.setNavigationOnClickListener(v -> { - if (backButtonSavesTask) { - discard(); - } else { - save(); - } - }); + toolbar.setNavigationIcon( + ContextCompat.getDrawable( + this, backButtonSavesTask ? R.drawable.ic_close_24dp : R.drawable.ic_save_24dp)); + toolbar.setNavigationOnClickListener( + v -> { + if (backButtonSavesTask) { + discard(); + } else { + save(); + } + }); toolbar.inflateMenu(R.menu.menu_tag_settings); toolbar.setOnMenuItemClickListener(this); toolbar.showOverflowMenu(); @@ -154,8 +165,7 @@ public class GoogleTaskListSettingsActivity extends ThemedInjectingAppCompatActi } if (isNewList) { - newCreateListDialog(newName) - .show(getSupportFragmentManager(), FRAG_TAG_CREATE_LIST_DIALOG); + newCreateListDialog(newName).show(getSupportFragmentManager(), FRAG_TAG_CREATE_LIST_DIALOG); } else if (nameChanged()) { newRenameListDialog(gtasksList.getRemoteId(), newName) .show(getSupportFragmentManager(), FRAG_TAG_RENAME_LIST_DIALOG); @@ -163,8 +173,10 @@ public class GoogleTaskListSettingsActivity extends ThemedInjectingAppCompatActi if (colorChanged()) { gtasksList.setColor(selectedTheme); googleTaskListDao.insertOrReplace(gtasksList); - setResult(RESULT_OK, new Intent(ACTION_RELOAD) - .putExtra(TaskListActivity.OPEN_FILTER, new GtasksFilter(gtasksList))); + setResult( + RESULT_OK, + new Intent(ACTION_RELOAD) + .putExtra(TaskListActivity.OPEN_FILTER, new GtasksFilter(gtasksList))); } finish(); } @@ -187,10 +199,13 @@ public class GoogleTaskListSettingsActivity extends ThemedInjectingAppCompatActi } private void deleteTag() { - dialogBuilder.newMessageDialog(R.string.delete_tag_confirmation, gtasksList.getTitle()) - .setPositiveButton(R.string.delete, - (dialog, which) -> newDeleteListDialog(gtasksList.getRemoteId()) - .show(getSupportFragmentManager(), FRAG_TAG_DELETE_LIST_DIALOG)) + dialogBuilder + .newMessageDialog(R.string.delete_tag_confirmation, gtasksList.getTitle()) + .setPositiveButton( + R.string.delete, + (dialog, which) -> + newDeleteListDialog(gtasksList.getRemoteId()) + .show(getSupportFragmentManager(), FRAG_TAG_DELETE_LIST_DIALOG)) .setNegativeButton(android.R.string.cancel, null) .show(); } @@ -207,7 +222,8 @@ public class GoogleTaskListSettingsActivity extends ThemedInjectingAppCompatActi private void discard() { if (hasChanges()) { - dialogBuilder.newMessageDialog(R.string.discard_changes) + dialogBuilder + .newMessageDialog(R.string.discard_changes) .setPositiveButton(R.string.keep_editing, null) .setNegativeButton(R.string.discard, (dialog, which) -> finish()) .show(); @@ -243,7 +259,8 @@ public class GoogleTaskListSettingsActivity extends ThemedInjectingAppCompatActi gtasksList.setTitle(taskList.getTitle()); gtasksList.setColor(selectedTheme); gtasksList.setId(googleTaskListDao.insertOrReplace(gtasksList)); - setResult(RESULT_OK, + setResult( + RESULT_OK, new Intent().putExtra(TaskListActivity.OPEN_FILTER, new GtasksFilter(gtasksList))); finish(); } @@ -262,8 +279,10 @@ public class GoogleTaskListSettingsActivity extends ThemedInjectingAppCompatActi gtasksList.setTitle(taskList.getTitle()); gtasksList.setColor(selectedTheme); googleTaskListDao.insertOrReplace(gtasksList); - setResult(RESULT_OK, new Intent(ACTION_RELOAD) - .putExtra(TaskListActivity.OPEN_FILTER, new GtasksFilter(gtasksList))); + setResult( + RESULT_OK, + new Intent(ACTION_RELOAD) + .putExtra(TaskListActivity.OPEN_FILTER, new GtasksFilter(gtasksList))); finish(); } diff --git a/app/src/main/java/org/tasks/activities/RemoteListSupportPicker.java b/app/src/main/java/org/tasks/activities/RemoteListSupportPicker.java index c92b1f6f3..7c274702f 100644 --- a/app/src/main/java/org/tasks/activities/RemoteListSupportPicker.java +++ b/app/src/main/java/org/tasks/activities/RemoteListSupportPicker.java @@ -33,22 +33,29 @@ public class RemoteListSupportPicker extends InjectingDialogFragment { return dialog; } - public static AlertDialog createDialog(FilterAdapter filterAdapter, DialogBuilder dialogBuilder, - Filter selected, RemoteListSelectionHandler handler) { + public static AlertDialog createDialog( + FilterAdapter filterAdapter, + DialogBuilder dialogBuilder, + Filter selected, + RemoteListSelectionHandler handler) { filterAdapter.populateRemoteListPicker(); int selectedIndex = selected == null ? 0 : filterAdapter.indexOf(selected); - return dialogBuilder.newDialog() - .setSingleChoiceItems(filterAdapter, selectedIndex, (dialog, which) -> { - if (which == 0) { - handler.selectedList(null); - } else { - FilterListItem item = filterAdapter.getItem(which); - if (item instanceof GtasksFilter || item instanceof CaldavFilter) { - handler.selectedList((Filter) item); - } - } - dialog.dismiss(); - }) + return dialogBuilder + .newDialog() + .setSingleChoiceItems( + filterAdapter, + selectedIndex, + (dialog, which) -> { + if (which == 0) { + handler.selectedList(null); + } else { + FilterListItem item = filterAdapter.getItem(which); + if (item instanceof GtasksFilter || item instanceof CaldavFilter) { + handler.selectedList((Filter) item); + } + } + dialog.dismiss(); + }) .show(); } diff --git a/app/src/main/java/org/tasks/activities/TagSettingsActivity.java b/app/src/main/java/org/tasks/activities/TagSettingsActivity.java index 55f9a7460..ad1e56ea3 100644 --- a/app/src/main/java/org/tasks/activities/TagSettingsActivity.java +++ b/app/src/main/java/org/tasks/activities/TagSettingsActivity.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package org.tasks.activities; import static android.text.TextUtils.isEmpty; @@ -41,14 +40,14 @@ import org.tasks.preferences.Preferences; import org.tasks.themes.ThemeCache; import org.tasks.themes.ThemeColor; -public class TagSettingsActivity extends ThemedInjectingAppCompatActivity implements - Toolbar.OnMenuItemClickListener { +public class TagSettingsActivity extends ThemedInjectingAppCompatActivity + implements Toolbar.OnMenuItemClickListener { - public static final String TOKEN_AUTOPOPULATE_NAME = "autopopulateName"; //$NON-NLS-1$ - public static final String EXTRA_TAG_DATA = "tagData"; //$NON-NLS-1$ - private static final String EXTRA_TAG_UUID = "uuid"; //$NON-NLS-1$ + public static final String TOKEN_AUTOPOPULATE_NAME = "autopopulateName"; // $NON-NLS-1$ + public static final String EXTRA_TAG_DATA = "tagData"; // $NON-NLS-1$ public static final String ACTION_RELOAD = "tagRenamed"; public static final String ACTION_DELETED = "tagDeleted"; + private static final String EXTRA_TAG_UUID = "uuid"; // $NON-NLS-1$ private static final String EXTRA_SELECTED_THEME = "extra_selected_theme"; private static final int REQUEST_COLOR_PICKER = 10109; @Inject TagService tagService; @@ -59,10 +58,19 @@ public class TagSettingsActivity extends ThemedInjectingAppCompatActivity implem @Inject ThemeCache themeCache; @Inject ThemeColor themeColor; @Inject Tracker tracker; - @BindView(R.id.name) TextInputEditText name; - @BindView(R.id.name_layout) TextInputLayout nameLayout; - @BindView(R.id.color) TextInputEditText color; - @BindView(R.id.toolbar) Toolbar toolbar; + + @BindView(R.id.name) + TextInputEditText name; + + @BindView(R.id.name_layout) + TextInputLayout nameLayout; + + @BindView(R.id.color) + TextInputEditText color; + + @BindView(R.id.toolbar) + Toolbar toolbar; + private boolean isNewTag; private TagData tagData; private int selectedTheme; @@ -88,15 +96,17 @@ public class TagSettingsActivity extends ThemedInjectingAppCompatActivity implem final boolean backButtonSavesTask = preferences.backButtonSavesTask(); toolbar.setTitle(isNewTag ? getString(R.string.new_tag) : tagData.getName()); - toolbar.setNavigationIcon(ContextCompat.getDrawable(this, - backButtonSavesTask ? R.drawable.ic_close_24dp : R.drawable.ic_save_24dp)); - toolbar.setNavigationOnClickListener(v -> { - if (backButtonSavesTask) { - discard(); - } else { - save(); - } - }); + toolbar.setNavigationIcon( + ContextCompat.getDrawable( + this, backButtonSavesTask ? R.drawable.ic_close_24dp : R.drawable.ic_save_24dp)); + toolbar.setNavigationOnClickListener( + v -> { + if (backButtonSavesTask) { + discard(); + } else { + save(); + } + }); toolbar.inflateMenu(R.menu.menu_tag_settings); toolbar.setOnMenuItemClickListener(this); toolbar.showOverflowMenu(); @@ -179,15 +189,16 @@ public class TagSettingsActivity extends ThemedInjectingAppCompatActivity implem tagData.setName(newName); tagData.setColor(selectedTheme); tagDataDao.createNew(tagData); - setResult(RESULT_OK, - new Intent().putExtra(TaskListActivity.OPEN_FILTER, new TagFilter(tagData))); + setResult( + RESULT_OK, new Intent().putExtra(TaskListActivity.OPEN_FILTER, new TagFilter(tagData))); } else if (hasChanges()) { tagData.setName(newName); tagData.setColor(selectedTheme); tagService.rename(tagData.getRemoteId(), newName); tagDataDao.update(tagData); tagDao.rename(tagData.getRemoteId(), newName); - setResult(RESULT_OK, + setResult( + RESULT_OK, new Intent(ACTION_RELOAD).putExtra(TaskListActivity.OPEN_FILTER, new TagFilter(tagData))); } @@ -232,16 +243,19 @@ public class TagSettingsActivity extends ThemedInjectingAppCompatActivity implem } private void deleteTag() { - dialogBuilder.newMessageDialog(R.string.delete_tag_confirmation, tagData.getName()) - .setPositiveButton(R.string.delete, (dialog, which) -> { - if (tagData != null) { - String uuid = tagData.getRemoteId(); - tagDao.deleteTag(uuid); - tagDataDao.delete(tagData.getId()); - setResult(RESULT_OK, new Intent(ACTION_DELETED).putExtra(EXTRA_TAG_UUID, uuid)); - } - finish(); - }) + dialogBuilder + .newMessageDialog(R.string.delete_tag_confirmation, tagData.getName()) + .setPositiveButton( + R.string.delete, + (dialog, which) -> { + if (tagData != null) { + String uuid = tagData.getRemoteId(); + tagDao.deleteTag(uuid); + tagDataDao.delete(tagData.getId()); + setResult(RESULT_OK, new Intent(ACTION_DELETED).putExtra(EXTRA_TAG_UUID, uuid)); + } + finish(); + }) .setNegativeButton(android.R.string.cancel, null) .show(); } @@ -250,7 +264,8 @@ public class TagSettingsActivity extends ThemedInjectingAppCompatActivity implem if (!hasChanges()) { finish(); } else { - dialogBuilder.newMessageDialog(R.string.discard_changes) + dialogBuilder + .newMessageDialog(R.string.discard_changes) .setPositiveButton(R.string.discard, (dialog, which) -> finish()) .setNegativeButton(android.R.string.cancel, null) .show(); diff --git a/app/src/main/java/org/tasks/activities/TimePickerActivity.java b/app/src/main/java/org/tasks/activities/TimePickerActivity.java index 8220b560b..72e1069d0 100644 --- a/app/src/main/java/org/tasks/activities/TimePickerActivity.java +++ b/app/src/main/java/org/tasks/activities/TimePickerActivity.java @@ -19,9 +19,9 @@ import org.tasks.themes.ThemeAccent; import org.tasks.themes.ThemeBase; import org.tasks.time.DateTime; - -public class TimePickerActivity extends InjectingAppCompatActivity implements - TimePickerDialog.OnTimeSetListener, NativeTimePickerDialog.NativeTimePickerDialogCallback { +public class TimePickerActivity extends InjectingAppCompatActivity + implements TimePickerDialog.OnTimeSetListener, + NativeTimePickerDialog.NativeTimePickerDialogCallback { public static final String EXTRA_TIMESTAMP = "extra_timestamp"; private static final String FRAG_TAG_TIME_PICKER = "frag_tag_time_picker"; @@ -40,15 +40,18 @@ public class TimePickerActivity extends InjectingAppCompatActivity implements FragmentManager fragmentManager = getFragmentManager(); if (preferences.getBoolean(R.string.p_use_native_datetime_pickers, false)) { if (fragmentManager.findFragmentByTag(FRAG_TAG_TIME_PICKER) == null) { - newNativeTimePickerDialog(initial) - .show(fragmentManager, FRAG_TAG_TIME_PICKER); + newNativeTimePickerDialog(initial).show(fragmentManager, FRAG_TAG_TIME_PICKER); } } else { - MyTimePickerDialog dialog = (MyTimePickerDialog) fragmentManager - .findFragmentByTag(FRAG_TAG_TIME_PICKER); + MyTimePickerDialog dialog = + (MyTimePickerDialog) fragmentManager.findFragmentByTag(FRAG_TAG_TIME_PICKER); if (dialog == null) { dialog = new MyTimePickerDialog(); - dialog.initialize(null, initial.getHourOfDay(), initial.getMinuteOfHour(), 0, + dialog.initialize( + null, + initial.getHourOfDay(), + initial.getMinuteOfHour(), + 0, DateFormat.is24HourFormat(this)); dialog.setThemeDark(themeBase.isDarkTheme(this)); dialog.setAccentColor(themeAccent.getAccentColor()); @@ -65,8 +68,8 @@ public class TimePickerActivity extends InjectingAppCompatActivity implements } @Override - public void onTimeSet(TimePickerDialog timePickerDialog, final int hours, final int minutes, - int seconds) { + public void onTimeSet( + TimePickerDialog timePickerDialog, final int hours, final int minutes, int seconds) { timeSet(hours, minutes); } @@ -82,11 +85,9 @@ public class TimePickerActivity extends InjectingAppCompatActivity implements private void timeSet(final int hour, final int minute) { Intent data = new Intent(); - data.putExtra(EXTRA_TIMESTAMP, initial - .startOfDay() - .withHourOfDay(hour) - .withMinuteOfHour(minute) - .getMillis()); + data.putExtra( + EXTRA_TIMESTAMP, + initial.startOfDay().withHourOfDay(hour).withMinuteOfHour(minute).getMillis()); setResult(RESULT_OK, data); finish(); } diff --git a/app/src/main/java/org/tasks/analytics/Tracking.java b/app/src/main/java/org/tasks/analytics/Tracking.java index 06efbb4a1..1371d3bfb 100644 --- a/app/src/main/java/org/tasks/analytics/Tracking.java +++ b/app/src/main/java/org/tasks/analytics/Tracking.java @@ -18,30 +18,30 @@ public class Tracking { GTASK_DISABLED(R.string.tracking_category_google_tasks, R.string.tracking_action_off), GTASK_LOGOUT(R.string.tracking_category_google_tasks, R.string.tracking_action_clear), GTASK_NEW_LIST(R.string.tracking_category_google_tasks, R.string.tracking_action_new_list), - GTASK_RENAME_LIST(R.string.tracking_category_google_tasks, - R.string.tracking_action_rename_list), - GTASK_DELETE_LIST(R.string.tracking_category_google_tasks, - R.string.tracking_action_delete_list), + GTASK_RENAME_LIST( + R.string.tracking_category_google_tasks, R.string.tracking_action_rename_list), + GTASK_DELETE_LIST( + R.string.tracking_category_google_tasks, R.string.tracking_action_delete_list), GTASK_SET_COLOR(R.string.tracking_category_google_tasks, R.string.p_theme_color), - GTASK_CLEAR_COMPLETED(R.string.tracking_category_google_tasks, - R.string.tracking_action_clear_completed), - MULTISELECT_DELETE(R.string.tracking_category_event, - R.string.tracking_event_multiselect_delete), + GTASK_CLEAR_COMPLETED( + R.string.tracking_category_google_tasks, R.string.tracking_action_clear_completed), + MULTISELECT_DELETE( + R.string.tracking_category_event, R.string.tracking_event_multiselect_delete), MULTISELECT_CLONE(R.string.tracking_category_event, R.string.tracking_event_multiselect_clone), CLEAR_COMPLETED(R.string.tracking_category_event, R.string.tracking_action_clear_completed), UPGRADE(R.string.tracking_category_event, R.string.tracking_event_upgrade), DB_OPEN_FAILED(R.string.tracking_category_error, R.string.tracking_event_db_open), TASK_CREATION_FAILED(R.string.tracking_category_error, R.string.tracking_event_task_creation), - NIGHT_MODE_MISMATCH(R.string.tracking_category_event, - R.string.tracking_event_night_mode_mismatch), + NIGHT_MODE_MISMATCH( + R.string.tracking_category_event, R.string.tracking_event_night_mode_mismatch), SET_PREFERENCE(R.string.tracking_category_preferences, 0), - PLAY_SERVICES_WARNING(R.string.tracking_category_event, - R.string.tracking_event_play_services_error), + PLAY_SERVICES_WARNING( + R.string.tracking_category_event, R.string.tracking_event_play_services_error), RECURRENCE_CUSTOM(R.string.tracking_category_recurrence, R.string.tracking_action_custom), RECURRENCE_PRESET(R.string.tracking_category_recurrence, R.string.tracking_action_preset), TASKER_CREATE(R.string.tracking_category_tasker, R.string.tracking_action_task_created), - TASKER_LIST_NOTIFICATION(R.string.tracking_category_tasker, - R.string.tracking_action_list_notification), + TASKER_LIST_NOTIFICATION( + R.string.tracking_category_tasker, R.string.tracking_action_list_notification), IMPORT_XML(R.string.tracking_category_backup, R.string.tracking_action_import_xml), IMPORT_JSON(R.string.tracking_category_backup, R.string.tracking_action_import_json), EXPORT(R.string.tracking_category_backup, R.string.tracking_action_export); diff --git a/app/src/main/java/org/tasks/backup/BackupContainer.java b/app/src/main/java/org/tasks/backup/BackupContainer.java index f9742d669..4ef5c345a 100644 --- a/app/src/main/java/org/tasks/backup/BackupContainer.java +++ b/app/src/main/java/org/tasks/backup/BackupContainer.java @@ -24,8 +24,12 @@ class BackupContainer { final List googleTaskLists; final List caldavAccounts; - BackupContainer(List tasks, List tags, List filters, - List googleTaskLists, List caldavAccounts) { + BackupContainer( + List tasks, + List tags, + List filters, + List googleTaskLists, + List caldavAccounts) { this.tasks = tasks; this.tags = tags; this.filters = filters; @@ -44,8 +48,14 @@ class BackupContainer { private final List attachments; private final List caldavTasks; - TaskBackup(Task task, List alarms, List locations, List tags, - List google, List comments, List attachments, + TaskBackup( + Task task, + List alarms, + List locations, + List tags, + List google, + List comments, + List attachments, List caldavTasks) { this.task = task; this.alarms = alarms; diff --git a/app/src/main/java/org/tasks/backup/TasksJsonExporter.java b/app/src/main/java/org/tasks/backup/TasksJsonExporter.java index 03668fba8..c69839938 100755 --- a/app/src/main/java/org/tasks/backup/TasksJsonExporter.java +++ b/app/src/main/java/org/tasks/backup/TasksJsonExporter.java @@ -10,7 +10,6 @@ import android.support.annotation.Nullable; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.andlib.utility.DialogUtilities; import com.todoroo.astrid.backup.BackupConstants; import com.todoroo.astrid.dao.TaskDao; @@ -64,10 +63,18 @@ public class TasksJsonExporter { private String latestSetVersionName; @Inject - public TasksJsonExporter(TagDataDao tagDataDao, TaskDao taskDao, UserActivityDao userActivityDao, - Preferences preferences, AlarmDao alarmDao, LocationDao locationDao, - TagDao tagDao, GoogleTaskDao googleTaskDao, FilterDao filterDao, - GoogleTaskListDao googleTaskListDao, TaskAttachmentDao taskAttachmentDao, + public TasksJsonExporter( + TagDataDao tagDataDao, + TaskDao taskDao, + UserActivityDao userActivityDao, + Preferences preferences, + AlarmDao alarmDao, + LocationDao locationDao, + TagDao tagDao, + GoogleTaskDao googleTaskDao, + FilterDao filterDao, + GoogleTaskListDao googleTaskListDao, + TaskAttachmentDao taskAttachmentDao, CaldavDao caldavDao) { this.tagDataDao = tagDataDao; this.taskDao = taskDao; @@ -94,13 +101,16 @@ public class TasksJsonExporter { } private void setProgress(final int taskNumber, final int total) { - post(() -> { - progressDialog.setMax(total); - progressDialog.setProgress(taskNumber); - }); + post( + () -> { + progressDialog.setMax(total); + progressDialog.setProgress(taskNumber); + }); } - public void exportTasks(final Context context, final ExportType exportType, + public void exportTasks( + final Context context, + final ExportType exportType, @Nullable final ProgressDialog progressDialog) { this.context = context; this.exportCount = 0; @@ -110,30 +120,34 @@ public class TasksJsonExporter { handler = exportType == ExportType.EXPORT_TYPE_MANUAL ? new Handler() : null; - new Thread(() -> { - try { - String output = setupFile(backupDirectory, - exportType); - - List tasks = taskDao.getAll(); - - if (tasks.size() > 0) { - doTasksExport(output, tasks); - } - - if (exportType == ExportType.EXPORT_TYPE_MANUAL) { - onFinishExport(output); - } - } catch (IOException e) { - Timber.e(e, e.getMessage()); - } finally { - post(() -> { - if (progressDialog != null && progressDialog.isShowing() && context instanceof Activity) { - DialogUtilities.dismissDialog((Activity) context, progressDialog); - } - }); - } - }).start(); + new Thread( + () -> { + try { + String output = setupFile(backupDirectory, exportType); + + List tasks = taskDao.getAll(); + + if (tasks.size() > 0) { + doTasksExport(output, tasks); + } + + if (exportType == ExportType.EXPORT_TYPE_MANUAL) { + onFinishExport(output); + } + } catch (IOException e) { + Timber.e(e, e.getMessage()); + } finally { + post( + () -> { + if (progressDialog != null + && progressDialog.isShowing() + && context instanceof Activity) { + DialogUtilities.dismissDialog((Activity) context, progressDialog); + } + }); + } + }) + .start(); } private void doTasksExport(String output, List tasks) throws IOException { @@ -143,34 +157,35 @@ public class TasksJsonExporter { for (Task task : tasks) { setProgress(taskBackups.size(), tasks.size()); long taskId = task.getId(); - taskBackups.add(new BackupContainer.TaskBackup( - task, - alarmDao.getAlarms(taskId), - locationDao.getGeofences(taskId), - tagDao.getTagsForTask(taskId), - googleTaskDao.getAllByTaskId(taskId), - userActivityDao.getCommentsForTask(task.getUuid()), - taskAttachmentDao.getAttachments(task.getUuid()), - caldavDao.getTasks(taskId))); + taskBackups.add( + new BackupContainer.TaskBackup( + task, + alarmDao.getAlarms(taskId), + locationDao.getGeofences(taskId), + tagDao.getTagsForTask(taskId), + googleTaskDao.getAllByTaskId(taskId), + userActivityDao.getCommentsForTask(task.getUuid()), + taskAttachmentDao.getAttachments(task.getUuid()), + caldavDao.getTasks(taskId))); } Map data = new HashMap<>(); data.put("version", BuildConfig.VERSION_CODE); data.put("timestamp", System.currentTimeMillis()); - data.put("data", new BackupContainer( - taskBackups, - tagDataDao.getAll(), - filterDao.getAll(), - googleTaskListDao.getAll(), - caldavDao.getAccounts())); + data.put( + "data", + new BackupContainer( + taskBackups, + tagDataDao.getAll(), + filterDao.getAll(), + googleTaskListDao.getAll(), + caldavDao.getAccounts())); File file = new File(output); file.createNewFile(); FileOutputStream fos = new FileOutputStream(file); OutputStreamWriter out = new OutputStreamWriter(fos); - Gson gson = BuildConfig.DEBUG - ? new GsonBuilder().setPrettyPrinting().create() - : new Gson(); + Gson gson = BuildConfig.DEBUG ? new GsonBuilder().setPrettyPrinting().create() : new Gson(); out.write(gson.toJson(data)); out.close(); fos.close(); @@ -178,18 +193,23 @@ public class TasksJsonExporter { } private void onFinishExport(final String outputFile) { - post(() -> { - 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(); - } - }); + post( + () -> { + 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(); + } + }); } /** @@ -213,13 +233,13 @@ public class TasksJsonExporter { fileName = String.format(BackupConstants.UPGRADE_FILE_NAME, latestSetVersionName); break; default: - throw new IllegalArgumentException("Invalid export type"); //$NON-NLS-1$ + throw new IllegalArgumentException("Invalid export type"); // $NON-NLS-1$ } return directory.getAbsolutePath() + File.separator + fileName; } else { // Unable to make the /sdcard/astrid directory. - throw new IOException(context.getString(R.string.DLG_error_sdcard, - directory.getAbsolutePath())); + throw new IOException( + context.getString(R.string.DLG_error_sdcard, directory.getAbsolutePath())); } } else { // Unable to access the sdcard because it's not in the mounted state. diff --git a/app/src/main/java/org/tasks/backup/TasksJsonImporter.java b/app/src/main/java/org/tasks/backup/TasksJsonImporter.java index 44cd7c981..49007702e 100644 --- a/app/src/main/java/org/tasks/backup/TasksJsonImporter.java +++ b/app/src/main/java/org/tasks/backup/TasksJsonImporter.java @@ -65,11 +65,20 @@ public class TasksJsonImporter { private String input; @Inject - public TasksJsonImporter(TagDataDao tagDataDao, UserActivityDao userActivityDao, - DialogBuilder dialogBuilder, TaskDao taskDao, LocationDao locationDao, - LocalBroadcastManager localBroadcastManager, AlarmDao alarmDao, - TagDao tagDao, GoogleTaskDao googleTaskDao, GoogleTaskListDao googleTaskListDao, - FilterDao filterDao, TaskAttachmentDao taskAttachmentDao, CaldavDao caldavDao) { + public TasksJsonImporter( + TagDataDao tagDataDao, + UserActivityDao userActivityDao, + DialogBuilder dialogBuilder, + TaskDao taskDao, + LocationDao locationDao, + LocalBroadcastManager localBroadcastManager, + AlarmDao alarmDao, + TagDao tagDao, + GoogleTaskDao googleTaskDao, + GoogleTaskListDao googleTaskListDao, + FilterDao filterDao, + TaskAttachmentDao taskAttachmentDao, + CaldavDao caldavDao) { this.tagDataDao = tagDataDao; this.userActivityDao = userActivityDao; this.dialogBuilder = dialogBuilder; @@ -96,13 +105,15 @@ public class TasksJsonImporter { handler = new Handler(); - new Thread(() -> { - try { - performImport(); - } catch (IOException e) { - Timber.e(e, e.getMessage()); - } - }).start(); + new Thread( + () -> { + try { + performImport(); + } catch (IOException e) { + Timber.e(e, e.getMessage()); + } + }) + .start(); } private void performImport() throws IOException { @@ -179,25 +190,29 @@ public class TasksJsonImporter { } } finally { localBroadcastManager.broadcastRefresh(); - handler.post(() -> { - if (progressDialog.isShowing()) { - DialogUtilities.dismissDialog(activity, progressDialog); - showSummary(); - } - }); + handler.post( + () -> { + if (progressDialog.isShowing()) { + DialogUtilities.dismissDialog(activity, progressDialog); + showSummary(); + } + }); } } private void showSummary() { Resources r = activity.getResources(); - dialogBuilder.newDialog() + dialogBuilder + .newDialog() .setTitle(R.string.import_summary_title) - .setMessage(activity.getString(R.string.import_summary_message, - input, - r.getQuantityString(R.plurals.Ntasks, taskCount, taskCount), - r.getQuantityString(R.plurals.Ntasks, importCount, importCount), - r.getQuantityString(R.plurals.Ntasks, skipCount, skipCount), - r.getQuantityString(R.plurals.Ntasks, 0, 0))) + .setMessage( + activity.getString( + R.string.import_summary_message, + input, + r.getQuantityString(R.plurals.Ntasks, taskCount, taskCount), + r.getQuantityString(R.plurals.Ntasks, importCount, importCount), + r.getQuantityString(R.plurals.Ntasks, skipCount, skipCount), + r.getQuantityString(R.plurals.Ntasks, 0, 0))) .setPositiveButton(android.R.string.ok, (dialog, id) -> dialog.dismiss()) .show(); } diff --git a/app/src/main/java/org/tasks/backup/XmlReader.java b/app/src/main/java/org/tasks/backup/XmlReader.java index 983dd81ca..55a0b8611 100644 --- a/app/src/main/java/org/tasks/backup/XmlReader.java +++ b/app/src/main/java/org/tasks/backup/XmlReader.java @@ -4,7 +4,7 @@ import org.xmlpull.v1.XmlPullParser; public class XmlReader { - private static final String XML_NULL = "null"; //$NON-NLS-1$ + private static final String XML_NULL = "null"; // $NON-NLS-1$ private final XmlPullParser xpp; public XmlReader(XmlPullParser xpp) { diff --git a/app/src/main/java/org/tasks/caldav/CalDAVSettingsActivity.java b/app/src/main/java/org/tasks/caldav/CalDAVSettingsActivity.java index 72d4b5fe1..9e32d5ab4 100644 --- a/app/src/main/java/org/tasks/caldav/CalDAVSettingsActivity.java +++ b/app/src/main/java/org/tasks/caldav/CalDAVSettingsActivity.java @@ -49,10 +49,10 @@ import timber.log.Timber; public class CaldavSettingsActivity extends ThemedInjectingAppCompatActivity implements Toolbar.OnMenuItemClickListener { - public static final String EXTRA_CALDAV_DATA = "caldavData"; //$NON-NLS-1$ - private static final String EXTRA_CALDAV_UUID = "uuid"; //$NON-NLS-1$ + public static final String EXTRA_CALDAV_DATA = "caldavData"; // $NON-NLS-1$ public static final String ACTION_RELOAD = "accountRenamed"; public static final String ACTION_DELETED = "accountDeleted"; + private static final String EXTRA_CALDAV_UUID = "uuid"; // $NON-NLS-1$ private static final String EXTRA_SELECTED_THEME = "extra_selected_theme"; private static final String PASSWORD_MASK = "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022"; private static final int REQUEST_COLOR_PICKER = 10109; @@ -63,15 +63,34 @@ public class CaldavSettingsActivity extends ThemedInjectingAppCompatActivity @Inject Tracker tracker; @Inject CaldavDao caldavDao; @Inject SyncAdapters syncAdapters; - @BindView(R.id.root_layout) LinearLayout root; - @BindView(R.id.url) TextInputEditText url; - @BindView(R.id.user) TextInputEditText user; - @BindView(R.id.password) TextInputEditText password; - @BindView(R.id.url_layout) TextInputLayout urlLayout; - @BindView(R.id.user_layout) TextInputLayout userLayout; - @BindView(R.id.password_layout) TextInputLayout passwordLayout; - @BindView(R.id.color) TextInputEditText color; - @BindView(R.id.toolbar) Toolbar toolbar; + + @BindView(R.id.root_layout) + LinearLayout root; + + @BindView(R.id.url) + TextInputEditText url; + + @BindView(R.id.user) + TextInputEditText user; + + @BindView(R.id.password) + TextInputEditText password; + + @BindView(R.id.url_layout) + TextInputLayout urlLayout; + + @BindView(R.id.user_layout) + TextInputLayout userLayout; + + @BindView(R.id.password_layout) + TextInputLayout passwordLayout; + + @BindView(R.id.color) + TextInputEditText color; + + @BindView(R.id.toolbar) + Toolbar toolbar; + private CaldavAccount caldavAccount; private int selectedTheme; @@ -104,15 +123,17 @@ public class CaldavSettingsActivity extends ThemedInjectingAppCompatActivity final boolean backButtonSavesTask = preferences.backButtonSavesTask(); toolbar.setTitle( caldavAccount == null ? getString(R.string.add_account) : caldavAccount.getName()); - toolbar.setNavigationIcon(ContextCompat.getDrawable(this, - backButtonSavesTask ? R.drawable.ic_close_24dp : R.drawable.ic_save_24dp)); - toolbar.setNavigationOnClickListener(v -> { - if (backButtonSavesTask) { - discard(); - } else { - save(); - } - }); + toolbar.setNavigationIcon( + ContextCompat.getDrawable( + this, backButtonSavesTask ? R.drawable.ic_close_24dp : R.drawable.ic_save_24dp)); + toolbar.setNavigationOnClickListener( + v -> { + if (backButtonSavesTask) { + discard(); + } else { + save(); + } + }); toolbar.inflateMenu(R.menu.menu_tag_settings); toolbar.setOnMenuItemClickListener(this); toolbar.showOverflowMenu(); @@ -255,14 +276,16 @@ public class CaldavSettingsActivity extends ThemedInjectingAppCompatActivity CaldavClient client = new CaldavClient(url, username, password); ProgressDialog dialog = dialogBuilder.newProgressDialog(R.string.contacting_server); dialog.show(); - client.getDisplayName() + client + .getDisplayName() .doAfterTerminate(dialog::dismiss) .subscribe(this::addAccount, this::getDisplayNameFailed); } else if (needsValidation()) { CaldavClient client = new CaldavClient(url, username, password); ProgressDialog dialog = dialogBuilder.newProgressDialog(R.string.contacting_server); dialog.show(); - client.getDisplayName() + client + .getDisplayName() .doAfterTerminate(dialog::dismiss) .subscribe(this::updateAccount, this::getDisplayNameFailed); } else if (hasChanges()) { @@ -279,10 +302,11 @@ public class CaldavSettingsActivity extends ThemedInjectingAppCompatActivity newAccount.setUsername(getNewUsername()); newAccount.setPassword(getNewPassword()); newAccount.setId(caldavDao.insert(newAccount)); - setResult(RESULT_OK, + setResult( + RESULT_OK, new Intent().putExtra(TaskListActivity.OPEN_FILTER, new CaldavFilter(newAccount))); finish(); - } + } private void updateAccount(String name) { caldavAccount.setName(name); @@ -291,7 +315,8 @@ public class CaldavSettingsActivity extends ThemedInjectingAppCompatActivity caldavAccount.setColor(selectedTheme); caldavAccount.setPassword(getNewPassword()); caldavDao.update(caldavAccount); - setResult(RESULT_OK, + setResult( + RESULT_OK, new Intent().putExtra(TaskListActivity.OPEN_FILTER, new CaldavFilter(caldavAccount))); finish(); } @@ -317,27 +342,29 @@ public class CaldavSettingsActivity extends ThemedInjectingAppCompatActivity } private void showSnackbar(String message) { - Snackbar snackbar = Snackbar.make(root, message, 8000) - .setActionTextColor(ContextCompat.getColor(this, R.color.snackbar_text_color)); - snackbar.getView() + Snackbar snackbar = + Snackbar.make(root, message, 8000) + .setActionTextColor(ContextCompat.getColor(this, R.color.snackbar_text_color)); + snackbar + .getView() .setBackgroundColor(ContextCompat.getColor(this, R.color.snackbar_background)); snackbar.show(); } private boolean hasChanges() { if (caldavAccount == null) { - return selectedTheme >= 0 || - !isEmpty(getNewPassword()) || !isEmpty(getNewURL()) || - !isEmpty(getNewUsername()); + return selectedTheme >= 0 + || !isEmpty(getNewPassword()) + || !isEmpty(getNewURL()) + || !isEmpty(getNewUsername()); } - return selectedTheme != caldavAccount.getColor() || - needsValidation(); + return selectedTheme != caldavAccount.getColor() || needsValidation(); } private boolean needsValidation() { - return !getNewURL().equals(caldavAccount.getUrl()) || - !getNewUsername().equals(caldavAccount.getUsername()) || - !getNewPassword().equals(caldavAccount.getPassword()); + return !getNewURL().equals(caldavAccount.getUrl()) + || !getNewUsername().equals(caldavAccount.getUsername()) + || !getNewPassword().equals(caldavAccount.getPassword()); } @Override @@ -371,15 +398,20 @@ public class CaldavSettingsActivity extends ThemedInjectingAppCompatActivity } private void deleteAccount() { - dialogBuilder.newMessageDialog(R.string.delete_tag_confirmation, caldavAccount.getName()) - .setPositiveButton(R.string.delete, (dialog, which) -> { - if (caldavAccount != null) { - caldavDao.delete(caldavAccount); - setResult(RESULT_OK, - new Intent(ACTION_DELETED).putExtra(EXTRA_CALDAV_UUID, caldavAccount.getUuid())); - } - finish(); - }) + dialogBuilder + .newMessageDialog(R.string.delete_tag_confirmation, caldavAccount.getName()) + .setPositiveButton( + R.string.delete, + (dialog, which) -> { + if (caldavAccount != null) { + caldavDao.delete(caldavAccount); + setResult( + RESULT_OK, + new Intent(ACTION_DELETED) + .putExtra(EXTRA_CALDAV_UUID, caldavAccount.getUuid())); + } + finish(); + }) .setNegativeButton(android.R.string.cancel, null) .show(); } @@ -388,7 +420,8 @@ public class CaldavSettingsActivity extends ThemedInjectingAppCompatActivity if (!hasChanges()) { finish(); } else { - dialogBuilder.newMessageDialog(R.string.discard_changes) + dialogBuilder + .newMessageDialog(R.string.discard_changes) .setPositiveButton(R.string.discard, (dialog, which) -> finish()) .setNegativeButton(android.R.string.cancel, null) .show(); diff --git a/app/src/main/java/org/tasks/caldav/CaldavClient.java b/app/src/main/java/org/tasks/caldav/CaldavClient.java index e410ea99a..15bfaa690 100644 --- a/app/src/main/java/org/tasks/caldav/CaldavClient.java +++ b/app/src/main/java/org/tasks/caldav/CaldavClient.java @@ -18,29 +18,32 @@ class CaldavClient { private final DavCalendar davCalendar; public CaldavClient(String url, String username, String password) { - BasicDigestAuthHandler basicDigestAuthHandler = new BasicDigestAuthHandler(null, username, - password); - OkHttpClient httpClient = new OkHttpClient().newBuilder() - .addNetworkInterceptor(basicDigestAuthHandler) - .authenticator(basicDigestAuthHandler) - .cookieJar(new MemoryCookieStore()) - .followRedirects(false) - .followSslRedirects(false) - .build(); + BasicDigestAuthHandler basicDigestAuthHandler = + new BasicDigestAuthHandler(null, username, password); + OkHttpClient httpClient = + new OkHttpClient() + .newBuilder() + .addNetworkInterceptor(basicDigestAuthHandler) + .authenticator(basicDigestAuthHandler) + .cookieJar(new MemoryCookieStore()) + .followRedirects(false) + .followSslRedirects(false) + .build(); URI uri = URI.create(url); HttpUrl httpUrl = HttpUrl.get(uri); davCalendar = new DavCalendar(httpClient, httpUrl); } public Single getDisplayName() { - Callable callable = () -> { - davCalendar.propfind(0, DisplayName.NAME); - DisplayName displayName = davCalendar.getProperties().get(DisplayName.class); - if (displayName == null) { - throw new DisplayableException(R.string.calendar_not_found); - } - return displayName.getDisplayName(); - }; + Callable callable = + () -> { + davCalendar.propfind(0, DisplayName.NAME); + DisplayName displayName = davCalendar.getProperties().get(DisplayName.class); + if (displayName == null) { + throw new DisplayableException(R.string.calendar_not_found); + } + return displayName.getDisplayName(); + }; return Single.fromCallable(callable) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); diff --git a/app/src/main/java/org/tasks/caldav/CaldavListFragment.java b/app/src/main/java/org/tasks/caldav/CaldavListFragment.java index 9f195c070..dd29d7b66 100644 --- a/app/src/main/java/org/tasks/caldav/CaldavListFragment.java +++ b/app/src/main/java/org/tasks/caldav/CaldavListFragment.java @@ -65,8 +65,11 @@ public class CaldavListFragment extends TaskListFragment { if (CaldavSettingsActivity.ACTION_DELETED.equals(action)) { activity.onFilterItemClicked(null); } else if (CaldavSettingsActivity.ACTION_RELOAD.equals(action)) { - activity.getIntent().putExtra(TaskListActivity.OPEN_FILTER, - (Filter) data.getParcelableExtra(TaskListActivity.OPEN_FILTER)); + activity + .getIntent() + .putExtra( + TaskListActivity.OPEN_FILTER, + (Filter) data.getParcelableExtra(TaskListActivity.OPEN_FILTER)); activity.recreate(); } } diff --git a/app/src/main/java/org/tasks/caldav/CaldavSettingsActivity.java b/app/src/main/java/org/tasks/caldav/CaldavSettingsActivity.java index 72d4b5fe1..9e32d5ab4 100644 --- a/app/src/main/java/org/tasks/caldav/CaldavSettingsActivity.java +++ b/app/src/main/java/org/tasks/caldav/CaldavSettingsActivity.java @@ -49,10 +49,10 @@ import timber.log.Timber; public class CaldavSettingsActivity extends ThemedInjectingAppCompatActivity implements Toolbar.OnMenuItemClickListener { - public static final String EXTRA_CALDAV_DATA = "caldavData"; //$NON-NLS-1$ - private static final String EXTRA_CALDAV_UUID = "uuid"; //$NON-NLS-1$ + public static final String EXTRA_CALDAV_DATA = "caldavData"; // $NON-NLS-1$ public static final String ACTION_RELOAD = "accountRenamed"; public static final String ACTION_DELETED = "accountDeleted"; + private static final String EXTRA_CALDAV_UUID = "uuid"; // $NON-NLS-1$ private static final String EXTRA_SELECTED_THEME = "extra_selected_theme"; private static final String PASSWORD_MASK = "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022"; private static final int REQUEST_COLOR_PICKER = 10109; @@ -63,15 +63,34 @@ public class CaldavSettingsActivity extends ThemedInjectingAppCompatActivity @Inject Tracker tracker; @Inject CaldavDao caldavDao; @Inject SyncAdapters syncAdapters; - @BindView(R.id.root_layout) LinearLayout root; - @BindView(R.id.url) TextInputEditText url; - @BindView(R.id.user) TextInputEditText user; - @BindView(R.id.password) TextInputEditText password; - @BindView(R.id.url_layout) TextInputLayout urlLayout; - @BindView(R.id.user_layout) TextInputLayout userLayout; - @BindView(R.id.password_layout) TextInputLayout passwordLayout; - @BindView(R.id.color) TextInputEditText color; - @BindView(R.id.toolbar) Toolbar toolbar; + + @BindView(R.id.root_layout) + LinearLayout root; + + @BindView(R.id.url) + TextInputEditText url; + + @BindView(R.id.user) + TextInputEditText user; + + @BindView(R.id.password) + TextInputEditText password; + + @BindView(R.id.url_layout) + TextInputLayout urlLayout; + + @BindView(R.id.user_layout) + TextInputLayout userLayout; + + @BindView(R.id.password_layout) + TextInputLayout passwordLayout; + + @BindView(R.id.color) + TextInputEditText color; + + @BindView(R.id.toolbar) + Toolbar toolbar; + private CaldavAccount caldavAccount; private int selectedTheme; @@ -104,15 +123,17 @@ public class CaldavSettingsActivity extends ThemedInjectingAppCompatActivity final boolean backButtonSavesTask = preferences.backButtonSavesTask(); toolbar.setTitle( caldavAccount == null ? getString(R.string.add_account) : caldavAccount.getName()); - toolbar.setNavigationIcon(ContextCompat.getDrawable(this, - backButtonSavesTask ? R.drawable.ic_close_24dp : R.drawable.ic_save_24dp)); - toolbar.setNavigationOnClickListener(v -> { - if (backButtonSavesTask) { - discard(); - } else { - save(); - } - }); + toolbar.setNavigationIcon( + ContextCompat.getDrawable( + this, backButtonSavesTask ? R.drawable.ic_close_24dp : R.drawable.ic_save_24dp)); + toolbar.setNavigationOnClickListener( + v -> { + if (backButtonSavesTask) { + discard(); + } else { + save(); + } + }); toolbar.inflateMenu(R.menu.menu_tag_settings); toolbar.setOnMenuItemClickListener(this); toolbar.showOverflowMenu(); @@ -255,14 +276,16 @@ public class CaldavSettingsActivity extends ThemedInjectingAppCompatActivity CaldavClient client = new CaldavClient(url, username, password); ProgressDialog dialog = dialogBuilder.newProgressDialog(R.string.contacting_server); dialog.show(); - client.getDisplayName() + client + .getDisplayName() .doAfterTerminate(dialog::dismiss) .subscribe(this::addAccount, this::getDisplayNameFailed); } else if (needsValidation()) { CaldavClient client = new CaldavClient(url, username, password); ProgressDialog dialog = dialogBuilder.newProgressDialog(R.string.contacting_server); dialog.show(); - client.getDisplayName() + client + .getDisplayName() .doAfterTerminate(dialog::dismiss) .subscribe(this::updateAccount, this::getDisplayNameFailed); } else if (hasChanges()) { @@ -279,10 +302,11 @@ public class CaldavSettingsActivity extends ThemedInjectingAppCompatActivity newAccount.setUsername(getNewUsername()); newAccount.setPassword(getNewPassword()); newAccount.setId(caldavDao.insert(newAccount)); - setResult(RESULT_OK, + setResult( + RESULT_OK, new Intent().putExtra(TaskListActivity.OPEN_FILTER, new CaldavFilter(newAccount))); finish(); - } + } private void updateAccount(String name) { caldavAccount.setName(name); @@ -291,7 +315,8 @@ public class CaldavSettingsActivity extends ThemedInjectingAppCompatActivity caldavAccount.setColor(selectedTheme); caldavAccount.setPassword(getNewPassword()); caldavDao.update(caldavAccount); - setResult(RESULT_OK, + setResult( + RESULT_OK, new Intent().putExtra(TaskListActivity.OPEN_FILTER, new CaldavFilter(caldavAccount))); finish(); } @@ -317,27 +342,29 @@ public class CaldavSettingsActivity extends ThemedInjectingAppCompatActivity } private void showSnackbar(String message) { - Snackbar snackbar = Snackbar.make(root, message, 8000) - .setActionTextColor(ContextCompat.getColor(this, R.color.snackbar_text_color)); - snackbar.getView() + Snackbar snackbar = + Snackbar.make(root, message, 8000) + .setActionTextColor(ContextCompat.getColor(this, R.color.snackbar_text_color)); + snackbar + .getView() .setBackgroundColor(ContextCompat.getColor(this, R.color.snackbar_background)); snackbar.show(); } private boolean hasChanges() { if (caldavAccount == null) { - return selectedTheme >= 0 || - !isEmpty(getNewPassword()) || !isEmpty(getNewURL()) || - !isEmpty(getNewUsername()); + return selectedTheme >= 0 + || !isEmpty(getNewPassword()) + || !isEmpty(getNewURL()) + || !isEmpty(getNewUsername()); } - return selectedTheme != caldavAccount.getColor() || - needsValidation(); + return selectedTheme != caldavAccount.getColor() || needsValidation(); } private boolean needsValidation() { - return !getNewURL().equals(caldavAccount.getUrl()) || - !getNewUsername().equals(caldavAccount.getUsername()) || - !getNewPassword().equals(caldavAccount.getPassword()); + return !getNewURL().equals(caldavAccount.getUrl()) + || !getNewUsername().equals(caldavAccount.getUsername()) + || !getNewPassword().equals(caldavAccount.getPassword()); } @Override @@ -371,15 +398,20 @@ public class CaldavSettingsActivity extends ThemedInjectingAppCompatActivity } private void deleteAccount() { - dialogBuilder.newMessageDialog(R.string.delete_tag_confirmation, caldavAccount.getName()) - .setPositiveButton(R.string.delete, (dialog, which) -> { - if (caldavAccount != null) { - caldavDao.delete(caldavAccount); - setResult(RESULT_OK, - new Intent(ACTION_DELETED).putExtra(EXTRA_CALDAV_UUID, caldavAccount.getUuid())); - } - finish(); - }) + dialogBuilder + .newMessageDialog(R.string.delete_tag_confirmation, caldavAccount.getName()) + .setPositiveButton( + R.string.delete, + (dialog, which) -> { + if (caldavAccount != null) { + caldavDao.delete(caldavAccount); + setResult( + RESULT_OK, + new Intent(ACTION_DELETED) + .putExtra(EXTRA_CALDAV_UUID, caldavAccount.getUuid())); + } + finish(); + }) .setNegativeButton(android.R.string.cancel, null) .show(); } @@ -388,7 +420,8 @@ public class CaldavSettingsActivity extends ThemedInjectingAppCompatActivity if (!hasChanges()) { finish(); } else { - dialogBuilder.newMessageDialog(R.string.discard_changes) + dialogBuilder + .newMessageDialog(R.string.discard_changes) .setPositiveButton(R.string.discard, (dialog, which) -> finish()) .setNegativeButton(android.R.string.cancel, null) .show(); diff --git a/app/src/main/java/org/tasks/caldav/CaldavSynchronizer.java b/app/src/main/java/org/tasks/caldav/CaldavSynchronizer.java index bcd5db3a8..6ad605a46 100644 --- a/app/src/main/java/org/tasks/caldav/CaldavSynchronizer.java +++ b/app/src/main/java/org/tasks/caldav/CaldavSynchronizer.java @@ -57,8 +57,8 @@ import timber.log.Timber; public class CaldavSynchronizer { static { - iCalendar.Companion - .setProdId(new ProdId("+//IDN tasks.org//android-" + BuildConfig.VERSION_CODE + "//EN")); + iCalendar.Companion.setProdId( + new ProdId("+//IDN tasks.org//android-" + BuildConfig.VERSION_CODE + "//EN")); } private final CaldavDao caldavDao; @@ -69,8 +69,12 @@ public class CaldavSynchronizer { private final Context context; @Inject - public CaldavSynchronizer(@ForApplication Context context, CaldavDao caldavDao, TaskDao taskDao, - LocalBroadcastManager localBroadcastManager, TaskCreator taskCreator, + public CaldavSynchronizer( + @ForApplication Context context, + CaldavDao caldavDao, + TaskDao taskDao, + LocalBroadcastManager localBroadcastManager, + TaskCreator taskCreator, TaskDeleter taskDeleter) { this.context = context; this.caldavDao = caldavDao; @@ -94,16 +98,18 @@ public class CaldavSynchronizer { return; } Timber.d("sync(%s)", caldavAccount); - BasicDigestAuthHandler basicDigestAuthHandler = new BasicDigestAuthHandler(null, - caldavAccount.getUsername(), caldavAccount.getPassword()); - OkHttpClient httpClient = new OkHttpClient().newBuilder() - .addNetworkInterceptor(basicDigestAuthHandler) - .authenticator(basicDigestAuthHandler) - .cookieJar(new MemoryCookieStore()) - .followRedirects(false) - .followSslRedirects(false) - .readTimeout(30, TimeUnit.SECONDS) - .build(); + BasicDigestAuthHandler basicDigestAuthHandler = + new BasicDigestAuthHandler(null, caldavAccount.getUsername(), caldavAccount.getPassword()); + OkHttpClient httpClient = + new OkHttpClient() + .newBuilder() + .addNetworkInterceptor(basicDigestAuthHandler) + .authenticator(basicDigestAuthHandler) + .cookieJar(new MemoryCookieStore()) + .followRedirects(false) + .followSslRedirects(false) + .readTimeout(30, TimeUnit.SECONDS) + .build(); URI uri = URI.create(caldavAccount.getUrl()); HttpUrl httpUrl = HttpUrl.get(uri); DavCalendar davCalendar = new DavCalendar(httpClient, httpUrl); @@ -131,17 +137,21 @@ public class CaldavSynchronizer { davCalendar.calendarQuery("VTODO", null, null); - Set remoteObjects = newHashSet( - transform(davCalendar.getMembers(), DavResource::fileName)); - - Iterable changed = filter(davCalendar.getMembers(), vCard -> { - GetETag eTag = (GetETag) vCard.getProperties().get(GetETag.NAME); - if (eTag == null || isNullOrEmpty(eTag.getETag())) { - return false; - } - CaldavTask caldavTask = caldavDao.getTask(caldavAccount.getUuid(), vCard.fileName()); - return caldavTask == null || !eTag.getETag().equals(caldavTask.getEtag()); - }); + Set remoteObjects = + newHashSet(transform(davCalendar.getMembers(), DavResource::fileName)); + + Iterable changed = + filter( + davCalendar.getMembers(), + vCard -> { + GetETag eTag = (GetETag) vCard.getProperties().get(GetETag.NAME); + if (eTag == null || isNullOrEmpty(eTag.getETag())) { + return false; + } + CaldavTask caldavTask = + caldavDao.getTask(caldavAccount.getUuid(), vCard.fileName()); + return caldavTask == null || !eTag.getETag().equals(caldavTask.getEtag()); + }); for (List items : partition(changed, 30)) { if (items.size() == 1) { @@ -157,8 +167,8 @@ public class CaldavSynchronizer { Reader reader = null; try { reader = responseBody.charStream(); - processVTodo(vCard.fileName(), caldavAccount, eTag.getETag(), - CharStreams.toString(reader)); + processVTodo( + vCard.fileName(), caldavAccount, eTag.getETag(), CharStreams.toString(reader)); } finally { if (reader != null) { reader.close(); @@ -184,15 +194,17 @@ public class CaldavSynchronizer { "Received CalDAV GET response without CalendarData for " + vCard.getLocation()); } - processVTodo(vCard.fileName(), caldavAccount, eTag.getETag(), - calendarData.getICalendar()); + processVTodo( + vCard.fileName(), caldavAccount, eTag.getETag(), calendarData.getICalendar()); } } } - List deleted = newArrayList(difference( - newHashSet(caldavDao.getObjects(caldavAccount.getUuid())), - newHashSet(remoteObjects))); + List deleted = + newArrayList( + difference( + newHashSet(caldavDao.getObjects(caldavAccount.getUuid())), + newHashSet(remoteObjects))); if (deleted.size() > 0) { Timber.d("DELETED %s", deleted); taskDeleter.markDeleted(caldavDao.getTasks(caldavAccount.getUuid(), deleted)); @@ -211,8 +223,8 @@ public class CaldavSynchronizer { localBroadcastManager.broadcastRefresh(); } - private void pushLocalChanges(CaldavAccount caldavAccount, OkHttpClient httpClient, - HttpUrl httpUrl) { + private void pushLocalChanges( + CaldavAccount caldavAccount, OkHttpClient httpClient, HttpUrl httpUrl) { List tasks = taskDao.getCaldavTasksToPush(caldavAccount.getUuid()); for (com.todoroo.astrid.data.Task task : tasks) { try { @@ -223,12 +235,13 @@ public class CaldavSynchronizer { } } - private boolean deleteRemoteResource(OkHttpClient httpClient, HttpUrl httpUrl, - CaldavTask caldavTask) { + private boolean deleteRemoteResource( + OkHttpClient httpClient, HttpUrl httpUrl, CaldavTask caldavTask) { try { if (!Strings.isNullOrEmpty(caldavTask.getObject())) { - DavResource remote = new DavResource(httpClient, - httpUrl.newBuilder().addPathSegment(caldavTask.getObject()).build()); + DavResource remote = + new DavResource( + httpClient, httpUrl.newBuilder().addPathSegment(caldavTask.getObject()).build()); remote.delete(null); } } catch (HttpException e) { @@ -244,8 +257,9 @@ public class CaldavSynchronizer { return true; } - private void pushTask(Task task, CaldavAccount caldavAccount, OkHttpClient httpClient, - HttpUrl httpUrl) throws IOException { + private void pushTask( + Task task, CaldavAccount caldavAccount, OkHttpClient httpClient, HttpUrl httpUrl) + throws IOException { Timber.d("pushing %s", task); List deleted = getDeleted(task.getId(), caldavAccount); if (!deleted.isEmpty()) { @@ -284,8 +298,9 @@ public class CaldavSynchronizer { RequestBody requestBody = RequestBody.create(DavCalendar.MIME_ICALENDAR, data); try { - DavResource remote = new DavResource(httpClient, - httpUrl.newBuilder().addPathSegment(caldavTask.getObject()).build()); + DavResource remote = + new DavResource( + httpClient, httpUrl.newBuilder().addPathSegment(caldavTask.getObject()).build()); remote.put(requestBody, null, false); GetETag getETag = remote.getProperties().get(GetETag.class); if (getETag != null && !isNullOrEmpty(getETag.getETag())) { @@ -323,8 +338,8 @@ public class CaldavSynchronizer { if (caldavTask == null) { task = taskCreator.createWithValues(null, ""); taskDao.createNew(task); - caldavTask = new CaldavTask(task.getId(), caldavAccount.getUuid(), remote.getUid(), - fileName); + caldavTask = + new CaldavTask(task.getId(), caldavAccount.getUuid(), remote.getUid(), fileName); } else { task = taskDao.fetch(caldavTask.getTask()); } diff --git a/app/src/main/java/org/tasks/caldav/MemoryCookieStore.java b/app/src/main/java/org/tasks/caldav/MemoryCookieStore.java index 1869a3361..e977d5b5e 100644 --- a/app/src/main/java/org/tasks/caldav/MemoryCookieStore.java +++ b/app/src/main/java/org/tasks/caldav/MemoryCookieStore.java @@ -19,18 +19,17 @@ import org.apache.commons.collections4.map.HashedMap; import org.apache.commons.collections4.map.MultiKeyMap; /** - * Primitive cookie store that stores cookies in a (volatile) hash map. - * Will be sufficient for session cookies. + * Primitive cookie store that stores cookies in a (volatile) hash map. Will be sufficient for + * session cookies. */ class MemoryCookieStore implements CookieJar { /** - * Stored cookies. The multi-key consists of three parts: name, domain, and path. - * This ensures that cookies can be overwritten. [RFC 6265 5.3 Storage Model] - * Not thread-safe! + * Stored cookies. The multi-key consists of three parts: name, domain, and path. This ensures + * that cookies can be overwritten. [RFC 6265 5.3 Storage Model] Not thread-safe! */ - private final MultiKeyMap storage = MultiKeyMap - .multiKeyMap(new HashedMap, Cookie>()); + private final MultiKeyMap storage = + MultiKeyMap.multiKeyMap(new HashedMap, Cookie>()); @Override public void saveFromResponse(HttpUrl url, List cookies) { @@ -66,5 +65,4 @@ class MemoryCookieStore implements CookieJar { return cookies; } - } diff --git a/app/src/main/java/org/tasks/caldav/TaskConverter.java b/app/src/main/java/org/tasks/caldav/TaskConverter.java index 6ffb9c69c..f556f15ff 100644 --- a/app/src/main/java/org/tasks/caldav/TaskConverter.java +++ b/app/src/main/java/org/tasks/caldav/TaskConverter.java @@ -49,8 +49,9 @@ class TaskConverter { local.setDueDate(Task.createDueDate(URGENCY_SPECIFIC_DAY_TIME, dueDate.getTime())); } else { try { - local.setDueDate(Task.createDueDate(URGENCY_SPECIFIC_DAY, - DUE_DATE_FORMAT.parse(due.getValue()).getTime())); + local.setDueDate( + Task.createDueDate( + URGENCY_SPECIFIC_DAY, DUE_DATE_FORMAT.parse(due.getValue()).getTime())); } catch (ParseException e) { Timber.e(e, e.getMessage()); } @@ -88,8 +89,8 @@ class TaskConverter { at.bitfire.ical4android.Task remote = null; try { if (!Strings.isNullOrEmpty(caldavTask.getVtodo())) { - remote = at.bitfire.ical4android.Task.fromReader(new StringReader(caldavTask.getVtodo())) - .get(0); + remote = + at.bitfire.ical4android.Task.fromReader(new StringReader(caldavTask.getVtodo())).get(0); } } catch (IOException | InvalidCalendarException e) { Timber.e(e, e.getMessage()); @@ -109,18 +110,18 @@ class TaskConverter { Timber.e(e, e.getMessage()); } } - remote.setDue(new Due(task.hasDueTime() - ? new DateTime(task.getDueDate()) - : new Date(new org.tasks.time.DateTime(task.getDueDate()).toUTC().getMillis()))); + remote.setDue( + new Due( + task.hasDueTime() + ? new DateTime(task.getDueDate()) + : new Date(new org.tasks.time.DateTime(task.getDueDate()).toUTC().getMillis()))); } if (task.isCompleted()) { remote.setCompletedAt(new Completed(new DateTime(task.getCompletionDate()))); } if (task.isRecurring()) { try { - String rrule = task - .getRecurrenceWithoutFrom() - .replace("RRULE:", ""); + String rrule = task.getRecurrenceWithoutFrom().replace("RRULE:", ""); remote.setRRule(new RRule(rrule)); } catch (ParseException e) { Timber.e(e, e.getMessage()); diff --git a/app/src/main/java/org/tasks/calendars/AndroidCalendar.java b/app/src/main/java/org/tasks/calendars/AndroidCalendar.java index 89e3da3e5..91e411aad 100644 --- a/app/src/main/java/org/tasks/calendars/AndroidCalendar.java +++ b/app/src/main/java/org/tasks/calendars/AndroidCalendar.java @@ -26,10 +26,15 @@ public class AndroidCalendar { @Override public String toString() { - return "AndroidCalendar{" + - "id='" + id + '\'' + - ", name='" + name + '\'' + - ", color=" + color + - '}'; + return "AndroidCalendar{" + + "id='" + + id + + '\'' + + ", name='" + + name + + '\'' + + ", color=" + + color + + '}'; } } diff --git a/app/src/main/java/org/tasks/calendars/AndroidCalendarEvent.java b/app/src/main/java/org/tasks/calendars/AndroidCalendarEvent.java index 1b34dbb61..c05946198 100644 --- a/app/src/main/java/org/tasks/calendars/AndroidCalendarEvent.java +++ b/app/src/main/java/org/tasks/calendars/AndroidCalendarEvent.java @@ -11,7 +11,12 @@ public class AndroidCalendarEvent { private final int calendarId; private final List attendees; - public AndroidCalendarEvent(long id, String title, long start, long end, int calendarId, + public AndroidCalendarEvent( + long id, + String title, + long start, + long end, + int calendarId, List attendees) { this.id = id; this.title = title; @@ -47,13 +52,20 @@ public class AndroidCalendarEvent { @Override public String toString() { - return "AndroidCalendarEvent{" + - "id=" + id + - ", title='" + title + '\'' + - ", start=" + start + - ", end=" + end + - ", calendarId=" + calendarId + - ", attendees=" + attendees + - '}'; + return "AndroidCalendarEvent{" + + "id=" + + id + + ", title='" + + title + + '\'' + + ", start=" + + start + + ", end=" + + end + + ", calendarId=" + + calendarId + + ", attendees=" + + attendees + + '}'; } } diff --git a/app/src/main/java/org/tasks/calendars/AndroidCalendarEventAttendee.java b/app/src/main/java/org/tasks/calendars/AndroidCalendarEventAttendee.java index 458026ef6..2fef91565 100644 --- a/app/src/main/java/org/tasks/calendars/AndroidCalendarEventAttendee.java +++ b/app/src/main/java/org/tasks/calendars/AndroidCalendarEventAttendee.java @@ -16,9 +16,13 @@ public class AndroidCalendarEventAttendee { @Override public String toString() { - return "AndroidCalendarEventAttendee{" + - "name='" + name + '\'' + - ", email='" + email + '\'' + - '}'; + return "AndroidCalendarEventAttendee{" + + "name='" + + name + + '\'' + + ", email='" + + email + + '\'' + + '}'; } } diff --git a/app/src/main/java/org/tasks/calendars/CalendarEventAttendeeProvider.java b/app/src/main/java/org/tasks/calendars/CalendarEventAttendeeProvider.java index b3399e3ee..7574213d5 100644 --- a/app/src/main/java/org/tasks/calendars/CalendarEventAttendeeProvider.java +++ b/app/src/main/java/org/tasks/calendars/CalendarEventAttendeeProvider.java @@ -15,16 +15,15 @@ import timber.log.Timber; public class CalendarEventAttendeeProvider { private static final String[] COLUMNS = { - CalendarContract.Attendees.ATTENDEE_NAME, - CalendarContract.Attendees.ATTENDEE_EMAIL, + CalendarContract.Attendees.ATTENDEE_NAME, CalendarContract.Attendees.ATTENDEE_EMAIL, }; private final PermissionChecker permissionChecker; private final ContentResolver contentResolver; @Inject - public CalendarEventAttendeeProvider(@ForApplication Context context, - PermissionChecker permissionChecker) { + public CalendarEventAttendeeProvider( + @ForApplication Context context, PermissionChecker permissionChecker) { this.permissionChecker = permissionChecker; contentResolver = context.getContentResolver(); } @@ -38,18 +37,20 @@ public class CalendarEventAttendeeProvider { Cursor cursor = null; try { //noinspection ResourceType - cursor = contentResolver.query( - CalendarContract.Attendees.CONTENT_URI, - COLUMNS, - CalendarContract.Attendees.EVENT_ID + " = ? ", - new String[]{Long.toString(id)}, null); + cursor = + contentResolver.query( + CalendarContract.Attendees.CONTENT_URI, + COLUMNS, + CalendarContract.Attendees.EVENT_ID + " = ? ", + new String[] {Long.toString(id)}, + null); if (cursor != null && cursor.getCount() > 0) { int emailIndex = cursor.getColumnIndexOrThrow(CalendarContract.Attendees.ATTENDEE_EMAIL); int nameIndex = cursor.getColumnIndexOrThrow(CalendarContract.Attendees.ATTENDEE_NAME); while (cursor.moveToNext()) { - attendees.add(new AndroidCalendarEventAttendee( - cursor.getString(nameIndex), - cursor.getString(emailIndex))); + attendees.add( + new AndroidCalendarEventAttendee( + cursor.getString(nameIndex), cursor.getString(emailIndex))); } } } catch (Exception e) { diff --git a/app/src/main/java/org/tasks/calendars/CalendarEventProvider.java b/app/src/main/java/org/tasks/calendars/CalendarEventProvider.java index f4213c9e5..a022037c2 100644 --- a/app/src/main/java/org/tasks/calendars/CalendarEventProvider.java +++ b/app/src/main/java/org/tasks/calendars/CalendarEventProvider.java @@ -21,11 +21,11 @@ import timber.log.Timber; public class CalendarEventProvider { private static final String[] COLUMNS = { - _ID, - CalendarContract.Events.DTSTART, - CalendarContract.Events.DTEND, - CalendarContract.Events.TITLE, - CalendarContract.Events.CALENDAR_ID + _ID, + CalendarContract.Events.DTSTART, + CalendarContract.Events.DTEND, + CalendarContract.Events.TITLE, + CalendarContract.Events.CALENDAR_ID }; private final ContentResolver contentResolver; @@ -33,7 +33,9 @@ public class CalendarEventProvider { private final CalendarEventAttendeeProvider calendarEventAttendeeProvider; @Inject - public CalendarEventProvider(@ForApplication Context context, PermissionChecker permissionChecker, + public CalendarEventProvider( + @ForApplication Context context, + PermissionChecker permissionChecker, CalendarEventAttendeeProvider calendarEventAttendeeProvider) { this.permissionChecker = permissionChecker; this.calendarEventAttendeeProvider = calendarEventAttendeeProvider; @@ -42,8 +44,11 @@ public class CalendarEventProvider { @Nullable public AndroidCalendarEvent getEvent(long eventId) { - List events = getCalendarEvents(CalendarContract.Events.CONTENT_URI, - _ID + " = ?", new String[]{Long.toString(eventId)}); + List events = + getCalendarEvents( + CalendarContract.Events.CONTENT_URI, + _ID + " = ?", + new String[] {Long.toString(eventId)}); return events.isEmpty() ? null : events.get(0); } @@ -81,11 +86,11 @@ public class CalendarEventProvider { return getCalendarEvents( CalendarContract.Events.CONTENT_URI, CalendarContract.Events.DTSTART + " > ? AND " + CalendarContract.Events.DTSTART + " < ?", - new String[]{Long.toString(start), Long.toString(end)}); + new String[] {Long.toString(start), Long.toString(end)}); } - private List getCalendarEvents(Uri uri, String selection, - String[] selectionArgs) { + private List getCalendarEvents( + Uri uri, String selection, String[] selectionArgs) { if (!permissionChecker.canAccessCalendars()) { return Collections.emptyList(); } @@ -102,13 +107,14 @@ public class CalendarEventProvider { int calendarIdIndex = cursor.getColumnIndexOrThrow(CalendarContract.Events.CALENDAR_ID); while (cursor.moveToNext()) { long id = cursor.getLong(idIndex); - events.add(new AndroidCalendarEvent( - id, - cursor.getString(titleIndex), - cursor.getLong(startIndex), - cursor.getLong(endIndex), - cursor.getInt(calendarIdIndex), - calendarEventAttendeeProvider.getAttendees(id))); + events.add( + new AndroidCalendarEvent( + id, + cursor.getString(titleIndex), + cursor.getLong(startIndex), + cursor.getLong(endIndex), + cursor.getInt(calendarIdIndex), + calendarEventAttendeeProvider.getAttendees(id))); } } } catch (Exception e) { diff --git a/app/src/main/java/org/tasks/calendars/CalendarProvider.java b/app/src/main/java/org/tasks/calendars/CalendarProvider.java index 865feaffc..20c8fec43 100644 --- a/app/src/main/java/org/tasks/calendars/CalendarProvider.java +++ b/app/src/main/java/org/tasks/calendars/CalendarProvider.java @@ -19,13 +19,13 @@ import timber.log.Timber; public class CalendarProvider { - private static final String CAN_MODIFY = CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL + ">= " - + CalendarContract.Calendars.CAL_ACCESS_CONTRIBUTOR; + private static final String CAN_MODIFY = + CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL + + ">= " + + CalendarContract.Calendars.CAL_ACCESS_CONTRIBUTOR; private static final String SORT = CalendarContract.Calendars.CALENDAR_DISPLAY_NAME + " ASC"; private static final String[] COLUMNS = { - _ID, - CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, - CalendarContract.Calendars.CALENDAR_COLOR + _ID, CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, CalendarContract.Calendars.CALENDAR_COLOR }; private final PermissionChecker permissionChecker; @@ -46,8 +46,9 @@ public class CalendarProvider { if (Strings.isNullOrEmpty(id)) { return null; } - List calendars = getCalendars(CalendarContract.Calendars.CONTENT_URI, - CAN_MODIFY + " AND Calendars._id=" + id); + List calendars = + getCalendars( + CalendarContract.Calendars.CONTENT_URI, CAN_MODIFY + " AND Calendars._id=" + id); return calendars.isEmpty() ? null : calendars.get(0); } @@ -66,7 +67,9 @@ public class CalendarProvider { int colorColumn = cursor.getColumnIndex(CalendarContract.Calendars.CALENDAR_COLOR); while (cursor.moveToNext()) { calendars.add( - new AndroidCalendar(cursor.getString(idColumn), cursor.getString(nameColumn), + new AndroidCalendar( + cursor.getString(idColumn), + cursor.getString(nameColumn), cursor.getInt(colorColumn))); } } diff --git a/app/src/main/java/org/tasks/dashclock/DashClockExtension.java b/app/src/main/java/org/tasks/dashclock/DashClockExtension.java index e3ffb2c86..20a127acc 100644 --- a/app/src/main/java/org/tasks/dashclock/DashClockExtension.java +++ b/app/src/main/java/org/tasks/dashclock/DashClockExtension.java @@ -22,21 +22,20 @@ public class DashClockExtension extends com.google.android.apps.dashclock.api.Da @Inject DefaultFilterProvider defaultFilterProvider; @Inject TaskDao taskDao; @Inject Preferences preferences; - private final BroadcastReceiver refreshReceiver = new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - refresh(); - } - }; + private final BroadcastReceiver refreshReceiver = + new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + refresh(); + } + }; @Inject LocalBroadcastManager localBroadcastManager; @Override public void onCreate() { super.onCreate(); - ((InjectingApplication) getApplication()) - .getComponent() - .inject(this); + ((InjectingApplication) getApplication()).getComponent().inject(this); localBroadcastManager.registerRefreshReceiver(refreshReceiver); } @@ -65,13 +64,14 @@ public class DashClockExtension extends com.google.android.apps.dashclock.api.Da } else { Intent clickIntent = new Intent(this, TaskListActivity.class); clickIntent.putExtra(TaskListActivity.LOAD_FILTER, filterPreference); - ExtensionData extensionData = new ExtensionData() - .visible(true) - .icon(R.drawable.ic_check_white_24dp) - .status(Integer.toString(count)) - .expandedTitle(getResources().getQuantityString(R.plurals.task_count, count, count)) - .expandedBody(filter.listingTitle) - .clickIntent(clickIntent); + ExtensionData extensionData = + new ExtensionData() + .visible(true) + .icon(R.drawable.ic_check_white_24dp) + .status(Integer.toString(count)) + .expandedTitle(getResources().getQuantityString(R.plurals.task_count, count, count)) + .expandedBody(filter.listingTitle) + .clickIntent(clickIntent); if (count == 1) { List tasks = taskDao.fetchFiltered(filter); if (!tasks.isEmpty()) { @@ -81,12 +81,13 @@ public class DashClockExtension extends com.google.android.apps.dashclock.api.Da publish(extensionData); } } else { - publish(new ExtensionData() - .visible(true) - .icon(R.drawable.ic_check_white_24dp) - .status(getString(R.string.buy)) - .expandedTitle(getString(R.string.buy_dashclock_extension)) - .clickIntent(new Intent(this, DashClockSettings.class))); + publish( + new ExtensionData() + .visible(true) + .icon(R.drawable.ic_check_white_24dp) + .status(getString(R.string.buy)) + .expandedTitle(getString(R.string.buy_dashclock_extension)) + .clickIntent(new Intent(this, DashClockSettings.class))); } } diff --git a/app/src/main/java/org/tasks/dashclock/DashClockSettings.java b/app/src/main/java/org/tasks/dashclock/DashClockSettings.java index 5f4c2ea25..ea652cb2a 100644 --- a/app/src/main/java/org/tasks/dashclock/DashClockSettings.java +++ b/app/src/main/java/org/tasks/dashclock/DashClockSettings.java @@ -15,8 +15,8 @@ import org.tasks.injection.InjectingPreferenceActivity; import org.tasks.preferences.DefaultFilterProvider; import org.tasks.preferences.Preferences; -public class DashClockSettings extends InjectingPreferenceActivity implements - PurchaseHelperCallback { +public class DashClockSettings extends InjectingPreferenceActivity + implements PurchaseHelperCallback { private static final String EXTRA_PURCHASE_INITIATED = "extra_purchase_initiated"; private static final int REQUEST_SELECT_FILTER = 1005; @@ -40,20 +40,25 @@ public class DashClockSettings extends InjectingPreferenceActivity implements addPreferencesFromResource(R.xml.preferences_dashclock); findPreference(getString(R.string.p_dashclock_filter)) - .setOnPreferenceClickListener(preference -> { - Intent intent = new Intent(DashClockSettings.this, FilterSelectionActivity.class); - intent.putExtra(FilterSelectionActivity.EXTRA_FILTER, - defaultFilterProvider.getDashclockFilter()); - intent.putExtra(FilterSelectionActivity.EXTRA_RETURN_FILTER, true); - startActivityForResult(intent, REQUEST_SELECT_FILTER); - return false; - }); + .setOnPreferenceClickListener( + preference -> { + Intent intent = new Intent(DashClockSettings.this, FilterSelectionActivity.class); + intent.putExtra( + FilterSelectionActivity.EXTRA_FILTER, defaultFilterProvider.getDashclockFilter()); + intent.putExtra(FilterSelectionActivity.EXTRA_RETURN_FILTER, true); + startActivityForResult(intent, REQUEST_SELECT_FILTER); + return false; + }); refreshPreferences(); if (!preferences.hasPurchase(R.string.p_purchased_dashclock) && !purchaseInitiated) { - purchaseHelper.purchase(this, getString(R.string.sku_dashclock), - getString(R.string.p_purchased_dashclock), REQUEST_PURCHASE, this); + purchaseHelper.purchase( + this, + getString(R.string.sku_dashclock), + getString(R.string.p_purchased_dashclock), + REQUEST_PURCHASE, + this); purchaseInitiated = true; } } diff --git a/app/src/main/java/org/tasks/data/Alarm.java b/app/src/main/java/org/tasks/data/Alarm.java index 9a21c64c1..203cb0eca 100644 --- a/app/src/main/java/org/tasks/data/Alarm.java +++ b/app/src/main/java/org/tasks/data/Alarm.java @@ -18,9 +18,7 @@ public class Alarm { @ColumnInfo(name = "time") private long time; - public Alarm() { - - } + public Alarm() {} @Ignore public Alarm(long task, long time) { @@ -82,10 +80,6 @@ public class Alarm { @Override public String toString() { - return "Alarm{" + - "id=" + id + - ", task=" + task + - ", time=" + time + - '}'; + return "Alarm{" + "id=" + id + ", task=" + task + ", time=" + time + '}'; } } diff --git a/app/src/main/java/org/tasks/data/AlarmDao.java b/app/src/main/java/org/tasks/data/AlarmDao.java index af4a373bc..568d8600b 100644 --- a/app/src/main/java/org/tasks/data/AlarmDao.java +++ b/app/src/main/java/org/tasks/data/AlarmDao.java @@ -9,15 +9,16 @@ import java.util.List; @Dao public interface AlarmDao { - @Query("SELECT alarms.* FROM alarms INNER JOIN tasks ON tasks._id = alarms.task " + - "WHERE tasks.completed = 0 AND tasks.deleted = 0 AND tasks.lastNotified < alarms.time " + - "ORDER BY time ASC") + @Query( + "SELECT alarms.* FROM alarms INNER JOIN tasks ON tasks._id = alarms.task " + + "WHERE tasks.completed = 0 AND tasks.deleted = 0 AND tasks.lastNotified < alarms.time " + + "ORDER BY time ASC") List getActiveAlarms(); - @Query("SELECT alarms.* FROM alarms INNER JOIN tasks ON tasks._id = alarms.task " + - "WHERE tasks._id = :taskId AND tasks.completed = 0 AND tasks.deleted = 0 AND tasks.lastNotified < alarms.time " - + - "ORDER BY time ASC") + @Query( + "SELECT alarms.* FROM alarms INNER JOIN tasks ON tasks._id = alarms.task " + + "WHERE tasks._id = :taskId AND tasks.completed = 0 AND tasks.deleted = 0 AND tasks.lastNotified < alarms.time " + + "ORDER BY time ASC") List getActiveAlarms(long taskId); @Query("SELECT * FROM alarms WHERE task = :taskId ORDER BY time ASC") diff --git a/app/src/main/java/org/tasks/data/CaldavAccount.java b/app/src/main/java/org/tasks/data/CaldavAccount.java index 6850abf70..93aa908e2 100644 --- a/app/src/main/java/org/tasks/data/CaldavAccount.java +++ b/app/src/main/java/org/tasks/data/CaldavAccount.java @@ -1,6 +1,5 @@ package org.tasks.data; - import static com.todoroo.astrid.data.Task.NO_UUID; import android.arch.persistence.room.ColumnInfo; @@ -14,39 +13,45 @@ import android.text.TextUtils; @Entity(tableName = "caldav_account") public final class CaldavAccount implements Parcelable { - public static Parcelable.Creator CREATOR = new Parcelable.Creator() { - @Override - public CaldavAccount createFromParcel(Parcel source) { - return new CaldavAccount(source); - } + public static Parcelable.Creator CREATOR = + new Parcelable.Creator() { + @Override + public CaldavAccount createFromParcel(Parcel source) { + return new CaldavAccount(source); + } - @Override - public CaldavAccount[] newArray(int size) { - return new CaldavAccount[size]; - } - }; + @Override + public CaldavAccount[] newArray(int size) { + return new CaldavAccount[size]; + } + }; @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "_id") private long id; + @ColumnInfo(name = "uuid") private String uuid = NO_UUID; + @ColumnInfo(name = "name") private String name = ""; + @ColumnInfo(name = "color") private int color = -1; + @ColumnInfo(name = "ctag") private String ctag; + @ColumnInfo(name = "url") private String url = ""; + @ColumnInfo(name = "username") private String username = ""; + @ColumnInfo(name = "password") private transient String password = ""; - public CaldavAccount() { - - } + public CaldavAccount() {} @Ignore public CaldavAccount(String name, String uuid) { @@ -149,16 +154,30 @@ public final class CaldavAccount implements Parcelable { @Override public String toString() { - return "CaldavAccount{" + - "id=" + id + - ", uuid='" + uuid + '\'' + - ", name='" + name + '\'' + - ", color=" + color + - ", ctag='" + ctag + '\'' + - ", url='" + url + '\'' + - ", username='" + username + '\'' + - ", password='" + (TextUtils.isEmpty(password) ? "null" : "******") + '\'' + - '}'; + return "CaldavAccount{" + + "id=" + + id + + ", uuid='" + + uuid + + '\'' + + ", name='" + + name + + '\'' + + ", color=" + + color + + ", ctag='" + + ctag + + '\'' + + ", url='" + + url + + '\'' + + ", username='" + + username + + '\'' + + ", password='" + + (TextUtils.isEmpty(password) ? "null" : "******") + + '\'' + + '}'; } @Override diff --git a/app/src/main/java/org/tasks/data/CaldavTask.java b/app/src/main/java/org/tasks/data/CaldavTask.java index 24d145da8..26e6363e1 100644 --- a/app/src/main/java/org/tasks/data/CaldavTask.java +++ b/app/src/main/java/org/tasks/data/CaldavTask.java @@ -11,8 +11,7 @@ public class CaldavTask { public static final String KEY = "caldav"; - @Deprecated - public static final Table TABLE = new Table("caldav_tasks"); + @Deprecated public static final Table TABLE = new Table("caldav_tasks"); @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "_id") @@ -42,9 +41,7 @@ public class CaldavTask { @ColumnInfo(name = "vtodo") private String vtodo; - public CaldavTask() { - - } + public CaldavTask() {} @Ignore public CaldavTask(long task, String account, String remoteId) { @@ -133,16 +130,30 @@ public class CaldavTask { @Override public String toString() { - return "CaldavTask{" + - "id=" + id + - ", task=" + task + - ", account='" + account + '\'' + - ", object='" + object + '\'' + - ", remoteId='" + remoteId + '\'' + - ", etag='" + etag + '\'' + - ", lastSync=" + lastSync + - ", deleted=" + deleted + - ", vtodo='" + vtodo + '\'' + - '}'; + return "CaldavTask{" + + "id=" + + id + + ", task=" + + task + + ", account='" + + account + + '\'' + + ", object='" + + object + + '\'' + + ", remoteId='" + + remoteId + + '\'' + + ", etag='" + + etag + + '\'' + + ", lastSync=" + + lastSync + + ", deleted=" + + deleted + + ", vtodo='" + + vtodo + + '\'' + + '}'; } } diff --git a/app/src/main/java/org/tasks/data/Filter.java b/app/src/main/java/org/tasks/data/Filter.java index db49d5bb0..ef46028fc 100644 --- a/app/src/main/java/org/tasks/data/Filter.java +++ b/app/src/main/java/org/tasks/data/Filter.java @@ -65,12 +65,21 @@ public class Filter { @Override public String toString() { - return "Filter{" + - "id=" + id + - ", title='" + title + '\'' + - ", sql='" + sql + '\'' + - ", values='" + values + '\'' + - ", criterion='" + criterion + '\'' + - '}'; + return "Filter{" + + "id=" + + id + + ", title='" + + title + + '\'' + + ", sql='" + + sql + + '\'' + + ", values='" + + values + + '\'' + + ", criterion='" + + criterion + + '\'' + + '}'; } } diff --git a/app/src/main/java/org/tasks/data/GoogleTask.java b/app/src/main/java/org/tasks/data/GoogleTask.java index 240eb46c8..4db8493f0 100644 --- a/app/src/main/java/org/tasks/data/GoogleTask.java +++ b/app/src/main/java/org/tasks/data/GoogleTask.java @@ -11,14 +11,13 @@ import com.todoroo.andlib.utility.DateUtilities; @Entity(tableName = "google_tasks") public class GoogleTask { - public static final String KEY = "gtasks"; //$NON-NLS-1$ + public static final String KEY = "gtasks"; // $NON-NLS-1$ - @Deprecated - public static final Table TABLE = new Table("google_tasks"); + @Deprecated public static final Table TABLE = new Table("google_tasks"); @Deprecated - public static final Property.IntegerProperty INDENT = new Property.IntegerProperty( - GoogleTask.TABLE, "indent"); + public static final Property.IntegerProperty INDENT = + new Property.IntegerProperty(GoogleTask.TABLE, "indent"); @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "_id") @@ -51,12 +50,9 @@ public class GoogleTask { @ColumnInfo(name = "deleted") private long deleted; - @Ignore - private transient boolean suppressSync; - - public GoogleTask() { + @Ignore private transient boolean suppressSync; - } + public GoogleTask() {} @Ignore public GoogleTask(long task, String listId) { @@ -215,17 +211,29 @@ public class GoogleTask { @Override public String toString() { - return "GoogleTask{" + - "id=" + id + - ", task=" + task + - ", remoteId='" + remoteId + '\'' + - ", listId='" + listId + '\'' + - ", parent=" + parent + - ", indent=" + indent + - ", order=" + order + - ", remoteOrder=" + remoteOrder + - ", lastSync=" + lastSync + - ", deleted=" + deleted + - '}'; + return "GoogleTask{" + + "id=" + + id + + ", task=" + + task + + ", remoteId='" + + remoteId + + '\'' + + ", listId='" + + listId + + '\'' + + ", parent=" + + parent + + ", indent=" + + indent + + ", order=" + + order + + ", remoteOrder=" + + remoteOrder + + ", lastSync=" + + lastSync + + ", deleted=" + + deleted + + '}'; } } diff --git a/app/src/main/java/org/tasks/data/GoogleTaskDao.java b/app/src/main/java/org/tasks/data/GoogleTaskDao.java index be4fe9f65..05a21b1cf 100644 --- a/app/src/main/java/org/tasks/data/GoogleTaskDao.java +++ b/app/src/main/java/org/tasks/data/GoogleTaskDao.java @@ -22,13 +22,16 @@ public interface GoogleTaskDao { @Update void update(GoogleTask googleTask); - @Query("SELECT * FROM google_tasks WHERE list_id = :listId AND parent = :parent ORDER BY remote_order ASC") + @Query( + "SELECT * FROM google_tasks WHERE list_id = :listId AND parent = :parent ORDER BY remote_order ASC") List byRemoteOrder(String listId, long parent); - @Query("SELECT * FROM google_tasks WHERE list_id = :listId AND `order` > :startAtOrder - 1 ORDER BY `order` ASC ") + @Query( + "SELECT * FROM google_tasks WHERE list_id = :listId AND `order` > :startAtOrder - 1 ORDER BY `order` ASC ") List getTasksFrom(String listId, long startAtOrder); - @Query("SELECT * FROM google_tasks WHERE list_id = :listId AND `order` < :startAtOrder ORDER BY `order` DESC") + @Query( + "SELECT * FROM google_tasks WHERE list_id = :listId AND `order` < :startAtOrder ORDER BY `order` DESC") List getTasksFromReverse(String listId, long startAtOrder); @Query("DELETE FROM google_tasks WHERE task = :taskId") diff --git a/app/src/main/java/org/tasks/data/GoogleTaskList.java b/app/src/main/java/org/tasks/data/GoogleTaskList.java index a1fe48e3c..af05fe2a2 100644 --- a/app/src/main/java/org/tasks/data/GoogleTaskList.java +++ b/app/src/main/java/org/tasks/data/GoogleTaskList.java @@ -10,36 +10,42 @@ import android.os.Parcelable; @Entity(tableName = "google_task_lists") public class GoogleTaskList implements Parcelable { - public static Creator CREATOR = new Creator() { - @Override - public GoogleTaskList createFromParcel(Parcel parcel) { - return new GoogleTaskList(parcel); - } + public static Creator CREATOR = + new Creator() { + @Override + public GoogleTaskList createFromParcel(Parcel parcel) { + return new GoogleTaskList(parcel); + } + + @Override + public GoogleTaskList[] newArray(int size) { + return new GoogleTaskList[size]; + } + }; - @Override - public GoogleTaskList[] newArray(int size) { - return new GoogleTaskList[size]; - } - }; @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "_id") private transient long id; + @ColumnInfo(name = "remote_id") private String remoteId; + @ColumnInfo(name = "title") private String title; + @ColumnInfo(name = "remote_order") private int remoteOrder; + @ColumnInfo(name = "last_sync") private long lastSync; + @ColumnInfo(name = "deleted") private long deleted; + @ColumnInfo(name = "color") private Integer color; - public GoogleTaskList() { - - } + public GoogleTaskList() {} @Ignore public GoogleTaskList(Parcel parcel) { @@ -154,15 +160,24 @@ public class GoogleTaskList implements Parcelable { @Override public String toString() { - return "GoogleTaskList{" + - "id=" + id + - ", remoteId='" + remoteId + '\'' + - ", title='" + title + '\'' + - ", remoteOrder=" + remoteOrder + - ", lastSync=" + lastSync + - ", deleted=" + deleted + - ", color=" + color + - '}'; + return "GoogleTaskList{" + + "id=" + + id + + ", remoteId='" + + remoteId + + '\'' + + ", title='" + + title + + '\'' + + ", remoteOrder=" + + remoteOrder + + ", lastSync=" + + lastSync + + ", deleted=" + + deleted + + ", color=" + + color + + '}'; } @Override diff --git a/app/src/main/java/org/tasks/data/LimitOffsetDataSource.java b/app/src/main/java/org/tasks/data/LimitOffsetDataSource.java index d4aed9fef..6ea5bf34f 100644 --- a/app/src/main/java/org/tasks/data/LimitOffsetDataSource.java +++ b/app/src/main/java/org/tasks/data/LimitOffsetDataSource.java @@ -48,7 +48,7 @@ public class LimitOffsetDataSource extends PositionalDataSource { @Nullable @WorkerThread private List loadRange(int startPosition, int loadCount) { - Cursor cursor = mDb.query(mLimitOffsetQuery, new Object[]{loadCount, startPosition}); + Cursor cursor = mDb.query(mLimitOffsetQuery, new Object[] {loadCount, startPosition}); //noinspection TryFinallyCanBeTryWithResources try { return convertRows(cursor); @@ -58,8 +58,8 @@ public class LimitOffsetDataSource extends PositionalDataSource { } @Override - public void loadInitial(@NonNull LoadInitialParams params, - @NonNull LoadInitialCallback callback) { + public void loadInitial( + @NonNull LoadInitialParams params, @NonNull LoadInitialCallback callback) { int totalCount = countItems(); if (totalCount == 0) { callback.onResult(Collections.emptyList(), 0, 0); @@ -83,8 +83,8 @@ public class LimitOffsetDataSource extends PositionalDataSource { @WorkerThread @Override - public void loadRange(@NonNull LoadRangeParams params, - @NonNull LoadRangeCallback callback) { + public void loadRange( + @NonNull LoadRangeParams params, @NonNull LoadRangeCallback callback) { List list = loadRange(params.startPosition, params.loadSize); if (list != null) { callback.onResult(list); @@ -92,4 +92,4 @@ public class LimitOffsetDataSource extends PositionalDataSource { invalidate(); } } -} \ No newline at end of file +} diff --git a/app/src/main/java/org/tasks/data/Location.java b/app/src/main/java/org/tasks/data/Location.java index 6e171c2c2..cd4b040d4 100644 --- a/app/src/main/java/org/tasks/data/Location.java +++ b/app/src/main/java/org/tasks/data/Location.java @@ -12,34 +12,39 @@ import org.tasks.backup.XmlReader; @Entity(tableName = "locations") public class Location implements Serializable, Parcelable { - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - @Override - public Location createFromParcel(Parcel source) { - return new Location(source); - } + public static final Parcelable.Creator CREATOR = + new Parcelable.Creator() { + @Override + public Location createFromParcel(Parcel source) { + return new Location(source); + } + + @Override + public Location[] newArray(int size) { + return new Location[size]; + } + }; - @Override - public Location[] newArray(int size) { - return new Location[size]; - } - }; @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "_id") private transient long id; + @ColumnInfo(name = "task") private transient long task; + @ColumnInfo(name = "name") private String name; + @ColumnInfo(name = "latitude") private double latitude; + @ColumnInfo(name = "longitude") private double longitude; + @ColumnInfo(name = "radius") private int radius; - public Location() { - - } + public Location() {} @Ignore public Location(Parcel parcel) { @@ -153,14 +158,21 @@ public class Location implements Serializable, Parcelable { @Override public String toString() { - return "Location{" + - "id=" + id + - ", task=" + task + - ", name='" + name + '\'' + - ", latitude=" + latitude + - ", longitude=" + longitude + - ", radius=" + radius + - '}'; + return "Location{" + + "id=" + + id + + ", task=" + + task + + ", name='" + + name + + '\'' + + ", latitude=" + + latitude + + ", longitude=" + + longitude + + ", radius=" + + radius + + '}'; } @Override @@ -177,4 +189,4 @@ public class Location implements Serializable, Parcelable { out.writeDouble(longitude); out.writeInt(radius); } -} \ No newline at end of file +} diff --git a/app/src/main/java/org/tasks/data/LocationDao.java b/app/src/main/java/org/tasks/data/LocationDao.java index 0a20b9165..83dd81ad6 100644 --- a/app/src/main/java/org/tasks/data/LocationDao.java +++ b/app/src/main/java/org/tasks/data/LocationDao.java @@ -15,10 +15,12 @@ public interface LocationDao { @Query("SELECT * FROM locations WHERE task = :taskId ORDER BY name ASC") List getGeofences(long taskId); - @Query("SELECT locations.* FROM locations INNER JOIN tasks ON tasks._id = locations.task WHERE tasks._id = :taskId AND tasks.deleted = 0 AND tasks.completed = 0") + @Query( + "SELECT locations.* FROM locations INNER JOIN tasks ON tasks._id = locations.task WHERE tasks._id = :taskId AND tasks.deleted = 0 AND tasks.completed = 0") List getActiveGeofences(long taskId); - @Query("SELECT locations.* FROM locations INNER JOIN tasks ON tasks._id = locations.task WHERE tasks.deleted = 0 AND tasks.completed = 0") + @Query( + "SELECT locations.* FROM locations INNER JOIN tasks ON tasks._id = locations.task WHERE tasks.deleted = 0 AND tasks.completed = 0") List getActiveGeofences(); @Delete diff --git a/app/src/main/java/org/tasks/data/Tag.java b/app/src/main/java/org/tasks/data/Tag.java index a8bc87e5d..a49bb1b04 100644 --- a/app/src/main/java/org/tasks/data/Tag.java +++ b/app/src/main/java/org/tasks/data/Tag.java @@ -11,10 +11,9 @@ import org.tasks.backup.XmlReader; @Entity(tableName = "tags") public class Tag { - public static final String KEY = "tags-tag"; //$NON-NLS-1$ + public static final String KEY = "tags-tag"; // $NON-NLS-1$ - @Deprecated - public static final Table TABLE = new Table("tags"); + @Deprecated public static final Table TABLE = new Table("tags"); @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "_id") @@ -32,9 +31,7 @@ public class Tag { @ColumnInfo(name = "task_uid") private transient String taskUid; - public Tag() { - - } + public Tag() {} @Ignore public Tag(long task, String taskUid, String name, String tagUid) { diff --git a/app/src/main/java/org/tasks/data/TagData.java b/app/src/main/java/org/tasks/data/TagData.java index 7082e3cd0..4bc0699de 100644 --- a/app/src/main/java/org/tasks/data/TagData.java +++ b/app/src/main/java/org/tasks/data/TagData.java @@ -13,31 +13,36 @@ import org.tasks.backup.XmlReader; @Entity(tableName = "tagdata") public final class TagData implements Parcelable { - public static final Creator CREATOR = new Creator() { - @Override - public TagData createFromParcel(Parcel source) { - return new TagData(source); - } + public static final Creator CREATOR = + new Creator() { + @Override + public TagData createFromParcel(Parcel source) { + return new TagData(source); + } + + @Override + public TagData[] newArray(int size) { + return new TagData[size]; + } + }; - @Override - public TagData[] newArray(int size) { - return new TagData[size]; - } - }; @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "_id") private transient Long id; + @ColumnInfo(name = "remoteId") private String remoteId = Task.NO_UUID; + @ColumnInfo(name = "name") private String name = ""; + @ColumnInfo(name = "color") private Integer color = -1; + @ColumnInfo(name = "tagOrdering") private String tagOrdering = "[]"; - public TagData() { - } + public TagData() {} @Ignore public TagData(XmlReader reader) { @@ -134,7 +139,8 @@ public final class TagData implements Parcelable { if (color != null ? !color.equals(tagData.color) : tagData.color != null) { return false; } - return tagOrdering != null ? tagOrdering.equals(tagData.tagOrdering) + return tagOrdering != null + ? tagOrdering.equals(tagData.tagOrdering) : tagData.tagOrdering == null; } @@ -150,12 +156,20 @@ public final class TagData implements Parcelable { @Override public String toString() { - return "TagData{" + - "id=" + id + - ", remoteId='" + remoteId + '\'' + - ", name='" + name + '\'' + - ", color=" + color + - ", tagOrdering='" + tagOrdering + '\'' + - '}'; + return "TagData{" + + "id=" + + id + + ", remoteId='" + + remoteId + + '\'' + + ", name='" + + name + + '\'' + + ", color=" + + color + + ", tagOrdering='" + + tagOrdering + + '\'' + + '}'; } } diff --git a/app/src/main/java/org/tasks/data/TagDataDao.java b/app/src/main/java/org/tasks/data/TagDataDao.java index 51168db05..9ae480422 100644 --- a/app/src/main/java/org/tasks/data/TagDataDao.java +++ b/app/src/main/java/org/tasks/data/TagDataDao.java @@ -42,4 +42,3 @@ public abstract class TagDataDao { tag.setId(insert(tag)); } } - diff --git a/app/src/main/java/org/tasks/data/TaskAttachment.java b/app/src/main/java/org/tasks/data/TaskAttachment.java index 1e5c9c1f6..6899fe811 100644 --- a/app/src/main/java/org/tasks/data/TaskAttachment.java +++ b/app/src/main/java/org/tasks/data/TaskAttachment.java @@ -1,6 +1,5 @@ package org.tasks.data; - import android.arch.persistence.room.ColumnInfo; import android.arch.persistence.room.Entity; import android.arch.persistence.room.PrimaryKey; @@ -11,40 +10,40 @@ import com.todoroo.astrid.data.Task; @Entity(tableName = "task_attachments") public final class TaskAttachment { - @Deprecated - public static final Table TABLE = new Table("task_attachments"); + @Deprecated public static final Table TABLE = new Table("task_attachments"); @Deprecated - public static final Property.LongProperty ID = new Property.LongProperty( - TABLE, "_id"); - /** - * default directory for files on external storage - */ - public static final String FILES_DIRECTORY_DEFAULT = "attachments"; //$NON-NLS-1$ - /** - * 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_OTHER = "application/octet-stream"; //$NON-NLS-1$ + public static final Property.LongProperty ID = new Property.LongProperty(TABLE, "_id"); + /** default directory for files on external storage */ + public static final String FILES_DIRECTORY_DEFAULT = "attachments"; // $NON-NLS-1$ + /** 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_OTHER = "application/octet-stream"; // $NON-NLS-1$ + @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "_id") private transient Long id; + @ColumnInfo(name = "remoteId") private String remoteId = Task.NO_UUID; // -- Constants @ColumnInfo(name = "task_id") private String taskId = Task.NO_UUID; + @ColumnInfo(name = "name") private String name = ""; + @ColumnInfo(name = "path") private String path = ""; + @ColumnInfo(name = "content_type") private String contentType = ""; - public static TaskAttachment createNewAttachment(String taskUuid, String filePath, - String fileName, String fileType) { + public static TaskAttachment createNewAttachment( + String taskUuid, String filePath, String fileName, String fileType) { TaskAttachment attachment = new TaskAttachment(); attachment.setTaskId(taskUuid); attachment.setName(fileName); diff --git a/app/src/main/java/org/tasks/data/TaskAttachmentDao.java b/app/src/main/java/org/tasks/data/TaskAttachmentDao.java index ba749b4f7..2a81ba5c1 100644 --- a/app/src/main/java/org/tasks/data/TaskAttachmentDao.java +++ b/app/src/main/java/org/tasks/data/TaskAttachmentDao.java @@ -32,4 +32,3 @@ public abstract class TaskAttachmentDao { insert(attachment); } } - diff --git a/app/src/main/java/org/tasks/data/TaskListMetadata.java b/app/src/main/java/org/tasks/data/TaskListMetadata.java index 8341ba92e..5e67e8e7d 100644 --- a/app/src/main/java/org/tasks/data/TaskListMetadata.java +++ b/app/src/main/java/org/tasks/data/TaskListMetadata.java @@ -1,6 +1,5 @@ package org.tasks.data; - import android.arch.persistence.room.ColumnInfo; import android.arch.persistence.room.Entity; import android.arch.persistence.room.PrimaryKey; diff --git a/app/src/main/java/org/tasks/data/TaskListMetadataDao.java b/app/src/main/java/org/tasks/data/TaskListMetadataDao.java index 413698b6a..97c718190 100644 --- a/app/src/main/java/org/tasks/data/TaskListMetadataDao.java +++ b/app/src/main/java/org/tasks/data/TaskListMetadataDao.java @@ -21,4 +21,3 @@ public abstract class TaskListMetadataDao { taskListMetadata.setId(insert(taskListMetadata)); } } - diff --git a/app/src/main/java/org/tasks/data/UserActivity.java b/app/src/main/java/org/tasks/data/UserActivity.java index d4542a9b5..f26bf0427 100644 --- a/app/src/main/java/org/tasks/data/UserActivity.java +++ b/app/src/main/java/org/tasks/data/UserActivity.java @@ -17,33 +17,39 @@ import timber.log.Timber; @Entity(tableName = "userActivity") public class UserActivity implements Parcelable { - public static final Creator CREATOR = new Creator() { - @Override - public UserActivity createFromParcel(Parcel source) { - return new UserActivity(source); - } + public static final Creator CREATOR = + new Creator() { + @Override + public UserActivity createFromParcel(Parcel source) { + return new UserActivity(source); + } + + @Override + public UserActivity[] newArray(int size) { + return new UserActivity[size]; + } + }; - @Override - public UserActivity[] newArray(int size) { - return new UserActivity[size]; - } - }; @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "_id") private transient Long id; + @ColumnInfo(name = "remoteId") private String remoteId = Task.NO_UUID; + @ColumnInfo(name = "message") private String message = ""; + @ColumnInfo(name = "picture") private String picture = ""; + @ColumnInfo(name = "target_id") private transient String targetId = Task.NO_UUID; + @ColumnInfo(name = "created_at") private Long created = 0L; - public UserActivity() { - } + public UserActivity() {} @Ignore public UserActivity(XmlReader reader) { diff --git a/app/src/main/java/org/tasks/date/DateTimeUtils.java b/app/src/main/java/org/tasks/date/DateTimeUtils.java index 41d47d5ae..eef1b464a 100644 --- a/app/src/main/java/org/tasks/date/DateTimeUtils.java +++ b/app/src/main/java/org/tasks/date/DateTimeUtils.java @@ -9,8 +9,8 @@ public class DateTimeUtils { return new DateTime(year, month, day, 0, 0, 0); } - public static DateTime newDateUtc(int year, int month, int day, int hour, int minute, - int second) { + public static DateTime newDateUtc( + int year, int month, int day, int hour, int minute, int second) { return new DateTime(year, month, day, hour, minute, second, 0, TimeZone.getTimeZone("GMT")); } diff --git a/app/src/main/java/org/tasks/db/Migrations.java b/app/src/main/java/org/tasks/db/Migrations.java index 9ae4e5877..414bc65ac 100644 --- a/app/src/main/java/org/tasks/db/Migrations.java +++ b/app/src/main/java/org/tasks/db/Migrations.java @@ -8,216 +8,229 @@ import timber.log.Timber; public class Migrations { - private static final Migration MIGRATION_35_36 = new Migration(35, 36) { - @Override - public void migrate(@NonNull SupportSQLiteDatabase database) { - database.execSQL("ALTER TABLE `tagdata` ADD COLUMN `color` INTEGER DEFAULT -1"); - } - }; - - private static final Migration MIGRATION_36_37 = new Migration(36, 37) { - @Override - public void migrate(@NonNull SupportSQLiteDatabase database) { - database.execSQL("ALTER TABLE `store` ADD COLUMN `deleted` INTEGER DEFAULT 0"); - } - }; - - private static final Migration MIGRATION_37_38 = new Migration(37, 38) { - @Override - public void migrate(@NonNull SupportSQLiteDatabase database) { - try { - database.execSQL("ALTER TABLE `store` ADD COLUMN `value4` TEXT DEFAULT -1"); - } catch (SQLiteException e) { - Timber.w(e, e.getMessage()); - } - } - }; - - private static final Migration MIGRATION_38_39 = new Migration(38, 39) { - @Override - public void migrate(@NonNull SupportSQLiteDatabase database) { - database.execSQL( - "CREATE TABLE IF NOT EXISTS `notification` (`uid` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task` INTEGER NOT NULL, `timestamp` INTEGER NOT NULL, `type` INTEGER NOT NULL)"); - database.execSQL("CREATE UNIQUE INDEX `index_notification_task` ON `notification` (`task`)"); - } - }; - - private static final Migration MIGRATION_46_47 = new Migration(46, 47) { - @Override - public void migrate(@NonNull SupportSQLiteDatabase database) { - database.execSQL( - "CREATE TABLE IF NOT EXISTS `alarms` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task` INTEGER NOT NULL, `time` INTEGER NOT NULL)"); - database.execSQL( - "INSERT INTO `alarms` (`task`, `time`) SELECT `task`, `value` FROM `metadata` WHERE `key` = 'alarm' AND `deleted` = 0"); - database.execSQL("DELETE FROM `metadata` WHERE `key` = 'alarm'"); - } - }; - - private static final Migration MIGRATION_47_48 = new Migration(47, 48) { - @Override - public void migrate(@NonNull SupportSQLiteDatabase database) { - database.execSQL( - "CREATE TABLE IF NOT EXISTS `locations` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task` INTEGER NOT NULL, `name` TEXT, `latitude` REAL NOT NULL, `longitude` REAL NOT NULL, `radius` INTEGER NOT NULL)"); - database - .execSQL("INSERT INTO `locations` (`task`, `name`, `latitude`, `longitude`, `radius`) " + - "SELECT `task`, `value`, `value2`, `value3`, `value4` FROM `metadata` WHERE `key` = 'geofence' AND `deleted` = 0"); - database.execSQL("DELETE FROM `metadata` WHERE `key` = 'geofence'"); - } - }; - - private static final Migration MIGRATION_48_49 = new Migration(48, 49) { - @Override - public void migrate(@NonNull SupportSQLiteDatabase database) { - database.execSQL( - "CREATE TABLE IF NOT EXISTS `tags` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task` INTEGER NOT NULL, `name` TEXT, `tag_uid` TEXT, `task_uid` TEXT)"); - database.execSQL("INSERT INTO `tags` (`task`, `name`, `tag_uid`, `task_uid`) " + - "SELECT `task`, `value`, `value2`, `value3` FROM `metadata` WHERE `key` = 'tags-tag' AND `deleted` = 0"); - database.execSQL("DELETE FROM `metadata` WHERE `key` = 'tags-tag'"); - } - }; - - private static final Migration MIGRATION_49_50 = new Migration(49, 50) { - @Override - public void migrate(@NonNull SupportSQLiteDatabase database) { - database.execSQL( - "CREATE TABLE IF NOT EXISTS `google_tasks` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task` INTEGER NOT NULL, `remote_id` TEXT, `list_id` TEXT, `parent` INTEGER NOT NULL, `indent` INTEGER NOT NULL, `order` INTEGER NOT NULL, `remote_order` INTEGER NOT NULL, `last_sync` INTEGER NOT NULL, `deleted` INTEGER NOT NULL)"); - database.execSQL( - "INSERT INTO `google_tasks` (`task`, `remote_id`, `list_id`, `parent`, `indent`, `order`, `remote_order`, `last_sync`, `deleted`) " - + - "SELECT `task`, `value`, `value2`, IFNULL(`value3`, 0), IFNULL(`value4`, 0), IFNULL(`value5`, 0), IFNULL(`value6`, 0), IFNULL(`value7`, 0), IFNULL(`deleted`, 0) FROM `metadata` WHERE `key` = 'gtasks'"); - database.execSQL("DROP TABLE IF EXISTS `metadata`"); - } - }; - - private static final Migration MIGRATION_50_51 = new Migration(50, 51) { - @Override - public void migrate(@NonNull SupportSQLiteDatabase database) { - database.execSQL( - "CREATE TABLE IF NOT EXISTS `filters` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `title` TEXT, `sql` TEXT, `values` TEXT, `criterion` TEXT)"); - database.execSQL("INSERT INTO `filters` (`title`, `sql`, `values`, `criterion`) " + - "SELECT `item`, `value`, `value2`, `value3` FROM `store` WHERE `type` = 'filter' AND `deleted` = 0"); - database.execSQL("DELETE FROM `store` WHERE `type` = 'filter'"); - } - }; - - private static final Migration MIGRATION_51_52 = new Migration(51, 52) { - @Override - public void migrate(@NonNull SupportSQLiteDatabase database) { - database.execSQL( - "CREATE TABLE IF NOT EXISTS `google_task_lists` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `remote_id` TEXT, `title` TEXT, `remote_order` INTEGER NOT NULL, `last_sync` INTEGER NOT NULL, `deleted` INTEGER NOT NULL, `color` INTEGER)"); - database.execSQL( - "INSERT INTO `google_task_lists` (`remote_id`, `title`, `remote_order`, `last_sync`, `color`, `deleted`) " - + - "SELECT `item`, `value`, `value2`, `value3`, `value4`, `deleted` FROM `store` WHERE `type` = 'gtasks-list'"); - database.execSQL("DROP TABLE IF EXISTS `store`"); - } - }; - - private static final Migration MIGRATION_52_53 = new Migration(52, 53) { - @Override - public void migrate(@NonNull SupportSQLiteDatabase database) { - database.execSQL("ALTER TABLE `tagdata` RENAME TO `tagdata-temp`"); - database.execSQL( - "CREATE TABLE `tagdata` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT, `remoteId` TEXT, `name` TEXT, `color` INTEGER, `tagOrdering` TEXT)"); - database.execSQL("INSERT INTO `tagdata` (`remoteId`, `name`, `color`, `tagOrdering`) " + - "SELECT `remoteId`, `name`, `color`, `tagOrdering` FROM `tagdata-temp`"); - database.execSQL("DROP TABLE `tagdata-temp`"); - - database.execSQL("ALTER TABLE `userActivity` RENAME TO `userActivity-temp`"); - database.execSQL( - "CREATE TABLE `userActivity` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT, `remoteId` TEXT, `message` TEXT, `picture` TEXT, `target_id` TEXT, `created_at` INTEGER)"); - database.execSQL( - "INSERT INTO `userActivity` (`remoteId`, `message`, `picture`, `target_id`, `created_at`) " - + - "SELECT `remoteId`, `message`, `picture`, `target_id`, `created_at` FROM `userActivity-temp`"); - database.execSQL("DROP TABLE `userActivity-temp`"); - - database.execSQL("ALTER TABLE `task_attachments` RENAME TO `task_attachments-temp`"); - database.execSQL( - "CREATE TABLE `task_attachments` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT, `remoteId` TEXT, `task_id` TEXT, `name` TEXT, `path` TEXT, `content_type` TEXT)"); - database.execSQL( - "INSERT INTO `task_attachments` (`remoteId`, `task_id`, `name`, `path`, `content_type`) " - + - "SELECT `remoteId`, `task_id`, `name`, `path`, `content_type` FROM `task_attachments-temp`"); - database.execSQL("DROP TABLE `task_attachments-temp`"); - } - }; - - private static final Migration MIGRATION_53_54 = new Migration(53, 54) { - @Override - public void migrate(@NonNull SupportSQLiteDatabase database) { - // need to drop columns that were removed in the past - database.execSQL("ALTER TABLE `task_list_metadata` RENAME TO `task_list_metadata-temp`"); - database.execSQL( - "CREATE TABLE `task_list_metadata` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT, `remoteId` TEXT, `tag_uuid` TEXT, `filter` TEXT, `task_ids` TEXT)"); - database.execSQL( - "INSERT INTO `task_list_metadata` (`remoteId`, `tag_uuid`, `filter`, `task_ids`) " + - "SELECT `remoteId`, `tag_uuid`, `filter`, `task_ids` FROM `task_list_metadata-temp`"); - database.execSQL("DROP TABLE `task_list_metadata-temp`"); - - database.execSQL("ALTER TABLE `tasks` RENAME TO `tasks-temp`"); - database.execSQL( - "CREATE TABLE `tasks` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT, `title` TEXT, `importance` INTEGER, `dueDate` INTEGER, `hideUntil` INTEGER, `created` INTEGER, `modified` INTEGER, `completed` INTEGER, `deleted` INTEGER, `notes` TEXT, `estimatedSeconds` INTEGER, `elapsedSeconds` INTEGER, `timerStart` INTEGER, `notificationFlags` INTEGER, `notifications` INTEGER, `lastNotified` INTEGER, `snoozeTime` INTEGER, `recurrence` TEXT, `repeatUntil` INTEGER, `calendarUri` TEXT, `remoteId` TEXT)"); - database.execSQL("DROP INDEX `t_rid`"); - database.execSQL("CREATE UNIQUE INDEX `t_rid` ON `tasks` (`remoteId`)"); - database.execSQL( - "INSERT INTO `tasks` (`_id`, `title`, `importance`, `dueDate`, `hideUntil`, `created`, `modified`, `completed`, `deleted`, `notes`, `estimatedSeconds`, `elapsedSeconds`, `timerStart`, `notificationFlags`, `notifications`, `lastNotified`, `snoozeTime`, `recurrence`, `repeatUntil`, `calendarUri`, `remoteId`) " - + - "SELECT `_id`, `title`, `importance`, `dueDate`, `hideUntil`, `created`, `modified`, `completed`, `deleted`, `notes`, `estimatedSeconds`, `elapsedSeconds`, `timerStart`, `notificationFlags`, `notifications`, `lastNotified`, `snoozeTime`, `recurrence`, `repeatUntil`, `calendarUri`, `remoteId` FROM `tasks-temp`"); - database.execSQL("DROP TABLE `tasks-temp`"); - } - }; - - private static final Migration MIGRATION_54_55 = new Migration(54, 55) { - @Override - public void migrate(@NonNull SupportSQLiteDatabase database) { - database.execSQL( - "CREATE TABLE IF NOT EXISTS `caldav_account` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `uuid` TEXT, `name` TEXT, `color` INTEGER NOT NULL, `ctag` TEXT, `url` TEXT, `username` TEXT)"); - database.execSQL( - "CREATE TABLE IF NOT EXISTS `caldav_tasks` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task` INTEGER NOT NULL, `account` TEXT, `remote_id` TEXT, `etag` TEXT, `last_sync` INTEGER NOT NULL, `deleted` INTEGER NOT NULL)"); - } - }; - - private static final Migration MIGRATION_55_56 = new Migration(55, 56) { - @Override - public void migrate(@NonNull SupportSQLiteDatabase database) { - database.execSQL("ALTER TABLE `caldav_tasks` ADD COLUMN `object` TEXT"); - database.execSQL("ALTER TABLE `caldav_tasks` ADD COLUMN `vtodo` TEXT"); - } - }; - - private static final Migration MIGRATION_56_57 = new Migration(56, 57) { - @Override - public void migrate(@NonNull SupportSQLiteDatabase database) { - database.execSQL("ALTER TABLE `caldav_account` ADD COLUMN `password` TEXT"); - } - }; - - public static final Migration[] MIGRATIONS = new Migration[]{ - MIGRATION_35_36, - MIGRATION_36_37, - MIGRATION_37_38, - MIGRATION_38_39, - NOOP(39, 46), - MIGRATION_46_47, - MIGRATION_47_48, - MIGRATION_48_49, - MIGRATION_49_50, - MIGRATION_50_51, - MIGRATION_51_52, - MIGRATION_52_53, - MIGRATION_53_54, - MIGRATION_54_55, - MIGRATION_55_56, - MIGRATION_56_57 - }; + private static final Migration MIGRATION_35_36 = + new Migration(35, 36) { + @Override + public void migrate(@NonNull SupportSQLiteDatabase database) { + database.execSQL("ALTER TABLE `tagdata` ADD COLUMN `color` INTEGER DEFAULT -1"); + } + }; + + private static final Migration MIGRATION_36_37 = + new Migration(36, 37) { + @Override + public void migrate(@NonNull SupportSQLiteDatabase database) { + database.execSQL("ALTER TABLE `store` ADD COLUMN `deleted` INTEGER DEFAULT 0"); + } + }; + + private static final Migration MIGRATION_37_38 = + new Migration(37, 38) { + @Override + public void migrate(@NonNull SupportSQLiteDatabase database) { + try { + database.execSQL("ALTER TABLE `store` ADD COLUMN `value4` TEXT DEFAULT -1"); + } catch (SQLiteException e) { + Timber.w(e, e.getMessage()); + } + } + }; + + private static final Migration MIGRATION_38_39 = + new Migration(38, 39) { + @Override + public void migrate(@NonNull SupportSQLiteDatabase database) { + database.execSQL( + "CREATE TABLE IF NOT EXISTS `notification` (`uid` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task` INTEGER NOT NULL, `timestamp` INTEGER NOT NULL, `type` INTEGER NOT NULL)"); + database.execSQL( + "CREATE UNIQUE INDEX `index_notification_task` ON `notification` (`task`)"); + } + }; + + private static final Migration MIGRATION_46_47 = + new Migration(46, 47) { + @Override + public void migrate(@NonNull SupportSQLiteDatabase database) { + database.execSQL( + "CREATE TABLE IF NOT EXISTS `alarms` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task` INTEGER NOT NULL, `time` INTEGER NOT NULL)"); + database.execSQL( + "INSERT INTO `alarms` (`task`, `time`) SELECT `task`, `value` FROM `metadata` WHERE `key` = 'alarm' AND `deleted` = 0"); + database.execSQL("DELETE FROM `metadata` WHERE `key` = 'alarm'"); + } + }; + + private static final Migration MIGRATION_47_48 = + new Migration(47, 48) { + @Override + public void migrate(@NonNull SupportSQLiteDatabase database) { + database.execSQL( + "CREATE TABLE IF NOT EXISTS `locations` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task` INTEGER NOT NULL, `name` TEXT, `latitude` REAL NOT NULL, `longitude` REAL NOT NULL, `radius` INTEGER NOT NULL)"); + database.execSQL( + "INSERT INTO `locations` (`task`, `name`, `latitude`, `longitude`, `radius`) " + + "SELECT `task`, `value`, `value2`, `value3`, `value4` FROM `metadata` WHERE `key` = 'geofence' AND `deleted` = 0"); + database.execSQL("DELETE FROM `metadata` WHERE `key` = 'geofence'"); + } + }; + + private static final Migration MIGRATION_48_49 = + new Migration(48, 49) { + @Override + public void migrate(@NonNull SupportSQLiteDatabase database) { + database.execSQL( + "CREATE TABLE IF NOT EXISTS `tags` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task` INTEGER NOT NULL, `name` TEXT, `tag_uid` TEXT, `task_uid` TEXT)"); + database.execSQL( + "INSERT INTO `tags` (`task`, `name`, `tag_uid`, `task_uid`) " + + "SELECT `task`, `value`, `value2`, `value3` FROM `metadata` WHERE `key` = 'tags-tag' AND `deleted` = 0"); + database.execSQL("DELETE FROM `metadata` WHERE `key` = 'tags-tag'"); + } + }; + + private static final Migration MIGRATION_49_50 = + new Migration(49, 50) { + @Override + public void migrate(@NonNull SupportSQLiteDatabase database) { + database.execSQL( + "CREATE TABLE IF NOT EXISTS `google_tasks` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task` INTEGER NOT NULL, `remote_id` TEXT, `list_id` TEXT, `parent` INTEGER NOT NULL, `indent` INTEGER NOT NULL, `order` INTEGER NOT NULL, `remote_order` INTEGER NOT NULL, `last_sync` INTEGER NOT NULL, `deleted` INTEGER NOT NULL)"); + database.execSQL( + "INSERT INTO `google_tasks` (`task`, `remote_id`, `list_id`, `parent`, `indent`, `order`, `remote_order`, `last_sync`, `deleted`) " + + "SELECT `task`, `value`, `value2`, IFNULL(`value3`, 0), IFNULL(`value4`, 0), IFNULL(`value5`, 0), IFNULL(`value6`, 0), IFNULL(`value7`, 0), IFNULL(`deleted`, 0) FROM `metadata` WHERE `key` = 'gtasks'"); + database.execSQL("DROP TABLE IF EXISTS `metadata`"); + } + }; + + private static final Migration MIGRATION_50_51 = + new Migration(50, 51) { + @Override + public void migrate(@NonNull SupportSQLiteDatabase database) { + database.execSQL( + "CREATE TABLE IF NOT EXISTS `filters` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `title` TEXT, `sql` TEXT, `values` TEXT, `criterion` TEXT)"); + database.execSQL( + "INSERT INTO `filters` (`title`, `sql`, `values`, `criterion`) " + + "SELECT `item`, `value`, `value2`, `value3` FROM `store` WHERE `type` = 'filter' AND `deleted` = 0"); + database.execSQL("DELETE FROM `store` WHERE `type` = 'filter'"); + } + }; + + private static final Migration MIGRATION_51_52 = + new Migration(51, 52) { + @Override + public void migrate(@NonNull SupportSQLiteDatabase database) { + database.execSQL( + "CREATE TABLE IF NOT EXISTS `google_task_lists` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `remote_id` TEXT, `title` TEXT, `remote_order` INTEGER NOT NULL, `last_sync` INTEGER NOT NULL, `deleted` INTEGER NOT NULL, `color` INTEGER)"); + database.execSQL( + "INSERT INTO `google_task_lists` (`remote_id`, `title`, `remote_order`, `last_sync`, `color`, `deleted`) " + + "SELECT `item`, `value`, `value2`, `value3`, `value4`, `deleted` FROM `store` WHERE `type` = 'gtasks-list'"); + database.execSQL("DROP TABLE IF EXISTS `store`"); + } + }; + + private static final Migration MIGRATION_52_53 = + new Migration(52, 53) { + @Override + public void migrate(@NonNull SupportSQLiteDatabase database) { + database.execSQL("ALTER TABLE `tagdata` RENAME TO `tagdata-temp`"); + database.execSQL( + "CREATE TABLE `tagdata` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT, `remoteId` TEXT, `name` TEXT, `color` INTEGER, `tagOrdering` TEXT)"); + database.execSQL( + "INSERT INTO `tagdata` (`remoteId`, `name`, `color`, `tagOrdering`) " + + "SELECT `remoteId`, `name`, `color`, `tagOrdering` FROM `tagdata-temp`"); + database.execSQL("DROP TABLE `tagdata-temp`"); + + database.execSQL("ALTER TABLE `userActivity` RENAME TO `userActivity-temp`"); + database.execSQL( + "CREATE TABLE `userActivity` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT, `remoteId` TEXT, `message` TEXT, `picture` TEXT, `target_id` TEXT, `created_at` INTEGER)"); + database.execSQL( + "INSERT INTO `userActivity` (`remoteId`, `message`, `picture`, `target_id`, `created_at`) " + + "SELECT `remoteId`, `message`, `picture`, `target_id`, `created_at` FROM `userActivity-temp`"); + database.execSQL("DROP TABLE `userActivity-temp`"); + + database.execSQL("ALTER TABLE `task_attachments` RENAME TO `task_attachments-temp`"); + database.execSQL( + "CREATE TABLE `task_attachments` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT, `remoteId` TEXT, `task_id` TEXT, `name` TEXT, `path` TEXT, `content_type` TEXT)"); + database.execSQL( + "INSERT INTO `task_attachments` (`remoteId`, `task_id`, `name`, `path`, `content_type`) " + + "SELECT `remoteId`, `task_id`, `name`, `path`, `content_type` FROM `task_attachments-temp`"); + database.execSQL("DROP TABLE `task_attachments-temp`"); + } + }; + + private static final Migration MIGRATION_53_54 = + new Migration(53, 54) { + @Override + public void migrate(@NonNull SupportSQLiteDatabase database) { + // need to drop columns that were removed in the past + database.execSQL("ALTER TABLE `task_list_metadata` RENAME TO `task_list_metadata-temp`"); + database.execSQL( + "CREATE TABLE `task_list_metadata` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT, `remoteId` TEXT, `tag_uuid` TEXT, `filter` TEXT, `task_ids` TEXT)"); + database.execSQL( + "INSERT INTO `task_list_metadata` (`remoteId`, `tag_uuid`, `filter`, `task_ids`) " + + "SELECT `remoteId`, `tag_uuid`, `filter`, `task_ids` FROM `task_list_metadata-temp`"); + database.execSQL("DROP TABLE `task_list_metadata-temp`"); + + database.execSQL("ALTER TABLE `tasks` RENAME TO `tasks-temp`"); + database.execSQL( + "CREATE TABLE `tasks` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT, `title` TEXT, `importance` INTEGER, `dueDate` INTEGER, `hideUntil` INTEGER, `created` INTEGER, `modified` INTEGER, `completed` INTEGER, `deleted` INTEGER, `notes` TEXT, `estimatedSeconds` INTEGER, `elapsedSeconds` INTEGER, `timerStart` INTEGER, `notificationFlags` INTEGER, `notifications` INTEGER, `lastNotified` INTEGER, `snoozeTime` INTEGER, `recurrence` TEXT, `repeatUntil` INTEGER, `calendarUri` TEXT, `remoteId` TEXT)"); + database.execSQL("DROP INDEX `t_rid`"); + database.execSQL("CREATE UNIQUE INDEX `t_rid` ON `tasks` (`remoteId`)"); + database.execSQL( + "INSERT INTO `tasks` (`_id`, `title`, `importance`, `dueDate`, `hideUntil`, `created`, `modified`, `completed`, `deleted`, `notes`, `estimatedSeconds`, `elapsedSeconds`, `timerStart`, `notificationFlags`, `notifications`, `lastNotified`, `snoozeTime`, `recurrence`, `repeatUntil`, `calendarUri`, `remoteId`) " + + "SELECT `_id`, `title`, `importance`, `dueDate`, `hideUntil`, `created`, `modified`, `completed`, `deleted`, `notes`, `estimatedSeconds`, `elapsedSeconds`, `timerStart`, `notificationFlags`, `notifications`, `lastNotified`, `snoozeTime`, `recurrence`, `repeatUntil`, `calendarUri`, `remoteId` FROM `tasks-temp`"); + database.execSQL("DROP TABLE `tasks-temp`"); + } + }; + + private static final Migration MIGRATION_54_55 = + new Migration(54, 55) { + @Override + public void migrate(@NonNull SupportSQLiteDatabase database) { + database.execSQL( + "CREATE TABLE IF NOT EXISTS `caldav_account` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `uuid` TEXT, `name` TEXT, `color` INTEGER NOT NULL, `ctag` TEXT, `url` TEXT, `username` TEXT)"); + database.execSQL( + "CREATE TABLE IF NOT EXISTS `caldav_tasks` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task` INTEGER NOT NULL, `account` TEXT, `remote_id` TEXT, `etag` TEXT, `last_sync` INTEGER NOT NULL, `deleted` INTEGER NOT NULL)"); + } + }; + + private static final Migration MIGRATION_55_56 = + new Migration(55, 56) { + @Override + public void migrate(@NonNull SupportSQLiteDatabase database) { + database.execSQL("ALTER TABLE `caldav_tasks` ADD COLUMN `object` TEXT"); + database.execSQL("ALTER TABLE `caldav_tasks` ADD COLUMN `vtodo` TEXT"); + } + }; + + private static final Migration MIGRATION_56_57 = + new Migration(56, 57) { + @Override + public void migrate(@NonNull SupportSQLiteDatabase database) { + database.execSQL("ALTER TABLE `caldav_account` ADD COLUMN `password` TEXT"); + } + }; + + public static final Migration[] MIGRATIONS = + new Migration[] { + MIGRATION_35_36, + MIGRATION_36_37, + MIGRATION_37_38, + MIGRATION_38_39, + NOOP(39, 46), + MIGRATION_46_47, + MIGRATION_47_48, + MIGRATION_48_49, + MIGRATION_49_50, + MIGRATION_50_51, + MIGRATION_51_52, + MIGRATION_52_53, + MIGRATION_53_54, + MIGRATION_54_55, + MIGRATION_55_56, + MIGRATION_56_57 + }; private static Migration NOOP(int from, int to) { return new Migration(from, to) { @Override - public void migrate(@NonNull SupportSQLiteDatabase database) { - - } + public void migrate(@NonNull SupportSQLiteDatabase database) {} }; } } diff --git a/app/src/main/java/org/tasks/dialogs/AddAttachmentDialog.java b/app/src/main/java/org/tasks/dialogs/AddAttachmentDialog.java index 1c479b8d2..80c93699f 100644 --- a/app/src/main/java/org/tasks/dialogs/AddAttachmentDialog.java +++ b/app/src/main/java/org/tasks/dialogs/AddAttachmentDialog.java @@ -42,7 +42,8 @@ public class AddAttachmentDialog extends InjectingDialogFragment { } entries.add(getString(R.string.pick_from_storage)); actions.add(() -> callback.pickFromStorage()); - return dialogBuilder.newDialog() + return dialogBuilder + .newDialog() .setItems(entries, (dialog, which) -> actions.get(which).run()) .show(); } diff --git a/app/src/main/java/org/tasks/dialogs/AlertDialogBuilder.java b/app/src/main/java/org/tasks/dialogs/AlertDialogBuilder.java index 70ac57bd8..4f67924e8 100644 --- a/app/src/main/java/org/tasks/dialogs/AlertDialogBuilder.java +++ b/app/src/main/java/org/tasks/dialogs/AlertDialogBuilder.java @@ -42,14 +42,14 @@ public class AlertDialogBuilder { return this; } - public AlertDialogBuilder setPositiveButton(int ok, - DialogInterface.OnClickListener onClickListener) { + public AlertDialogBuilder setPositiveButton( + int ok, DialogInterface.OnClickListener onClickListener) { builder.setPositiveButton(ok, onClickListener); return this; } - public AlertDialogBuilder setNegativeButton(int cancel, - DialogInterface.OnClickListener onClickListener) { + public AlertDialogBuilder setNegativeButton( + int cancel, DialogInterface.OnClickListener onClickListener) { builder.setNegativeButton(cancel, onClickListener); return this; } @@ -59,13 +59,13 @@ public class AlertDialogBuilder { return this; } - public AlertDialogBuilder setItems(List strings, - DialogInterface.OnClickListener onClickListener) { + public AlertDialogBuilder setItems( + List strings, DialogInterface.OnClickListener onClickListener) { return setItems(strings.toArray(new String[strings.size()]), onClickListener); } - public AlertDialogBuilder setItems(String[] strings, - DialogInterface.OnClickListener onClickListener) { + public AlertDialogBuilder setItems( + String[] strings, DialogInterface.OnClickListener onClickListener) { builder.setItems(addDirectionality(strings.clone()), onClickListener); return this; } @@ -80,10 +80,12 @@ public class AlertDialogBuilder { return this; } - public AlertDialogBuilder setSingleChoiceItems(List strings, int selectedIndex, - DialogInterface.OnClickListener onClickListener) { - builder.setSingleChoiceItems(addDirectionality(strings.toArray(new String[strings.size()])), - selectedIndex, onClickListener); + public AlertDialogBuilder setSingleChoiceItems( + List strings, int selectedIndex, DialogInterface.OnClickListener onClickListener) { + builder.setSingleChoiceItems( + addDirectionality(strings.toArray(new String[strings.size()])), + selectedIndex, + onClickListener); return this; } @@ -100,14 +102,14 @@ public class AlertDialogBuilder { return locale.getDirectionalityMark() + string; } - public AlertDialogBuilder setSingleChoiceItems(ListAdapter adapter, int selectedIndex, - DialogInterface.OnClickListener onClickListener) { + public AlertDialogBuilder setSingleChoiceItems( + ListAdapter adapter, int selectedIndex, DialogInterface.OnClickListener onClickListener) { builder.setSingleChoiceItems(adapter, selectedIndex, onClickListener); return this; } - public AlertDialogBuilder setNeutralButton(int reverse, - DialogInterface.OnClickListener onClickListener) { + public AlertDialogBuilder setNeutralButton( + int reverse, DialogInterface.OnClickListener onClickListener) { builder.setNeutralButton(reverse, onClickListener); return this; } diff --git a/app/src/main/java/org/tasks/dialogs/ColorPickerDialog.java b/app/src/main/java/org/tasks/dialogs/ColorPickerDialog.java index abf144e7b..df3fd4755 100644 --- a/app/src/main/java/org/tasks/dialogs/ColorPickerDialog.java +++ b/app/src/main/java/org/tasks/dialogs/ColorPickerDialog.java @@ -34,8 +34,8 @@ public class ColorPickerDialog extends InjectingDialogFragment { private SingleCheckedArrayAdapter adapter; private Dialog dialog; - public static ColorPickerDialog newColorPickerDialog(List items, - boolean showNone, int selection) { + public static ColorPickerDialog newColorPickerDialog( + List items, boolean showNone, int selection) { ColorPickerDialog dialog = new ColorPickerDialog(); Bundle args = new Bundle(); args.putParcelableArrayList(EXTRA_ITEMS, new ArrayList(items)); @@ -54,31 +54,38 @@ public class ColorPickerDialog extends InjectingDialogFragment { boolean showNone = arguments.getBoolean(EXTRA_SHOW_NONE); int selected = arguments.getInt(EXTRA_SELECTED, -1); - adapter = new SingleCheckedArrayAdapter(context, transform(items, Pickable::getName), - theme.getThemeAccent()) { - @Override - protected int getDrawable(int position) { - return preferences.hasPurchase(R.string.p_purchased_themes) || items.get(position).isFree() - ? R.drawable.ic_lens_black_24dp - : R.drawable.ic_vpn_key_black_24dp; - } - - @Override - protected int getDrawableColor(int position) { - return items.get(position).getPickerColor(); - } - }; - - AlertDialogBuilder builder = dialogBuilder.newDialog(theme) - .setSingleChoiceItems(adapter, selected, (dialog, which) -> { - Pickable picked = items.get(which); - if (preferences.hasPurchase(R.string.p_purchased_themes) || picked.isFree()) { - callback.themePicked(picked); - } else { - callback.initiateThemePurchase(); + adapter = + new SingleCheckedArrayAdapter( + context, transform(items, Pickable::getName), theme.getThemeAccent()) { + @Override + protected int getDrawable(int position) { + return preferences.hasPurchase(R.string.p_purchased_themes) + || items.get(position).isFree() + ? R.drawable.ic_lens_black_24dp + : R.drawable.ic_vpn_key_black_24dp; } - }) - .setOnDismissListener(dialogInterface -> callback.dismissed()); + + @Override + protected int getDrawableColor(int position) { + return items.get(position).getPickerColor(); + } + }; + + AlertDialogBuilder builder = + dialogBuilder + .newDialog(theme) + .setSingleChoiceItems( + adapter, + selected, + (dialog, which) -> { + Pickable picked = items.get(which); + if (preferences.hasPurchase(R.string.p_purchased_themes) || picked.isFree()) { + callback.themePicked(picked); + } else { + callback.initiateThemePurchase(); + } + }) + .setOnDismissListener(dialogInterface -> callback.dismissed()); if (showNone) { builder.setNeutralButton(R.string.none, (dialogInterface, i) -> callback.themePicked(null)); } diff --git a/app/src/main/java/org/tasks/dialogs/DialogBuilder.java b/app/src/main/java/org/tasks/dialogs/DialogBuilder.java index 955300abb..40b153afd 100644 --- a/app/src/main/java/org/tasks/dialogs/DialogBuilder.java +++ b/app/src/main/java/org/tasks/dialogs/DialogBuilder.java @@ -34,12 +34,12 @@ public class DialogBuilder { } public ProgressDialog newProgressDialog() { - ProgressDialog progressDialog = new ProgressDialog(activity, - theme.getThemeBase().getAlertDialogStyle()); + ProgressDialog progressDialog = + new ProgressDialog(activity, theme.getThemeBase().getAlertDialogStyle()); theme.applyToContext(progressDialog.getContext()); if (AndroidUtilities.preLollipop()) { - ColorDrawable background = new ColorDrawable( - activity.getResources().getColor(android.R.color.transparent)); + ColorDrawable background = + new ColorDrawable(activity.getResources().getColor(android.R.color.transparent)); progressDialog.getWindow().setBackgroundDrawable(background); } return progressDialog; diff --git a/app/src/main/java/org/tasks/dialogs/DonationDialog.java b/app/src/main/java/org/tasks/dialogs/DonationDialog.java index 44c071279..da5332b33 100644 --- a/app/src/main/java/org/tasks/dialogs/DonationDialog.java +++ b/app/src/main/java/org/tasks/dialogs/DonationDialog.java @@ -25,19 +25,27 @@ public class DonationDialog extends InjectingNativeDialogFragment { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final List donationValues = getDonationValues(); - return dialogBuilder.newDialog() + return dialogBuilder + .newDialog() .setTitle(R.string.select_amount) - .setItems(donationValues, (dialog, which) -> { - String value = donationValues.get(which); - Pattern pattern = Pattern.compile("\\$(\\d+) USD"); - Matcher matcher = pattern.matcher(value); - //noinspection ResultOfMethodCallIgnored - matcher.matches(); - String sku = String - .format(java.util.Locale.ENGLISH, "%03d", Integer.parseInt(matcher.group(1))); - purchaseHelper.purchase(getActivity(), sku, null, BasicPreferences.REQUEST_PURCHASE, - (BasicPreferences) getActivity()); - }) + .setItems( + donationValues, + (dialog, which) -> { + String value = donationValues.get(which); + Pattern pattern = Pattern.compile("\\$(\\d+) USD"); + Matcher matcher = pattern.matcher(value); + //noinspection ResultOfMethodCallIgnored + matcher.matches(); + String sku = + String.format( + java.util.Locale.ENGLISH, "%03d", Integer.parseInt(matcher.group(1))); + purchaseHelper.purchase( + getActivity(), + sku, + null, + BasicPreferences.REQUEST_PURCHASE, + (BasicPreferences) getActivity()); + }) .setNegativeButton(android.R.string.cancel, null) .show(); } diff --git a/app/src/main/java/org/tasks/dialogs/ExportTasksDialog.java b/app/src/main/java/org/tasks/dialogs/ExportTasksDialog.java index dced4f8dd..a32e407bc 100644 --- a/app/src/main/java/org/tasks/dialogs/ExportTasksDialog.java +++ b/app/src/main/java/org/tasks/dialogs/ExportTasksDialog.java @@ -32,8 +32,8 @@ public class ExportTasksDialog extends InjectingNativeDialogFragment { progressDialog.show(); setCancelable(false); - tasksJsonExporter.exportTasks(getActivity(), TasksJsonExporter.ExportType.EXPORT_TYPE_MANUAL, - progressDialog); + tasksJsonExporter.exportTasks( + getActivity(), TasksJsonExporter.ExportType.EXPORT_TYPE_MANUAL, progressDialog); tracker.reportEvent(Tracking.Events.EXPORT); return progressDialog; } diff --git a/app/src/main/java/org/tasks/dialogs/NativeDatePickerDialog.java b/app/src/main/java/org/tasks/dialogs/NativeDatePickerDialog.java index a1ef8efcb..a6300c79d 100644 --- a/app/src/main/java/org/tasks/dialogs/NativeDatePickerDialog.java +++ b/app/src/main/java/org/tasks/dialogs/NativeDatePickerDialog.java @@ -16,8 +16,8 @@ import org.tasks.preferences.Preferences; import org.tasks.themes.Theme; import org.tasks.time.DateTime; -public class NativeDatePickerDialog extends InjectingNativeDialogFragment implements - DatePickerDialog.OnDateSetListener { +public class NativeDatePickerDialog extends InjectingNativeDialogFragment + implements DatePickerDialog.OnDateSetListener { private static final String EXTRA_YEAR = "extra_year"; private static final String EXTRA_MONTH = "extra_month"; @@ -47,8 +47,13 @@ public class NativeDatePickerDialog extends InjectingNativeDialogFragment implem @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Bundle args = getArguments(); - DatePickerDialog datePickerDialog = new DatePickerDialog(theme.wrap(getActivity()), this, - args.getInt(EXTRA_YEAR), args.getInt(EXTRA_MONTH), args.getInt(EXTRA_DAY)); + DatePickerDialog datePickerDialog = + new DatePickerDialog( + theme.wrap(getActivity()), + this, + args.getInt(EXTRA_YEAR), + args.getInt(EXTRA_MONTH), + args.getInt(EXTRA_DAY)); int firstDayOfWeek = preferences.getFirstDayOfWeek(); if (firstDayOfWeek >= 1 && firstDayOfWeek <= 7 && atLeastMarshmallow()) { datePickerDialog.getDatePicker().setFirstDayOfWeek(firstDayOfWeek); diff --git a/app/src/main/java/org/tasks/dialogs/NativeTimePickerDialog.java b/app/src/main/java/org/tasks/dialogs/NativeTimePickerDialog.java index e2deb2cf2..e8db2d077 100644 --- a/app/src/main/java/org/tasks/dialogs/NativeTimePickerDialog.java +++ b/app/src/main/java/org/tasks/dialogs/NativeTimePickerDialog.java @@ -14,8 +14,8 @@ import org.tasks.injection.NativeDialogFragmentComponent; import org.tasks.themes.Theme; import org.tasks.time.DateTime; -public class NativeTimePickerDialog extends InjectingNativeDialogFragment implements - TimePickerDialog.OnTimeSetListener { +public class NativeTimePickerDialog extends InjectingNativeDialogFragment + implements TimePickerDialog.OnTimeSetListener { private static final String EXTRA_HOUR = "extra_hour"; private static final String EXTRA_MINUTE = "extra_minute"; @@ -42,8 +42,13 @@ public class NativeTimePickerDialog extends InjectingNativeDialogFragment implem public Dialog onCreateDialog(Bundle savedInstanceState) { Context context = theme.wrap(getActivity()); Bundle args = getArguments(); - TimePickerDialog timePickerDialog = new TimePickerDialog(context, this, args.getInt(EXTRA_HOUR), - args.getInt(EXTRA_MINUTE), DateUtilities.is24HourFormat(context)); + TimePickerDialog timePickerDialog = + new TimePickerDialog( + context, + this, + args.getInt(EXTRA_HOUR), + args.getInt(EXTRA_MINUTE), + DateUtilities.is24HourFormat(context)); timePickerDialog.setTitle(""); return timePickerDialog; } diff --git a/app/src/main/java/org/tasks/dialogs/RecordAudioDialog.java b/app/src/main/java/org/tasks/dialogs/RecordAudioDialog.java index e6f0eff62..8c1be32d3 100644 --- a/app/src/main/java/org/tasks/dialogs/RecordAudioDialog.java +++ b/app/src/main/java/org/tasks/dialogs/RecordAudioDialog.java @@ -19,14 +19,17 @@ import org.tasks.injection.InjectingDialogFragment; import org.tasks.preferences.Preferences; import org.tasks.themes.Theme; -public class RecordAudioDialog extends InjectingDialogFragment implements - AACRecorder.AACRecorderCallbacks { +public class RecordAudioDialog extends InjectingDialogFragment + implements AACRecorder.AACRecorderCallbacks { private final AtomicReference nameRef = new AtomicReference<>(); @Inject Preferences preferences; @Inject DialogBuilder dialogBuilder; @Inject Theme theme; - @BindView(R.id.timer) Chronometer timer; + + @BindView(R.id.timer) + Chronometer timer; + private AACRecorder recorder; private String tempFile; private RecordAudioDialogCallback callback; @@ -44,7 +47,8 @@ public class RecordAudioDialog extends InjectingDialogFragment implements startRecording(); - return dialogBuilder.newDialog() + return dialogBuilder + .newDialog() .setTitle(R.string.audio_recording_title) .setView(view) .create(); diff --git a/app/src/main/java/org/tasks/dialogs/SeekBarDialog.java b/app/src/main/java/org/tasks/dialogs/SeekBarDialog.java index 7bdc8409b..b6b2d93e3 100644 --- a/app/src/main/java/org/tasks/dialogs/SeekBarDialog.java +++ b/app/src/main/java/org/tasks/dialogs/SeekBarDialog.java @@ -24,9 +24,16 @@ public class SeekBarDialog extends InjectingNativeDialogFragment { private static final String EXTRA_MIN = "extra_min"; private static final String EXTRA_MAX = "extra_max"; private static final String EXTRA_REQUEST_CODE = "extra_request_code"; - @BindView(R.id.slider) Slider slider; - @BindView(R.id.min) TextView min; - @BindView(R.id.max) TextView max; + + @BindView(R.id.slider) + Slider slider; + + @BindView(R.id.min) + TextView min; + + @BindView(R.id.max) + TextView max; + @Inject DialogBuilder dialogBuilder; @Inject Theme theme; @Inject Locale locale; @@ -34,8 +41,8 @@ public class SeekBarDialog extends InjectingNativeDialogFragment { private int requestCode; private SeekBarCallback callback; - public static SeekBarDialog newSeekBarDialog(int layout, int min, int max, int initial, - int requestCode) { + public static SeekBarDialog newSeekBarDialog( + int layout, int min, int max, int initial, int requestCode) { SeekBarDialog dialog = new SeekBarDialog(); Bundle args = new Bundle(); args.putInt(EXTRA_LAYOUT, layout); @@ -66,9 +73,11 @@ public class SeekBarDialog extends InjectingNativeDialogFragment { slider.setValueRange(arguments.getInt(EXTRA_MIN), arguments.getInt(EXTRA_MAX), false); min.setText(locale.formatNumber(slider.getMinValue())); max.setText(locale.formatNumber(slider.getMaxValue())); - return dialogBuilder.newDialog() + return dialogBuilder + .newDialog() .setView(view) - .setPositiveButton(android.R.string.ok, + .setPositiveButton( + android.R.string.ok, (dialogInterface, i) -> callback.valueSelected(slider.getValue(), requestCode)) .setNegativeButton(android.R.string.cancel, null) .show(); diff --git a/app/src/main/java/org/tasks/dialogs/SortDialog.java b/app/src/main/java/org/tasks/dialogs/SortDialog.java index c0f407abc..7fb1b5c49 100644 --- a/app/src/main/java/org/tasks/dialogs/SortDialog.java +++ b/app/src/main/java/org/tasks/dialogs/SortDialog.java @@ -69,15 +69,20 @@ public class SortDialog extends InjectingDialogFragment { selectedIndex -= 1; } - alertDialog = dialogBuilder.newDialog() - .setSingleChoiceItems(items, selectedIndex, (dialog, which) -> { - selectedIndex = which; - enableReverse(); - }) - .setPositiveButton(R.string.TLA_menu_sort, (dialog, which) -> setSelection(false)) - .setNeutralButton(R.string.reverse, (dialog, which) -> setSelection(true)) - .setNegativeButton(android.R.string.cancel, null) - .showThemedListView(); + alertDialog = + dialogBuilder + .newDialog() + .setSingleChoiceItems( + items, + selectedIndex, + (dialog, which) -> { + selectedIndex = which; + enableReverse(); + }) + .setPositiveButton(R.string.TLA_menu_sort, (dialog, which) -> setSelection(false)) + .setNeutralButton(R.string.reverse, (dialog, which) -> setSelection(true)) + .setNegativeButton(android.R.string.cancel, null) + .showThemedListView(); enableReverse(); diff --git a/app/src/main/java/org/tasks/files/FileExplore.java b/app/src/main/java/org/tasks/files/FileExplore.java index 39c3f02c3..3b5e83222 100644 --- a/app/src/main/java/org/tasks/files/FileExplore.java +++ b/app/src/main/java/org/tasks/files/FileExplore.java @@ -19,10 +19,10 @@ import org.tasks.preferences.PermissionRequestor; public class FileExplore extends InjectingAppCompatActivity { - public static final String EXTRA_FILE = "extra_file"; //$NON-NLS-1$ - public static final String EXTRA_DIRECTORY = "extra_directory"; //$NON-NLS-1$ + public static final String EXTRA_FILE = "extra_file"; // $NON-NLS-1$ + public static final String EXTRA_DIRECTORY = "extra_directory"; // $NON-NLS-1$ public static final String EXTRA_START_PATH = "extra_start_path"; - public static final String EXTRA_DIRECTORY_MODE = "extra_directory_mode"; //$NON-NLS-1$ + public static final String EXTRA_DIRECTORY_MODE = "extra_directory_mode"; // $NON-NLS-1$ private static final int REQUEST_PICKER = 1000; @Inject ActivityPermissionRequestor permissionRequestor; @@ -72,8 +72,8 @@ public class FileExplore extends InjectingAppCompatActivity { } @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, - @NonNull int[] grantResults) { + public void onRequestPermissionsResult( + int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == PermissionRequestor.REQUEST_FILE_WRITE) { if (verifyPermissions(grantResults)) { launchPicker(); diff --git a/app/src/main/java/org/tasks/files/FileHelper.java b/app/src/main/java/org/tasks/files/FileHelper.java index bebf81ee9..3eb372007 100644 --- a/app/src/main/java/org/tasks/files/FileHelper.java +++ b/app/src/main/java/org/tasks/files/FileHelper.java @@ -22,8 +22,7 @@ public class FileHelper { Cursor cursor = activity.managedQuery(uri, projection, null, null, null); if (cursor != null) { - int column_index = cursor - .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); + int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } else { @@ -33,8 +32,8 @@ public class FileHelper { public static Intent getReadableActionView(Context context, String path, String type) { Intent intent = new Intent(Intent.ACTION_VIEW); - Uri uri = FileProvider - .getUriForFile(context, Constants.FILE_PROVIDER_AUTHORITY, new File(path)); + Uri uri = + FileProvider.getUriForFile(context, Constants.FILE_PROVIDER_AUTHORITY, new File(path)); intent.setDataAndType(uri, type); grantReadPermissions(context, intent, uri); return intent; @@ -47,13 +46,13 @@ public class FileHelper { if (atLeastLollipop()) { intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); } else { - List resolveInfoList = context.getPackageManager() - .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); + List resolveInfoList = + context + .getPackageManager() + .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo resolveInfo : resolveInfoList) { context.grantUriPermission( - resolveInfo.activityInfo.packageName, - uri, - Intent.FLAG_GRANT_READ_URI_PERMISSION); + resolveInfo.activityInfo.packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION); } } } diff --git a/app/src/main/java/org/tasks/files/ImageHelper.java b/app/src/main/java/org/tasks/files/ImageHelper.java index 30758fba3..462badc2b 100644 --- a/app/src/main/java/org/tasks/files/ImageHelper.java +++ b/app/src/main/java/org/tasks/files/ImageHelper.java @@ -5,8 +5,8 @@ import android.graphics.BitmapFactory; public class ImageHelper { - private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, - int reqHeight) { + private static int calculateInSampleSize( + BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; @@ -19,8 +19,7 @@ public class ImageHelper { // Calculate the largest inSampleSize value that is a power of 2 and keeps both // height and width larger than the requested height and width. - while ((halfHeight / inSampleSize) > reqHeight - && (halfWidth / inSampleSize) > reqWidth) { + while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) { inSampleSize *= 2; } } diff --git a/app/src/main/java/org/tasks/filters/FilterCounter.java b/app/src/main/java/org/tasks/filters/FilterCounter.java index 347194cf3..855cc3c85 100644 --- a/app/src/main/java/org/tasks/filters/FilterCounter.java +++ b/app/src/main/java/org/tasks/filters/FilterCounter.java @@ -13,12 +13,18 @@ import javax.inject.Inject; public class FilterCounter { - // Previous solution involved a queue of filters and a filterSizeLoadingThread. The filterSizeLoadingThread had - // a few problems: how to make sure that the thread is resumed when the controlling activity is resumed, and - // how to make sure that the the filterQueue does not accumulate filters without being processed. I am replacing - // both the queue and a the thread with a thread pool, which will shut itself off after a second if it has - // nothing to do (corePoolSize == 0, which makes it available for garbage collection), and will wake itself up - // if new filters are queued (obviously it cannot be garbage collected if it is possible for new filters to + // Previous solution involved a queue of filters and a filterSizeLoadingThread. The + // filterSizeLoadingThread had + // a few problems: how to make sure that the thread is resumed when the controlling activity is + // resumed, and + // how to make sure that the the filterQueue does not accumulate filters without being processed. + // I am replacing + // both the queue and a the thread with a thread pool, which will shut itself off after a second + // if it has + // nothing to do (corePoolSize == 0, which makes it available for garbage collection), and will + // wake itself up + // if new filters are queued (obviously it cannot be garbage collected if it is possible for new + // filters to // be added). private final ExecutorService executorService; @@ -37,15 +43,16 @@ public class FilterCounter { } public void refreshFilterCounts(final Runnable onComplete) { - executorService.submit(() -> { - for (Filter filter : filterCounts.keySet()) { - int size = taskDao.count(filter); - filterCounts.put(filter, size); - } - if (onComplete != null) { - onComplete.run(); - } - }); + executorService.submit( + () -> { + for (Filter filter : filterCounts.keySet()) { + int size = taskDao.count(filter); + filterCounts.put(filter, size); + } + if (onComplete != null) { + onComplete.run(); + } + }); } public void registerFilter(Filter filter) { @@ -61,5 +68,4 @@ public class FilterCounter { public Integer get(FilterListItem filter) { return filterCounts.get(filter); } - } diff --git a/app/src/main/java/org/tasks/filters/FilterCriteriaProvider.java b/app/src/main/java/org/tasks/filters/FilterCriteriaProvider.java index 536f0ba99..b070b4d0c 100644 --- a/app/src/main/java/org/tasks/filters/FilterCriteriaProvider.java +++ b/app/src/main/java/org/tasks/filters/FilterCriteriaProvider.java @@ -32,12 +32,12 @@ import org.tasks.sync.SyncAdapters; public class FilterCriteriaProvider { - private static final String IDENTIFIER_TITLE = "title"; //$NON-NLS-1$ - private static final String IDENTIFIER_IMPORTANCE = "importance"; //$NON-NLS-1$ - private static final String IDENTIFIER_DUEDATE = "dueDate"; //$NON-NLS-1$ - private static final String IDENTIFIER_GTASKS = "gtaskslist"; //$NON-NLS-1$ - private static final String IDENTIFIER_TAG_IS = "tag_is"; //$NON-NLS-1$ - private static final String IDENTIFIER_TAG_CONTAINS = "tag_contains"; //$NON-NLS-1$ + private static final String IDENTIFIER_TITLE = "title"; // $NON-NLS-1$ + private static final String IDENTIFIER_IMPORTANCE = "importance"; // $NON-NLS-1$ + private static final String IDENTIFIER_DUEDATE = "dueDate"; // $NON-NLS-1$ + private static final String IDENTIFIER_GTASKS = "gtaskslist"; // $NON-NLS-1$ + private static final String IDENTIFIER_TAG_IS = "tag_is"; // $NON-NLS-1$ + private static final String IDENTIFIER_TAG_CONTAINS = "tag_contains"; // $NON-NLS-1$ private final Context context; private final TagService tagService; @@ -46,8 +46,11 @@ public class FilterCriteriaProvider { private final SyncAdapters syncAdapters; @Inject - public FilterCriteriaProvider(@ForApplication Context context, TagService tagService, - GtasksListService gtasksListService, SyncAdapters syncAdapters) { + public FilterCriteriaProvider( + @ForApplication Context context, + TagService tagService, + GtasksListService gtasksListService, + SyncAdapters syncAdapters) { this.context = context; this.tagService = tagService; this.gtasksListService = gtasksListService; @@ -73,19 +76,23 @@ public class FilterCriteriaProvider { private CustomFilterCriterion getTagFilter() { // TODO: adding to hash set because duplicate tag name bug hasn't been fixed yet - List tags = newArrayList( - newLinkedHashSet(transform(tagService.getTagList(), TagData::getName))); + List tags = + newArrayList(newLinkedHashSet(transform(tagService.getTagList(), TagData::getName))); String[] tagNames = tags.toArray(new String[tags.size()]); Map values = new HashMap<>(); values.put(Tag.KEY, "?"); return new MultipleSelectCriterion( IDENTIFIER_TAG_IS, context.getString(R.string.CFC_tag_text), - Query.select(Field.field("task")).from(Tag.TABLE).join(Join.inner( - Task.TABLE, Field.field("task").eq(Task.ID))).where(Criterion.and( - TaskDao.TaskCriteria.activeAndVisible(), - Field.field("name").eq("?"))).toString(), - values, tagNames, tagNames, + Query.select(Field.field("task")) + .from(Tag.TABLE) + .join(Join.inner(Task.TABLE, Field.field("task").eq(Task.ID))) + .where( + Criterion.and(TaskDao.TaskCriteria.activeAndVisible(), Field.field("name").eq("?"))) + .toString(), + values, + tagNames, + tagNames, null, context.getString(R.string.CFC_tag_name)); } @@ -94,62 +101,72 @@ public class FilterCriteriaProvider { return new TextInputCriterion( IDENTIFIER_TAG_CONTAINS, context.getString(R.string.CFC_tag_contains_text), - Query.select(Field.field("task")).from(Tag.TABLE).join(Join.inner( - Task.TABLE, Field.field("task").eq(Task.ID))).where(Criterion.and( - TaskDao.TaskCriteria.activeAndVisible(), - Field.field("name").like("%?%"))).toString(), - context.getString(R.string.CFC_tag_contains_name), "", + Query.select(Field.field("task")) + .from(Tag.TABLE) + .join(Join.inner(Task.TABLE, Field.field("task").eq(Task.ID))) + .where( + Criterion.and( + TaskDao.TaskCriteria.activeAndVisible(), Field.field("name").like("%?%"))) + .toString(), + context.getString(R.string.CFC_tag_contains_name), + "", null, context.getString(R.string.CFC_tag_contains_name)); } private CustomFilterCriterion getDueDateFilter() { - String[] entryValues = new String[]{ - "0", - PermaSql.VALUE_EOD_YESTERDAY, - PermaSql.VALUE_EOD, - PermaSql.VALUE_EOD_TOMORROW, - PermaSql.VALUE_EOD_DAY_AFTER, - PermaSql.VALUE_EOD_NEXT_WEEK, - PermaSql.VALUE_EOD_NEXT_MONTH, - }; + String[] entryValues = + new String[] { + "0", + PermaSql.VALUE_EOD_YESTERDAY, + PermaSql.VALUE_EOD, + PermaSql.VALUE_EOD_TOMORROW, + PermaSql.VALUE_EOD_DAY_AFTER, + PermaSql.VALUE_EOD_NEXT_WEEK, + PermaSql.VALUE_EOD_NEXT_MONTH, + }; Map values = new HashMap<>(); values.put(Task.DUE_DATE.name, "?"); return new MultipleSelectCriterion( IDENTIFIER_DUEDATE, r.getString(R.string.CFC_dueBefore_text), - Query.select(Task.ID).from(Task.TABLE).where( - Criterion.and( - TaskDao.TaskCriteria.activeAndVisible(), - Criterion.or( - Field.field("?").eq(0), - Task.DUE_DATE.gt(0)), - Task.DUE_DATE.lte("?"))).toString(), - values, r.getStringArray(R.array.CFC_dueBefore_entries), - entryValues, null, + Query.select(Task.ID) + .from(Task.TABLE) + .where( + Criterion.and( + TaskDao.TaskCriteria.activeAndVisible(), + Criterion.or(Field.field("?").eq(0), Task.DUE_DATE.gt(0)), + Task.DUE_DATE.lte("?"))) + .toString(), + values, + r.getStringArray(R.array.CFC_dueBefore_entries), + entryValues, + null, r.getString(R.string.CFC_dueBefore_name)); } private CustomFilterCriterion getImportanceFilter() { - 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" - }; + 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"}; Map values = new HashMap<>(); values.put(Task.IMPORTANCE.name, "?"); return new MultipleSelectCriterion( IDENTIFIER_IMPORTANCE, r.getString(R.string.CFC_importance_text), - Query.select(Task.ID).from(Task.TABLE).where( - Criterion.and(TaskDao.TaskCriteria.activeAndVisible(), - Task.IMPORTANCE.lte("?"))).toString(), - values, entries, - entryValues, null, + Query.select(Task.ID) + .from(Task.TABLE) + .where(Criterion.and(TaskDao.TaskCriteria.activeAndVisible(), Task.IMPORTANCE.lte("?"))) + .toString(), + values, + entries, + entryValues, + null, r.getString(R.string.CFC_importance_name)); } @@ -157,10 +174,12 @@ public class FilterCriteriaProvider { return new TextInputCriterion( IDENTIFIER_TITLE, r.getString(R.string.CFC_title_contains_text), - Query.select(Task.ID).from(Task.TABLE).where( - Criterion.and(TaskDao.TaskCriteria.activeAndVisible(), - Task.TITLE.like("%?%"))).toString(), - r.getString(R.string.CFC_title_contains_name), "", + Query.select(Task.ID) + .from(Task.TABLE) + .where(Criterion.and(TaskDao.TaskCriteria.activeAndVisible(), Task.TITLE.like("%?%"))) + .toString(), + r.getString(R.string.CFC_title_contains_name), + "", null, r.getString(R.string.CFC_title_contains_name)); } @@ -181,11 +200,13 @@ public class FilterCriteriaProvider { return new MultipleSelectCriterion( IDENTIFIER_GTASKS, context.getString(R.string.CFC_gtasks_list_text), - Query.select(Field.field("task")).from(GoogleTask.TABLE) + Query.select(Field.field("task")) + .from(GoogleTask.TABLE) .join(Join.inner(Task.TABLE, Field.field("task").eq(Task.ID))) - .where(Criterion.and( - TaskDao.TaskCriteria.activeAndVisible(), - Field.field("list_id").eq("?"))).toString(), + .where( + Criterion.and( + TaskDao.TaskCriteria.activeAndVisible(), Field.field("list_id").eq("?"))) + .toString(), values, listNames, listIds, diff --git a/app/src/main/java/org/tasks/filters/FilterProvider.java b/app/src/main/java/org/tasks/filters/FilterProvider.java index c66e785e7..c58861c5f 100644 --- a/app/src/main/java/org/tasks/filters/FilterProvider.java +++ b/app/src/main/java/org/tasks/filters/FilterProvider.java @@ -21,10 +21,13 @@ public class FilterProvider { private final CaldavFilterExposer caldavFilterExposer; @Inject - public FilterProvider(BuiltInFilterExposer builtInFilterExposer, + public FilterProvider( + BuiltInFilterExposer builtInFilterExposer, TimerFilterExposer timerFilterExposer, - CustomFilterExposer customFilterExposer, TagFilterExposer tagFilterExposer, - GtasksFilterExposer gtasksFilterExposer, CaldavFilterExposer caldavFilterExposer) { + CustomFilterExposer customFilterExposer, + TagFilterExposer tagFilterExposer, + GtasksFilterExposer gtasksFilterExposer, + CaldavFilterExposer caldavFilterExposer) { this.builtInFilterExposer = builtInFilterExposer; this.timerFilterExposer = timerFilterExposer; this.customFilterExposer = customFilterExposer; diff --git a/app/src/main/java/org/tasks/filters/NavigationDrawerAction.java b/app/src/main/java/org/tasks/filters/NavigationDrawerAction.java index 2a87be36d..4da6c233b 100644 --- a/app/src/main/java/org/tasks/filters/NavigationDrawerAction.java +++ b/app/src/main/java/org/tasks/filters/NavigationDrawerAction.java @@ -7,35 +7,29 @@ import com.todoroo.astrid.api.FilterListItem; public class NavigationDrawerAction extends FilterListItem { - /** - * Parcelable Creator Object - */ - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + /** Parcelable Creator Object */ + public static final Parcelable.Creator CREATOR = + new Parcelable.Creator() { + + /** {@inheritDoc} */ + @Override + public NavigationDrawerAction createFromParcel(Parcel source) { + NavigationDrawerAction item = new NavigationDrawerAction(); + item.readFromParcel(source); + return item; + } + + /** {@inheritDoc} */ + @Override + public NavigationDrawerAction[] newArray(int size) { + return new NavigationDrawerAction[size]; + } + }; - /** - * {@inheritDoc} - */ - @Override - public NavigationDrawerAction createFromParcel(Parcel source) { - NavigationDrawerAction item = new NavigationDrawerAction(); - item.readFromParcel(source); - return item; - } - - /** - * {@inheritDoc} - */ - @Override - public NavigationDrawerAction[] newArray(int size) { - return new NavigationDrawerAction[size]; - } - }; public Intent intent; public int requestCode; - private NavigationDrawerAction() { - - } + private NavigationDrawerAction() {} public NavigationDrawerAction(String listingTitle, int icon, Intent intent, int requestCode) { this.listingTitle = listingTitle; @@ -49,9 +43,7 @@ public class NavigationDrawerAction extends FilterListItem { return Type.ITEM; } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); diff --git a/app/src/main/java/org/tasks/filters/NavigationDrawerSeparator.java b/app/src/main/java/org/tasks/filters/NavigationDrawerSeparator.java index bb091fc67..e736cc06b 100644 --- a/app/src/main/java/org/tasks/filters/NavigationDrawerSeparator.java +++ b/app/src/main/java/org/tasks/filters/NavigationDrawerSeparator.java @@ -6,26 +6,23 @@ import com.todoroo.astrid.api.FilterListItem; public class NavigationDrawerSeparator extends FilterListItem { - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public static final Parcelable.Creator CREATOR = + new Parcelable.Creator() { - /** - * {@inheritDoc} - */ - @Override - public NavigationDrawerSeparator createFromParcel(Parcel source) { - NavigationDrawerSeparator navigationDrawerSeparator = new NavigationDrawerSeparator(); - navigationDrawerSeparator.readFromParcel(source); - return navigationDrawerSeparator; - } + /** {@inheritDoc} */ + @Override + public NavigationDrawerSeparator createFromParcel(Parcel source) { + NavigationDrawerSeparator navigationDrawerSeparator = new NavigationDrawerSeparator(); + navigationDrawerSeparator.readFromParcel(source); + return navigationDrawerSeparator; + } - /** - * {@inheritDoc} - */ - @Override - public NavigationDrawerSeparator[] newArray(int size) { - return new NavigationDrawerSeparator[size]; - } - }; + /** {@inheritDoc} */ + @Override + public NavigationDrawerSeparator[] newArray(int size) { + return new NavigationDrawerSeparator[size]; + } + }; @Override public Type getItemType() { diff --git a/app/src/main/java/org/tasks/filters/NavigationDrawerSubheader.java b/app/src/main/java/org/tasks/filters/NavigationDrawerSubheader.java index ac3039a4e..36698954a 100644 --- a/app/src/main/java/org/tasks/filters/NavigationDrawerSubheader.java +++ b/app/src/main/java/org/tasks/filters/NavigationDrawerSubheader.java @@ -6,30 +6,25 @@ import com.todoroo.astrid.api.FilterListItem; public class NavigationDrawerSubheader extends FilterListItem { - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - - /** - * {@inheritDoc} - */ - @Override - public NavigationDrawerSubheader createFromParcel(Parcel source) { - NavigationDrawerSubheader navigationDrawerSubheader = new NavigationDrawerSubheader(); - navigationDrawerSubheader.readFromParcel(source); - return navigationDrawerSubheader; - } - - /** - * {@inheritDoc} - */ - @Override - public NavigationDrawerSubheader[] newArray(int size) { - return new NavigationDrawerSubheader[size]; - } - }; - - private NavigationDrawerSubheader() { - - } + public static final Parcelable.Creator CREATOR = + new Parcelable.Creator() { + + /** {@inheritDoc} */ + @Override + public NavigationDrawerSubheader createFromParcel(Parcel source) { + NavigationDrawerSubheader navigationDrawerSubheader = new NavigationDrawerSubheader(); + navigationDrawerSubheader.readFromParcel(source); + return navigationDrawerSubheader; + } + + /** {@inheritDoc} */ + @Override + public NavigationDrawerSubheader[] newArray(int size) { + return new NavigationDrawerSubheader[size]; + } + }; + + private NavigationDrawerSubheader() {} public NavigationDrawerSubheader(String listingTitle) { this.listingTitle = listingTitle; diff --git a/app/src/main/java/org/tasks/fragments/CommentBarFragment.java b/app/src/main/java/org/tasks/fragments/CommentBarFragment.java index 88aa49568..4feb9001e 100644 --- a/app/src/main/java/org/tasks/fragments/CommentBarFragment.java +++ b/app/src/main/java/org/tasks/fragments/CommentBarFragment.java @@ -55,10 +55,19 @@ public class CommentBarFragment extends TaskEditControlFragment { @Inject DialogBuilder dialogBuilder; @Inject Device device; @Inject Preferences preferences; - @BindView(R.id.commentButton) View commentButton; - @BindView(R.id.commentField) EditText commentField; - @BindView(R.id.picture) ImageView pictureButton; - @BindView(R.id.updatesFooter) LinearLayout commentBar; + + @BindView(R.id.commentButton) + View commentButton; + + @BindView(R.id.commentField) + EditText commentField; + + @BindView(R.id.picture) + ImageView pictureButton; + + @BindView(R.id.updatesFooter) + LinearLayout commentBar; + private CommentBarFragmentCallback callback; private Uri pendingCommentPicture = null; @@ -87,8 +96,8 @@ public class CommentBarFragment extends TaskEditControlFragment { @Nullable @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(getLayout(), container, false); ButterKnife.bind(this, view); @@ -128,15 +137,14 @@ public class CommentBarFragment extends TaskEditControlFragment { } @Override - public void apply(Task task) { - - } + public void apply(Task task) {} @OnTextChanged(R.id.commentField) void onTextChanged(CharSequence s) { - commentButton.setVisibility(pendingCommentPicture == null && Strings.isNullOrEmpty(s.toString()) - ? View.GONE - : View.VISIBLE); + commentButton.setVisibility( + pendingCommentPicture == null && Strings.isNullOrEmpty(s.toString()) + ? View.GONE + : View.VISIBLE); } @OnEditorAction(R.id.commentField) @@ -171,10 +179,11 @@ public class CommentBarFragment extends TaskEditControlFragment { if (pendingCommentPicture == null) { showPictureLauncher(null); } else { - showPictureLauncher(() -> { - pendingCommentPicture = null; - resetPictureButton(); - }); + showPictureLauncher( + () -> { + pendingCommentPicture = null; + resetPictureButton(); + }); } } @@ -198,8 +207,9 @@ public class CommentBarFragment extends TaskEditControlFragment { private void setPictureButtonToPendingPicture() { String path = getPathFromUri(activity, pendingCommentPicture); - Bitmap bitmap = sampleBitmap(path, pictureButton.getLayoutParams().width, - pictureButton.getLayoutParams().height); + Bitmap bitmap = + sampleBitmap( + path, pictureButton.getLayoutParams().width, pictureButton.getLayoutParams().height); pictureButton.setImageBitmap(bitmap); commentButton.setVisibility(View.VISIBLE); } @@ -218,7 +228,7 @@ public class CommentBarFragment extends TaskEditControlFragment { } if (commentField != null) { - commentField.setText(""); //$NON-NLS-1$ + commentField.setText(""); // $NON-NLS-1$ } pendingCommentPicture = null; @@ -229,8 +239,9 @@ public class CommentBarFragment extends TaskEditControlFragment { private void resetPictureButton() { TypedValue typedValue = new TypedValue(); getActivity().getTheme().resolveAttribute(R.attr.actionBarPrimaryText, typedValue, true); - Drawable drawable = DrawableCompat - .wrap(ContextCompat.getDrawable(getContext(), R.drawable.ic_camera_alt_black_24dp)); + Drawable drawable = + DrawableCompat.wrap( + ContextCompat.getDrawable(getContext(), R.drawable.ic_camera_alt_black_24dp)); drawable.mutate(); DrawableCompat.setTint(drawable, typedValue.data); pictureButton.setImageDrawable(drawable); @@ -242,8 +253,10 @@ public class CommentBarFragment extends TaskEditControlFragment { final boolean cameraAvailable = device.hasCamera(); if (cameraAvailable) { - runnables.add(() -> startActivityForResult(new Intent(activity, CameraActivity.class), - REQUEST_CODE_CAMERA)); + runnables.add( + () -> + startActivityForResult( + new Intent(activity, CameraActivity.class), REQUEST_CODE_CAMERA)); options.add(getString(R.string.take_a_picture)); } @@ -255,15 +268,14 @@ public class CommentBarFragment extends TaskEditControlFragment { if (runnables.size() == 1) { runnables.get(0).run(); } else { - DialogInterface.OnClickListener listener = (d, which) -> { - runnables.get(which).run(); - d.dismiss(); - }; + DialogInterface.OnClickListener listener = + (d, which) -> { + runnables.get(which).run(); + d.dismiss(); + }; // show a menu of available options - dialogBuilder.newDialog() - .setItems(options, listener) - .show().setOwnerActivity(activity); + dialogBuilder.newDialog().setItems(options, listener).show().setOwnerActivity(activity); } } diff --git a/app/src/main/java/org/tasks/fragments/TaskEditControlSetFragmentManager.java b/app/src/main/java/org/tasks/fragments/TaskEditControlSetFragmentManager.java index b00d30597..d4376241d 100644 --- a/app/src/main/java/org/tasks/fragments/TaskEditControlSetFragmentManager.java +++ b/app/src/main/java/org/tasks/fragments/TaskEditControlSetFragmentManager.java @@ -29,37 +29,39 @@ import org.tasks.ui.TaskEditControlFragment; public class TaskEditControlSetFragmentManager { - public static final int[] TASK_EDIT_CONTROL_FRAGMENT_ROWS = new int[]{ - R.id.row_title, - R.id.comment_bar, - R.id.row_1, - R.id.row_2, - R.id.row_3, - R.id.row_4, - R.id.row_5, - R.id.row_6, - R.id.row_7, - R.id.row_8, - R.id.row_9, - R.id.row_10, - R.id.row_11 - }; + public static final int[] TASK_EDIT_CONTROL_FRAGMENT_ROWS = + new int[] { + R.id.row_title, + R.id.comment_bar, + R.id.row_1, + R.id.row_2, + R.id.row_3, + R.id.row_4, + R.id.row_5, + R.id.row_6, + R.id.row_7, + R.id.row_8, + R.id.row_9, + R.id.row_10, + R.id.row_11 + }; - private static final int[] TASK_EDIT_CONTROL_SET_FRAGMENTS = new int[]{ - EditTitleControlSet.TAG, - DeadlineControlSet.TAG, - TimerControlSet.TAG, - DescriptionControlSet.TAG, - CalendarControlSet.TAG, - PriorityControlSet.TAG, - HideUntilControlSet.TAG, - ReminderControlSet.TAG, - FilesControlSet.TAG, - TagsControlSet.TAG, - RepeatControlSet.TAG, - CommentBarFragment.TAG, - RemoteListFragment.TAG - }; + private static final int[] TASK_EDIT_CONTROL_SET_FRAGMENTS = + new int[] { + EditTitleControlSet.TAG, + DeadlineControlSet.TAG, + TimerControlSet.TAG, + DescriptionControlSet.TAG, + CalendarControlSet.TAG, + PriorityControlSet.TAG, + HideUntilControlSet.TAG, + ReminderControlSet.TAG, + FilesControlSet.TAG, + TagsControlSet.TAG, + RepeatControlSet.TAG, + CommentBarFragment.TAG, + RemoteListFragment.TAG + }; static { if (BuildConfig.DEBUG @@ -73,8 +75,8 @@ public class TaskEditControlSetFragmentManager { private final SyncAdapters syncAdapters; private int numRows; - public TaskEditControlSetFragmentManager(Activity activity, Preferences preferences, - SyncAdapters syncAdapters) { + public TaskEditControlSetFragmentManager( + Activity activity, Preferences preferences, SyncAdapters syncAdapters) { this.syncAdapters = syncAdapters; displayOrder = BeastModePreferences.constructOrderedControlList(preferences, activity); displayOrder.add(0, activity.getString(EditTitleControlSet.TAG)); @@ -94,8 +96,8 @@ public class TaskEditControlSetFragmentManager { public List getFragmentsInPersistOrder(FragmentManager fragmentManager) { List fragments = new ArrayList<>(); for (String tag : controlSetFragments.keySet()) { - TaskEditControlFragment fragment = (TaskEditControlFragment) fragmentManager - .findFragmentByTag(tag); + TaskEditControlFragment fragment = + (TaskEditControlFragment) fragmentManager.findFragmentByTag(tag); if (fragment != null) { fragments.add(fragment); } @@ -103,16 +105,16 @@ public class TaskEditControlSetFragmentManager { return fragments; } - public List getOrCreateFragments(FragmentManager fragmentManager, - Task task) { + public List getOrCreateFragments( + FragmentManager fragmentManager, Task task) { Bundle arguments = new Bundle(); arguments.putParcelable(TaskEditControlFragment.EXTRA_TASK, task); List fragments = new ArrayList<>(); for (int i = 0; i < numRows; i++) { String tag = displayOrder.get(i); - TaskEditControlFragment fragment = (TaskEditControlFragment) fragmentManager - .findFragmentByTag(tag); + TaskEditControlFragment fragment = + (TaskEditControlFragment) fragmentManager.findFragmentByTag(tag); if (fragment == null) { Integer resId = controlSetFragments.get(tag); fragment = createFragment(resId); @@ -153,9 +155,7 @@ public class TaskEditControlSetFragmentManager { case CommentBarFragment.TAG: return new CommentBarFragment(); case RemoteListFragment.TAG: - return syncAdapters.isSyncEnabled() - ? new RemoteListFragment() - : null; + return syncAdapters.isSyncEnabled() ? new RemoteListFragment() : null; default: throw new RuntimeException("Unsupported fragment"); } diff --git a/app/src/main/java/org/tasks/gtasks/GoogleAccountManager.java b/app/src/main/java/org/tasks/gtasks/GoogleAccountManager.java index 14cd22e29..878c44277 100644 --- a/app/src/main/java/org/tasks/gtasks/GoogleAccountManager.java +++ b/app/src/main/java/org/tasks/gtasks/GoogleAccountManager.java @@ -21,7 +21,9 @@ public class GoogleAccountManager { private final GtasksPreferenceService gtasksPreferenceService; @Inject - public GoogleAccountManager(@ForApplication Context context, PermissionChecker permissionChecker, + public GoogleAccountManager( + @ForApplication Context context, + PermissionChecker permissionChecker, GtasksPreferenceService gtasksPreferenceService) { this.permissionChecker = permissionChecker; diff --git a/app/src/main/java/org/tasks/gtasks/GoogleTaskSynchronizer.java b/app/src/main/java/org/tasks/gtasks/GoogleTaskSynchronizer.java index 53178132b..db613e277 100644 --- a/app/src/main/java/org/tasks/gtasks/GoogleTaskSynchronizer.java +++ b/app/src/main/java/org/tasks/gtasks/GoogleTaskSynchronizer.java @@ -49,7 +49,7 @@ import timber.log.Timber; public class GoogleTaskSynchronizer { - private static final String DEFAULT_LIST = "@default"; //$NON-NLS-1$ + private static final String DEFAULT_LIST = "@default"; // $NON-NLS-1$ private final Context context; private final GtasksPreferenceService gtasksPreferenceService; @@ -68,12 +68,21 @@ public class GoogleTaskSynchronizer { private final DefaultFilterProvider defaultFilterProvider; @Inject - public GoogleTaskSynchronizer(@ForApplication Context context, - GtasksPreferenceService gtasksPreferenceService, LocalBroadcastManager localBroadcastManager, - GoogleTaskListDao googleTaskListDao, GtasksSyncService gtasksSyncService, - GtasksListService gtasksListService, GtasksTaskListUpdater gtasksTaskListUpdater, - Preferences preferences, GtasksInvoker gtasksInvoker, TaskDao taskDao, Tracker tracker, - NotificationManager notificationManager, GoogleTaskDao googleTaskDao, TaskCreator taskCreator, + public GoogleTaskSynchronizer( + @ForApplication Context context, + GtasksPreferenceService gtasksPreferenceService, + LocalBroadcastManager localBroadcastManager, + GoogleTaskListDao googleTaskListDao, + GtasksSyncService gtasksSyncService, + GtasksListService gtasksListService, + GtasksTaskListUpdater gtasksTaskListUpdater, + Preferences preferences, + GtasksInvoker gtasksInvoker, + TaskDao taskDao, + Tracker tracker, + NotificationManager notificationManager, + GoogleTaskDao googleTaskDao, + TaskCreator taskCreator, DefaultFilterProvider defaultFilterProvider) { this.context = context; this.gtasksPreferenceService = gtasksPreferenceService; @@ -95,10 +104,11 @@ public class GoogleTaskSynchronizer { public static void mergeDates(long remoteDueDate, Task local) { if (remoteDueDate > 0 && local.hasDueTime()) { DateTime oldDate = newDateTime(local.getDueDate()); - DateTime newDate = newDateTime(remoteDueDate) - .withHourOfDay(oldDate.getHourOfDay()) - .withMinuteOfHour(oldDate.getMinuteOfHour()) - .withSecondOfMinute(oldDate.getSecondOfMinute()); + DateTime newDate = + newDateTime(remoteDueDate) + .withHourOfDay(oldDate.getHourOfDay()) + .withMinuteOfHour(oldDate.getMinuteOfHour()) + .withSecondOfMinute(oldDate.getSecondOfMinute()); local.setDueDateAdjustingHideUntil( Task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, newDate.getMillis())); } else { @@ -112,8 +122,8 @@ public class GoogleTaskSynchronizer { return; } Timber.d("%s: start sync", account); - RecordSyncStatusCallback callback = new RecordSyncStatusCallback(gtasksPreferenceService, - localBroadcastManager); + RecordSyncStatusCallback callback = + new RecordSyncStatusCallback(gtasksPreferenceService, localBroadcastManager); try { callback.started(); synchronize(); @@ -134,16 +144,18 @@ public class GoogleTaskSynchronizer { private void sendNotification(Context context, Intent intent) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_FROM_BACKGROUND); - PendingIntent resolve = PendingIntent - .getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); - NotificationCompat.Builder builder = new NotificationCompat.Builder(context, - NotificationManager.NOTIFICATION_CHANNEL_DEFAULT).setAutoCancel(true) - .setContentIntent(resolve) - .setContentTitle(context.getString(R.string.sync_error_permissions)) - .setContentText(context.getString(R.string.common_google_play_services_notification_ticker)) - .setAutoCancel(true) - .setSmallIcon(R.drawable.ic_warning_white_24dp) - .setTicker(context.getString(R.string.common_google_play_services_notification_ticker)); + PendingIntent resolve = + PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); + NotificationCompat.Builder builder = + new NotificationCompat.Builder(context, NotificationManager.NOTIFICATION_CHANNEL_DEFAULT) + .setAutoCancel(true) + .setContentIntent(resolve) + .setContentTitle(context.getString(R.string.sync_error_permissions)) + .setContentText( + context.getString(R.string.common_google_play_services_notification_ticker)) + .setAutoCancel(true) + .setSmallIcon(R.drawable.ic_warning_white_24dp) + .setTicker(context.getString(R.string.common_google_play_services_notification_ticker)); notificationManager.notify(Constants.NOTIFICATION_SYNC_ERROR, builder, true, false, false); } @@ -166,8 +178,8 @@ public class GoogleTaskSynchronizer { gtasksListService.updateLists(gtaskLists); Filter defaultRemoteList = defaultFilterProvider.getDefaultRemoteList(); if (defaultRemoteList instanceof GtasksFilter) { - GoogleTaskList list = gtasksListService - .getList(((GtasksFilter) defaultRemoteList).getRemoteId()); + GoogleTaskList list = + gtasksListService.getList(((GtasksFilter) defaultRemoteList).getRemoteId()); if (list == null) { preferences.setString(R.string.p_default_remote_list, null); } @@ -207,32 +219,33 @@ public class GoogleTaskSynchronizer { String remoteId; Filter defaultRemoteList = defaultFilterProvider.getDefaultRemoteList(); - String listId = defaultRemoteList instanceof GtasksFilter - ? ((GtasksFilter) defaultRemoteList).getRemoteId() - : DEFAULT_LIST; + String listId = + defaultRemoteList instanceof GtasksFilter + ? ((GtasksFilter) defaultRemoteList).getRemoteId() + : DEFAULT_LIST; - if (Strings.isNullOrEmpty(gtasksMetadata.getRemoteId())) { //Create case + if (Strings.isNullOrEmpty(gtasksMetadata.getRemoteId())) { // Create case String selectedList = gtasksMetadata.getListId(); if (!Strings.isNullOrEmpty(selectedList)) { listId = selectedList; } remoteModel = new com.google.api.services.tasks.model.Task(); newlyCreated = true; - } else { //update case + } else { // update case remoteId = gtasksMetadata.getRemoteId(); listId = gtasksMetadata.getListId(); remoteModel = new com.google.api.services.tasks.model.Task(); remoteModel.setId(remoteId); } - //If task was newly created but without a title, don't sync--we're in the middle of - //creating a task which may end up being cancelled. Also don't sync new but already - //deleted tasks + // If task was newly created but without a title, don't sync--we're in the middle of + // creating a task which may end up being cancelled. Also don't sync new but already + // deleted tasks if (newlyCreated && (TextUtils.isEmpty(task.getTitle()) || task.getDeletionDate() > 0)) { return; } - //Update the remote model's changed properties + // Update the remote model's changed properties if (task.isDeleted()) { remoteModel.setDeleted(true); } @@ -245,10 +258,10 @@ public class GoogleTaskSynchronizer { if (task.isCompleted()) { remoteModel.setCompleted( GtasksApiUtilities.unixTimeToGtasksCompletionTime(task.getCompletionDate())); - remoteModel.setStatus("completed"); //$NON-NLS-1$ + remoteModel.setStatus("completed"); // $NON-NLS-1$ } else { remoteModel.setCompleted(null); - remoteModel.setStatus("needsAction"); //$NON-NLS-1$ + remoteModel.setStatus("needsAction"); // $NON-NLS-1$ } if (!newlyCreated) { @@ -263,11 +276,11 @@ public class GoogleTaskSynchronizer { String parent = gtasksSyncService.getRemoteParentId(gtasksMetadata); String priorSibling = gtasksSyncService.getRemoteSiblingId(listId, gtasksMetadata); - com.google.api.services.tasks.model.Task created = invoker - .createGtask(listId, remoteModel, parent, priorSibling); + com.google.api.services.tasks.model.Task created = + invoker.createGtask(listId, remoteModel, parent, priorSibling); if (created != null) { - //Update the metadata for the newly created task + // Update the metadata for the newly created task gtasksMetadata.setRemoteId(created.getId()); gtasksMetadata.setListId(listId); } else { @@ -296,8 +309,13 @@ public class GoogleTaskSynchronizer { List tasks = new ArrayList<>(); String nextPageToken = null; do { - Tasks taskList = gtasksInvoker.getAllGtasksFromListId(listId, includeDeletedAndHidden, - includeDeletedAndHidden, lastSyncDate + 1000L, nextPageToken); + Tasks taskList = + gtasksInvoker.getAllGtasksFromListId( + listId, + includeDeletedAndHidden, + includeDeletedAndHidden, + lastSyncDate + 1000L, + nextPageToken); if (taskList == null) { break; } @@ -362,9 +380,8 @@ public class GoogleTaskSynchronizer { } /** - * Synchronize metadata for given task id. Deletes rows in database that - * are not identical to those in the metadata list, creates rows that - * have no match. + * Synchronize metadata for given task id. Deletes rows in database that are not identical to + * those in the metadata list, creates rows that have no match. * * @param taskId id of task to perform synchronization on * @param metadata list of new metadata items to save diff --git a/app/src/main/java/org/tasks/gtasks/GoogleTasksUnsuccessfulResponseHandler.java b/app/src/main/java/org/tasks/gtasks/GoogleTasksUnsuccessfulResponseHandler.java index 6866a71f2..c878bfae8 100644 --- a/app/src/main/java/org/tasks/gtasks/GoogleTasksUnsuccessfulResponseHandler.java +++ b/app/src/main/java/org/tasks/gtasks/GoogleTasksUnsuccessfulResponseHandler.java @@ -19,11 +19,11 @@ public class GoogleTasksUnsuccessfulResponseHandler implements HttpUnsuccessfulR private final PlayServices playServices; private final GoogleAccountCredential googleAccountCredential; - private final HttpBackOffUnsuccessfulResponseHandler backoffHandler = new HttpBackOffUnsuccessfulResponseHandler( - BACKOFF); + private final HttpBackOffUnsuccessfulResponseHandler backoffHandler = + new HttpBackOffUnsuccessfulResponseHandler(BACKOFF); - public GoogleTasksUnsuccessfulResponseHandler(PlayServices playServices, - GoogleAccountCredential googleAccountCredential) { + public GoogleTasksUnsuccessfulResponseHandler( + PlayServices playServices, GoogleAccountCredential googleAccountCredential) { this.playServices = playServices; this.googleAccountCredential = googleAccountCredential; } diff --git a/app/src/main/java/org/tasks/gtasks/GtaskSyncAdapterHelper.java b/app/src/main/java/org/tasks/gtasks/GtaskSyncAdapterHelper.java index 6454bc1e6..4b26b375e 100644 --- a/app/src/main/java/org/tasks/gtasks/GtaskSyncAdapterHelper.java +++ b/app/src/main/java/org/tasks/gtasks/GtaskSyncAdapterHelper.java @@ -2,8 +2,6 @@ package org.tasks.gtasks; import android.accounts.Account; import android.app.Activity; -import android.content.ContentResolver; -import android.os.Bundle; import javax.inject.Inject; import org.tasks.R; import org.tasks.analytics.Tracker; @@ -20,8 +18,11 @@ public class GtaskSyncAdapterHelper { private final Tracker tracker; @Inject - public GtaskSyncAdapterHelper(GoogleAccountManager accountManager, Preferences preferences, - PlayServices playServices, Tracker tracker) { + public GtaskSyncAdapterHelper( + GoogleAccountManager accountManager, + Preferences preferences, + PlayServices playServices, + Tracker tracker) { this.accountManager = accountManager; this.preferences = preferences; this.playServices = playServices; @@ -29,9 +30,9 @@ public class GtaskSyncAdapterHelper { } public boolean isEnabled() { - return preferences.getBoolean(R.string.sync_gtasks, false) && - playServices.isPlayServicesAvailable() && - getAccount() != null; + return preferences.getBoolean(R.string.sync_gtasks, false) + && playServices.isPlayServicesAvailable() + && getAccount() != null; } private Account getAccount() { @@ -39,9 +40,9 @@ public class GtaskSyncAdapterHelper { } public void checkPlayServices(Activity activity) { - if (preferences.getBoolean(R.string.sync_gtasks, false) && - !playServices.refreshAndCheck() && - !preferences.getBoolean(R.string.warned_play_services, false)) { + if (preferences.getBoolean(R.string.sync_gtasks, false) + && !playServices.refreshAndCheck() + && !preferences.getBoolean(R.string.warned_play_services, false)) { preferences.setBoolean(R.string.warned_play_services, true); playServices.resolve(activity); tracker.reportEvent(Tracking.Events.PLAY_SERVICES_WARNING, playServices.getStatus()); diff --git a/app/src/main/java/org/tasks/injection/ActivityScope.java b/app/src/main/java/org/tasks/injection/ActivityScope.java index c18c0b6c0..8669c6e93 100644 --- a/app/src/main/java/org/tasks/injection/ActivityScope.java +++ b/app/src/main/java/org/tasks/injection/ActivityScope.java @@ -6,6 +6,4 @@ import javax.inject.Scope; @Scope @Retention(RetentionPolicy.RUNTIME) -@interface ActivityScope { - -} +@interface ActivityScope {} diff --git a/app/src/main/java/org/tasks/injection/ApplicationModule.java b/app/src/main/java/org/tasks/injection/ApplicationModule.java index 69605ef4a..bca4f886d 100644 --- a/app/src/main/java/org/tasks/injection/ApplicationModule.java +++ b/app/src/main/java/org/tasks/injection/ApplicationModule.java @@ -57,8 +57,7 @@ public class ApplicationModule { @Provides @ApplicationScope public Database getAppDatabase(Tracker tracker) { - return Room - .databaseBuilder(context, Database.class, Database.NAME) + return Room.databaseBuilder(context, Database.class, Database.NAME) .allowMainThreadQueries() // TODO: remove me .addMigrations(Migrations.MIGRATIONS) .build() diff --git a/app/src/main/java/org/tasks/injection/ApplicationScope.java b/app/src/main/java/org/tasks/injection/ApplicationScope.java index cd2528346..6953e6890 100644 --- a/app/src/main/java/org/tasks/injection/ApplicationScope.java +++ b/app/src/main/java/org/tasks/injection/ApplicationScope.java @@ -6,6 +6,4 @@ import javax.inject.Scope; @Scope @Retention(RetentionPolicy.RUNTIME) -public @interface ApplicationScope { - -} \ No newline at end of file +public @interface ApplicationScope {} diff --git a/app/src/main/java/org/tasks/injection/BroadcastModule.java b/app/src/main/java/org/tasks/injection/BroadcastModule.java index 8783f7e4f..96931bffb 100644 --- a/app/src/main/java/org/tasks/injection/BroadcastModule.java +++ b/app/src/main/java/org/tasks/injection/BroadcastModule.java @@ -3,6 +3,4 @@ package org.tasks.injection; import dagger.Module; @Module -public class BroadcastModule { - -} +public class BroadcastModule {} diff --git a/app/src/main/java/org/tasks/injection/ContentProviderComponent.java b/app/src/main/java/org/tasks/injection/ContentProviderComponent.java index 5c699bc2d..7c1cf04a9 100644 --- a/app/src/main/java/org/tasks/injection/ContentProviderComponent.java +++ b/app/src/main/java/org/tasks/injection/ContentProviderComponent.java @@ -4,10 +4,7 @@ import com.todoroo.astrid.provider.Astrid2TaskProvider; import dagger.Component; @ApplicationScope -@Component(modules = { - ApplicationModule.class, - ContentProviderModule.class -}) +@Component(modules = {ApplicationModule.class, ContentProviderModule.class}) public interface ContentProviderComponent { void inject(Astrid2TaskProvider astrid2TaskProvider); diff --git a/app/src/main/java/org/tasks/injection/ContentProviderModule.java b/app/src/main/java/org/tasks/injection/ContentProviderModule.java index e9dfae514..9126191e3 100644 --- a/app/src/main/java/org/tasks/injection/ContentProviderModule.java +++ b/app/src/main/java/org/tasks/injection/ContentProviderModule.java @@ -3,6 +3,4 @@ package org.tasks.injection; import dagger.Module; @Module -public class ContentProviderModule { - -} +public class ContentProviderModule {} diff --git a/app/src/main/java/org/tasks/injection/Dagger.java b/app/src/main/java/org/tasks/injection/Dagger.java index 8b0f35183..4ab82f6d7 100644 --- a/app/src/main/java/org/tasks/injection/Dagger.java +++ b/app/src/main/java/org/tasks/injection/Dagger.java @@ -14,15 +14,15 @@ class Dagger { private Dagger(Context context) { Context localeContext = context.getApplicationContext(); try { - localeContext = Locale.getInstance(localeContext) - .createConfigurationContext(localeContext); + localeContext = Locale.getInstance(localeContext).createConfigurationContext(localeContext); } catch (Exception e) { Timber.e(e.getMessage(), e); } - applicationComponent = DaggerApplicationComponent.builder() - .applicationModule(new ApplicationModule(localeContext)) - .build(); + applicationComponent = + DaggerApplicationComponent.builder() + .applicationModule(new ApplicationModule(localeContext)) + .build(); } public static Dagger get(Context context) { diff --git a/app/src/main/java/org/tasks/injection/ForActivity.java b/app/src/main/java/org/tasks/injection/ForActivity.java index f06690c31..d2a7764a1 100644 --- a/app/src/main/java/org/tasks/injection/ForActivity.java +++ b/app/src/main/java/org/tasks/injection/ForActivity.java @@ -14,6 +14,4 @@ import javax.inject.Qualifier; @Target({FIELD, PARAMETER, METHOD}) @Documented @Retention(RUNTIME) -public @interface ForActivity { - -} +public @interface ForActivity {} diff --git a/app/src/main/java/org/tasks/injection/ForApplication.java b/app/src/main/java/org/tasks/injection/ForApplication.java index ed658fed2..819ac8701 100644 --- a/app/src/main/java/org/tasks/injection/ForApplication.java +++ b/app/src/main/java/org/tasks/injection/ForApplication.java @@ -14,6 +14,4 @@ import javax.inject.Qualifier; @Target({FIELD, PARAMETER, METHOD}) @Documented @Retention(RUNTIME) -public @interface ForApplication { - -} \ No newline at end of file +public @interface ForApplication {} diff --git a/app/src/main/java/org/tasks/injection/InjectingAppCompatActivity.java b/app/src/main/java/org/tasks/injection/InjectingAppCompatActivity.java index 724ea9c69..5d77ed622 100644 --- a/app/src/main/java/org/tasks/injection/InjectingAppCompatActivity.java +++ b/app/src/main/java/org/tasks/injection/InjectingAppCompatActivity.java @@ -4,8 +4,8 @@ import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import org.tasks.locale.Locale; -public abstract class InjectingAppCompatActivity extends AppCompatActivity implements - InjectingActivity { +public abstract class InjectingAppCompatActivity extends AppCompatActivity + implements InjectingActivity { private ActivityComponent activityComponent; @@ -15,8 +15,8 @@ public abstract class InjectingAppCompatActivity extends AppCompatActivity imple @Override protected void onCreate(Bundle savedInstanceState) { - activityComponent = ((InjectingApplication) getApplication()).getComponent() - .plus(new ActivityModule(this)); + activityComponent = + ((InjectingApplication) getApplication()).getComponent().plus(new ActivityModule(this)); inject(activityComponent); setTitle(""); super.onCreate(savedInstanceState); diff --git a/app/src/main/java/org/tasks/injection/InjectingAppWidgetProvider.java b/app/src/main/java/org/tasks/injection/InjectingAppWidgetProvider.java index 0dc241217..3e51d8177 100644 --- a/app/src/main/java/org/tasks/injection/InjectingAppWidgetProvider.java +++ b/app/src/main/java/org/tasks/injection/InjectingAppWidgetProvider.java @@ -8,9 +8,10 @@ public abstract class InjectingAppWidgetProvider extends AppWidgetProvider { @Override public void onReceive(Context context, Intent intent) { - inject(((InjectingApplication) context.getApplicationContext()) - .getComponent() - .plus(new BroadcastModule())); + inject( + ((InjectingApplication) context.getApplicationContext()) + .getComponent() + .plus(new BroadcastModule())); super.onReceive(context, intent); } diff --git a/app/src/main/java/org/tasks/injection/InjectingBroadcastReceiver.java b/app/src/main/java/org/tasks/injection/InjectingBroadcastReceiver.java index fc462e37e..9f13fbe60 100644 --- a/app/src/main/java/org/tasks/injection/InjectingBroadcastReceiver.java +++ b/app/src/main/java/org/tasks/injection/InjectingBroadcastReceiver.java @@ -8,9 +8,10 @@ public abstract class InjectingBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { - inject(((InjectingApplication) context.getApplicationContext()) - .getComponent() - .plus(new BroadcastModule())); + inject( + ((InjectingApplication) context.getApplicationContext()) + .getComponent() + .plus(new BroadcastModule())); } protected abstract void inject(BroadcastComponent component); diff --git a/app/src/main/java/org/tasks/injection/InjectingContentProvider.java b/app/src/main/java/org/tasks/injection/InjectingContentProvider.java index 1bad45a93..eba699179 100644 --- a/app/src/main/java/org/tasks/injection/InjectingContentProvider.java +++ b/app/src/main/java/org/tasks/injection/InjectingContentProvider.java @@ -8,10 +8,11 @@ public abstract class InjectingContentProvider extends ContentProvider { @Override public boolean onCreate() { Context context = getContext(); - inject(DaggerContentProviderComponent.builder() - .applicationModule(new ApplicationModule(context.getApplicationContext())) - .contentProviderModule(new ContentProviderModule()) - .build()); + inject( + DaggerContentProviderComponent.builder() + .applicationModule(new ApplicationModule(context.getApplicationContext())) + .contentProviderModule(new ContentProviderModule()) + .build()); return true; } diff --git a/app/src/main/java/org/tasks/injection/InjectingDialogFragment.java b/app/src/main/java/org/tasks/injection/InjectingDialogFragment.java index 074945246..73dcd1673 100644 --- a/app/src/main/java/org/tasks/injection/InjectingDialogFragment.java +++ b/app/src/main/java/org/tasks/injection/InjectingDialogFragment.java @@ -12,9 +12,7 @@ public abstract class InjectingDialogFragment extends DialogFragment { super.onAttach(activity); if (!injected) { - inject(((InjectingActivity) activity) - .getComponent() - .plus(new DialogFragmentModule(this))); + inject(((InjectingActivity) activity).getComponent().plus(new DialogFragmentModule(this))); injected = true; } } diff --git a/app/src/main/java/org/tasks/injection/InjectingFragment.java b/app/src/main/java/org/tasks/injection/InjectingFragment.java index 5efb2d9f6..fc4160aec 100644 --- a/app/src/main/java/org/tasks/injection/InjectingFragment.java +++ b/app/src/main/java/org/tasks/injection/InjectingFragment.java @@ -12,9 +12,7 @@ public abstract class InjectingFragment extends Fragment { super.onAttach(activity); if (!injected) { - inject(((InjectingActivity) activity) - .getComponent() - .plus(new FragmentModule(this))); + inject(((InjectingActivity) activity).getComponent().plus(new FragmentModule(this))); injected = true; } } diff --git a/app/src/main/java/org/tasks/injection/InjectingJobIntentService.java b/app/src/main/java/org/tasks/injection/InjectingJobIntentService.java index 98653cfaf..c0c8e6dad 100644 --- a/app/src/main/java/org/tasks/injection/InjectingJobIntentService.java +++ b/app/src/main/java/org/tasks/injection/InjectingJobIntentService.java @@ -8,11 +8,9 @@ public abstract class InjectingJobIntentService extends JobIntentService { @Override protected void onHandleWork(@NonNull Intent intent) { - inject(((InjectingApplication) getApplication()) - .getComponent() - .plus(new IntentServiceModule())); + inject( + ((InjectingApplication) getApplication()).getComponent().plus(new IntentServiceModule())); } - protected abstract void inject(IntentServiceComponent component); } diff --git a/app/src/main/java/org/tasks/injection/InjectingNativeDialogFragment.java b/app/src/main/java/org/tasks/injection/InjectingNativeDialogFragment.java index d0a08d70b..ce5f5ca62 100644 --- a/app/src/main/java/org/tasks/injection/InjectingNativeDialogFragment.java +++ b/app/src/main/java/org/tasks/injection/InjectingNativeDialogFragment.java @@ -13,9 +13,8 @@ public abstract class InjectingNativeDialogFragment extends DialogFragment { super.onAttach(activity); if (!injected) { - inject(((InjectingActivity) activity) - .getComponent() - .plus(new NativeDialogFragmentModule(this))); + inject( + ((InjectingActivity) activity).getComponent().plus(new NativeDialogFragmentModule(this))); injected = true; } } diff --git a/app/src/main/java/org/tasks/injection/InjectingPreferenceActivity.java b/app/src/main/java/org/tasks/injection/InjectingPreferenceActivity.java index c77510144..90068c6c0 100644 --- a/app/src/main/java/org/tasks/injection/InjectingPreferenceActivity.java +++ b/app/src/main/java/org/tasks/injection/InjectingPreferenceActivity.java @@ -24,8 +24,8 @@ import org.tasks.themes.Theme; import org.tasks.ui.MenuColorizer; import timber.log.Timber; -public abstract class InjectingPreferenceActivity extends AppCompatPreferenceActivity implements - InjectingActivity { +public abstract class InjectingPreferenceActivity extends AppCompatPreferenceActivity + implements InjectingActivity { @Inject DialogBuilder dialogBuilder; private ActivityComponent activityComponent; @@ -36,9 +36,8 @@ public abstract class InjectingPreferenceActivity extends AppCompatPreferenceAct @Override public void onCreate(Bundle savedInstanceState) { - activityComponent = ((InjectingApplication) getApplication()) - .getComponent() - .plus(new ActivityModule(this)); + activityComponent = + ((InjectingApplication) getApplication()).getComponent().plus(new ActivityModule(this)); inject(activityComponent); Theme theme = activityComponent.getTheme(); @@ -49,8 +48,8 @@ public abstract class InjectingPreferenceActivity extends AppCompatPreferenceAct ViewGroup root = findViewById(android.R.id.content); View content = root.getChildAt(0); - LinearLayout toolbarContainer = (LinearLayout) View - .inflate(this, R.layout.activity_prefs, null); + LinearLayout toolbarContainer = + (LinearLayout) View.inflate(this, R.layout.activity_prefs, null); root.removeAllViews(); toolbarContainer.addView(content); @@ -114,13 +113,17 @@ public abstract class InjectingPreferenceActivity extends AppCompatPreferenceAct } protected void showRestartDialog() { - dialogBuilder.newDialog() + dialogBuilder + .newDialog() .setMessage(R.string.restart_required) - .setPositiveButton(R.string.restart_now, (dialogInterface, i) -> { - Intent nextIntent = new Intent(InjectingPreferenceActivity.this, TaskListActivity.class); - nextIntent.putExtra(TaskListActivity.OPEN_FILTER, (Filter) null); - ProcessPhoenix.triggerRebirth(InjectingPreferenceActivity.this, nextIntent); - }) + .setPositiveButton( + R.string.restart_now, + (dialogInterface, i) -> { + Intent nextIntent = + new Intent(InjectingPreferenceActivity.this, TaskListActivity.class); + nextIntent.putExtra(TaskListActivity.OPEN_FILTER, (Filter) null); + ProcessPhoenix.triggerRebirth(InjectingPreferenceActivity.this, nextIntent); + }) .setNegativeButton(R.string.restart_later, null) .show(); } diff --git a/app/src/main/java/org/tasks/injection/IntentServiceModule.java b/app/src/main/java/org/tasks/injection/IntentServiceModule.java index a16677801..1c97a2043 100644 --- a/app/src/main/java/org/tasks/injection/IntentServiceModule.java +++ b/app/src/main/java/org/tasks/injection/IntentServiceModule.java @@ -3,6 +3,4 @@ package org.tasks.injection; import dagger.Module; @Module -public class IntentServiceModule { - -} +public class IntentServiceModule {} diff --git a/app/src/main/java/org/tasks/injection/ThemedInjectingAppCompatActivity.java b/app/src/main/java/org/tasks/injection/ThemedInjectingAppCompatActivity.java index b4a14530e..366d8f6f9 100644 --- a/app/src/main/java/org/tasks/injection/ThemedInjectingAppCompatActivity.java +++ b/app/src/main/java/org/tasks/injection/ThemedInjectingAppCompatActivity.java @@ -6,8 +6,8 @@ import javax.inject.Inject; import org.tasks.locale.Locale; import org.tasks.themes.Theme; -public abstract class ThemedInjectingAppCompatActivity extends AppCompatActivity implements - InjectingActivity { +public abstract class ThemedInjectingAppCompatActivity extends AppCompatActivity + implements InjectingActivity { @Inject Theme theme; private ActivityComponent activityComponent; @@ -18,8 +18,8 @@ public abstract class ThemedInjectingAppCompatActivity extends AppCompatActivity @Override protected void onCreate(Bundle savedInstanceState) { - activityComponent = ((InjectingApplication) getApplication()).getComponent() - .plus(new ActivityModule(this)); + activityComponent = + ((InjectingApplication) getApplication()).getComponent().plus(new ActivityModule(this)); inject(activityComponent); setTitle(null); super.onCreate(savedInstanceState); diff --git a/app/src/main/java/org/tasks/intents/TaskIntents.java b/app/src/main/java/org/tasks/intents/TaskIntents.java index 19e4d052e..f3c0b3e1b 100644 --- a/app/src/main/java/org/tasks/intents/TaskIntents.java +++ b/app/src/main/java/org/tasks/intents/TaskIntents.java @@ -16,8 +16,8 @@ public class TaskIntents { return TaskStackBuilder.create(context).addNextIntent(intent); } - public static TaskStackBuilder getEditTaskStack(Context context, final Filter filter, - final long taskId) { + public static TaskStackBuilder getEditTaskStack( + Context context, final Filter filter, final long taskId) { Intent intent = getTaskListIntent(context, filter); intent.putExtra(TaskListActivity.OPEN_TASK, taskId); return TaskStackBuilder.create(context).addNextIntent(intent); diff --git a/app/src/main/java/org/tasks/jobs/AfterSaveIntentService.java b/app/src/main/java/org/tasks/jobs/AfterSaveIntentService.java index 8593603ce..efe72d998 100644 --- a/app/src/main/java/org/tasks/jobs/AfterSaveIntentService.java +++ b/app/src/main/java/org/tasks/jobs/AfterSaveIntentService.java @@ -44,9 +44,8 @@ public class AfterSaveIntentService extends InjectingJobIntentService { Intent intent = new Intent(); intent.putExtra(EXTRA_CURRENT, current); intent.putExtra(EXTRA_ORIGINAL, original); - AfterSaveIntentService - .enqueueWork(context, AfterSaveIntentService.class, JobManager.JOB_ID_TASK_STATUS_CHANGE, - intent); + AfterSaveIntentService.enqueueWork( + context, AfterSaveIntentService.class, JobManager.JOB_ID_TASK_STATUS_CHANGE, intent); } @Override @@ -61,12 +60,12 @@ public class AfterSaveIntentService extends InjectingJobIntentService { long taskId = task.getId(); Task original = intent.getParcelableExtra(EXTRA_ORIGINAL); - if (original == null || - !task.getDueDate().equals(original.getDueDate()) || - !task.getReminderFlags().equals(original.getReminderFlags()) || - !task.getReminderPeriod().equals(original.getReminderPeriod()) || - !task.getReminderLast().equals(original.getReminderLast()) || - !task.getReminderSnooze().equals(original.getReminderSnooze())) { + if (original == null + || !task.getDueDate().equals(original.getDueDate()) + || !task.getReminderFlags().equals(original.getReminderFlags()) + || !task.getReminderPeriod().equals(original.getReminderPeriod()) + || !task.getReminderLast().equals(original.getReminderLast()) + || !task.getReminderSnooze().equals(original.getReminderSnooze())) { reminderService.scheduleAlarm(task); } @@ -107,8 +106,9 @@ public class AfterSaveIntentService extends InjectingJobIntentService { // change title of calendar event ContentResolver cr = context.getContentResolver(); ContentValues values = new ContentValues(); - values.put(CalendarContract.Events.TITLE, context.getString(R.string.gcal_completed_title, - task.getTitle())); + values.put( + CalendarContract.Events.TITLE, + context.getString(R.string.gcal_completed_title, task.getTitle())); cr.update(Uri.parse(calendarUri), values, null, null); } catch (Exception e) { Timber.e(e, e.getMessage()); diff --git a/app/src/main/java/org/tasks/jobs/AlarmEntry.java b/app/src/main/java/org/tasks/jobs/AlarmEntry.java index bd9767b32..c8603ed3a 100644 --- a/app/src/main/java/org/tasks/jobs/AlarmEntry.java +++ b/app/src/main/java/org/tasks/jobs/AlarmEntry.java @@ -70,10 +70,6 @@ public class AlarmEntry implements NotificationQueueEntry { @Override public String toString() { - return "AlarmEntry{" + - "alarmId=" + alarmId + - ", taskId=" + taskId + - ", time=" + time + - '}'; + return "AlarmEntry{" + "alarmId=" + alarmId + ", taskId=" + taskId + ", time=" + time + '}'; } } diff --git a/app/src/main/java/org/tasks/jobs/BackupJob.java b/app/src/main/java/org/tasks/jobs/BackupJob.java index 61d053ebf..d804d2abd 100644 --- a/app/src/main/java/org/tasks/jobs/BackupJob.java +++ b/app/src/main/java/org/tasks/jobs/BackupJob.java @@ -21,8 +21,8 @@ public class BackupJob extends Job { static final String BACKUP_FILE_NAME_REGEX = "auto\\.[-\\d]+\\.json"; static final FileFilter FILE_FILTER = f -> f.getName().matches(BACKUP_FILE_NAME_REGEX); - private static final Comparator BY_LAST_MODIFIED = (f1, f2) -> - Long.compare(f2.lastModified(), f1.lastModified()); + private static final Comparator BY_LAST_MODIFIED = + (f1, f2) -> Long.compare(f2.lastModified(), f1.lastModified()); private static final int DAYS_TO_KEEP_BACKUP = 7; private final Context context; @@ -35,6 +35,16 @@ public class BackupJob extends Job { this.preferences = preferences; } + static List getDeleteList(File[] fileArray, int keepNewest) { + if (fileArray == null) { + return emptyList(); + } + + List files = Arrays.asList(fileArray); + Collections.sort(files, BY_LAST_MODIFIED); + return newArrayList(skip(files, keepNewest)); + } + @NonNull @Override protected Result onRunJob(@NonNull Params params) { @@ -50,8 +60,8 @@ public class BackupJob extends Job { } try { - tasksJsonExporter - .exportTasks(context, TasksJsonExporter.ExportType.EXPORT_TYPE_SERVICE, null); + tasksJsonExporter.exportTasks( + context, TasksJsonExporter.ExportType.EXPORT_TYPE_SERVICE, null); } catch (Exception e) { Timber.e(e, e.getMessage()); } @@ -71,14 +81,4 @@ public class BackupJob extends Job { } } } - - static List getDeleteList(File[] fileArray, int keepNewest) { - if (fileArray == null) { - return emptyList(); - } - - List files = Arrays.asList(fileArray); - Collections.sort(files, BY_LAST_MODIFIED); - return newArrayList(skip(files, keepNewest)); - } } diff --git a/app/src/main/java/org/tasks/jobs/JobCreator.java b/app/src/main/java/org/tasks/jobs/JobCreator.java index 08622cbee..966051bd8 100644 --- a/app/src/main/java/org/tasks/jobs/JobCreator.java +++ b/app/src/main/java/org/tasks/jobs/JobCreator.java @@ -19,6 +19,12 @@ import timber.log.Timber; @ApplicationScope public class JobCreator implements com.evernote.android.job.JobCreator { + static final String TAG_BACKUP = "tag_backup"; + static final String TAG_REFRESH = "tag_refresh"; + static final String TAG_MIDNIGHT_REFRESH = "tag_midnight_refresh"; + static final String TAG_NOTIFICATION = "tag_notification"; + static final String TAG_BACKGROUND_SYNC = "tag_background_sync"; + static final String TAG_SYNC = "tag_sync"; private final Context context; private final Preferences preferences; private final Notifier notifier; @@ -29,18 +35,17 @@ public class JobCreator implements com.evernote.android.job.JobCreator { private final CaldavSynchronizer caldavSynchronizer; private final GoogleTaskSynchronizer googleTaskSynchronizer; - static final String TAG_BACKUP = "tag_backup"; - static final String TAG_REFRESH = "tag_refresh"; - static final String TAG_MIDNIGHT_REFRESH = "tag_midnight_refresh"; - static final String TAG_NOTIFICATION = "tag_notification"; - static final String TAG_BACKGROUND_SYNC = "tag_background_sync"; - static final String TAG_SYNC = "tag_sync"; - @Inject - public JobCreator(@ForApplication Context context, Preferences preferences, Notifier notifier, - NotificationQueue notificationQueue, TasksJsonExporter tasksJsonExporter, - RefreshScheduler refreshScheduler, LocalBroadcastManager localBroadcastManager, - CaldavSynchronizer caldavSynchronizer, GoogleTaskSynchronizer googleTaskSynchronizer) { + public JobCreator( + @ForApplication Context context, + Preferences preferences, + Notifier notifier, + NotificationQueue notificationQueue, + TasksJsonExporter tasksJsonExporter, + RefreshScheduler refreshScheduler, + LocalBroadcastManager localBroadcastManager, + CaldavSynchronizer caldavSynchronizer, + GoogleTaskSynchronizer googleTaskSynchronizer) { this.context = context; this.preferences = preferences; this.notifier = notifier; diff --git a/app/src/main/java/org/tasks/jobs/JobManager.java b/app/src/main/java/org/tasks/jobs/JobManager.java index 32870aa65..30ecbeede 100644 --- a/app/src/main/java/org/tasks/jobs/JobManager.java +++ b/app/src/main/java/org/tasks/jobs/JobManager.java @@ -1,6 +1,5 @@ package org.tasks.jobs; -import static android.text.TextUtils.isEmpty; import static org.tasks.time.DateTimeUtils.currentTimeMillis; import static org.tasks.time.DateTimeUtils.printTimestamp; @@ -8,7 +7,6 @@ import com.evernote.android.job.DailyJob; import com.evernote.android.job.JobRequest; import com.evernote.android.job.JobRequest.Builder; import com.evernote.android.job.JobRequest.NetworkType; -import com.todoroo.astrid.gtasks.GtasksPreferenceService; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; import javax.inject.Inject; @@ -60,25 +58,30 @@ public class JobManager { } public void scheduleBackup() { - DailyJob.schedule(new Builder(JobCreator.TAG_BACKUP), 0, - TimeUnit.HOURS.toMillis(24) - 1); + DailyJob.schedule(new Builder(JobCreator.TAG_BACKUP), 0, TimeUnit.HOURS.toMillis(24) - 1); } public void updateBackgroundSync() { updateBackgroundSync(null, null, null); } - public void updateBackgroundSync(@Nullable Boolean forceAccountPresent, - @Nullable Boolean forceBackgroundEnabled, @Nullable Boolean forceOnlyOnUnmetered) { - boolean backgroundEnabled = forceBackgroundEnabled == null - ? preferences.getBoolean(R.string.p_background_sync, true) - : forceBackgroundEnabled; - boolean accountsPresent = forceAccountPresent == null - ? (preferences.getBoolean(R.string.sync_gtasks, false) || preferences.getBoolean(R.string.p_sync_caldav, false)) - : forceAccountPresent; - boolean onlyOnWifi = forceOnlyOnUnmetered == null - ? preferences.getBoolean(R.string.p_background_sync_unmetered_only, false) - : forceOnlyOnUnmetered; + public void updateBackgroundSync( + @Nullable Boolean forceAccountPresent, + @Nullable Boolean forceBackgroundEnabled, + @Nullable Boolean forceOnlyOnUnmetered) { + boolean backgroundEnabled = + forceBackgroundEnabled == null + ? preferences.getBoolean(R.string.p_background_sync, true) + : forceBackgroundEnabled; + boolean accountsPresent = + forceAccountPresent == null + ? (preferences.getBoolean(R.string.sync_gtasks, false) + || preferences.getBoolean(R.string.p_sync_caldav, false)) + : forceAccountPresent; + boolean onlyOnWifi = + forceOnlyOnUnmetered == null + ? preferences.getBoolean(R.string.p_background_sync_unmetered_only, false) + : forceOnlyOnUnmetered; scheduleBackgroundSynchronization(backgroundEnabled && accountsPresent, onlyOnWifi); } diff --git a/app/src/main/java/org/tasks/jobs/NotificationQueue.java b/app/src/main/java/org/tasks/jobs/NotificationQueue.java index 538428e59..8b7ebf35e 100644 --- a/app/src/main/java/org/tasks/jobs/NotificationQueue.java +++ b/app/src/main/java/org/tasks/jobs/NotificationQueue.java @@ -16,8 +16,8 @@ import org.tasks.time.DateTime; @ApplicationScope public class NotificationQueue { - private final TreeMultimap jobs = TreeMultimap - .create(Ordering.natural(), (l, r) -> Ints.compare(l.hashCode(), r.hashCode())); + private final TreeMultimap jobs = + TreeMultimap.create(Ordering.natural(), (l, r) -> Ints.compare(l.hashCode(), r.hashCode())); private final Preferences preferences; private final JobManager jobManager; @@ -51,8 +51,8 @@ public class NotificationQueue { private synchronized void cancel(Class c, long id) { boolean reschedule = false; long firstTime = firstTime(); - List existing = newArrayList( - filter(jobs.values(), r -> r.getClass().equals(c) && r.getId() == id)); + List existing = + newArrayList(filter(jobs.values(), r -> r.getClass().equals(c) && r.getId() == id)); for (NotificationQueueEntry entry : existing) { reschedule |= entry.getTime() == firstTime; jobs.remove(entry.getTime(), entry); @@ -105,8 +105,7 @@ public class NotificationQueue { public synchronized boolean remove(List entries) { boolean success = true; for (NotificationQueueEntry entry : entries) { - success &= !jobs.containsEntry(entry.getTime(), entry) || - jobs.remove(entry.getTime(), entry); + success &= !jobs.containsEntry(entry.getTime(), entry) || jobs.remove(entry.getTime(), entry); } return success; } diff --git a/app/src/main/java/org/tasks/jobs/ReminderEntry.java b/app/src/main/java/org/tasks/jobs/ReminderEntry.java index 310b787cd..9c0a2a870 100644 --- a/app/src/main/java/org/tasks/jobs/ReminderEntry.java +++ b/app/src/main/java/org/tasks/jobs/ReminderEntry.java @@ -53,7 +53,6 @@ public class ReminderEntry implements NotificationQueueEntry { return false; } return type == reminderEntry.type; - } @Override @@ -66,10 +65,6 @@ public class ReminderEntry implements NotificationQueueEntry { @Override public String toString() { - return "ReminderEntry{" + - "taskId=" + taskId + - ", time=" + time + - ", type=" + type + - '}'; + return "ReminderEntry{" + "taskId=" + taskId + ", time=" + time + ", type=" + type + '}'; } } diff --git a/app/src/main/java/org/tasks/jobs/SyncJob.java b/app/src/main/java/org/tasks/jobs/SyncJob.java index 8da33014a..3d0abf9f6 100644 --- a/app/src/main/java/org/tasks/jobs/SyncJob.java +++ b/app/src/main/java/org/tasks/jobs/SyncJob.java @@ -5,7 +5,7 @@ import com.evernote.android.job.Job; import org.tasks.caldav.CaldavSynchronizer; import org.tasks.gtasks.GoogleTaskSynchronizer; -public class SyncJob extends Job{ +public class SyncJob extends Job { private final CaldavSynchronizer caldavSynchronizer; private final GoogleTaskSynchronizer googleTaskSynchronizer; diff --git a/app/src/main/java/org/tasks/locale/Locale.java b/app/src/main/java/org/tasks/locale/Locale.java index 438ab0fcd..f8741c28d 100644 --- a/app/src/main/java/org/tasks/locale/Locale.java +++ b/app/src/main/java/org/tasks/locale/Locale.java @@ -22,8 +22,8 @@ import org.tasks.R; public class Locale { private static final Locale DEFAULT = new Locale(java.util.Locale.getDefault(), null, -1); - private static final int[] sDialogButtons = new int[]{android.R.id.button1, android.R.id.button2, - android.R.id.button3}; + private static final int[] sDialogButtons = + new int[] {android.R.id.button1, android.R.id.button2, android.R.id.button3}; private static final char LEFT_TO_RIGHT_MARK = '\u200e'; private static final char RIGHT_TO_LEFT_MARK = '\u200f'; private static Locale INSTANCE; @@ -66,12 +66,13 @@ public class Locale { synchronized (DEFAULT) { if (INSTANCE == null) { Context applicationContext = context.getApplicationContext(); - SharedPreferences prefs = PreferenceManager - .getDefaultSharedPreferences(applicationContext); - String language = prefs - .getString(applicationContext.getString(R.string.p_language), null); - int directionOverride = Integer.parseInt( - prefs.getString(applicationContext.getString(R.string.p_layout_direction), "-1")); + SharedPreferences prefs = + PreferenceManager.getDefaultSharedPreferences(applicationContext); + String language = + prefs.getString(applicationContext.getString(R.string.p_language), null); + int directionOverride = + Integer.parseInt( + prefs.getString(applicationContext.getString(R.string.p_layout_direction), "-1")); setDefault(DEFAULT.getLocale(), language, directionOverride); } } @@ -84,8 +85,8 @@ public class Locale { setDefault(locale, null, -1); } - private static void setDefault(java.util.Locale locale, String languageOverride, - int directionOverride) { + private static void setDefault( + java.util.Locale locale, String languageOverride, int directionOverride) { INSTANCE = new Locale(locale, languageOverride, directionOverride); java.util.Locale.setDefault(locale); } @@ -141,8 +142,8 @@ public class Locale { configuration.locale = getLocale(); final int layoutDirection = 1 + appDirectionality; configuration.screenLayout = - (configuration.screenLayout & ~Configuration.SCREENLAYOUT_LAYOUTDIR_MASK) | - (layoutDirection << Configuration.SCREENLAYOUT_LAYOUTDIR_SHIFT); + (configuration.screenLayout & ~Configuration.SCREENLAYOUT_LAYOUTDIR_MASK) + | (layoutDirection << Configuration.SCREENLAYOUT_LAYOUTDIR_SHIFT); return configuration; } @@ -172,9 +173,7 @@ public class Locale { public Integer parseInteger(String number) { try { - return NumberFormat.getNumberInstance(appLocale) - .parse(number) - .intValue(); + return NumberFormat.getNumberInstance(appLocale).parse(number).intValue(); } catch (ParseException e) { return null; } @@ -195,7 +194,8 @@ public class Locale { Locale locale = (Locale) o; - return languageOverride != null ? languageOverride.equals(locale.languageOverride) + return languageOverride != null + ? languageOverride.equals(locale.languageOverride) : locale.languageOverride == null; } @@ -206,14 +206,21 @@ public class Locale { @Override public String toString() { - return "Locale{" + - "deviceLocale=" + deviceLocale + - ", appLocale=" + appLocale + - ", appDirectionality=" + appDirectionality + - ", languageOverride='" + languageOverride + '\'' + - ", directionOverride=" + directionOverride + - ", hasUserOverrides=" + hasUserOverrides + - '}'; + return "Locale{" + + "deviceLocale=" + + deviceLocale + + ", appLocale=" + + appLocale + + ", appDirectionality=" + + appDirectionality + + ", languageOverride='" + + languageOverride + + '\'' + + ", directionOverride=" + + directionOverride + + ", hasUserOverrides=" + + hasUserOverrides + + '}'; } @SuppressLint("NewApi") diff --git a/app/src/main/java/org/tasks/locale/LocalePickerDialog.java b/app/src/main/java/org/tasks/locale/LocalePickerDialog.java index f4f95205f..49e8306af 100644 --- a/app/src/main/java/org/tasks/locale/LocalePickerDialog.java +++ b/app/src/main/java/org/tasks/locale/LocalePickerDialog.java @@ -17,7 +17,6 @@ import org.tasks.injection.NativeDialogFragmentComponent; import org.tasks.themes.ThemeAccent; import org.tasks.ui.SingleCheckedArrayAdapter; - public class LocalePickerDialog extends InjectingNativeDialogFragment { @Inject @ForActivity Context context; @@ -38,10 +37,13 @@ public class LocalePickerDialog extends InjectingNativeDialogFragment { locales.add(locale.withLanguage(override)); } final List display = transform(locales, Locale::getDisplayName); - SingleCheckedArrayAdapter adapter = new SingleCheckedArrayAdapter(context, display, - themeAccent); - return dialogBuilder.newDialog() - .setSingleChoiceItems(adapter, display.indexOf(locale.getDisplayName()), + SingleCheckedArrayAdapter adapter = + new SingleCheckedArrayAdapter(context, display, themeAccent); + return dialogBuilder + .newDialog() + .setSingleChoiceItems( + adapter, + display.indexOf(locale.getDisplayName()), (dialogInterface, i) -> { callback.onLocaleSelected(locales.get(i)); dialogInterface.dismiss(); diff --git a/app/src/main/java/org/tasks/locale/bundle/ListNotificationBundle.java b/app/src/main/java/org/tasks/locale/bundle/ListNotificationBundle.java index b3ca8443d..08a08d32c 100755 --- a/app/src/main/java/org/tasks/locale/bundle/ListNotificationBundle.java +++ b/app/src/main/java/org/tasks/locale/bundle/ListNotificationBundle.java @@ -12,8 +12,7 @@ public final class ListNotificationBundle { public static final String BUNDLE_EXTRA_PREVIOUS_BUNDLE = "org.tasks.locale.PREVIOUS_BUNDLE"; private static final String BUNDLE_EXTRA_INT_VERSION_CODE = "org.tasks.locale.INT_VERSION_CODE"; - private ListNotificationBundle() { - } + private ListNotificationBundle() {} public static boolean isBundleValid(final Bundle bundle) { if (null == bundle) { diff --git a/app/src/main/java/org/tasks/locale/bundle/TaskCreationBundle.java b/app/src/main/java/org/tasks/locale/bundle/TaskCreationBundle.java index 9ebd9285e..1c29110d9 100644 --- a/app/src/main/java/org/tasks/locale/bundle/TaskCreationBundle.java +++ b/app/src/main/java/org/tasks/locale/bundle/TaskCreationBundle.java @@ -79,8 +79,6 @@ public class TaskCreationBundle { @Override public String toString() { - return "TaskCreationBundle{" + - "bundle=" + bundle + - '}'; + return "TaskCreationBundle{" + "bundle=" + bundle + '}'; } } diff --git a/app/src/main/java/org/tasks/locale/receiver/FireReceiver.java b/app/src/main/java/org/tasks/locale/receiver/FireReceiver.java index af8a58047..ea704f8c5 100755 --- a/app/src/main/java/org/tasks/locale/receiver/FireReceiver.java +++ b/app/src/main/java/org/tasks/locale/receiver/FireReceiver.java @@ -12,7 +12,7 @@ public final class FireReceiver extends BroadcastReceiver { @Override public final void onReceive(final Context context, final Intent intent) { - Timber.d("Received %s", intent); //$NON-NLS-1$ + Timber.d("Received %s", intent); // $NON-NLS-1$ /* * Note: It is OK if a host sends an ordered broadcast for plug-in @@ -21,8 +21,9 @@ public final class FireReceiver extends BroadcastReceiver { */ if (!com.twofortyfouram.locale.api.Intent.ACTION_FIRE_SETTING.equals(intent.getAction())) { - Timber.e("Intent action is not %s", - com.twofortyfouram.locale.api.Intent.ACTION_FIRE_SETTING); //$NON-NLS-1$ + Timber.e( + "Intent action is not %s", + com.twofortyfouram.locale.api.Intent.ACTION_FIRE_SETTING); // $NON-NLS-1$ return; } @@ -35,13 +36,12 @@ public final class FireReceiver extends BroadcastReceiver { * asserting the package is probably good enough. */ if (!context.getPackageName().equals(intent.getPackage()) - && !new ComponentName(context, this.getClass().getName()).equals(intent - .getComponent())) { - Timber.e("Intent is not explicit"); //$NON-NLS-1$ + && !new ComponentName(context, this.getClass().getName()).equals(intent.getComponent())) { + Timber.e("Intent is not explicit"); // $NON-NLS-1$ return; } - JobIntentService - .enqueueWork(context, TaskerIntentService.class, JobManager.JOB_ID_TASKER, intent); + JobIntentService.enqueueWork( + context, TaskerIntentService.class, JobManager.JOB_ID_TASKER, intent); } } diff --git a/app/src/main/java/org/tasks/locale/receiver/TaskerIntentService.java b/app/src/main/java/org/tasks/locale/receiver/TaskerIntentService.java index 241022e05..83b4e0074 100644 --- a/app/src/main/java/org/tasks/locale/receiver/TaskerIntentService.java +++ b/app/src/main/java/org/tasks/locale/receiver/TaskerIntentService.java @@ -29,18 +29,17 @@ public class TaskerIntentService extends InjectingJobIntentService { protected void onHandleWork(@NonNull Intent intent) { super.onHandleWork(intent); - final Bundle bundle = intent - .getBundleExtra(com.twofortyfouram.locale.api.Intent.EXTRA_BUNDLE); + final Bundle bundle = intent.getBundleExtra(com.twofortyfouram.locale.api.Intent.EXTRA_BUNDLE); if (null == bundle) { - Timber.e("%s is missing", - com.twofortyfouram.locale.api.Intent.EXTRA_BUNDLE); //$NON-NLS-1$ + Timber.e("%s is missing", com.twofortyfouram.locale.api.Intent.EXTRA_BUNDLE); // $NON-NLS-1$ return; } if (ListNotificationBundle.isBundleValid(bundle)) { - Filter filter = defaultFilterProvider.getFilterFromPreference( - bundle.getString(ListNotificationBundle.BUNDLE_EXTRA_STRING_FILTER)); + Filter filter = + defaultFilterProvider.getFilterFromPreference( + bundle.getString(ListNotificationBundle.BUNDLE_EXTRA_STRING_FILTER)); notifier.triggerFilterNotification(filter); tracker.reportEvent(Tracking.Events.TASKER_LIST_NOTIFICATION); } else if (TaskCreationBundle.isBundleValid(bundle)) { diff --git a/app/src/main/java/org/tasks/locale/receiver/TaskerTaskCreator.java b/app/src/main/java/org/tasks/locale/receiver/TaskerTaskCreator.java index 78b15eaca..8bdba737b 100644 --- a/app/src/main/java/org/tasks/locale/receiver/TaskerTaskCreator.java +++ b/app/src/main/java/org/tasks/locale/receiver/TaskerTaskCreator.java @@ -35,8 +35,8 @@ public class TaskerTaskCreator { if (!isNullOrEmpty(dueDateString)) { try { LocalDate dueDate = LocalDate.parse(dueDateString, dateFormatter); - DateTime dt = new DateTime(dueDate.getYear(), dueDate.getMonthValue(), - dueDate.getDayOfMonth()); + DateTime dt = + new DateTime(dueDate.getYear(), dueDate.getMonthValue(), dueDate.getDayOfMonth()); task.setDueDate(Task.createDueDate(Task.URGENCY_SPECIFIC_DAY, dt.getMillis())); } catch (Exception e) { Timber.e(e, e.getMessage()); @@ -47,11 +47,13 @@ public class TaskerTaskCreator { if (!isNullOrEmpty(dueTimeString)) { try { LocalTime dueTime = LocalTime.parse(dueTimeString, timeFormatter); - task.setDueDate(Task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, - new DateTime(task.hasDueDate() ? task.getDueDate() : currentTimeMillis()) - .withHourOfDay(dueTime.getHour()) - .withMinuteOfHour(dueTime.getMinute()) - .getMillis())); + task.setDueDate( + Task.createDueDate( + Task.URGENCY_SPECIFIC_DAY_TIME, + new DateTime(task.hasDueDate() ? task.getDueDate() : currentTimeMillis()) + .withHourOfDay(dueTime.getHour()) + .withMinuteOfHour(dueTime.getMinute()) + .getMillis())); } catch (Exception e) { Timber.e(e, e.getMessage()); } diff --git a/app/src/main/java/org/tasks/locale/ui/activity/AbstractFragmentPluginAppCompatActivity.java b/app/src/main/java/org/tasks/locale/ui/activity/AbstractFragmentPluginAppCompatActivity.java index 98c7e0d02..344a6ecd4 100644 --- a/app/src/main/java/org/tasks/locale/ui/activity/AbstractFragmentPluginAppCompatActivity.java +++ b/app/src/main/java/org/tasks/locale/ui/activity/AbstractFragmentPluginAppCompatActivity.java @@ -6,8 +6,8 @@ import com.todoroo.andlib.utility.AndroidUtilities; import org.tasks.injection.ThemedInjectingAppCompatActivity; import timber.log.Timber; -public abstract class AbstractFragmentPluginAppCompatActivity extends - ThemedInjectingAppCompatActivity { +public abstract class AbstractFragmentPluginAppCompatActivity + extends ThemedInjectingAppCompatActivity { boolean mIsCancelled = false; @@ -26,8 +26,9 @@ public abstract class AbstractFragmentPluginAppCompatActivity extends if (isLocalePluginIntent(getIntent())) { final Bundle previousBundle = getPreviousBundle(); - Timber.d("Creating Activity with Intent=%s, savedInstanceState=%s, EXTRA_BUNDLE=%s", - getIntent(), savedInstanceState, previousBundle); //$NON-NLS-1$ + Timber.d( + "Creating Activity with Intent=%s, savedInstanceState=%s, EXTRA_BUNDLE=%s", + getIntent(), savedInstanceState, previousBundle); // $NON-NLS-1$ } } @@ -56,10 +57,8 @@ public abstract class AbstractFragmentPluginAppCompatActivity extends if (null != resultBundle) { String blurb = getResultBlurb(resultBundle); Intent resultIntent = new Intent(); - resultIntent.putExtra(com.twofortyfouram.locale.api.Intent.EXTRA_BUNDLE, - resultBundle); - resultIntent.putExtra(com.twofortyfouram.locale.api.Intent.EXTRA_STRING_BLURB, - blurb); + resultIntent.putExtra(com.twofortyfouram.locale.api.Intent.EXTRA_BUNDLE, resultBundle); + resultIntent.putExtra(com.twofortyfouram.locale.api.Intent.EXTRA_STRING_BLURB, blurb); setResult(RESULT_OK, resultIntent); } } @@ -69,13 +68,13 @@ public abstract class AbstractFragmentPluginAppCompatActivity extends /** * @return The {@link com.twofortyfouram.locale.api.Intent#EXTRA_BUNDLE EXTRA_BUNDLE} that was - * previously saved to the host and subsequently passed back to this Activity for further editing. - * Internally, this method relies on {@link #isBundleValid(Bundle)}. If the bundle exists but is - * not valid, this method will return null. + * previously saved to the host and subsequently passed back to this Activity for further + * editing. Internally, this method relies on {@link #isBundleValid(Bundle)}. If the bundle + * exists but is not valid, this method will return null. */ private Bundle getPreviousBundle() { - final Bundle bundle = getIntent().getBundleExtra( - com.twofortyfouram.locale.api.Intent.EXTRA_BUNDLE); + final Bundle bundle = + getIntent().getBundleExtra(com.twofortyfouram.locale.api.Intent.EXTRA_BUNDLE); if (null != bundle) { if (isBundleValid(bundle)) { @@ -88,38 +87,36 @@ public abstract class AbstractFragmentPluginAppCompatActivity extends /** * @return The {@link com.twofortyfouram.locale.api.Intent#EXTRA_STRING_BLURB EXTRA_STRING_BLURB} - * that was previously saved to the host and subsequently passed back to this Activity for further - * editing. + * that was previously saved to the host and subsequently passed back to this Activity for + * further editing. */ private String getPreviousBlurb() { - return getIntent().getStringExtra( - com.twofortyfouram.locale.api.Intent.EXTRA_STRING_BLURB); + return getIntent().getStringExtra(com.twofortyfouram.locale.api.Intent.EXTRA_STRING_BLURB); } /** - *

    Validates the Bundle, to ensure that a malicious application isn't attempting to pass - * an invalid Bundle.

    + * Validates the Bundle, to ensure that a malicious application isn't attempting to pass an + * invalid Bundle. * - * @param bundle The plug-in's Bundle previously returned by the edit Activity. {@code bundle} - * should not be mutated by this method. + * @param bundle The plug-in's Bundle previously returned by the edit Activity. {@code bundle} + * should not be mutated by this method. * @return true if {@code bundle} is valid for the plug-in. */ protected abstract boolean isBundleValid(final Bundle bundle); /** - * Plug-in Activity lifecycle callback to allow the Activity to restore - * state for editing a previously saved plug-in instance. This callback will - * occur during the onPostCreate() phase of the Activity lifecycle. - *

    {@code bundle} will have been - * validated by {@link #isBundleValid(Bundle)} prior to this - * method being called. If {@link #isBundleValid(Bundle)} returned false, then this - * method will not be called. This helps ensure that plug-in Activity subclasses only have to - * worry about bundle validation once, in the {@link #isBundleValid(Bundle)} - * method.

    + * Plug-in Activity lifecycle callback to allow the Activity to restore state for editing a + * previously saved plug-in instance. This callback will occur during the onPostCreate() phase of + * the Activity lifecycle. + * + *

    {@code bundle} will have been validated by {@link #isBundleValid(Bundle)} prior to this + * method being called. If {@link #isBundleValid(Bundle)} returned false, then this method will + * not be called. This helps ensure that plug-in Activity subclasses only have to worry about + * bundle validation once, in the {@link #isBundleValid(Bundle)} method. + * *

    Note this callback only occurs the first time the Activity is created, so it will not be - * called - * when the Activity is recreated (e.g. {@code savedInstanceState != null}) such as after a - * configuration change like a screen rotation.

    + * called when the Activity is recreated (e.g. {@code savedInstanceState != null}) such as after a + * configuration change like a screen rotation. * * @param previousBundle Previous bundle that the Activity saved. * @param previousBlurb Previous blurb that the Activity saved @@ -127,9 +124,7 @@ public abstract class AbstractFragmentPluginAppCompatActivity extends protected abstract void onPostCreateWithPreviousResult( final Bundle previousBundle, final String previousBlurb); - /** - * @return Bundle for the plug-in or {@code null} if a valid Bundle cannot be generated. - */ + /** @return Bundle for the plug-in or {@code null} if a valid Bundle cannot be generated. */ protected abstract Bundle getResultBundle(); /** @@ -137,4 +132,4 @@ public abstract class AbstractFragmentPluginAppCompatActivity extends * @return Blurb for {@code bundle}. */ protected abstract String getResultBlurb(final Bundle bundle); -} \ No newline at end of file +} diff --git a/app/src/main/java/org/tasks/locale/ui/activity/AbstractFragmentPluginPreferenceActivity.java b/app/src/main/java/org/tasks/locale/ui/activity/AbstractFragmentPluginPreferenceActivity.java index 2c8ad44f4..0cb5f3484 100644 --- a/app/src/main/java/org/tasks/locale/ui/activity/AbstractFragmentPluginPreferenceActivity.java +++ b/app/src/main/java/org/tasks/locale/ui/activity/AbstractFragmentPluginPreferenceActivity.java @@ -24,8 +24,9 @@ public abstract class AbstractFragmentPluginPreferenceActivity extends Injecting if (isLocalePluginIntent(getIntent())) { final Bundle previousBundle = getPreviousBundle(); - Timber.d("Creating Activity with Intent=%s, savedInstanceState=%s, EXTRA_BUNDLE=%s", - getIntent(), savedInstanceState, previousBundle); //$NON-NLS-1$ + Timber.d( + "Creating Activity with Intent=%s, savedInstanceState=%s, EXTRA_BUNDLE=%s", + getIntent(), savedInstanceState, previousBundle); // $NON-NLS-1$ } } @@ -53,10 +54,8 @@ public abstract class AbstractFragmentPluginPreferenceActivity extends Injecting if (null != resultBundle) { String blurb = getResultBlurb(resultBundle); Intent resultIntent = new Intent(); - resultIntent.putExtra(com.twofortyfouram.locale.api.Intent.EXTRA_BUNDLE, - resultBundle); - resultIntent.putExtra(com.twofortyfouram.locale.api.Intent.EXTRA_STRING_BLURB, - blurb); + resultIntent.putExtra(com.twofortyfouram.locale.api.Intent.EXTRA_BUNDLE, resultBundle); + resultIntent.putExtra(com.twofortyfouram.locale.api.Intent.EXTRA_STRING_BLURB, blurb); setResult(RESULT_OK, resultIntent); } } @@ -66,13 +65,13 @@ public abstract class AbstractFragmentPluginPreferenceActivity extends Injecting /** * @return The {@link com.twofortyfouram.locale.api.Intent#EXTRA_BUNDLE EXTRA_BUNDLE} that was - * previously saved to the host and subsequently passed back to this Activity for further editing. - * Internally, this method relies on {@link #isBundleValid(Bundle)}. If the bundle exists but is - * not valid, this method will return null. + * previously saved to the host and subsequently passed back to this Activity for further + * editing. Internally, this method relies on {@link #isBundleValid(Bundle)}. If the bundle + * exists but is not valid, this method will return null. */ private Bundle getPreviousBundle() { - final Bundle bundle = getIntent().getBundleExtra( - com.twofortyfouram.locale.api.Intent.EXTRA_BUNDLE); + final Bundle bundle = + getIntent().getBundleExtra(com.twofortyfouram.locale.api.Intent.EXTRA_BUNDLE); if (null != bundle) { if (isBundleValid(bundle)) { @@ -85,38 +84,36 @@ public abstract class AbstractFragmentPluginPreferenceActivity extends Injecting /** * @return The {@link com.twofortyfouram.locale.api.Intent#EXTRA_STRING_BLURB EXTRA_STRING_BLURB} - * that was previously saved to the host and subsequently passed back to this Activity for further - * editing. + * that was previously saved to the host and subsequently passed back to this Activity for + * further editing. */ private String getPreviousBlurb() { - return getIntent().getStringExtra( - com.twofortyfouram.locale.api.Intent.EXTRA_STRING_BLURB); + return getIntent().getStringExtra(com.twofortyfouram.locale.api.Intent.EXTRA_STRING_BLURB); } /** - *

    Validates the Bundle, to ensure that a malicious application isn't attempting to pass - * an invalid Bundle.

    + * Validates the Bundle, to ensure that a malicious application isn't attempting to pass an + * invalid Bundle. * - * @param bundle The plug-in's Bundle previously returned by the edit Activity. {@code bundle} - * should not be mutated by this method. + * @param bundle The plug-in's Bundle previously returned by the edit Activity. {@code bundle} + * should not be mutated by this method. * @return true if {@code bundle} is valid for the plug-in. */ protected abstract boolean isBundleValid(final Bundle bundle); /** - * Plug-in Activity lifecycle callback to allow the Activity to restore - * state for editing a previously saved plug-in instance. This callback will - * occur during the onPostCreate() phase of the Activity lifecycle. - *

    {@code bundle} will have been - * validated by {@link #isBundleValid(Bundle)} prior to this - * method being called. If {@link #isBundleValid(Bundle)} returned false, then this - * method will not be called. This helps ensure that plug-in Activity subclasses only have to - * worry about bundle validation once, in the {@link #isBundleValid(Bundle)} - * method.

    + * Plug-in Activity lifecycle callback to allow the Activity to restore state for editing a + * previously saved plug-in instance. This callback will occur during the onPostCreate() phase of + * the Activity lifecycle. + * + *

    {@code bundle} will have been validated by {@link #isBundleValid(Bundle)} prior to this + * method being called. If {@link #isBundleValid(Bundle)} returned false, then this method will + * not be called. This helps ensure that plug-in Activity subclasses only have to worry about + * bundle validation once, in the {@link #isBundleValid(Bundle)} method. + * *

    Note this callback only occurs the first time the Activity is created, so it will not be - * called - * when the Activity is recreated (e.g. {@code savedInstanceState != null}) such as after a - * configuration change like a screen rotation.

    + * called when the Activity is recreated (e.g. {@code savedInstanceState != null}) such as after a + * configuration change like a screen rotation. * * @param previousBundle Previous bundle that the Activity saved. * @param previousBlurb Previous blurb that the Activity saved @@ -124,9 +121,7 @@ public abstract class AbstractFragmentPluginPreferenceActivity extends Injecting protected abstract void onPostCreateWithPreviousResult( final Bundle previousBundle, final String previousBlurb); - /** - * @return Bundle for the plug-in or {@code null} if a valid Bundle cannot be generated. - */ + /** @return Bundle for the plug-in or {@code null} if a valid Bundle cannot be generated. */ protected abstract Bundle getResultBundle(); /** @@ -134,4 +129,4 @@ public abstract class AbstractFragmentPluginPreferenceActivity extends Injecting * @return Blurb for {@code bundle}. */ protected abstract String getResultBlurb(final Bundle bundle); -} \ No newline at end of file +} diff --git a/app/src/main/java/org/tasks/locale/ui/activity/TaskerCreateTaskActivity.java b/app/src/main/java/org/tasks/locale/ui/activity/TaskerCreateTaskActivity.java index fba7bac88..fc5af1d84 100755 --- a/app/src/main/java/org/tasks/locale/ui/activity/TaskerCreateTaskActivity.java +++ b/app/src/main/java/org/tasks/locale/ui/activity/TaskerCreateTaskActivity.java @@ -19,9 +19,8 @@ import org.tasks.locale.bundle.TaskCreationBundle; import org.tasks.preferences.Preferences; import org.tasks.ui.MenuColorizer; -public final class TaskerCreateTaskActivity extends - AbstractFragmentPluginAppCompatActivity implements PurchaseHelperCallback, - Toolbar.OnMenuItemClickListener { +public final class TaskerCreateTaskActivity extends AbstractFragmentPluginAppCompatActivity + implements PurchaseHelperCallback, Toolbar.OnMenuItemClickListener { private static final int REQUEST_PURCHASE = 10125; private static final String EXTRA_PURCHASE_INITIATED = "extra_purchase_initiated"; @@ -29,12 +28,23 @@ public final class TaskerCreateTaskActivity extends @Inject Preferences preferences; @Inject PurchaseHelper purchaseHelper; - @BindView(R.id.title) TextInputEditText title; - @BindView(R.id.toolbar) Toolbar toolbar; - @BindView(R.id.due_date) TextInputEditText dueDate; - @BindView(R.id.due_time) TextInputEditText dueTime; - @BindView(R.id.priority) TextInputEditText priority; - @BindView(R.id.description) TextInputEditText description; + @BindView(R.id.title) + TextInputEditText title; + + @BindView(R.id.toolbar) + Toolbar toolbar; + + @BindView(R.id.due_date) + TextInputEditText dueDate; + + @BindView(R.id.due_time) + TextInputEditText dueTime; + + @BindView(R.id.priority) + TextInputEditText priority; + + @BindView(R.id.description) + TextInputEditText description; private Bundle previousBundle; private boolean purchaseInitiated; @@ -49,15 +59,17 @@ public final class TaskerCreateTaskActivity extends toolbar.setTitle(R.string.tasker_create_task); final boolean backButtonSavesTask = preferences.backButtonSavesTask(); - toolbar.setNavigationIcon(ContextCompat.getDrawable(this, - backButtonSavesTask ? R.drawable.ic_close_24dp : R.drawable.ic_save_24dp)); - toolbar.setNavigationOnClickListener(v -> { - if (backButtonSavesTask) { - discardButtonClick(); - } else { - save(); - } - }); + toolbar.setNavigationIcon( + ContextCompat.getDrawable( + this, backButtonSavesTask ? R.drawable.ic_close_24dp : R.drawable.ic_save_24dp)); + toolbar.setNavigationOnClickListener( + v -> { + if (backButtonSavesTask) { + discardButtonClick(); + } else { + save(); + } + }); toolbar.setOnMenuItemClickListener(this); toolbar.inflateMenu(R.menu.menu_tasker_create_task); MenuColorizer.colorToolbar(this, toolbar); @@ -70,15 +82,19 @@ public final class TaskerCreateTaskActivity extends } if (!preferences.hasPurchase(R.string.p_purchased_tasker) && !purchaseInitiated) { - purchaseInitiated = purchaseHelper - .purchase(this, getString(R.string.sku_tasker), getString(R.string.p_purchased_tasker), - REQUEST_PURCHASE, this); + purchaseInitiated = + purchaseHelper.purchase( + this, + getString(R.string.sku_tasker), + getString(R.string.p_purchased_tasker), + REQUEST_PURCHASE, + this); } } @Override - public void onPostCreateWithPreviousResult(final Bundle previousBundle, - final String previousBlurb) { + public void onPostCreateWithPreviousResult( + final Bundle previousBundle, final String previousBlurb) { this.previousBundle = previousBundle; TaskCreationBundle bundle = new TaskCreationBundle(previousBundle); title.setText(bundle.getTitle()); @@ -103,13 +119,15 @@ public final class TaskerCreateTaskActivity extends bundle.setDescription(description.getText().toString().trim()); Bundle resultBundle = bundle.build(); if (TaskerPlugin.Setting.hostSupportsOnFireVariableReplacement(this)) { - TaskerPlugin.Setting.setVariableReplaceKeys(resultBundle, new String[]{ - TaskCreationBundle.EXTRA_TITLE, - TaskCreationBundle.EXTRA_DUE_DATE, - TaskCreationBundle.EXTRA_DUE_TIME, - TaskCreationBundle.EXTRA_PRIORITY, - TaskCreationBundle.EXTRA_DESCRIPTION - }); + TaskerPlugin.Setting.setVariableReplaceKeys( + resultBundle, + new String[] { + TaskCreationBundle.EXTRA_TITLE, + TaskCreationBundle.EXTRA_DUE_DATE, + TaskCreationBundle.EXTRA_DUE_TIME, + TaskCreationBundle.EXTRA_PRIORITY, + TaskCreationBundle.EXTRA_DESCRIPTION + }); } return resultBundle; } diff --git a/app/src/main/java/org/tasks/locale/ui/activity/TaskerSettingsActivity.java b/app/src/main/java/org/tasks/locale/ui/activity/TaskerSettingsActivity.java index d279dc963..ac6891709 100755 --- a/app/src/main/java/org/tasks/locale/ui/activity/TaskerSettingsActivity.java +++ b/app/src/main/java/org/tasks/locale/ui/activity/TaskerSettingsActivity.java @@ -15,9 +15,8 @@ import org.tasks.locale.bundle.ListNotificationBundle; import org.tasks.preferences.DefaultFilterProvider; import org.tasks.preferences.Preferences; -public final class TaskerSettingsActivity extends - AbstractFragmentPluginPreferenceActivity implements PurchaseHelperCallback, - Toolbar.OnMenuItemClickListener { +public final class TaskerSettingsActivity extends AbstractFragmentPluginPreferenceActivity + implements PurchaseHelperCallback, Toolbar.OnMenuItemClickListener { private static final int REQUEST_SELECT_FILTER = 10124; private static final int REQUEST_PURCHASE = 10125; @@ -39,37 +38,45 @@ public final class TaskerSettingsActivity extends addPreferencesFromResource(R.xml.preferences_tasker); if (savedInstanceState != null) { - previousBundle = savedInstanceState - .getParcelable(ListNotificationBundle.BUNDLE_EXTRA_PREVIOUS_BUNDLE); + previousBundle = + savedInstanceState.getParcelable(ListNotificationBundle.BUNDLE_EXTRA_PREVIOUS_BUNDLE); filter = savedInstanceState.getParcelable(EXTRA_FILTER); purchaseInitiated = savedInstanceState.getBoolean(EXTRA_PURCHASE_INITIATED); } else { filter = defaultFilterProvider.getDefaultFilter(); } - findPreference(R.string.filter).setOnPreferenceClickListener(preference -> { - Intent intent = new Intent(TaskerSettingsActivity.this, FilterSelectionActivity.class); - intent.putExtra(FilterSelectionActivity.EXTRA_FILTER, filter); - intent.putExtra(FilterSelectionActivity.EXTRA_RETURN_FILTER, true); - startActivityForResult(intent, REQUEST_SELECT_FILTER); - return false; - }); + findPreference(R.string.filter) + .setOnPreferenceClickListener( + preference -> { + Intent intent = + new Intent(TaskerSettingsActivity.this, FilterSelectionActivity.class); + intent.putExtra(FilterSelectionActivity.EXTRA_FILTER, filter); + intent.putExtra(FilterSelectionActivity.EXTRA_RETURN_FILTER, true); + startActivityForResult(intent, REQUEST_SELECT_FILTER); + return false; + }); refreshPreferences(); if (!preferences.hasPurchase(R.string.p_purchased_tasker) && !purchaseInitiated) { - purchaseInitiated = purchaseHelper - .purchase(this, getString(R.string.sku_tasker), getString(R.string.p_purchased_tasker), - REQUEST_PURCHASE, this); + purchaseInitiated = + purchaseHelper.purchase( + this, + getString(R.string.sku_tasker), + getString(R.string.p_purchased_tasker), + REQUEST_PURCHASE, + this); } } @Override - public void onPostCreateWithPreviousResult(final Bundle previousBundle, - final String previousBlurb) { + public void onPostCreateWithPreviousResult( + final Bundle previousBundle, final String previousBlurb) { this.previousBundle = previousBundle; - this.filter = defaultFilterProvider - .getFilterFromPreference(ListNotificationBundle.getFilter(previousBundle)); + this.filter = + defaultFilterProvider.getFilterFromPreference( + ListNotificationBundle.getFilter(previousBundle)); refreshPreferences(); } @@ -80,8 +87,8 @@ public final class TaskerSettingsActivity extends @Override protected Bundle getResultBundle() { - return ListNotificationBundle - .generateBundle(defaultFilterProvider.getFilterPreferenceValue(filter)); + return ListNotificationBundle.generateBundle( + defaultFilterProvider.getFilterPreferenceValue(filter)); } @Override diff --git a/app/src/main/java/org/tasks/location/GeofenceService.java b/app/src/main/java/org/tasks/location/GeofenceService.java index 6f79f5b9c..50d0aa464 100644 --- a/app/src/main/java/org/tasks/location/GeofenceService.java +++ b/app/src/main/java/org/tasks/location/GeofenceService.java @@ -51,8 +51,8 @@ public class GeofenceService { return changed; } - private boolean synchronizeMetadata(long taskId, List locations, - final SynchronizeGeofenceCallback callback) { + private boolean synchronizeMetadata( + long taskId, List locations, final SynchronizeGeofenceCallback callback) { boolean dirty = false; for (Location metadatum : locations) { metadatum.setTask(taskId); diff --git a/app/src/main/java/org/tasks/notifications/Notification.java b/app/src/main/java/org/tasks/notifications/Notification.java index 2c046d092..21b22cdab 100644 --- a/app/src/main/java/org/tasks/notifications/Notification.java +++ b/app/src/main/java/org/tasks/notifications/Notification.java @@ -5,8 +5,10 @@ import android.arch.persistence.room.Entity; import android.arch.persistence.room.Index; import android.arch.persistence.room.PrimaryKey; -@Entity(tableName = "notification", - indices = {@Index(value = "task", unique = true)}) +@Entity( + tableName = "notification", + indices = {@Index(value = "task", unique = true)} +) public class Notification { @PrimaryKey(autoGenerate = true) @@ -24,11 +26,15 @@ public class Notification { @Override public String toString() { - return "Notification{" + - "uid=" + uid + - ", taskId=" + taskId + - ", timestamp=" + timestamp + - ", type=" + type + - '}'; + return "Notification{" + + "uid=" + + uid + + ", taskId=" + + taskId + + ", timestamp=" + + timestamp + + ", type=" + + type + + '}'; } } diff --git a/app/src/main/java/org/tasks/notifications/NotificationManager.java b/app/src/main/java/org/tasks/notifications/NotificationManager.java index 0c612f7e6..3ba882774 100644 --- a/app/src/main/java/org/tasks/notifications/NotificationManager.java +++ b/app/src/main/java/org/tasks/notifications/NotificationManager.java @@ -55,8 +55,8 @@ public class NotificationManager { public static final String NOTIFICATION_CHANNEL_TASKER = "notifications_tasker"; public static final String NOTIFICATION_CHANNEL_CALLS = "notifications_calls"; public static final String NOTIFICATION_CHANNEL_TIMERS = "notifications_timers"; - private static final String GROUP_KEY = "tasks"; static final String EXTRA_NOTIFICATION_ID = "extra_notification_id"; + private static final String GROUP_KEY = "tasks"; private static final int SUMMARY_NOTIFICATION_ID = 0; private final NotificationManagerCompat notificationManagerCompat; private final NotificationDao notificationDao; @@ -66,8 +66,12 @@ public class NotificationManager { private final CheckBoxes checkBoxes; @Inject - public NotificationManager(@ForApplication Context context, Preferences preferences, - NotificationDao notificationDao, TaskDao taskDao, CheckBoxes checkBoxes) { + public NotificationManager( + @ForApplication Context context, + Preferences preferences, + NotificationDao notificationDao, + TaskDao taskDao, + CheckBoxes checkBoxes) { this.context = context; this.preferences = preferences; this.notificationDao = notificationDao; @@ -75,8 +79,8 @@ public class NotificationManager { this.checkBoxes = checkBoxes; notificationManagerCompat = NotificationManagerCompat.from(context); if (atLeastOreo()) { - android.app.NotificationManager notificationManager = (android.app.NotificationManager) - context.getSystemService(Context.NOTIFICATION_SERVICE); + android.app.NotificationManager notificationManager = + (android.app.NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.createNotificationChannel( createNotificationChannel(NOTIFICATION_CHANNEL_DEFAULT, R.string.notifications)); notificationManager.createNotificationChannel( @@ -91,8 +95,9 @@ public class NotificationManager { @TargetApi(Build.VERSION_CODES.O) private NotificationChannel createNotificationChannel(String channelId, int nameResId) { String channelName = context.getString(nameResId); - NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, - android.app.NotificationManager.IMPORTANCE_HIGH); + NotificationChannel notificationChannel = + new NotificationChannel( + channelId, channelName, android.app.NotificationManager.IMPORTANCE_HIGH); notificationChannel.enableLights(true); notificationChannel.enableVibration(true); notificationChannel.setBypassDnd(true); @@ -103,31 +108,33 @@ public class NotificationManager { public void cancel(long id) { notificationManagerCompat.cancel((int) id); - Completable.fromAction(() -> { - if (id == SUMMARY_NOTIFICATION_ID) { - List tasks = transform(notificationDao.getAll(), n -> n.taskId); - for (Long task : tasks) { - notificationManagerCompat.cancel(task.intValue()); - } - notificationDao.deleteAll(tasks); - } else if (notificationDao.delete(id) > 0) { - notifyTasks(Collections.emptyList(), false, false, false); - } - }) + Completable.fromAction( + () -> { + if (id == SUMMARY_NOTIFICATION_ID) { + List tasks = transform(notificationDao.getAll(), n -> n.taskId); + for (Long task : tasks) { + notificationManagerCompat.cancel(task.intValue()); + } + notificationDao.deleteAll(tasks); + } else if (notificationDao.delete(id) > 0) { + notifyTasks(Collections.emptyList(), false, false, false); + } + }) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(); } public void cancel(List ids) { - Completable.fromAction(() -> { - for (Long id : ids) { - notificationManagerCompat.cancel(id.intValue()); - } - if (notificationDao.deleteAll(ids) > 0) { - notifyTasks(Collections.emptyList(), false, false, false); - } - }) + Completable.fromAction( + () -> { + for (Long id : ids) { + notificationManagerCompat.cancel(id.intValue()); + } + if (notificationDao.deleteAll(ids) > 0) { + notifyTasks(Collections.emptyList(), false, false, false); + } + }) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(); @@ -150,10 +157,13 @@ public class NotificationManager { } } - public void notifyTasks(List newNotifications, - boolean alert, boolean nonstop, boolean fiveTimes) { - List existingNotifications = notificationDao - .getAllOrdered(); + public void notifyTasks( + List newNotifications, + boolean alert, + boolean nonstop, + boolean fiveTimes) { + List existingNotifications = + notificationDao.getAllOrdered(); notificationDao.insertAll(newNotifications); int totalCount = existingNotifications.size() + newNotifications.size(); if (totalCount == 0) { @@ -181,37 +191,50 @@ public class NotificationManager { } } - private void createNotifications(List notifications, - boolean alert, boolean nonstop, boolean fiveTimes, boolean useGroupKey) { + private void createNotifications( + List notifications, + boolean alert, + boolean nonstop, + boolean fiveTimes, + boolean useGroupKey) { for (org.tasks.notifications.Notification notification : notifications) { NotificationCompat.Builder builder = getTaskNotification(notification); if (builder == null) { notificationManagerCompat.cancel((int) notification.taskId); notificationDao.delete(notification.taskId); } else { - builder.setGroup( - useGroupKey ? GROUP_KEY : (atLeastNougat() ? Long.toString(notification.taskId) : null)) - .setGroupAlertBehavior(alert ? NotificationCompat.GROUP_ALERT_CHILDREN - : NotificationCompat.GROUP_ALERT_SUMMARY); + builder + .setGroup( + useGroupKey + ? GROUP_KEY + : (atLeastNougat() ? Long.toString(notification.taskId) : null)) + .setGroupAlertBehavior( + alert + ? NotificationCompat.GROUP_ALERT_CHILDREN + : NotificationCompat.GROUP_ALERT_SUMMARY); notify(notification.taskId, builder, alert, nonstop, fiveTimes); alert = false; } } } - public void notify(long notificationId, NotificationCompat.Builder builder, boolean alert, - boolean nonstop, boolean fiveTimes) { + public void notify( + long notificationId, + NotificationCompat.Builder builder, + boolean alert, + boolean nonstop, + boolean fiveTimes) { if (!preferences.getBoolean(R.string.p_rmd_enabled, true)) { return; } int ringTimes = fiveTimes ? 5 : 1; if (alert) { - builder.setSound(preferences.getRingtone()) + builder + .setSound(preferences.getRingtone()) .setPriority(NotificationCompat.PRIORITY_HIGH) .setDefaults(preferences.getNotificationDefaults()); } else { - builder.setDefaults(0) - .setTicker(null); + builder.setDefaults(0).setTicker(null); } Notification notification = builder.build(); if (alert && nonstop) { @@ -223,27 +246,32 @@ public class NotificationManager { } Intent deleteIntent = new Intent(context, NotificationClearedReceiver.class); deleteIntent.putExtra(EXTRA_NOTIFICATION_ID, notificationId); - notification.deleteIntent = PendingIntent - .getBroadcast(context, (int) notificationId, deleteIntent, - PendingIntent.FLAG_UPDATE_CURRENT); + notification.deleteIntent = + PendingIntent.getBroadcast( + context, (int) notificationId, deleteIntent, PendingIntent.FLAG_UPDATE_CURRENT); for (int i = 0; i < ringTimes; i++) { notificationManagerCompat.notify((int) notificationId, notification); } } - private void updateSummary(boolean notify, boolean nonStop, boolean fiveTimes, + private void updateSummary( + boolean notify, + boolean nonStop, + boolean fiveTimes, List newNotifications) { List tasks = taskDao.activeNotifications(); int taskCount = tasks.size(); ArrayList taskIds = newArrayList(transform(tasks, Task::getId)); - Filter filter = new Filter(context.getString(R.string.notifications), - new QueryTemplate().where(Task.ID.in(taskIds))); + Filter filter = + new Filter( + context.getString(R.string.notifications), + new QueryTemplate().where(Task.ID.in(taskIds))); long when = notificationDao.latestTimestamp(); int maxPriority = 3; - String summaryTitle = context.getResources() - .getQuantityString(R.plurals.task_count, taskCount, taskCount); - NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle() - .setBigContentTitle(summaryTitle); + String summaryTitle = + context.getResources().getQuantityString(R.plurals.task_count, taskCount, taskCount); + NotificationCompat.InboxStyle style = + new NotificationCompat.InboxStyle().setBigContentTitle(summaryTitle); List titles = newArrayList(); List ticker = newArrayList(); for (Task task : tasks) { @@ -259,25 +287,31 @@ public class NotificationManager { } ticker.add(task.getTitle()); } - NotificationCompat.Builder builder = new NotificationCompat.Builder(context, - NotificationManager.NOTIFICATION_CHANNEL_DEFAULT) - .setContentTitle(summaryTitle) - .setContentText( - Joiner.on(context.getString(R.string.list_separator_with_space)).join(titles)) - .setShowWhen(true) - .setWhen(when) - .setSmallIcon(R.drawable.ic_done_all_white_24dp) - .setStyle(style) - .setColor(checkBoxes.getPriorityColor(maxPriority)) - .setOnlyAlertOnce(false) - .setContentIntent(PendingIntent - .getActivity(context, 0, TaskIntents.getTaskListIntent(context, filter), - PendingIntent.FLAG_UPDATE_CURRENT)) - .setGroupSummary(true) - .setGroup(GROUP_KEY) - .setTicker(Joiner.on(context.getString(R.string.list_separator_with_space)).join(ticker)) - .setGroupAlertBehavior(notify ? NotificationCompat.GROUP_ALERT_SUMMARY - : NotificationCompat.GROUP_ALERT_CHILDREN); + NotificationCompat.Builder builder = + new NotificationCompat.Builder(context, NotificationManager.NOTIFICATION_CHANNEL_DEFAULT) + .setContentTitle(summaryTitle) + .setContentText( + Joiner.on(context.getString(R.string.list_separator_with_space)).join(titles)) + .setShowWhen(true) + .setWhen(when) + .setSmallIcon(R.drawable.ic_done_all_white_24dp) + .setStyle(style) + .setColor(checkBoxes.getPriorityColor(maxPriority)) + .setOnlyAlertOnce(false) + .setContentIntent( + PendingIntent.getActivity( + context, + 0, + TaskIntents.getTaskListIntent(context, filter), + PendingIntent.FLAG_UPDATE_CURRENT)) + .setGroupSummary(true) + .setGroup(GROUP_KEY) + .setTicker( + Joiner.on(context.getString(R.string.list_separator_with_space)).join(ticker)) + .setGroupAlertBehavior( + notify + ? NotificationCompat.GROUP_ALERT_SUMMARY + : NotificationCompat.GROUP_ALERT_CHILDREN); Intent snoozeIntent = new Intent(context, SnoozeActivity.class); snoozeIntent.setFlags(FLAG_ACTIVITY_NEW_TASK); @@ -317,10 +351,12 @@ public class NotificationManager { } // task due date was changed, but alarm wasn't rescheduled - boolean dueInFuture = task.hasDueTime() && task.getDueDate() > DateUtilities.now() || - !task.hasDueTime() && task.getDueDate() - DateUtilities.now() > DateUtilities.ONE_DAY; - if ((type == ReminderService.TYPE_DUE || type == ReminderService.TYPE_OVERDUE) && - (!task.hasDueDate() || dueInFuture)) { + boolean dueInFuture = + task.hasDueTime() && task.getDueDate() > DateUtilities.now() + || !task.hasDueTime() + && task.getDueDate() - DateUtilities.now() > DateUtilities.ONE_DAY; + if ((type == ReminderService.TYPE_DUE || type == ReminderService.TYPE_OVERDUE) + && (!task.hasDueDate() || dueInFuture)) { return null; } @@ -332,21 +368,21 @@ public class NotificationManager { task.setReminderLast(new DateTime(when).endOfMinute().getMillis()); taskDao.save(task); - NotificationCompat.Builder builder = new NotificationCompat.Builder(context, - NotificationManager.NOTIFICATION_CHANNEL_DEFAULT) - .setCategory(NotificationCompat.CATEGORY_REMINDER) - .setContentTitle(taskTitle) - .setContentText(context.getString(R.string.app_name)) - .setColor(checkBoxes.getPriorityColor(task.getImportance())) - .setSmallIcon(R.drawable.ic_check_white_24dp) - .setWhen(when) - .setOnlyAlertOnce(false) - .setShowWhen(true) - .setTicker(taskTitle); + NotificationCompat.Builder builder = + new NotificationCompat.Builder(context, NotificationManager.NOTIFICATION_CHANNEL_DEFAULT) + .setCategory(NotificationCompat.CATEGORY_REMINDER) + .setContentTitle(taskTitle) + .setContentText(context.getString(R.string.app_name)) + .setColor(checkBoxes.getPriorityColor(task.getImportance())) + .setSmallIcon(R.drawable.ic_check_white_24dp) + .setWhen(when) + .setOnlyAlertOnce(false) + .setShowWhen(true) + .setTicker(taskTitle); final Intent intent = new Intent(context, NotificationActivity.class); intent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_MULTIPLE_TASK); - intent.setAction("NOTIFY" + id); //$NON-NLS-1$ + intent.setAction("NOTIFY" + id); // $NON-NLS-1$ intent.putExtra(NotificationActivity.EXTRA_TASK_ID, id); intent.putExtra(NotificationActivity.EXTRA_TITLE, taskTitle); builder.setContentIntent( @@ -357,20 +393,26 @@ public class NotificationManager { } Intent completeIntent = new Intent(context, CompleteTaskReceiver.class); completeIntent.putExtra(CompleteTaskReceiver.TASK_ID, id); - PendingIntent completePendingIntent = PendingIntent - .getBroadcast(context, (int) id, completeIntent, PendingIntent.FLAG_UPDATE_CURRENT); + PendingIntent completePendingIntent = + PendingIntent.getBroadcast( + context, (int) id, completeIntent, PendingIntent.FLAG_UPDATE_CURRENT); - NotificationCompat.Action completeAction = new NotificationCompat.Action.Builder( - R.drawable.ic_check_white_24dp, context.getResources().getString(R.string.rmd_NoA_done), - completePendingIntent).build(); + NotificationCompat.Action completeAction = + new NotificationCompat.Action.Builder( + R.drawable.ic_check_white_24dp, + context.getResources().getString(R.string.rmd_NoA_done), + completePendingIntent) + .build(); Intent snoozeIntent = new Intent(context, SnoozeActivity.class); snoozeIntent.setFlags(FLAG_ACTIVITY_NEW_TASK); snoozeIntent.putExtra(SnoozeActivity.EXTRA_TASK_ID, id); - PendingIntent snoozePendingIntent = PendingIntent - .getActivity(context, (int) id, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT); + PendingIntent snoozePendingIntent = + PendingIntent.getActivity( + context, (int) id, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT); - NotificationCompat.WearableExtender wearableExtender = new NotificationCompat.WearableExtender(); + NotificationCompat.WearableExtender wearableExtender = + new NotificationCompat.WearableExtender(); wearableExtender.addAction(completeAction); for (final SnoozeOption snoozeOption : SnoozeDialog.getSnoozeOptions(preferences)) { final long timestamp = snoozeOption.getDateTime().getMillis(); @@ -379,17 +421,23 @@ public class NotificationManager { wearableIntent.setAction(String.format("snooze-%s-%s", id, timestamp)); wearableIntent.putExtra(SnoozeActivity.EXTRA_TASK_ID, id); wearableIntent.putExtra(SnoozeActivity.EXTRA_SNOOZE_TIME, timestamp); - PendingIntent wearablePendingIntent = PendingIntent - .getActivity(context, (int) id, wearableIntent, PendingIntent.FLAG_UPDATE_CURRENT); - wearableExtender.addAction(new NotificationCompat.Action.Builder( - R.drawable.ic_snooze_white_24dp, context.getString(snoozeOption.getResId()), - wearablePendingIntent) - .build()); + PendingIntent wearablePendingIntent = + PendingIntent.getActivity( + context, (int) id, wearableIntent, PendingIntent.FLAG_UPDATE_CURRENT); + wearableExtender.addAction( + new NotificationCompat.Action.Builder( + R.drawable.ic_snooze_white_24dp, + context.getString(snoozeOption.getResId()), + wearablePendingIntent) + .build()); } - return builder.addAction(completeAction) - .addAction(R.drawable.ic_snooze_white_24dp, - context.getResources().getString(R.string.rmd_NoA_snooze), snoozePendingIntent) + return builder + .addAction(completeAction) + .addAction( + R.drawable.ic_snooze_white_24dp, + context.getResources().getString(R.string.rmd_NoA_snooze), + snoozePendingIntent) .extend(wearableExtender); } } diff --git a/app/src/main/java/org/tasks/notifications/TelephonyManager.java b/app/src/main/java/org/tasks/notifications/TelephonyManager.java index 58917b013..bcc9fb660 100644 --- a/app/src/main/java/org/tasks/notifications/TelephonyManager.java +++ b/app/src/main/java/org/tasks/notifications/TelephonyManager.java @@ -10,8 +10,8 @@ public class TelephonyManager { @Inject public TelephonyManager(@ForApplication Context context) { - telephonyManager = (android.telephony.TelephonyManager) - context.getSystemService(Context.TELEPHONY_SERVICE); + telephonyManager = + (android.telephony.TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); } public boolean callStateIdle() { diff --git a/app/src/main/java/org/tasks/preferences/AppCompatPreferenceActivity.java b/app/src/main/java/org/tasks/preferences/AppCompatPreferenceActivity.java index e6f319b5c..3d278f2e0 100644 --- a/app/src/main/java/org/tasks/preferences/AppCompatPreferenceActivity.java +++ b/app/src/main/java/org/tasks/preferences/AppCompatPreferenceActivity.java @@ -29,9 +29,9 @@ import android.view.ViewGroup; /** * A {@link android.preference.PreferenceActivity} which implements and proxies the necessary calls * to be used with AppCompat. - *

    - * This technique can be used with an {@link android.app.Activity} class, not just - * {@link android.preference.PreferenceActivity}. + * + *

    This technique can be used with an {@link android.app.Activity} class, not just {@link + * android.preference.PreferenceActivity}. */ public abstract class AppCompatPreferenceActivity extends PreferenceActivity { @@ -117,4 +117,4 @@ public abstract class AppCompatPreferenceActivity extends PreferenceActivity { } return mDelegate; } -} \ No newline at end of file +} diff --git a/app/src/main/java/org/tasks/preferences/AppearancePreferences.java b/app/src/main/java/org/tasks/preferences/AppearancePreferences.java index f026ae56b..66cba21d5 100644 --- a/app/src/main/java/org/tasks/preferences/AppearancePreferences.java +++ b/app/src/main/java/org/tasks/preferences/AppearancePreferences.java @@ -18,8 +18,8 @@ import org.tasks.injection.ActivityComponent; import org.tasks.injection.InjectingPreferenceActivity; import org.tasks.locale.Locale; -public class AppearancePreferences extends InjectingPreferenceActivity implements - SeekBarDialog.SeekBarCallback { +public class AppearancePreferences extends InjectingPreferenceActivity + implements SeekBarDialog.SeekBarCallback { public static final String EXTRA_RESTART = "extra_restart"; private static final String EXTRA_FILTERS_CHANGED = "extra_filters_changed"; @@ -42,9 +42,7 @@ public class AppearancePreferences extends InjectingPreferenceActivity implement public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - result = savedInstanceState == null - ? new Bundle() - : savedInstanceState.getBundle(EXTRA_BUNDLE); + result = savedInstanceState == null ? new Bundle() : savedInstanceState.getBundle(EXTRA_BUNDLE); addPreferencesFromResource(R.xml.preferences_appearance); @@ -55,38 +53,53 @@ public class AppearancePreferences extends InjectingPreferenceActivity implement setExtraOnChange(R.string.p_show_recently_modified_filter, EXTRA_FILTERS_CHANGED); setExtraOnChange(R.string.p_show_not_in_list_filter, EXTRA_FILTERS_CHANGED); findPreference(getString(R.string.customize_edit_screen)) - .setOnPreferenceClickListener(preference -> { - startActivityForResult(new Intent(AppearancePreferences.this, BeastModePreferences.class), - REQUEST_CUSTOMIZE); - return true; - }); - - findPreference(R.string.p_fontSize).setOnPreferenceClickListener(preference -> { - newSeekBarDialog(R.layout.dialog_font_size_seekbar, 10, 48, preferences.getFontSize(), - REQUEST_FONT_SIZE) - .show(getFragmentManager(), FRAG_TAG_FONT_SIZE_SEEKBAR); - return false; - }); + .setOnPreferenceClickListener( + preference -> { + startActivityForResult( + new Intent(AppearancePreferences.this, BeastModePreferences.class), + REQUEST_CUSTOMIZE); + return true; + }); + + findPreference(R.string.p_fontSize) + .setOnPreferenceClickListener( + preference -> { + newSeekBarDialog( + R.layout.dialog_font_size_seekbar, + 10, + 48, + preferences.getFontSize(), + REQUEST_FONT_SIZE) + .show(getFragmentManager(), FRAG_TAG_FONT_SIZE_SEEKBAR); + return false; + }); updateFontSize(); - findPreference(R.string.p_rowPadding).setOnPreferenceClickListener(preference -> { - newSeekBarDialog(R.layout.dialog_font_size_seekbar, 0, 16, preferences.getRowPadding(), - REQUEST_ROW_PADDING) - .show(getFragmentManager(), FRAG_TAG_ROW_PADDING_SEEKBAR); - return false; - }); + findPreference(R.string.p_rowPadding) + .setOnPreferenceClickListener( + preference -> { + newSeekBarDialog( + R.layout.dialog_font_size_seekbar, + 0, + 16, + preferences.getRowPadding(), + REQUEST_ROW_PADDING) + .show(getFragmentManager(), FRAG_TAG_ROW_PADDING_SEEKBAR); + return false; + }); updateRowPadding(); Preference defaultList = findPreference(getString(R.string.p_default_list)); Filter filter = defaultFilterProvider.getDefaultFilter(); defaultList.setSummary(filter.listingTitle); - defaultList.setOnPreferenceClickListener(preference -> { - Intent intent = new Intent(AppearancePreferences.this, FilterSelectionActivity.class); - intent - .putExtra(FilterSelectionActivity.EXTRA_FILTER, defaultFilterProvider.getDefaultFilter()); - intent.putExtra(FilterSelectionActivity.EXTRA_RETURN_FILTER, true); - startActivityForResult(intent, REQUEST_DEFAULT_LIST); - return true; - }); + defaultList.setOnPreferenceClickListener( + preference -> { + Intent intent = new Intent(AppearancePreferences.this, FilterSelectionActivity.class); + intent.putExtra( + FilterSelectionActivity.EXTRA_FILTER, defaultFilterProvider.getDefaultFilter()); + intent.putExtra(FilterSelectionActivity.EXTRA_RETURN_FILTER, true); + startActivityForResult(intent, REQUEST_DEFAULT_LIST); + return true; + }); } @Override @@ -123,11 +136,13 @@ public class AppearancePreferences extends InjectingPreferenceActivity implement } private void setExtraOnChange(final int resId, final String extra) { - findPreference(getString(resId)).setOnPreferenceChangeListener((preference, newValue) -> { - tracker.reportEvent(Tracking.Events.SET_PREFERENCE, resId, newValue.toString()); - result.putBoolean(extra, true); - return true; - }); + findPreference(getString(resId)) + .setOnPreferenceChangeListener( + (preference, newValue) -> { + tracker.reportEvent(Tracking.Events.SET_PREFERENCE, resId, newValue.toString()); + result.putBoolean(extra, true); + return true; + }); } @Override diff --git a/app/src/main/java/org/tasks/preferences/BasicPreferences.java b/app/src/main/java/org/tasks/preferences/BasicPreferences.java index 43dbf6a23..b955eaa68 100644 --- a/app/src/main/java/org/tasks/preferences/BasicPreferences.java +++ b/app/src/main/java/org/tasks/preferences/BasicPreferences.java @@ -36,8 +36,8 @@ import org.tasks.themes.ThemeCache; import org.tasks.themes.ThemeColor; import timber.log.Timber; -public class BasicPreferences extends InjectingPreferenceActivity implements - LocalePickerDialog.LocaleSelectionHandler, PurchaseHelperCallback { +public class BasicPreferences extends InjectingPreferenceActivity + implements LocalePickerDialog.LocaleSelectionHandler, PurchaseHelperCallback { public static final int REQUEST_PURCHASE = 10007; private static final String EXTRA_RESULT = "extra_result"; @@ -79,131 +79,169 @@ public class BasicPreferences extends InjectingPreferenceActivity implements Preference themePreference = findPreference(getString(R.string.p_theme)); themePreference.setSummary(themeBase.getName()); - themePreference.setOnPreferenceClickListener(preference -> { - Intent intent = new Intent(BasicPreferences.this, ColorPickerActivity.class); - intent.putExtra(ColorPickerActivity.EXTRA_PALETTE, ColorPickerActivity.ColorPalette.THEMES); - startActivityForResult(intent, REQUEST_THEME_PICKER); - return false; - }); + themePreference.setOnPreferenceClickListener( + preference -> { + Intent intent = new Intent(BasicPreferences.this, ColorPickerActivity.class); + intent.putExtra( + ColorPickerActivity.EXTRA_PALETTE, ColorPickerActivity.ColorPalette.THEMES); + startActivityForResult(intent, REQUEST_THEME_PICKER); + return false; + }); Preference colorPreference = findPreference(getString(R.string.p_theme_color)); colorPreference.setSummary(themeColor.getName()); - colorPreference.setOnPreferenceClickListener(preference -> { - Intent intent = new Intent(BasicPreferences.this, ColorPickerActivity.class); - intent.putExtra(ColorPickerActivity.EXTRA_PALETTE, ColorPickerActivity.ColorPalette.COLORS); - startActivityForResult(intent, REQUEST_COLOR_PICKER); - return false; - }); + colorPreference.setOnPreferenceClickListener( + preference -> { + Intent intent = new Intent(BasicPreferences.this, ColorPickerActivity.class); + intent.putExtra( + ColorPickerActivity.EXTRA_PALETTE, ColorPickerActivity.ColorPalette.COLORS); + startActivityForResult(intent, REQUEST_COLOR_PICKER); + return false; + }); Preference accentPreference = findPreference(getString(R.string.p_theme_accent)); accentPreference.setSummary(themeAccent.getName()); - accentPreference.setOnPreferenceClickListener(preference -> { - Intent intent = new Intent(BasicPreferences.this, ColorPickerActivity.class); - intent.putExtra(ColorPickerActivity.EXTRA_PALETTE, ColorPickerActivity.ColorPalette.ACCENTS); - startActivityForResult(intent, REQUEST_ACCENT_PICKER); - return false; - }); + accentPreference.setOnPreferenceClickListener( + preference -> { + Intent intent = new Intent(BasicPreferences.this, ColorPickerActivity.class); + intent.putExtra( + ColorPickerActivity.EXTRA_PALETTE, ColorPickerActivity.ColorPalette.ACCENTS); + startActivityForResult(intent, REQUEST_ACCENT_PICKER); + return false; + }); Preference languagePreference = findPreference(getString(R.string.p_language)); updateLocale(); - languagePreference.setOnPreferenceClickListener(preference -> { - newLocalePickerDialog() - .show(getFragmentManager(), FRAG_TAG_LOCALE_PICKER); - return false; - }); - findPreference(getString(R.string.p_layout_direction)) - .setOnPreferenceChangeListener((preference, o) -> { - tracker.reportEvent(Tracking.Events.SET_PREFERENCE, R.string.p_layout_direction, - o.toString()); - int newValue = Integer.parseInt((String) o); - if (locale.getDirectionality() != locale.withDirectionality(newValue) - .getDirectionality()) { - showRestartDialog(); - } - return true; - }); - findPreference(getString(R.string.p_collect_statistics)) - .setOnPreferenceChangeListener((preference, newValue) -> { - if (newValue != null) { - tracker.setTrackingEnabled((boolean) newValue); - return true; - } + languagePreference.setOnPreferenceClickListener( + preference -> { + newLocalePickerDialog().show(getFragmentManager(), FRAG_TAG_LOCALE_PICKER); return false; }); - - findPreference(R.string.TLA_menu_donate).setOnPreferenceClickListener(preference -> { - if (BuildConfig.FLAVOR.equals("googleplay")) { - newDonationDialog().show(getFragmentManager(), FRAG_TAG_DONATION); - } else { - startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://tasks.org/donate"))); - } - return false; - }); + findPreference(getString(R.string.p_layout_direction)) + .setOnPreferenceChangeListener( + (preference, o) -> { + tracker.reportEvent( + Tracking.Events.SET_PREFERENCE, R.string.p_layout_direction, o.toString()); + int newValue = Integer.parseInt((String) o); + if (locale.getDirectionality() + != locale.withDirectionality(newValue).getDirectionality()) { + showRestartDialog(); + } + return true; + }); + findPreference(getString(R.string.p_collect_statistics)) + .setOnPreferenceChangeListener( + (preference, newValue) -> { + if (newValue != null) { + tracker.setTrackingEnabled((boolean) newValue); + return true; + } + return false; + }); + + findPreference(R.string.TLA_menu_donate) + .setOnPreferenceClickListener( + preference -> { + if (BuildConfig.FLAVOR.equals("googleplay")) { + newDonationDialog().show(getFragmentManager(), FRAG_TAG_DONATION); + } else { + startActivity( + new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://tasks.org/donate"))); + } + return false; + }); findPreference(R.string.p_purchased_themes) - .setOnPreferenceChangeListener((preference, newValue) -> { - if (newValue != null && (boolean) newValue && !preferences - .hasPurchase(R.string.p_purchased_themes)) { - purchaseHelper.purchase(BasicPreferences.this, getString(R.string.sku_themes), - getString(R.string.p_purchased_themes), REQUEST_PURCHASE, BasicPreferences.this); - } - return false; - }); + .setOnPreferenceChangeListener( + (preference, newValue) -> { + if (newValue != null + && (boolean) newValue + && !preferences.hasPurchase(R.string.p_purchased_themes)) { + purchaseHelper.purchase( + BasicPreferences.this, + getString(R.string.sku_themes), + getString(R.string.p_purchased_themes), + REQUEST_PURCHASE, + BasicPreferences.this); + } + return false; + }); findPreference(R.string.p_purchased_tasker) - .setOnPreferenceChangeListener((preference, newValue) -> { - if (newValue != null && (boolean) newValue && !preferences - .hasPurchase(R.string.p_purchased_tasker)) { - purchaseHelper.purchase(BasicPreferences.this, getString(R.string.sku_tasker), - getString(R.string.p_purchased_tasker), REQUEST_PURCHASE, BasicPreferences.this); - } - return false; - }); + .setOnPreferenceChangeListener( + (preference, newValue) -> { + if (newValue != null + && (boolean) newValue + && !preferences.hasPurchase(R.string.p_purchased_tasker)) { + purchaseHelper.purchase( + BasicPreferences.this, + getString(R.string.sku_tasker), + getString(R.string.p_purchased_tasker), + REQUEST_PURCHASE, + BasicPreferences.this); + } + return false; + }); findPreference(R.string.p_purchased_dashclock) - .setOnPreferenceChangeListener((preference, newValue) -> { - if (newValue != null && (boolean) newValue && !preferences - .hasPurchase(R.string.p_purchased_dashclock)) { - purchaseHelper.purchase(BasicPreferences.this, getString(R.string.sku_dashclock), - getString(R.string.p_purchased_dashclock), REQUEST_PURCHASE, BasicPreferences.this); - } - return false; - }); + .setOnPreferenceChangeListener( + (preference, newValue) -> { + if (newValue != null + && (boolean) newValue + && !preferences.hasPurchase(R.string.p_purchased_dashclock)) { + purchaseHelper.purchase( + BasicPreferences.this, + getString(R.string.sku_dashclock), + getString(R.string.p_purchased_dashclock), + REQUEST_PURCHASE, + BasicPreferences.this); + } + return false; + }); if (BuildConfig.DEBUG) { addPreferencesFromResource(R.xml.preferences_debug); findPreference(getString(R.string.debug_unlock_purchases)) - .setOnPreferenceClickListener(preference -> { - preferences.setBoolean(R.string.p_purchased_dashclock, true); - preferences.setBoolean(R.string.p_purchased_tasker, true); - preferences.setBoolean(R.string.p_purchased_themes, true); - recreate(); - return true; - }); + .setOnPreferenceClickListener( + preference -> { + preferences.setBoolean(R.string.p_purchased_dashclock, true); + preferences.setBoolean(R.string.p_purchased_tasker, true); + preferences.setBoolean(R.string.p_purchased_themes, true); + recreate(); + return true; + }); findPreference(getString(R.string.debug_consume_purchases)) - .setOnPreferenceClickListener(preference -> { - purchaseHelper.consumePurchases(); - recreate(); - return true; - }); + .setOnPreferenceClickListener( + preference -> { + purchaseHelper.consumePurchases(); + recreate(); + return true; + }); } - findPreference(R.string.backup_BAc_import).setOnPreferenceClickListener(preference -> { - Intent intent = new Intent(BasicPreferences.this, FileExplore.class); - intent.putExtra(FileExplore.EXTRA_START_PATH, - preferences.getBackupDirectory().getAbsolutePath()); - startActivityForResult(intent, REQUEST_PICKER); - return false; - }); - - findPreference(R.string.backup_BAc_export).setOnPreferenceClickListener(preference -> { - newExportTasksDialog().show(getFragmentManager(), FRAG_TAG_EXPORT_TASKS); - return false; - }); + findPreference(R.string.backup_BAc_import) + .setOnPreferenceClickListener( + preference -> { + Intent intent = new Intent(BasicPreferences.this, FileExplore.class); + intent.putExtra( + FileExplore.EXTRA_START_PATH, preferences.getBackupDirectory().getAbsolutePath()); + startActivityForResult(intent, REQUEST_PICKER); + return false; + }); + + findPreference(R.string.backup_BAc_export) + .setOnPreferenceClickListener( + preference -> { + newExportTasksDialog().show(getFragmentManager(), FRAG_TAG_EXPORT_TASKS); + return false; + }); initializeBackupDirectory(); requires(R.string.get_plugins, atLeastJellybeanMR1(), R.string.p_purchased_dashclock); - requires(R.string.settings_localization, atLeastJellybeanMR1(), R.string.p_language, + requires( + R.string.settings_localization, + atLeastJellybeanMR1(), + R.string.p_language, R.string.p_layout_direction); if (!BuildConfig.FLAVOR.equals("googleplay")) { @@ -213,10 +251,12 @@ public class BasicPreferences extends InjectingPreferenceActivity implements } private void setupActivity(int key, final Class target) { - findPreference(getString(key)).setOnPreferenceClickListener(preference -> { - startActivityForResult(new Intent(BasicPreferences.this, target), RC_PREFS); - return true; - }); + findPreference(getString(key)) + .setOnPreferenceClickListener( + preference -> { + startActivityForResult(new Intent(BasicPreferences.this, target), RC_PREFS); + return true; + }); } @Override @@ -306,17 +346,19 @@ public class BasicPreferences extends InjectingPreferenceActivity implements @Override public void purchaseCompleted(final boolean success, final String sku) { - runOnUiThread(() -> { - if (getString(R.string.sku_tasker).equals(sku)) { - ((TwoStatePreference) findPreference(R.string.p_purchased_tasker)).setChecked(success); - } else if (getString(R.string.sku_dashclock).equals(sku)) { - ((TwoStatePreference) findPreference(R.string.p_purchased_dashclock)).setChecked(success); - } else if (getString(R.string.sku_themes).equals(sku)) { - ((TwoStatePreference) findPreference(R.string.p_purchased_themes)).setChecked(success); - } else { - Timber.d("Unhandled sku: %s", sku); - } - }); + runOnUiThread( + () -> { + if (getString(R.string.sku_tasker).equals(sku)) { + ((TwoStatePreference) findPreference(R.string.p_purchased_tasker)).setChecked(success); + } else if (getString(R.string.sku_dashclock).equals(sku)) { + ((TwoStatePreference) findPreference(R.string.p_purchased_dashclock)) + .setChecked(success); + } else if (getString(R.string.sku_themes).equals(sku)) { + ((TwoStatePreference) findPreference(R.string.p_purchased_themes)).setChecked(success); + } else { + Timber.d("Unhandled sku: %s", sku); + } + }); } @Override @@ -329,12 +371,14 @@ public class BasicPreferences extends InjectingPreferenceActivity implements } private void initializeBackupDirectory() { - findPreference(getString(R.string.p_backup_dir)).setOnPreferenceClickListener(p -> { - Intent filesDir = new Intent(BasicPreferences.this, FileExplore.class); - filesDir.putExtra(FileExplore.EXTRA_DIRECTORY_MODE, true); - startActivityForResult(filesDir, REQUEST_CODE_BACKUP_DIR); - return true; - }); + findPreference(getString(R.string.p_backup_dir)) + .setOnPreferenceClickListener( + p -> { + Intent filesDir = new Intent(BasicPreferences.this, FileExplore.class); + filesDir.putExtra(FileExplore.EXTRA_DIRECTORY_MODE, true); + startActivityForResult(filesDir, REQUEST_CODE_BACKUP_DIR); + return true; + }); updateBackupDirectory(); } diff --git a/app/src/main/java/org/tasks/preferences/DateTimePreferences.java b/app/src/main/java/org/tasks/preferences/DateTimePreferences.java index 84680bfdb..1ac2aa622 100644 --- a/app/src/main/java/org/tasks/preferences/DateTimePreferences.java +++ b/app/src/main/java/org/tasks/preferences/DateTimePreferences.java @@ -18,8 +18,8 @@ import org.tasks.ui.TimePreference; import org.threeten.bp.DayOfWeek; import org.threeten.bp.format.TextStyle; -public class DateTimePreferences extends InjectingPreferenceActivity implements - Preference.OnPreferenceChangeListener { +public class DateTimePreferences extends InjectingPreferenceActivity + implements Preference.OnPreferenceChangeListener { private static final int REQUEST_MORNING = 10001; private static final int REQUEST_AFTERNOON = 10002; @@ -49,10 +49,10 @@ public class DateTimePreferences extends InjectingPreferenceActivity implements } private String[] getWeekdayEntries() { - return new String[]{ - getString(R.string.use_locale_default), - getWeekdayDisplayName(DayOfWeek.SUNDAY), - getWeekdayDisplayName(DayOfWeek.MONDAY) + return new String[] { + getString(R.string.use_locale_default), + getWeekdayDisplayName(DayOfWeek.SUNDAY), + getWeekdayDisplayName(DayOfWeek.MONDAY) }; } @@ -82,13 +82,14 @@ public class DateTimePreferences extends InjectingPreferenceActivity implements private void initializeTimePreference(final TimePreference preference, final int requestCode) { preference.setOnPreferenceChangeListener(this); - preference.setOnPreferenceClickListener(ignored -> { - final DateTime current = new DateTime().withMillisOfDay(preference.getMillisOfDay()); - Intent intent = new Intent(DateTimePreferences.this, TimePickerActivity.class); - intent.putExtra(TimePickerActivity.EXTRA_TIMESTAMP, current.getMillis()); - startActivityForResult(intent, requestCode); - return true; - }); + preference.setOnPreferenceClickListener( + ignored -> { + final DateTime current = new DateTime().withMillisOfDay(preference.getMillisOfDay()); + Intent intent = new Intent(DateTimePreferences.this, TimePickerActivity.class); + intent.putExtra(TimePickerActivity.EXTRA_TIMESTAMP, current.getMillis()); + startActivityForResult(intent, requestCode); + return true; + }); } @Override @@ -161,9 +162,10 @@ public class DateTimePreferences extends InjectingPreferenceActivity implements } private void invalidSetting(int errorResId, int settingResId, int relativeResId) { - Toast.makeText(this, - getString(errorResId, getString(settingResId), getString(relativeResId)), - Toast.LENGTH_SHORT) + Toast.makeText( + this, + getString(errorResId, getString(settingResId), getString(relativeResId)), + Toast.LENGTH_SHORT) .show(); } diff --git a/app/src/main/java/org/tasks/preferences/DefaultFilterProvider.java b/app/src/main/java/org/tasks/preferences/DefaultFilterProvider.java index 8b677215a..9762339b2 100644 --- a/app/src/main/java/org/tasks/preferences/DefaultFilterProvider.java +++ b/app/src/main/java/org/tasks/preferences/DefaultFilterProvider.java @@ -51,9 +51,13 @@ public class DefaultFilterProvider { private final CaldavFilterExposer caldavFilterExposer; @Inject - public DefaultFilterProvider(@ForApplication Context context, Preferences preferences, - Tracker tracker, CustomFilterExposer customFilterExposer, - TagFilterExposer tagFilterExposer, GtasksFilterExposer gtasksFilterExposer, + public DefaultFilterProvider( + @ForApplication Context context, + Preferences preferences, + Tracker tracker, + CustomFilterExposer customFilterExposer, + TagFilterExposer tagFilterExposer, + GtasksFilterExposer gtasksFilterExposer, CaldavFilterExposer caldavFilterExposer) { this.context = context; this.preferences = preferences; @@ -91,8 +95,8 @@ public class DefaultFilterProvider { } public Filter getDefaultRemoteList() { - return getFilterFromPreference(preferences.getStringValue(R.string.p_default_remote_list), - null); + return getFilterFromPreference( + preferences.getStringValue(R.string.p_default_remote_list), null); } public void setDefaultRemoteList(Filter filter) { @@ -104,8 +108,8 @@ public class DefaultFilterProvider { } public Filter getFilterFromPreference(String preferenceValue) { - return getFilterFromPreference(preferenceValue, - BuiltInFilterExposer.getMyTasksFilter(context.getResources())); + return getFilterFromPreference( + preferenceValue, BuiltInFilterExposer.getMyTasksFilter(context.getResources())); } private Filter getFilterFromPreference(String preferenceValue, Filter def) { diff --git a/app/src/main/java/org/tasks/preferences/Device.java b/app/src/main/java/org/tasks/preferences/Device.java index 6332e3434..416b0c1ff 100644 --- a/app/src/main/java/org/tasks/preferences/Device.java +++ b/app/src/main/java/org/tasks/preferences/Device.java @@ -30,8 +30,11 @@ public class Device { } public boolean hasCamera() { - return context.getPackageManager() - .queryIntentActivities(new Intent(MediaStore.ACTION_IMAGE_CAPTURE), 0).size() > 0; + return context + .getPackageManager() + .queryIntentActivities(new Intent(MediaStore.ACTION_IMAGE_CAPTURE), 0) + .size() + > 0; } public boolean hasGallery() { @@ -46,8 +49,8 @@ public class Device { public boolean voiceInputAvailable() { PackageManager pm = context.getPackageManager(); - List activities = pm.queryIntentActivities( - new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0); + List activities = + pm.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0); return (activities.size() != 0); } @@ -55,20 +58,31 @@ public class Device { try { java.util.Locale appLocale = locale.getLocale(); java.util.Locale deviceLocale = locale.getDeviceLocale(); - return Joiner.on("\n").join(asList( - "", - "----------", - "Tasks: " + BuildConfig.VERSION_NAME + " (" + BuildConfig.FLAVOR + " build " - + BuildConfig.VERSION_CODE + ")", - "Android: " + Build.VERSION.RELEASE + " (" + Build.DISPLAY + ")", - "Locale: " + deviceLocale + (!deviceLocale.equals(appLocale) ? " (" + appLocale + ")" - : ""), - "Model: " + Build.MANUFACTURER + " " + Build.MODEL, - "Product: " + Build.PRODUCT + " (" + Build.DEVICE + ")", - "Kernel: " + System.getProperty("os.version") + " (" + Build.VERSION.INCREMENTAL + ")", - "----------", - "" - )); + return Joiner.on("\n") + .join( + asList( + "", + "----------", + "Tasks: " + + BuildConfig.VERSION_NAME + + " (" + + BuildConfig.FLAVOR + + " build " + + BuildConfig.VERSION_CODE + + ")", + "Android: " + Build.VERSION.RELEASE + " (" + Build.DISPLAY + ")", + "Locale: " + + deviceLocale + + (!deviceLocale.equals(appLocale) ? " (" + appLocale + ")" : ""), + "Model: " + Build.MANUFACTURER + " " + Build.MODEL, + "Product: " + Build.PRODUCT + " (" + Build.DEVICE + ")", + "Kernel: " + + System.getProperty("os.version") + + " (" + + Build.VERSION.INCREMENTAL + + ")", + "----------", + "")); } catch (Exception e) { Timber.e(e, e.getMessage()); } diff --git a/app/src/main/java/org/tasks/preferences/HelpAndFeedbackActivity.java b/app/src/main/java/org/tasks/preferences/HelpAndFeedbackActivity.java index 188fa4ea7..86d399689 100644 --- a/app/src/main/java/org/tasks/preferences/HelpAndFeedbackActivity.java +++ b/app/src/main/java/org/tasks/preferences/HelpAndFeedbackActivity.java @@ -19,8 +19,10 @@ public class HelpAndFeedbackActivity extends InjectingPreferenceActivity { addPreferencesFromResource(R.xml.preferences_help); - Intent mailto = new Intent(Intent.ACTION_SENDTO, - Uri.fromParts("mailto", "Tasks Support ", null)); + Intent mailto = + new Intent( + Intent.ACTION_SENDTO, + Uri.fromParts("mailto", "Tasks Support ", null)); mailto.putExtra(Intent.EXTRA_SUBJECT, "Tasks Feedback"); mailto.putExtra(Intent.EXTRA_TEXT, device.getDebugInfo()); findPreference(getString(R.string.contact_developer)).setIntent(mailto); @@ -33,4 +35,4 @@ public class HelpAndFeedbackActivity extends InjectingPreferenceActivity { public void inject(ActivityComponent component) { component.inject(this); } -} \ No newline at end of file +} diff --git a/app/src/main/java/org/tasks/preferences/MiscellaneousPreferences.java b/app/src/main/java/org/tasks/preferences/MiscellaneousPreferences.java index 1ce2e6a39..c86628f25 100644 --- a/app/src/main/java/org/tasks/preferences/MiscellaneousPreferences.java +++ b/app/src/main/java/org/tasks/preferences/MiscellaneousPreferences.java @@ -35,8 +35,8 @@ public class MiscellaneousPreferences extends InjectingPreferenceActivity { addPreferencesFromResource(R.xml.preferences_misc); - calendarReminderPreference = (CheckBoxPreference) findPreference( - getString(R.string.p_calendar_reminders)); + calendarReminderPreference = + (CheckBoxPreference) findPreference(getString(R.string.p_calendar_reminders)); initializeAttachmentDirectoryPreference(); initializeCalendarReminderPreference(); @@ -80,12 +80,14 @@ public class MiscellaneousPreferences extends InjectingPreferenceActivity { } private void initializeAttachmentDirectoryPreference() { - findPreference(getString(R.string.p_attachment_dir)).setOnPreferenceClickListener(p -> { - Intent filesDir = new Intent(MiscellaneousPreferences.this, FileExplore.class); - filesDir.putExtra(FileExplore.EXTRA_DIRECTORY_MODE, true); - startActivityForResult(filesDir, REQUEST_CODE_FILES_DIR); - return true; - }); + findPreference(getString(R.string.p_attachment_dir)) + .setOnPreferenceClickListener( + p -> { + Intent filesDir = new Intent(MiscellaneousPreferences.this, FileExplore.class); + filesDir.putExtra(FileExplore.EXTRA_DIRECTORY_MODE, true); + startActivityForResult(filesDir, REQUEST_CODE_FILES_DIR); + return true; + }); updateAttachmentDirectory(); } @@ -99,49 +101,51 @@ public class MiscellaneousPreferences extends InjectingPreferenceActivity { } private void initializeCalendarReminderPreference() { - CheckBoxPreference calendarReminderPreference = (CheckBoxPreference) findPreference( - getString(R.string.p_calendar_reminders)); - calendarReminderPreference.setOnPreferenceChangeListener((preference, newValue) -> { - if (newValue == null) { - return false; - } - if (!(Boolean) newValue) { - return true; - } - if (permissionRequestor.requestCalendarPermissions()) { - CalendarNotificationIntentService.enqueueWork(this); - return true; - } - return false; - }); + CheckBoxPreference calendarReminderPreference = + (CheckBoxPreference) findPreference(getString(R.string.p_calendar_reminders)); + calendarReminderPreference.setOnPreferenceChangeListener( + (preference, newValue) -> { + if (newValue == null) { + return false; + } + if (!(Boolean) newValue) { + return true; + } + if (permissionRequestor.requestCalendarPermissions()) { + CalendarNotificationIntentService.enqueueWork(this); + return true; + } + return false; + }); calendarReminderPreference.setChecked( calendarReminderPreference.isChecked() && permissionChecker.canAccessCalendars()); } private void initializeVoiceReminderPreference() { findPreference(getString(R.string.p_voiceRemindersEnabled)) - .setOnPreferenceChangeListener((preference, newValue) -> { - boolean enabled = (boolean) newValue; - try { - if (enabled && !voiceOutputAssistant.isTTSInitialized()) { - Intent checkIntent = new Intent(); - checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA); - startActivityForResult(checkIntent, REQUEST_CODE_TTS_CHECK); - } else if (!enabled && voiceOutputAssistant.isTTSInitialized()) { - voiceOutputAssistant.shutdown(); - } - } catch (VerifyError e) { - Timber.e(e, e.getMessage()); - preference.setEnabled(false); - preferences.setBoolean(preference.getKey(), false); - } - return true; - }); + .setOnPreferenceChangeListener( + (preference, newValue) -> { + boolean enabled = (boolean) newValue; + try { + if (enabled && !voiceOutputAssistant.isTTSInitialized()) { + Intent checkIntent = new Intent(); + checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA); + startActivityForResult(checkIntent, REQUEST_CODE_TTS_CHECK); + } else if (!enabled && voiceOutputAssistant.isTTSInitialized()) { + voiceOutputAssistant.shutdown(); + } + } catch (VerifyError e) { + Timber.e(e, e.getMessage()); + preference.setEnabled(false); + preferences.setBoolean(preference.getKey(), false); + } + return true; + }); } @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, - @NonNull int[] grantResults) { + public void onRequestPermissionsResult( + int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == PermissionRequestor.REQUEST_CALENDAR) { if (verifyPermissions(grantResults)) { calendarReminderPreference.setChecked(true); diff --git a/app/src/main/java/org/tasks/preferences/PermissionChecker.java b/app/src/main/java/org/tasks/preferences/PermissionChecker.java index 9d355b081..c01072788 100644 --- a/app/src/main/java/org/tasks/preferences/PermissionChecker.java +++ b/app/src/main/java/org/tasks/preferences/PermissionChecker.java @@ -48,9 +48,9 @@ public class PermissionChecker { @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public boolean canAccessMissedCallPermissions() { - return checkPermission(Manifest.permission.READ_CONTACTS) && - checkPermission(Manifest.permission.READ_PHONE_STATE) && - (preJellybean() || checkPermission(Manifest.permission.READ_CALL_LOG)); + return checkPermission(Manifest.permission.READ_CONTACTS) + && checkPermission(Manifest.permission.READ_PHONE_STATE) + && (preJellybean() || checkPermission(Manifest.permission.READ_CALL_LOG)); } private boolean checkPermission(String permission) { diff --git a/app/src/main/java/org/tasks/preferences/PermissionRequestor.java b/app/src/main/java/org/tasks/preferences/PermissionRequestor.java index 96fa61d26..8cefc3d29 100644 --- a/app/src/main/java/org/tasks/preferences/PermissionRequestor.java +++ b/app/src/main/java/org/tasks/preferences/PermissionRequestor.java @@ -44,7 +44,7 @@ public abstract class PermissionRequestor { return true; } requestPermissions( - new String[]{Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR}, + new String[] {Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR}, requestCode); return false; } @@ -69,16 +69,22 @@ public abstract class PermissionRequestor { if (permissionChecker.canAccessMissedCallPermissions()) { return true; } - String[] permissions = atLeastJellybean() - ? new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.READ_PHONE_STATE, - Manifest.permission.READ_CALL_LOG} - : new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.READ_PHONE_STATE}; + String[] permissions = + atLeastJellybean() + ? new String[] { + Manifest.permission.READ_CONTACTS, + Manifest.permission.READ_PHONE_STATE, + Manifest.permission.READ_CALL_LOG + } + : new String[] { + Manifest.permission.READ_CONTACTS, Manifest.permission.READ_PHONE_STATE + }; requestPermissions(permissions, REQUEST_CONTACTS); return false; } private void requestPermission(String permission, int rc) { - requestPermissions(new String[]{permission}, rc); + requestPermissions(new String[] {permission}, rc); } protected abstract void requestPermissions(String[] permissions, int requestCode); diff --git a/app/src/main/java/org/tasks/preferences/Preferences.java b/app/src/main/java/org/tasks/preferences/Preferences.java index fee926d3a..5b9c272c1 100644 --- a/app/src/main/java/org/tasks/preferences/Preferences.java +++ b/app/src/main/java/org/tasks/preferences/Preferences.java @@ -27,9 +27,9 @@ import timber.log.Timber; public class Preferences { - private static final String P_CURRENT_VERSION = "cv"; //$NON-NLS-1$ + private static final String P_CURRENT_VERSION = "cv"; // $NON-NLS-1$ - private static final String PREF_SORT_SORT = "sort_sort"; //$NON-NLS-1$ + private static final String PREF_SORT_SORT = "sort_sort"; // $NON-NLS-1$ private final Context context; private final PermissionChecker permissionChecker; @@ -41,8 +41,8 @@ public class Preferences { this.context = context; this.permissionChecker = permissionChecker; prefs = PreferenceManager.getDefaultSharedPreferences(context); - publicPrefs = context - .getSharedPreferences(AstridApiConstants.PUBLIC_PREFS, Context.MODE_PRIVATE); + publicPrefs = + context.getSharedPreferences(AstridApiConstants.PUBLIC_PREFS, Context.MODE_PRIVATE); } private static String getNonCollidingFileName(String dir, String baseName, String extension) { @@ -50,7 +50,7 @@ public class Preferences { File f = new File(dir + File.separator + baseName + extension); String tempName = baseName; while (f.exists()) { - tempName = baseName + "-" + tries; //$NON-NLS-1$ + tempName = baseName + "-" + tries; // $NON-NLS-1$ f = new File(dir + File.separator + tempName + extension); tries++; } @@ -165,10 +165,7 @@ public class Preferences { } public void clear() { - prefs - .edit() - .clear() - .commit(); + prefs.edit().clear().commit(); } public void setDefaults() { @@ -202,8 +199,8 @@ public class Preferences { } public int getDefaultReminders() { - return getIntegerFromString(R.string.p_default_reminders_key, - Task.NOTIFY_AT_DEADLINE | Task.NOTIFY_AFTER_DEADLINE); + return getIntegerFromString( + R.string.p_default_reminders_key, Task.NOTIFY_AT_DEADLINE | Task.NOTIFY_AFTER_DEADLINE); } public int getDefaultRingMode() { @@ -263,9 +260,9 @@ public class Preferences { } public boolean fieldMissedPhoneCalls() { - return getBoolean(R.string.p_field_missed_calls, true) && - notificationsEnabled() && - permissionChecker.canAccessMissedCallPermissions(); + return getBoolean(R.string.p_field_missed_calls, true) + && notificationsEnabled() + && permissionChecker.canAccessMissedCallPermissions(); } public boolean hasPurchase(int keyResource) { @@ -364,15 +361,13 @@ public class Preferences { if (externalFilesDir == null) { return null; } - String path = String.format("%s/%s", - externalFilesDir.getAbsolutePath(), - type); + String path = String.format("%s/%s", externalFilesDir.getAbsolutePath(), type); File file = new File(path); return file.isDirectory() || file.mkdirs() ? file : null; } public String getNewAudioAttachmentPath(AtomicReference nameReference) { - return getNewAttachmentPath(".m4a", nameReference); //$NON-NLS-1$ + return getNewAttachmentPath(".m4a", nameReference); // $NON-NLS-1$ } public String getNewAttachmentPath(String extension, AtomicReference nameReference) { diff --git a/app/src/main/java/org/tasks/preferences/beast/BeastModeRecyclerAdapter.java b/app/src/main/java/org/tasks/preferences/beast/BeastModeRecyclerAdapter.java index e643a49ee..dd29cf8ee 100644 --- a/app/src/main/java/org/tasks/preferences/beast/BeastModeRecyclerAdapter.java +++ b/app/src/main/java/org/tasks/preferences/beast/BeastModeRecyclerAdapter.java @@ -42,8 +42,9 @@ public class BeastModeRecyclerAdapter extends RecyclerView.Adapter { - task.setDueDateAdjustingHideUntil(oldDueDate); - task.setCompletionDate(0L); - try { - RRule rrule = new RRule(task.getRecurrenceWithoutFrom()); - int count = rrule.getCount(); - if (count > 0) { - rrule.setCount(count + 1); - } - task.setRecurrence(rrule, task.repeatAfterCompletion()); - } catch (ParseException e) { - Timber.e(e, e.getMessage()); - } - taskDao.save(task); - }) + String snackbarText = + activity.getString(R.string.repeat_snackbar, task.getTitle(), dueDateString); + taskListFragment + .makeSnackbar(snackbarText) + .setAction( + R.string.DLG_undo, + v -> { + task.setDueDateAdjustingHideUntil(oldDueDate); + task.setCompletionDate(0L); + try { + RRule rrule = new RRule(task.getRecurrenceWithoutFrom()); + int count = rrule.getCount(); + if (count > 0) { + rrule.setCount(count + 1); + } + task.setRecurrence(rrule, task.repeatAfterCompletion()); + } catch (ParseException e) { + Timber.e(e, e.getMessage()); + } + taskDao.save(task); + }) .show(); } @@ -83,8 +89,11 @@ public class RepeatConfirmationReceiver extends BroadcastReceiver { String dueString = date > 0 ? DateUtilities.getRelativeDay(context, date, false) : ""; if (Task.hasDueTime(date)) { // TODO: localize this - dueString = String.format("%s at %s", dueString, //$NON-NLS-1$ - DateUtilities.getTimeString(context, date)); + dueString = + String.format( + "%s at %s", + dueString, // $NON-NLS-1$ + DateUtilities.getTimeString(context, date)); } return dueString; } diff --git a/app/src/main/java/org/tasks/reminders/MissedCallActivity.java b/app/src/main/java/org/tasks/reminders/MissedCallActivity.java index ba828737d..56fde3749 100644 --- a/app/src/main/java/org/tasks/reminders/MissedCallActivity.java +++ b/app/src/main/java/org/tasks/reminders/MissedCallActivity.java @@ -14,11 +14,11 @@ import org.tasks.injection.InjectingAppCompatActivity; import org.tasks.intents.TaskIntents; import org.tasks.notifications.NotificationManager; -public class MissedCallActivity extends InjectingAppCompatActivity implements - MissedCallDialog.MissedCallHandler { +public class MissedCallActivity extends InjectingAppCompatActivity + implements MissedCallDialog.MissedCallHandler { - public static final String EXTRA_NUMBER = "number"; //$NON-NLS-1$ - public static final String EXTRA_NAME = "name"; //$NON-NLS-1$ + public static final String EXTRA_NUMBER = "number"; // $NON-NLS-1$ + public static final String EXTRA_NAME = "name"; // $NON-NLS-1$ public static final String EXTRA_TITLE = "extra_title"; public static final String EXTRA_CALL_NOW = "extra_call_now"; public static final String EXTRA_CALL_LATER = "extra_call_later"; @@ -58,8 +58,8 @@ public class MissedCallActivity extends InjectingAppCompatActivity implements callLater(); } else { FragmentManager fragmentManager = getSupportFragmentManager(); - MissedCallDialog fragment = (MissedCallDialog) fragmentManager - .findFragmentByTag(FRAG_TAG_MISSED_CALL_FRAGMENT); + MissedCallDialog fragment = + (MissedCallDialog) fragmentManager.findFragmentByTag(FRAG_TAG_MISSED_CALL_FRAGMENT); if (fragment == null) { fragment = new MissedCallDialog(); fragment.show(fragmentManager, FRAG_TAG_MISSED_CALL_FRAGMENT); @@ -76,20 +76,19 @@ public class MissedCallActivity extends InjectingAppCompatActivity implements @Override public void callNow() { Intent call = new Intent(Intent.ACTION_VIEW); - call.setData(Uri.parse("tel:" + number)); //$NON-NLS-1$ + call.setData(Uri.parse("tel:" + number)); // $NON-NLS-1$ startActivity(call); cancelNotificationAndFinish(); } @Override public void callLater() { - String title = TextUtils.isEmpty(name) - ? getString(R.string.MCA_task_title_no_name, number) - : getString(R.string.MCA_task_title_name, name, number); + String title = + TextUtils.isEmpty(name) + ? getString(R.string.MCA_task_title_no_name, number) + : getString(R.string.MCA_task_title_name, name, number); Task task = taskCreator.basicQuickAddTask(title); - TaskIntents - .getEditTaskStack(this, null, task.getId()) - .startActivities(); + TaskIntents.getEditTaskStack(this, null, task.getId()).startActivities(); cancelNotificationAndFinish(); } diff --git a/app/src/main/java/org/tasks/reminders/MissedCallDialog.java b/app/src/main/java/org/tasks/reminders/MissedCallDialog.java index 906eedcce..08a9db8a8 100644 --- a/app/src/main/java/org/tasks/reminders/MissedCallDialog.java +++ b/app/src/main/java/org/tasks/reminders/MissedCallDialog.java @@ -27,28 +27,32 @@ public class MissedCallDialog extends InjectingDialogFragment { @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { - List actions = asList( - getString(R.string.MCA_return_call), - getString(R.string.MCA_add_task), - getString(R.string.MCA_ignore)); + List actions = + asList( + getString(R.string.MCA_return_call), + getString(R.string.MCA_add_task), + getString(R.string.MCA_ignore)); handler = (MissedCallHandler) getActivity(); - return dialogBuilder.newDialog() + return dialogBuilder + .newDialog() .setTitle(title) - .setItems(actions, (dialog, which) -> { - switch (which) { - case 0: - handler.callNow(); - break; - case 1: - handler.callLater(); - break; - default: - handler.ignore(); - break; - } - }) + .setItems( + actions, + (dialog, which) -> { + switch (which) { + case 0: + handler.callNow(); + break; + case 1: + handler.callLater(); + break; + default: + handler.ignore(); + break; + } + }) .show(); } diff --git a/app/src/main/java/org/tasks/reminders/NotificationActivity.java b/app/src/main/java/org/tasks/reminders/NotificationActivity.java index 2a5a2b1e7..03101140d 100644 --- a/app/src/main/java/org/tasks/reminders/NotificationActivity.java +++ b/app/src/main/java/org/tasks/reminders/NotificationActivity.java @@ -12,8 +12,8 @@ import org.tasks.intents.TaskIntents; import org.tasks.notifications.NotificationManager; import org.tasks.receivers.CompleteTaskReceiver; -public class NotificationActivity extends InjectingAppCompatActivity implements - NotificationDialog.NotificationHandler { +public class NotificationActivity extends InjectingAppCompatActivity + implements NotificationDialog.NotificationHandler { public static final String EXTRA_TITLE = "extra_title"; public static final String EXTRA_TASK_ID = "extra_task_id"; @@ -46,8 +46,8 @@ public class NotificationActivity extends InjectingAppCompatActivity implements taskId = intent.getLongExtra(EXTRA_TASK_ID, 0L); FragmentManager fragmentManager = getSupportFragmentManager(); - NotificationDialog fragment = (NotificationDialog) fragmentManager - .findFragmentByTag(FRAG_TAG_NOTIFICATION_FRAGMENT); + NotificationDialog fragment = + (NotificationDialog) fragmentManager.findFragmentByTag(FRAG_TAG_NOTIFICATION_FRAGMENT); if (fragment == null) { fragment = new NotificationDialog(); fragment.show(fragmentManager, FRAG_TAG_NOTIFICATION_FRAGMENT); @@ -62,9 +62,7 @@ public class NotificationActivity extends InjectingAppCompatActivity implements @Override public void edit() { - TaskIntents - .getEditTaskStack(this, null, taskId) - .startActivities(); + TaskIntents.getEditTaskStack(this, null, taskId).startActivities(); notificationManager.cancel(taskId); finish(); } diff --git a/app/src/main/java/org/tasks/reminders/NotificationDialog.java b/app/src/main/java/org/tasks/reminders/NotificationDialog.java index 1088f35eb..a27a25ee5 100644 --- a/app/src/main/java/org/tasks/reminders/NotificationDialog.java +++ b/app/src/main/java/org/tasks/reminders/NotificationDialog.java @@ -27,28 +27,32 @@ public class NotificationDialog extends InjectingDialogFragment { @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { - List items = asList( - getString(R.string.TAd_actionEditTask), - getString(R.string.rmd_NoA_snooze), - getString(R.string.rmd_NoA_done)); + List items = + asList( + getString(R.string.TAd_actionEditTask), + getString(R.string.rmd_NoA_snooze), + getString(R.string.rmd_NoA_done)); handler = (NotificationHandler) getActivity(); - return dialogBuilder.newDialog() + return dialogBuilder + .newDialog() .setTitle(title) - .setItems(items, (dialog, which) -> { - switch (which) { - case 0: - handler.edit(); - break; - case 1: - handler.snooze(); - break; - case 2: - handler.complete(); - break; - } - }) + .setItems( + items, + (dialog, which) -> { + switch (which) { + case 0: + handler.edit(); + break; + case 1: + handler.snooze(); + break; + case 2: + handler.complete(); + break; + } + }) .show(); } diff --git a/app/src/main/java/org/tasks/reminders/SnoozeActivity.java b/app/src/main/java/org/tasks/reminders/SnoozeActivity.java index 87cd2cca6..efb7d446a 100644 --- a/app/src/main/java/org/tasks/reminders/SnoozeActivity.java +++ b/app/src/main/java/org/tasks/reminders/SnoozeActivity.java @@ -16,8 +16,8 @@ import org.tasks.injection.InjectingAppCompatActivity; import org.tasks.notifications.NotificationManager; import org.tasks.time.DateTime; -public class SnoozeActivity extends InjectingAppCompatActivity implements SnoozeCallback, - DialogInterface.OnCancelListener { +public class SnoozeActivity extends InjectingAppCompatActivity + implements SnoozeCallback, DialogInterface.OnCancelListener { public static final String EXTRA_TASK_ID = "id"; public static final String EXTRA_TASK_IDS = "ids"; @@ -25,11 +25,10 @@ public class SnoozeActivity extends InjectingAppCompatActivity implements Snooze private static final String FRAG_TAG_SNOOZE_DIALOG = "frag_tag_snooze_dialog"; private static final String EXTRA_PICKING_DATE_TIME = "extra_picking_date_time"; private static final int REQUEST_DATE_TIME = 10101; + private final List taskIds = new ArrayList<>(); @Inject NotificationManager notificationManager; @Inject TaskDao taskDao; @Inject ReminderService reminderService; - - private final List taskIds = new ArrayList<>(); private boolean pickingDateTime; @Override @@ -70,8 +69,8 @@ public class SnoozeActivity extends InjectingAppCompatActivity implements Snooze snoozeForTime(new DateTime(intent.getLongExtra(EXTRA_SNOOZE_TIME, 0L))); } else { FragmentManager fragmentManager = getSupportFragmentManager(); - SnoozeDialog fragmentByTag = (SnoozeDialog) fragmentManager - .findFragmentByTag(FRAG_TAG_SNOOZE_DIALOG); + SnoozeDialog fragmentByTag = + (SnoozeDialog) fragmentManager.findFragmentByTag(FRAG_TAG_SNOOZE_DIALOG); if (fragmentByTag == null) { fragmentByTag = new SnoozeDialog(); fragmentByTag.show(fragmentManager, FRAG_TAG_SNOOZE_DIALOG); @@ -101,8 +100,8 @@ public class SnoozeActivity extends InjectingAppCompatActivity implements Snooze pickingDateTime = true; Intent intent = new Intent(this, DateAndTimePickerActivity.class); - intent.putExtra(DateAndTimePickerActivity.EXTRA_TIMESTAMP, - new DateTime().plusMinutes(30).getMillis()); + intent.putExtra( + DateAndTimePickerActivity.EXTRA_TIMESTAMP, new DateTime().plusMinutes(30).getMillis()); startActivityForResult(intent, REQUEST_DATE_TIME); } diff --git a/app/src/main/java/org/tasks/reminders/SnoozeCallback.java b/app/src/main/java/org/tasks/reminders/SnoozeCallback.java index 96c6d593b..459bb3de7 100644 --- a/app/src/main/java/org/tasks/reminders/SnoozeCallback.java +++ b/app/src/main/java/org/tasks/reminders/SnoozeCallback.java @@ -7,5 +7,4 @@ interface SnoozeCallback { void snoozeForTime(DateTime time); void pickDateTime(); - } diff --git a/app/src/main/java/org/tasks/reminders/SnoozeDialog.java b/app/src/main/java/org/tasks/reminders/SnoozeDialog.java index 7592b346a..3581a7101 100644 --- a/app/src/main/java/org/tasks/reminders/SnoozeDialog.java +++ b/app/src/main/java/org/tasks/reminders/SnoozeDialog.java @@ -57,8 +57,8 @@ public class SnoozeDialog extends InjectingDialogFragment { snoozeOptions.add(new SnoozeOption(R.string.date_shortcut_tomorrow_morning, tomorrowMorning)); } else { snoozeOptions.add(new SnoozeOption(R.string.date_shortcut_tomorrow_morning, tomorrowMorning)); - snoozeOptions - .add(new SnoozeOption(R.string.date_shortcut_tomorrow_afternoon, tomorrowAfternoon)); + snoozeOptions.add( + new SnoozeOption(R.string.date_shortcut_tomorrow_afternoon, tomorrowAfternoon)); } return snoozeOptions; @@ -70,28 +70,33 @@ public class SnoozeDialog extends InjectingDialogFragment { final List snoozeOptions = getSnoozeOptions(preferences); for (SnoozeOption snoozeOption : snoozeOptions) { - items.add(String.format("%s (%s)", - getString(snoozeOption.getResId()), - getTimeString(context, snoozeOption.getDateTime()))); + items.add( + String.format( + "%s (%s)", + getString(snoozeOption.getResId()), + getTimeString(context, snoozeOption.getDateTime()))); } items.add(getString(R.string.pick_a_date_and_time)); - return dialogBuilder.newDialog() + return dialogBuilder + .newDialog() .setTitle(R.string.rmd_NoA_snooze) - .setItems(items, (dialog, which) -> { - switch (which) { - case 0: - case 1: - case 2: - snoozeCallback.snoozeForTime(snoozeOptions.get(which).getDateTime()); - break; - case 3: - dialog.dismiss(); - snoozeCallback.pickDateTime(); - break; - } - }) + .setItems( + items, + (dialog, which) -> { + switch (which) { + case 0: + case 1: + case 2: + snoozeCallback.snoozeForTime(snoozeOptions.get(which).getDateTime()); + break; + case 3: + dialog.dismiss(); + snoozeCallback.pickDateTime(); + break; + } + }) .show(); } @@ -116,4 +121,4 @@ public class SnoozeDialog extends InjectingDialogFragment { protected void inject(DialogFragmentComponent component) { component.inject(this); } -} \ No newline at end of file +} diff --git a/app/src/main/java/org/tasks/reminders/SnoozeOption.java b/app/src/main/java/org/tasks/reminders/SnoozeOption.java index 742dd8010..27495b519 100644 --- a/app/src/main/java/org/tasks/reminders/SnoozeOption.java +++ b/app/src/main/java/org/tasks/reminders/SnoozeOption.java @@ -22,9 +22,6 @@ public class SnoozeOption { @Override public String toString() { - return "SnoozeOption{" + - "resId=" + resId + - ", dateTime=" + dateTime + - '}'; + return "SnoozeOption{" + "resId=" + resId + ", dateTime=" + dateTime + '}'; } -} \ No newline at end of file +} diff --git a/app/src/main/java/org/tasks/repeats/CustomRecurrenceDialog.java b/app/src/main/java/org/tasks/repeats/CustomRecurrenceDialog.java index 9d8e77366..ca6e29c10 100644 --- a/app/src/main/java/org/tasks/repeats/CustomRecurrenceDialog.java +++ b/app/src/main/java/org/tasks/repeats/CustomRecurrenceDialog.java @@ -71,8 +71,8 @@ import timber.log.Timber; public class CustomRecurrenceDialog extends InjectingDialogFragment { - private static final List FREQUENCIES = asList(MINUTELY, HOURLY, DAILY, WEEKLY, - MONTHLY, YEARLY); + private static final List FREQUENCIES = + asList(MINUTELY, HOURLY, DAILY, WEEKLY, MONTHLY, YEARLY); private static final String EXTRA_RRULE = "extra_rrule"; private static final String EXTRA_DATE = "extra_date"; private static final int REQUEST_PICK_DATE = 505; @@ -80,32 +80,71 @@ public class CustomRecurrenceDialog extends InjectingDialogFragment { @Inject @ForActivity Context context; @Inject DialogBuilder dialogBuilder; @Inject Locale locale; - @BindView(R.id.weekGroup) LinearLayout weekGroup1; - @BindView(R.id.weekGroup2) @Nullable + + @BindView(R.id.weekGroup) + LinearLayout weekGroup1; + + @BindView(R.id.weekGroup2) + @Nullable LinearLayout weekGroup2; - @BindView(R.id.week_day_1) ToggleButton day1; - @BindView(R.id.week_day_2) ToggleButton day2; - @BindView(R.id.week_day_3) ToggleButton day3; - @BindView(R.id.week_day_4) ToggleButton day4; - @BindView(R.id.week_day_5) ToggleButton day5; - @BindView(R.id.week_day_6) ToggleButton day6; - @BindView(R.id.week_day_7) ToggleButton day7; - @BindView(R.id.month_group) RadioGroup monthGroup; - @BindView(R.id.repeat_monthly_same_day) RadioButton repeatMonthlySameDay; - @BindView(R.id.repeat_monthly_day_of_nth_week) RadioButton repeatMonthlyDayOfNthWeek; - @BindView(R.id.repeat_monthly_day_of_last_week) RadioButton repeatMonthlyDayOfLastWeek; - @BindView(R.id.repeat_until) Spinner repeatUntilSpinner; - @BindView(R.id.frequency) Spinner frequencySpinner; - @BindView(R.id.intervalValue) EditText intervalEditText; - @BindView(R.id.intervalText) TextView intervalTextView; - @BindView(R.id.repeatTimesValue) EditText repeatTimes; - @BindView(R.id.repeatTimesText) TextView repeatTimesText; + + @BindView(R.id.week_day_1) + ToggleButton day1; + + @BindView(R.id.week_day_2) + ToggleButton day2; + + @BindView(R.id.week_day_3) + ToggleButton day3; + + @BindView(R.id.week_day_4) + ToggleButton day4; + + @BindView(R.id.week_day_5) + ToggleButton day5; + + @BindView(R.id.week_day_6) + ToggleButton day6; + + @BindView(R.id.week_day_7) + ToggleButton day7; + + @BindView(R.id.month_group) + RadioGroup monthGroup; + + @BindView(R.id.repeat_monthly_same_day) + RadioButton repeatMonthlySameDay; + + @BindView(R.id.repeat_monthly_day_of_nth_week) + RadioButton repeatMonthlyDayOfNthWeek; + + @BindView(R.id.repeat_monthly_day_of_last_week) + RadioButton repeatMonthlyDayOfLastWeek; + + @BindView(R.id.repeat_until) + Spinner repeatUntilSpinner; + + @BindView(R.id.frequency) + Spinner frequencySpinner; + + @BindView(R.id.intervalValue) + EditText intervalEditText; + + @BindView(R.id.intervalText) + TextView intervalTextView; + + @BindView(R.id.repeatTimesValue) + EditText repeatTimes; + + @BindView(R.id.repeatTimesText) + TextView repeatTimesText; + private ArrayAdapter repeatUntilAdapter; private ToggleButton[] weekButtons; private RRule rrule; - public static CustomRecurrenceDialog newCustomRecurrenceDialog(Fragment target, RRule rrule, - long dueDate) { + public static CustomRecurrenceDialog newCustomRecurrenceDialog( + Fragment target, RRule rrule, long dueDate) { CustomRecurrenceDialog dialog = new CustomRecurrenceDialog(); dialog.setTargetFragment(target, 0); Bundle arguments = new Bundle(); @@ -123,7 +162,7 @@ public class CustomRecurrenceDialog extends InjectingDialogFragment { if (d.getMillis() > 0) { displayString.append(DateUtilities.getDateString(d)); if (Task.hasDueTime(repeatUntilValue)) { - displayString.append(", "); //$NON-NLS-1$ //$NON-NLS-2$ + displayString.append(", "); // $NON-NLS-1$ //$NON-NLS-2$ displayString.append(DateUtilities.getTimeString(context, repeatUntilValue)); } } @@ -138,9 +177,10 @@ public class CustomRecurrenceDialog extends InjectingDialogFragment { Bundle arguments = getArguments(); long dueDate = arguments.getLong(EXTRA_DATE, currentTimeMillis()); - String rule = savedInstanceState == null - ? arguments.getString(EXTRA_RRULE) - : savedInstanceState.getString(EXTRA_RRULE); + String rule = + savedInstanceState == null + ? arguments.getString(EXTRA_RRULE) + : savedInstanceState.getString(EXTRA_RRULE); try { if (!Strings.isNullOrEmpty(rule)) { rrule = new RRule(rule); @@ -177,17 +217,18 @@ public class CustomRecurrenceDialog extends InjectingDialogFragment { } if (dayOfWeekInMonth < 5) { - int[] resources = new int[]{ - R.string.repeat_monthly_first_week, - R.string.repeat_monthly_second_week, - R.string.repeat_monthly_third_week, - R.string.repeat_monthly_fourth_week - }; + int[] resources = + new int[] { + R.string.repeat_monthly_first_week, + R.string.repeat_monthly_second_week, + R.string.repeat_monthly_third_week, + R.string.repeat_monthly_fourth_week + }; repeatMonthlyDayOfNthWeek.setVisibility(View.VISIBLE); String nth = getString(resources[dayOfWeekInMonth - 1]); String text = getString(R.string.repeat_monthly_on_every_day_of_nth_week, nth, today); - repeatMonthlyDayOfNthWeek - .setTag(new WeekdayNum(dayOfWeekInMonth, calendarDayToWeekday(dueDayOfWeek))); + repeatMonthlyDayOfNthWeek.setTag( + new WeekdayNum(dayOfWeekInMonth, calendarDayToWeekday(dueDayOfWeek))); repeatMonthlyDayOfNthWeek.setText(text); } else { repeatMonthlyDayOfNthWeek.setVisibility(View.GONE); @@ -203,48 +244,49 @@ public class CustomRecurrenceDialog extends InjectingDialogFragment { } } } - if (monthGroup.getCheckedRadioButtonId() != R.id.repeat_monthly_day_of_last_week && - monthGroup.getCheckedRadioButtonId() != R.id.repeat_monthly_day_of_nth_week) { + if (monthGroup.getCheckedRadioButtonId() != R.id.repeat_monthly_day_of_last_week + && monthGroup.getCheckedRadioButtonId() != R.id.repeat_monthly_day_of_nth_week) { repeatMonthlySameDay.setChecked(true); } - ArrayAdapter frequencyAdapter = ArrayAdapter - .createFromResource(context, R.array.repeat_frequency, R.layout.frequency_item); + ArrayAdapter frequencyAdapter = + ArrayAdapter.createFromResource(context, R.array.repeat_frequency, R.layout.frequency_item); frequencyAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); frequencySpinner.setAdapter(frequencyAdapter); frequencySpinner.setSelection(FREQUENCIES.indexOf(rrule.getFreq())); intervalEditText.setText(locale.formatNumber(rrule.getInterval())); - repeatUntilAdapter = new ArrayAdapter(context, 0, repeatUntilOptions) { - @Override - public View getDropDownView(int position, @Nullable View convertView, - @NonNull ViewGroup parent) { - ViewGroup vg = (ViewGroup) inflater - .inflate(R.layout.simple_spinner_dropdown_item, parent, false); - ((TextView) vg.findViewById(R.id.text1)).setText(getItem(position)); - return vg; - } - - @NonNull - @Override - public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { - int selectedItemPosition = position; - if (parent instanceof AdapterView) { - selectedItemPosition = ((AdapterView) parent).getSelectedItemPosition(); - } - TextView tv = (TextView) inflater - .inflate(android.R.layout.simple_spinner_item, parent, false); - tv.setPadding(0, 0, 0, 0); - tv.setText(repeatUntilOptions.get(selectedItemPosition)); - return tv; - } - }; + repeatUntilAdapter = + new ArrayAdapter(context, 0, repeatUntilOptions) { + @Override + public View getDropDownView( + int position, @Nullable View convertView, @NonNull ViewGroup parent) { + ViewGroup vg = + (ViewGroup) inflater.inflate(R.layout.simple_spinner_dropdown_item, parent, false); + ((TextView) vg.findViewById(R.id.text1)).setText(getItem(position)); + return vg; + } + + @NonNull + @Override + public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { + int selectedItemPosition = position; + if (parent instanceof AdapterView) { + selectedItemPosition = ((AdapterView) parent).getSelectedItemPosition(); + } + TextView tv = + (TextView) inflater.inflate(android.R.layout.simple_spinner_item, parent, false); + tv.setPadding(0, 0, 0, 0); + tv.setText(repeatUntilOptions.get(selectedItemPosition)); + return tv; + } + }; repeatUntilAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); repeatUntilSpinner.setAdapter(repeatUntilAdapter); updateRepeatUntilOptions(); - weekButtons = new ToggleButton[]{day1, day2, day3, day4, day5, day6, day7}; + weekButtons = new ToggleButton[] {day1, day2, day3, day4, day5, day6, day7}; // set up days of week Calendar dayOfWeekCalendar = Calendar.getInstance(locale.getLocale()); @@ -252,32 +294,35 @@ public class CustomRecurrenceDialog extends InjectingDialogFragment { WeekdayNum todayWeekday = new WeekdayNum(0, new DateTime(dueDate).getWeekday()); - ColorStateList colorStateList = new ColorStateList(new int[][]{ - new int[]{android.R.attr.state_checked}, - new int[]{-android.R.attr.state_checked} - }, new int[]{ - ResourceResolver.getData(context, R.attr.fab_text), - getColor(context, R.color.text_primary) - }); + ColorStateList colorStateList = + new ColorStateList( + new int[][] { + new int[] {android.R.attr.state_checked}, new int[] {-android.R.attr.state_checked} + }, + new int[] { + ResourceResolver.getData(context, R.attr.fab_text), + getColor(context, R.color.text_primary) + }); int inset = (int) context.getResources().getDimension(R.dimen.week_button_inset); int accentColor = ResourceResolver.getData(context, R.attr.colorAccent); - int animationDuration = context.getResources() - .getInteger(android.R.integer.config_shortAnimTime); + int animationDuration = + context.getResources().getInteger(android.R.integer.config_shortAnimTime); for (int i = 0; i < 7; i++) { ToggleButton weekButton = weekButtons[i]; - GradientDrawable ovalDrawable = (GradientDrawable) context.getResources() - .getDrawable(R.drawable.week_day_button_oval).mutate(); + GradientDrawable ovalDrawable = + (GradientDrawable) + context.getResources().getDrawable(R.drawable.week_day_button_oval).mutate(); ovalDrawable.setColor(accentColor); - LayerDrawable layerDrawable = new LayerDrawable(new Drawable[]{ovalDrawable}); + LayerDrawable layerDrawable = new LayerDrawable(new Drawable[] {ovalDrawable}); layerDrawable.setLayerInset(0, inset, inset, inset, inset); StateListDrawable stateListDrawable = new StateListDrawable(); stateListDrawable.setEnterFadeDuration(animationDuration); stateListDrawable.setExitFadeDuration(animationDuration); - stateListDrawable - .addState(new int[]{-android.R.attr.state_checked}, new ColorDrawable(Color.TRANSPARENT)); - stateListDrawable.addState(new int[]{android.R.attr.state_checked}, layerDrawable); + stateListDrawable.addState( + new int[] {-android.R.attr.state_checked}, new ColorDrawable(Color.TRANSPARENT)); + stateListDrawable.addState(new int[] {android.R.attr.state_checked}, layerDrawable); int paddingBottom = weekButton.getPaddingBottom(); int paddingTop = weekButton.getPaddingTop(); int paddingLeft = weekButton.getPaddingLeft(); @@ -292,16 +337,18 @@ public class CustomRecurrenceDialog extends InjectingDialogFragment { weekButton.setTextOff(text); weekButton.setTag(new WeekdayNum(0, calendarDayToWeekday(dayOfWeek))); if (savedInstanceState == null) { - weekButton.setChecked(rrule.getFreq() != WEEKLY || rrule.getByDay().isEmpty() - ? todayWeekday.equals(weekButton.getTag()) - : rrule.getByDay().contains(weekButton.getTag())); + weekButton.setChecked( + rrule.getFreq() != WEEKLY || rrule.getByDay().isEmpty() + ? todayWeekday.equals(weekButton.getTag()) + : rrule.getByDay().contains(weekButton.getTag())); } dayOfWeekCalendar.add(Calendar.DATE, 1); } setCancelable(false); - return dialogBuilder.newDialog() + return dialogBuilder + .newDialog() .setView(dialogView) .setPositiveButton(android.R.string.ok, this::onRuleSelected) .setNegativeButton(android.R.string.cancel, null) @@ -386,8 +433,8 @@ public class CustomRecurrenceDialog extends InjectingDialogFragment { } private void updateCountText() { - repeatTimesText - .setText(getResources().getQuantityString(R.plurals.repeat_times, rrule.getCount())); + repeatTimesText.setText( + getResources().getQuantityString(R.plurals.repeat_times, rrule.getCount())); } private int getFrequencyPlural() { @@ -478,8 +525,8 @@ public class CustomRecurrenceDialog extends InjectingDialogFragment { long repeatUntil = DateTime.from(rrule.getUntil()).getMillis(); int count = rrule.getCount(); if (repeatUntil > 0) { - repeatUntilOptions - .add(getString(R.string.repeat_until, getDisplayString(context, repeatUntil))); + repeatUntilOptions.add( + getString(R.string.repeat_until, getDisplayString(context, repeatUntil))); repeatTimes.setVisibility(View.GONE); repeatTimesText.setVisibility(View.GONE); } else if (count > 0) { diff --git a/app/src/main/java/org/tasks/repeats/RepeatRuleToString.java b/app/src/main/java/org/tasks/repeats/RepeatRuleToString.java index 21cc0139b..bd3f34f8e 100644 --- a/app/src/main/java/org/tasks/repeats/RepeatRuleToString.java +++ b/app/src/main/java/org/tasks/repeats/RepeatRuleToString.java @@ -45,22 +45,30 @@ public class RepeatRuleToString { if ((frequency == WEEKLY || frequency == MONTHLY) && !rrule.getByDay().isEmpty()) { String dayString = getDayString(rrule); if (count > 0) { - return context - .getString(R.string.repeats_single_on_number_of_times, frequencyString, dayString, - count, countString); + return context.getString( + R.string.repeats_single_on_number_of_times, + frequencyString, + dayString, + count, + countString); } else if (repeatUntil == null) { return context.getString(R.string.repeats_single_on, frequencyString, dayString); } else { - return context.getString(R.string.repeats_single_on_until, frequencyString, dayString, + return context.getString( + R.string.repeats_single_on_until, + frequencyString, + dayString, DateUtilities.getLongDateString(repeatUntil)); } } else if (count > 0) { - return context.getString(R.string.repeats_single_number_of_times, frequencyString, count, - countString); + return context.getString( + R.string.repeats_single_number_of_times, frequencyString, count, countString); } else if (repeatUntil == null) { return context.getString(R.string.repeats_single, frequencyString); } else { - return context.getString(R.string.repeats_single_until, frequencyString, + return context.getString( + R.string.repeats_single_until, + frequencyString, DateUtilities.getLongDateString(repeatUntil)); } } else { @@ -69,22 +77,30 @@ public class RepeatRuleToString { if ((frequency == WEEKLY || frequency == MONTHLY) && !rrule.getByDay().isEmpty()) { String dayString = getDayString(rrule); if (count > 0) { - return context - .getString(R.string.repeats_plural_on_number_of_times, frequencyPlural, dayString, - count, countString); + return context.getString( + R.string.repeats_plural_on_number_of_times, + frequencyPlural, + dayString, + count, + countString); } else if (repeatUntil == null) { return context.getString(R.string.repeats_plural_on, frequencyPlural, dayString); } else { - return context.getString(R.string.repeats_plural_on_until, frequencyPlural, dayString, + return context.getString( + R.string.repeats_plural_on_until, + frequencyPlural, + dayString, DateUtilities.getLongDateString(repeatUntil)); } } else if (count > 0) { - return context.getString(R.string.repeats_plural_number_of_times, frequencyPlural, count, - countString); + return context.getString( + R.string.repeats_plural_number_of_times, frequencyPlural, count, countString); } else if (repeatUntil == null) { return context.getString(R.string.repeats_plural, frequencyPlural); } else { - return context.getString(R.string.repeats_plural_until, frequencyPlural, + return context.getString( + R.string.repeats_plural_until, + frequencyPlural, DateUtilities.getLongDateString(repeatUntil)); } } @@ -107,17 +123,20 @@ public class RepeatRuleToString { dayOfWeekCalendar.set(Calendar.DAY_OF_WEEK, weekdayToCalendarDay(weekdayNum.wday)); weekday = longWeekdays[dayOfWeekCalendar.get(Calendar.DAY_OF_WEEK)]; if (weekdayNum.num == -1) { - return context.getString(R.string.repeat_monthly_every_day_of_nth_week, + return context.getString( + R.string.repeat_monthly_every_day_of_nth_week, context.getString(R.string.repeat_monthly_last_week), weekday); } else { - int[] resources = new int[]{ - R.string.repeat_monthly_first_week, - R.string.repeat_monthly_second_week, - R.string.repeat_monthly_third_week, - R.string.repeat_monthly_fourth_week - }; - return context.getString(R.string.repeat_monthly_every_day_of_nth_week, + int[] resources = + new int[] { + R.string.repeat_monthly_first_week, + R.string.repeat_monthly_second_week, + R.string.repeat_monthly_third_week, + R.string.repeat_monthly_fourth_week + }; + return context.getString( + R.string.repeat_monthly_every_day_of_nth_week, context.getString(resources[weekdayNum.num - 1]), weekday); } diff --git a/app/src/main/java/org/tasks/scheduling/AlarmManager.java b/app/src/main/java/org/tasks/scheduling/AlarmManager.java index d7bc179e5..6eae93e28 100644 --- a/app/src/main/java/org/tasks/scheduling/AlarmManager.java +++ b/app/src/main/java/org/tasks/scheduling/AlarmManager.java @@ -25,8 +25,8 @@ public class AlarmManager { @SuppressLint("NewApi") public void wakeup(long time, PendingIntent pendingIntent) { if (atLeastMarshmallow()) { - alarmManager - .setExactAndAllowWhileIdle(android.app.AlarmManager.RTC_WAKEUP, time, pendingIntent); + alarmManager.setExactAndAllowWhileIdle( + android.app.AlarmManager.RTC_WAKEUP, time, pendingIntent); } else if (atLeastKitKat()) { alarmManager.setExact(android.app.AlarmManager.RTC_WAKEUP, time, pendingIntent); } else { diff --git a/app/src/main/java/org/tasks/scheduling/BackgroundScheduler.java b/app/src/main/java/org/tasks/scheduling/BackgroundScheduler.java index 3d31ad2fe..308787c10 100644 --- a/app/src/main/java/org/tasks/scheduling/BackgroundScheduler.java +++ b/app/src/main/java/org/tasks/scheduling/BackgroundScheduler.java @@ -20,9 +20,8 @@ public class BackgroundScheduler extends InjectingJobIntentService { @Inject RefreshScheduler refreshScheduler; public static void enqueueWork(Context context) { - BackgroundScheduler - .enqueueWork(context, BackgroundScheduler.class, JobManager.JOB_ID_BACKGROUND_SCHEDULER, - new Intent()); + BackgroundScheduler.enqueueWork( + context, BackgroundScheduler.class, JobManager.JOB_ID_BACKGROUND_SCHEDULER, new Intent()); } @Override diff --git a/app/src/main/java/org/tasks/scheduling/CalendarNotificationIntentService.java b/app/src/main/java/org/tasks/scheduling/CalendarNotificationIntentService.java index 9736cb816..98a9802d3 100644 --- a/app/src/main/java/org/tasks/scheduling/CalendarNotificationIntentService.java +++ b/app/src/main/java/org/tasks/scheduling/CalendarNotificationIntentService.java @@ -30,8 +30,11 @@ public class CalendarNotificationIntentService extends RecurringIntervalIntentSe @Inject AlarmManager alarmManager; public static void enqueueWork(Context context) { - JobIntentService.enqueueWork(context, CalendarNotificationIntentService.class, - JobManager.JOB_ID_CALENDAR_NOTIFICATION, new Intent()); + JobIntentService.enqueueWork( + context, + CalendarNotificationIntentService.class, + JobManager.JOB_ID_CALENDAR_NOTIFICATION, + new Intent()); } @Override @@ -49,9 +52,12 @@ public class CalendarNotificationIntentService extends RecurringIntervalIntentSe eventAlarm.setAction(CalendarAlarmReceiver.BROADCAST_CALENDAR_REMINDER); eventAlarm.setData(Uri.parse(URI_PREFIX + "://" + event.getId())); - PendingIntent pendingIntent = PendingIntent.getBroadcast(context, - CalendarAlarmReceiver.REQUEST_CODE_CAL_REMINDER, eventAlarm, - PendingIntent.FLAG_UPDATE_CURRENT); + PendingIntent pendingIntent = + PendingIntent.getBroadcast( + context, + CalendarAlarmReceiver.REQUEST_CODE_CAL_REMINDER, + eventAlarm, + PendingIntent.FLAG_UPDATE_CURRENT); long reminderTime = event.getStart() - FIFTEEN_MINUTES; alarmManager.wakeup(reminderTime, pendingIntent); @@ -61,8 +67,9 @@ public class CalendarNotificationIntentService extends RecurringIntervalIntentSe @Override long intervalMillis() { - return preferences.getBoolean(R.string.p_calendar_reminders, false) ? TimeUnit.HOURS - .toMillis(12) : 0; + return preferences.getBoolean(R.string.p_calendar_reminders, false) + ? TimeUnit.HOURS.toMillis(12) + : 0; } @Override diff --git a/app/src/main/java/org/tasks/scheduling/GeofenceSchedulingIntentService.java b/app/src/main/java/org/tasks/scheduling/GeofenceSchedulingIntentService.java index 6b6adfaeb..0d4be6242 100644 --- a/app/src/main/java/org/tasks/scheduling/GeofenceSchedulingIntentService.java +++ b/app/src/main/java/org/tasks/scheduling/GeofenceSchedulingIntentService.java @@ -15,8 +15,11 @@ public class GeofenceSchedulingIntentService extends InjectingJobIntentService { @Inject GeofenceService geofenceService; public static void enqueueWork(Context context) { - JobIntentService.enqueueWork(context, GeofenceSchedulingIntentService.class, - JobManager.JOB_ID_GEOFENCE_SCHEDULING, new Intent()); + JobIntentService.enqueueWork( + context, + GeofenceSchedulingIntentService.class, + JobManager.JOB_ID_GEOFENCE_SCHEDULING, + new Intent()); } @Override diff --git a/app/src/main/java/org/tasks/scheduling/NotificationSchedulerIntentService.java b/app/src/main/java/org/tasks/scheduling/NotificationSchedulerIntentService.java index 3debe5364..2a44932cb 100644 --- a/app/src/main/java/org/tasks/scheduling/NotificationSchedulerIntentService.java +++ b/app/src/main/java/org/tasks/scheduling/NotificationSchedulerIntentService.java @@ -15,7 +15,8 @@ import timber.log.Timber; public class NotificationSchedulerIntentService extends InjectingJobIntentService { - private static final String EXTRA_CANCEL_EXISTING_NOTIFICATIONS = "extra_cancel_existing_notifications"; + private static final String EXTRA_CANCEL_EXISTING_NOTIFICATIONS = + "extra_cancel_existing_notifications"; @Inject AlarmService alarmService; @Inject ReminderService reminderService; @Inject NotificationQueue notificationQueue; @@ -24,8 +25,11 @@ public class NotificationSchedulerIntentService extends InjectingJobIntentServic public static void enqueueWork(Context context, boolean cancelNotifications) { Intent intent = new Intent(); intent.putExtra(EXTRA_CANCEL_EXISTING_NOTIFICATIONS, cancelNotifications); - JobIntentService.enqueueWork(context, NotificationSchedulerIntentService.class, - JobManager.JOB_ID_NOTIFICATION_SCHEDULER, intent); + JobIntentService.enqueueWork( + context, + NotificationSchedulerIntentService.class, + JobManager.JOB_ID_NOTIFICATION_SCHEDULER, + intent); } @Override @@ -36,8 +40,8 @@ public class NotificationSchedulerIntentService extends InjectingJobIntentServic notificationQueue.clear(); - boolean cancelExistingNotifications = intent - .getBooleanExtra(EXTRA_CANCEL_EXISTING_NOTIFICATIONS, false); + boolean cancelExistingNotifications = + intent.getBooleanExtra(EXTRA_CANCEL_EXISTING_NOTIFICATIONS, false); notificationManager.restoreNotifications(cancelExistingNotifications); reminderService.scheduleAllAlarms(); diff --git a/app/src/main/java/org/tasks/scheduling/RecurringIntervalIntentService.java b/app/src/main/java/org/tasks/scheduling/RecurringIntervalIntentService.java index ad25ec2f0..882577a2d 100644 --- a/app/src/main/java/org/tasks/scheduling/RecurringIntervalIntentService.java +++ b/app/src/main/java/org/tasks/scheduling/RecurringIntervalIntentService.java @@ -46,9 +46,9 @@ public abstract class RecurringIntervalIntentService extends InjectingJobIntentS Timber.d("will run at %s [lastRun=%s]", printTimestamp(nextRun), printTimestamp(lastRun)); } - PendingIntent pendingIntent = PendingIntent - .getBroadcast(this, 0, new Intent(this, getBroadcastClass()), - PendingIntent.FLAG_UPDATE_CURRENT); + PendingIntent pendingIntent = + PendingIntent.getBroadcast( + this, 0, new Intent(this, getBroadcastClass()), PendingIntent.FLAG_UPDATE_CURRENT); alarmManager.wakeup(nextRun, pendingIntent); } diff --git a/app/src/main/java/org/tasks/sync/RecordSyncStatusCallback.java b/app/src/main/java/org/tasks/sync/RecordSyncStatusCallback.java index 274bcf405..4348ce9f2 100644 --- a/app/src/main/java/org/tasks/sync/RecordSyncStatusCallback.java +++ b/app/src/main/java/org/tasks/sync/RecordSyncStatusCallback.java @@ -9,7 +9,8 @@ public class RecordSyncStatusCallback implements SyncResultCallback { private final GtasksPreferenceService gtasksPreferenceService; private final LocalBroadcastManager localBroadcastManager; - public RecordSyncStatusCallback(GtasksPreferenceService gtasksPreferenceService, + public RecordSyncStatusCallback( + GtasksPreferenceService gtasksPreferenceService, LocalBroadcastManager localBroadcastManager) { this.gtasksPreferenceService = gtasksPreferenceService; this.localBroadcastManager = localBroadcastManager; diff --git a/app/src/main/java/org/tasks/sync/SyncAdapters.java b/app/src/main/java/org/tasks/sync/SyncAdapters.java index 4ea3982b6..737e7d751 100644 --- a/app/src/main/java/org/tasks/sync/SyncAdapters.java +++ b/app/src/main/java/org/tasks/sync/SyncAdapters.java @@ -1,7 +1,6 @@ package org.tasks.sync; import android.app.Activity; -import android.content.ContentResolver; import javax.inject.Inject; import org.tasks.R; import org.tasks.gtasks.GtaskSyncAdapterHelper; @@ -15,7 +14,9 @@ public class SyncAdapters { private final JobManager jobManager; @Inject - public SyncAdapters(GtaskSyncAdapterHelper gtaskSyncAdapterHelper, Preferences preferences, + public SyncAdapters( + GtaskSyncAdapterHelper gtaskSyncAdapterHelper, + Preferences preferences, JobManager jobManager) { this.gtaskSyncAdapterHelper = gtaskSyncAdapterHelper; this.preferences = preferences; diff --git a/app/src/main/java/org/tasks/sync/SyncExecutor.java b/app/src/main/java/org/tasks/sync/SyncExecutor.java index 8071d833f..76ad3b1ab 100644 --- a/app/src/main/java/org/tasks/sync/SyncExecutor.java +++ b/app/src/main/java/org/tasks/sync/SyncExecutor.java @@ -14,8 +14,8 @@ import timber.log.Timber; @ApplicationScope public class SyncExecutor { - private final ExecutorService executor = newSingleThreadExecutor( - new ThreadFactoryBuilder().setNameFormat("sync-executor-%d").build()); + private final ExecutorService executor = + newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat("sync-executor-%d").build()); private final Tracker tracker; @@ -34,8 +34,8 @@ public class SyncExecutor { } } - private Runnable wrapWithExceptionHandling(final SyncResultCallback callback, - final Runnable command) { + private Runnable wrapWithExceptionHandling( + final SyncResultCallback callback, final Runnable command) { return () -> { try { command.run(); diff --git a/app/src/main/java/org/tasks/sync/SynchronizationPreferences.java b/app/src/main/java/org/tasks/sync/SynchronizationPreferences.java index 5c6b4fe12..7e6b3a62d 100644 --- a/app/src/main/java/org/tasks/sync/SynchronizationPreferences.java +++ b/app/src/main/java/org/tasks/sync/SynchronizationPreferences.java @@ -1,9 +1,8 @@ /** * Copyright (c) 2012 Todoroo Inc * - * See the file "LICENSE" for the full license governing this code. + *

    See the file "LICENSE" for the full license governing this code. */ - package org.tasks.sync; import static org.tasks.PermissionUtil.verifyPermissions; @@ -55,65 +54,75 @@ public class SynchronizationPreferences extends InjectingPreferenceActivity { addPreferencesFromResource(R.xml.preferences_synchronization); - CheckBoxPreference caldavEnabled = (CheckBoxPreference) findPreference( - getString(R.string.p_sync_caldav)); + CheckBoxPreference caldavEnabled = + (CheckBoxPreference) findPreference(getString(R.string.p_sync_caldav)); caldavEnabled.setChecked(syncAdapters.isCaldavSyncEnabled()); - caldavEnabled.setOnPreferenceChangeListener((preference, newValue) -> { - jobManager.updateBackgroundSync(((boolean) newValue), null, null); - return true; - }); - final CheckBoxPreference gtaskPreference = (CheckBoxPreference) findPreference( - getString(R.string.sync_gtasks)); + caldavEnabled.setOnPreferenceChangeListener( + (preference, newValue) -> { + jobManager.updateBackgroundSync(((boolean) newValue), null, null); + return true; + }); + final CheckBoxPreference gtaskPreference = + (CheckBoxPreference) findPreference(getString(R.string.sync_gtasks)); gtaskPreference.setChecked(syncAdapters.isGoogleTaskSyncEnabled()); - gtaskPreference.setOnPreferenceChangeListener((preference, newValue) -> { - if ((boolean) newValue) { - if (!playServices.refreshAndCheck()) { - playServices.resolve(SynchronizationPreferences.this); - } else if (permissionRequestor.requestAccountPermissions()) { - requestLogin(); - } - return false; - } else { - jobManager.updateBackgroundSync(); - tracker.reportEvent(Tracking.Events.GTASK_DISABLED); - gtasksPreferenceService.stopOngoing(); - return true; - } - }); + gtaskPreference.setOnPreferenceChangeListener( + (preference, newValue) -> { + if ((boolean) newValue) { + if (!playServices.refreshAndCheck()) { + playServices.resolve(SynchronizationPreferences.this); + } else if (permissionRequestor.requestAccountPermissions()) { + requestLogin(); + } + return false; + } else { + jobManager.updateBackgroundSync(); + tracker.reportEvent(Tracking.Events.GTASK_DISABLED); + gtasksPreferenceService.stopOngoing(); + return true; + } + }); if (gtasksPreferenceService.getLastSyncDate() > 0) { - gtaskPreference.setSummary(getString(R.string.sync_status_success, - DateUtilities.getDateStringWithTime(SynchronizationPreferences.this, - gtasksPreferenceService.getLastSyncDate()))); + gtaskPreference.setSummary( + getString( + R.string.sync_status_success, + DateUtilities.getDateStringWithTime( + SynchronizationPreferences.this, gtasksPreferenceService.getLastSyncDate()))); } findPreference(getString(R.string.p_background_sync_unmetered_only)) - .setOnPreferenceChangeListener((preference, o) -> { - jobManager.updateBackgroundSync(null, null, (Boolean) o); - return true; - }); + .setOnPreferenceChangeListener( + (preference, o) -> { + jobManager.updateBackgroundSync(null, null, (Boolean) o); + return true; + }); findPreference(getString(R.string.p_background_sync)) - .setOnPreferenceChangeListener((preference, o) -> { - jobManager.updateBackgroundSync(null, (Boolean) o, null); - return true; - }); + .setOnPreferenceChangeListener( + (preference, o) -> { + jobManager.updateBackgroundSync(null, (Boolean) o, null); + return true; + }); findPreference(getString(R.string.sync_SPr_forget_key)) - .setOnPreferenceClickListener(preference -> { - dialogBuilder.newMessageDialog(R.string.sync_forget_confirm) - .setPositiveButton(android.R.string.ok, (dialog, which) -> { - gtasksPreferenceService.clearLastSyncDate(); - gtasksPreferenceService.setUserName(null); - googleTaskDao.deleteAll(); - tracker.reportEvent(Tracking.Events.GTASK_LOGOUT); - gtaskPreference.setChecked(false); - }) - .setNegativeButton(android.R.string.cancel, null) - .show(); - return true; - }); + .setOnPreferenceClickListener( + preference -> { + dialogBuilder + .newMessageDialog(R.string.sync_forget_confirm) + .setPositiveButton( + android.R.string.ok, + (dialog, which) -> { + gtasksPreferenceService.clearLastSyncDate(); + gtasksPreferenceService.setUserName(null); + googleTaskDao.deleteAll(); + tracker.reportEvent(Tracking.Events.GTASK_LOGOUT); + gtaskPreference.setChecked(false); + }) + .setNegativeButton(android.R.string.cancel, null) + .show(); + return true; + }); } private void requestLogin() { - startActivityForResult(new Intent(SynchronizationPreferences.this, GtasksLoginActivity.class), - REQUEST_LOGIN); + startActivityForResult( + new Intent(SynchronizationPreferences.this, GtasksLoginActivity.class), REQUEST_LOGIN); } @Override @@ -140,8 +149,8 @@ public class SynchronizationPreferences extends InjectingPreferenceActivity { } @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, - @NonNull int[] grantResults) { + public void onRequestPermissionsResult( + int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == PermissionRequestor.REQUEST_GOOGLE_ACCOUNTS) { if (verifyPermissions(grantResults)) { requestLogin(); diff --git a/app/src/main/java/org/tasks/tasklist/ActionUtils.java b/app/src/main/java/org/tasks/tasklist/ActionUtils.java index a10634bb8..7d636dd0c 100644 --- a/app/src/main/java/org/tasks/tasklist/ActionUtils.java +++ b/app/src/main/java/org/tasks/tasklist/ActionUtils.java @@ -13,23 +13,29 @@ import org.tasks.themes.ThemeColor; public class ActionUtils { // cribbed from Twittnuker - public static void applySupportActionModeColor(ThemeColor themeColor, - final android.support.v7.view.ActionMode modeCompat) { + public static void applySupportActionModeColor( + ThemeColor themeColor, final android.support.v7.view.ActionMode modeCompat) { // Very dirty implementation // This call ensures TitleView created modeCompat.setTitle(modeCompat.getTitle()); View contextView = null; if (modeCompat instanceof WindowDecorActionBar.ActionModeImpl) { - WindowDecorActionBar actionBar = (WindowDecorActionBar) findFieldOfTypes(modeCompat, - WindowDecorActionBar.ActionModeImpl.class, WindowDecorActionBar.class); + WindowDecorActionBar actionBar = + (WindowDecorActionBar) + findFieldOfTypes( + modeCompat, + WindowDecorActionBar.ActionModeImpl.class, + WindowDecorActionBar.class); if (actionBar == null) { return; } - contextView = (View) findFieldOfTypes(actionBar, WindowDecorActionBar.class, - ActionBarContextView.class); + contextView = + (View) + findFieldOfTypes(actionBar, WindowDecorActionBar.class, ActionBarContextView.class); } else if (modeCompat instanceof StandaloneActionMode) { - contextView = (View) findFieldOfTypes(modeCompat, StandaloneActionMode.class, - ActionBarContextView.class); + contextView = + (View) + findFieldOfTypes(modeCompat, StandaloneActionMode.class, ActionBarContextView.class); } if (!(contextView instanceof ActionBarContextView)) { return; @@ -48,8 +54,8 @@ public class ActionUtils { } } - private static Object findFieldOfTypes(T obj, Class cls, - Class... checkTypes) { + private static Object findFieldOfTypes( + T obj, Class cls, Class... checkTypes) { labelField: for (Field field : cls.getDeclaredFields()) { field.setAccessible(true); diff --git a/app/src/main/java/org/tasks/tasklist/GtasksListFragment.java b/app/src/main/java/org/tasks/tasklist/GtasksListFragment.java index 389572e2f..1addbb5bd 100644 --- a/app/src/main/java/org/tasks/tasklist/GtasksListFragment.java +++ b/app/src/main/java/org/tasks/tasklist/GtasksListFragment.java @@ -70,8 +70,11 @@ public class GtasksListFragment extends TaskListFragment { if (GoogleTaskListSettingsActivity.ACTION_DELETED.equals(action)) { activity.onFilterItemClicked(null); } else if (GoogleTaskListSettingsActivity.ACTION_RELOAD.equals(action)) { - activity.getIntent().putExtra(TaskListActivity.OPEN_FILTER, - (Filter) data.getParcelableExtra(TaskListActivity.OPEN_FILTER)); + activity + .getIntent() + .putExtra( + TaskListActivity.OPEN_FILTER, + (Filter) data.getParcelableExtra(TaskListActivity.OPEN_FILTER)); activity.recreate(); } } @@ -83,19 +86,21 @@ public class GtasksListFragment extends TaskListFragment { @Override protected void clearCompleted() { tracker.reportEvent(Tracking.Events.GTASK_CLEAR_COMPLETED); - syncService.clearCompleted(list, new SyncResultCallback() { - @Override - public void started() { - setSyncOngoing(true); - } - - @Override - public void finished() { - setSyncOngoing(false); - - onRefresh(); - } - }); + syncService.clearCompleted( + list, + new SyncResultCallback() { + @Override + public void started() { + setSyncOngoing(true); + } + + @Override + public void finished() { + setSyncOngoing(false); + + onRefresh(); + } + }); } @Override diff --git a/app/src/main/java/org/tasks/tasklist/TagFormatter.java b/app/src/main/java/org/tasks/tasklist/TagFormatter.java index 2e7ab23c7..e199bb1c8 100644 --- a/app/src/main/java/org/tasks/tasklist/TagFormatter.java +++ b/app/src/main/java/org/tasks/tasklist/TagFormatter.java @@ -34,30 +34,32 @@ public class TagFormatter { private final ThemeCache themeCache; private final float tagCharacters; private final Function uuidToTag = this::getTag; - private final Ordering orderByName = new Ordering() { - @Override - public int compare(TagData left, TagData right) { - return left.getName().compareTo(right.getName()); - } - }; - private final Ordering orderByLength = new Ordering() { - @Override - public int compare(TagData left, TagData right) { - int leftLength = left.getName().length(); - int rightLength = right.getName().length(); - if (leftLength < rightLength) { - return -1; - } else if (rightLength < leftLength) { - return 1; - } else { - return 0; - } - } - }; + private final Ordering orderByName = + new Ordering() { + @Override + public int compare(TagData left, TagData right) { + return left.getName().compareTo(right.getName()); + } + }; + private final Ordering orderByLength = + new Ordering() { + @Override + public int compare(TagData left, TagData right) { + int leftLength = left.getName().length(); + int rightLength = right.getName().length(); + if (leftLength < rightLength) { + return -1; + } else if (rightLength < leftLength) { + return 1; + } else { + return 0; + } + } + }; @Inject - public TagFormatter(@ForApplication Context context, TagService tagService, - ThemeCache themeCache) { + public TagFormatter( + @ForApplication Context context, TagService tagService, ThemeCache themeCache) { this.tagService = tagService; this.themeCache = themeCache; @@ -109,9 +111,15 @@ public class TagFormatter { int themeIndex = tagData.getColor(); ThemeColor color = themeIndex >= 0 ? themeCache.getThemeColor(themeIndex) : themeCache.getUntaggedColor(); - string.setSpan(new BackgroundColorSpan(color.getPrimaryColor()), 0, string.length(), + string.setSpan( + new BackgroundColorSpan(color.getPrimaryColor()), + 0, + string.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); - string.setSpan(new ForegroundColorSpan(color.getActionBarTint()), 0, string.length(), + string.setSpan( + new ForegroundColorSpan(color.getActionBarTint()), + 0, + string.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); return string; }; diff --git a/app/src/main/java/org/tasks/tasklist/TagListFragment.java b/app/src/main/java/org/tasks/tasklist/TagListFragment.java index 6a8e5183b..48a023c61 100644 --- a/app/src/main/java/org/tasks/tasklist/TagListFragment.java +++ b/app/src/main/java/org/tasks/tasklist/TagListFragment.java @@ -64,8 +64,11 @@ public class TagListFragment extends TaskListFragment { if (TagSettingsActivity.ACTION_DELETED.equals(action)) { activity.onFilterItemClicked(null); } else if (TagSettingsActivity.ACTION_RELOAD.equals(action)) { - activity.getIntent().putExtra(TaskListActivity.OPEN_FILTER, - (Filter) data.getParcelableExtra(TaskListActivity.OPEN_FILTER)); + activity + .getIntent() + .putExtra( + TaskListActivity.OPEN_FILTER, + (Filter) data.getParcelableExtra(TaskListActivity.OPEN_FILTER)); activity.recreate(); } } diff --git a/app/src/main/java/org/tasks/tasklist/TaskListRecyclerAdapter.java b/app/src/main/java/org/tasks/tasklist/TaskListRecyclerAdapter.java index a4c602103..04fe45628 100644 --- a/app/src/main/java/org/tasks/tasklist/TaskListRecyclerAdapter.java +++ b/app/src/main/java/org/tasks/tasklist/TaskListRecyclerAdapter.java @@ -48,55 +48,64 @@ public class TaskListRecyclerAdapter extends RecyclerView.Adapter private ActionMode mode = null; private boolean dragging; - private boolean animate; - private final ActionMode.Callback actionModeCallback = new ActionMode.Callback() { - @Override - public boolean onCreateActionMode(ActionMode actionMode, Menu menu) { - MenuInflater inflater = actionMode.getMenuInflater(); - inflater.inflate(R.menu.menu_multi_select, menu); - MenuColorizer.colorMenu(activity, menu); - return true; - } - - @Override - public boolean onPrepareActionMode(ActionMode mode, Menu menu) { - return false; - } - - @Override - public boolean onActionItemClicked(ActionMode mode, MenuItem item) { - switch (item.getItemId()) { - case R.id.delete: - dialogBuilder.newMessageDialog(R.string.delete_selected_tasks) - .setPositiveButton(android.R.string.ok, (dialogInterface, i) -> deleteSelectedItems()) - .setNegativeButton(android.R.string.cancel, null) - .show(); + private final ActionMode.Callback actionModeCallback = + new ActionMode.Callback() { + @Override + public boolean onCreateActionMode(ActionMode actionMode, Menu menu) { + MenuInflater inflater = actionMode.getMenuInflater(); + inflater.inflate(R.menu.menu_multi_select, menu); + MenuColorizer.colorMenu(activity, menu); return true; - case R.id.copy_tasks: - dialogBuilder.newMessageDialog(R.string.copy_selected_tasks) - .setPositiveButton(android.R.string.ok, ((dialogInterface, i) -> copySelectedItems())) - .setNegativeButton(android.R.string.cancel, null) - .show(); - return true; - default: + } + + @Override + public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; - } - } + } - @Override - public void onDestroyActionMode(ActionMode actionMode) { - adapter.clearSelections(); - TaskListRecyclerAdapter.this.mode = null; - if (!dragging) { - notifyDataSetChanged(); - } - } - }; + @Override + public boolean onActionItemClicked(ActionMode mode, MenuItem item) { + switch (item.getItemId()) { + case R.id.delete: + dialogBuilder + .newMessageDialog(R.string.delete_selected_tasks) + .setPositiveButton( + android.R.string.ok, (dialogInterface, i) -> deleteSelectedItems()) + .setNegativeButton(android.R.string.cancel, null) + .show(); + return true; + case R.id.copy_tasks: + dialogBuilder + .newMessageDialog(R.string.copy_selected_tasks) + .setPositiveButton( + android.R.string.ok, ((dialogInterface, i) -> copySelectedItems())) + .setNegativeButton(android.R.string.cancel, null) + .show(); + return true; + default: + return false; + } + } + + @Override + public void onDestroyActionMode(ActionMode actionMode) { + adapter.clearSelections(); + TaskListRecyclerAdapter.this.mode = null; + if (!dragging) { + notifyDataSetChanged(); + } + } + }; + private boolean animate; - public TaskListRecyclerAdapter(Activity activity, TaskAdapter adapter, + public TaskListRecyclerAdapter( + Activity activity, + TaskAdapter adapter, ViewHolderFactory viewHolderFactory, - TaskListFragment taskList, TaskDeleter taskDeleter, - TaskDuplicator taskDuplicator, Tracker tracker, + TaskListFragment taskList, + TaskDeleter taskDeleter, + TaskDuplicator taskDuplicator, + Tracker tracker, DialogBuilder dialogBuilder) { this.activity = activity; this.adapter = adapter; @@ -107,8 +116,9 @@ public class TaskListRecyclerAdapter extends RecyclerView.Adapter this.tracker = tracker; this.dialogBuilder = dialogBuilder; itemTouchHelper = new ItemTouchHelper(new ItemTouchHelperCallback()); - adapterHelper = new AsyncPagedListDiffer<>(this, - new AsyncDifferConfig.Builder<>(new DiffCallback(adapter)).build()); + adapterHelper = + new AsyncPagedListDiffer<>( + this, new AsyncDifferConfig.Builder<>(new DiffCallback(adapter)).build()); } public void applyToRecyclerView(RecyclerView recyclerView) { @@ -135,8 +145,9 @@ public class TaskListRecyclerAdapter extends RecyclerView.Adapter @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - ViewGroup view = (ViewGroup) LayoutInflater.from(activity) - .inflate(R.layout.task_adapter_row_simple, parent, false); + ViewGroup view = + (ViewGroup) + LayoutInflater.from(activity).inflate(R.layout.task_adapter_row_simple, parent, false); return viewHolderFactory.newViewHolder(view, this); } @@ -206,8 +217,10 @@ public class TaskListRecyclerAdapter extends RecyclerView.Adapter finishActionMode(); List result = taskDeleter.markDeleted(tasks); taskList.onTaskDelete(result); - taskList.makeSnackbar(activity - .getString(R.string.delete_multiple_tasks_confirmation, Integer.toString(result.size()))) + taskList + .makeSnackbar( + activity.getString( + R.string.delete_multiple_tasks_confirmation, Integer.toString(result.size()))) .show(); } @@ -217,8 +230,10 @@ public class TaskListRecyclerAdapter extends RecyclerView.Adapter finishActionMode(); List duplicates = taskDuplicator.duplicate(tasks); taskList.onTaskCreated(duplicates); - taskList.makeSnackbar(activity - .getString(R.string.copy_multiple_tasks_confirmation, Integer.toString(duplicates.size()))) + taskList + .makeSnackbar( + activity.getString( + R.string.copy_multiple_tasks_confirmation, Integer.toString(duplicates.size()))) .show(); } @@ -311,8 +326,8 @@ public class TaskListRecyclerAdapter extends RecyclerView.Adapter } @Override - public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder source, - RecyclerView.ViewHolder target) { + public boolean onMove( + RecyclerView recyclerView, RecyclerView.ViewHolder source, RecyclerView.ViewHolder target) { finishActionMode(); int fromPosition = source.getAdapterPosition(); int toPosition = target.getAdapterPosition(); @@ -331,8 +346,14 @@ public class TaskListRecyclerAdapter extends RecyclerView.Adapter } @Override - public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, - float dX, float dY, int actionState, boolean isCurrentlyActive) { + public void onChildDraw( + Canvas c, + RecyclerView recyclerView, + RecyclerView.ViewHolder viewHolder, + float dX, + float dY, + int actionState, + boolean isCurrentlyActive) { if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) { float shiftSize = ((ViewHolder) viewHolder).getShiftSize(); dX = Math.max(-shiftSize, Math.min(shiftSize, dX)); @@ -365,8 +386,7 @@ public class TaskListRecyclerAdapter extends RecyclerView.Adapter @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) { adapter.indented( - viewHolder.getAdapterPosition(), - direction == ItemTouchHelper.RIGHT ? 1 : -1); + viewHolder.getAdapterPosition(), direction == ItemTouchHelper.RIGHT ? 1 : -1); taskList.loadTaskListContent(false); } } diff --git a/app/src/main/java/org/tasks/tasklist/ViewHolder.java b/app/src/main/java/org/tasks/tasklist/ViewHolder.java index fbc1f01f8..753aab66c 100644 --- a/app/src/main/java/org/tasks/tasklist/ViewHolder.java +++ b/app/src/main/java/org/tasks/tasklist/ViewHolder.java @@ -52,23 +52,51 @@ class ViewHolder extends RecyclerView.ViewHolder { private final int background; private final int selectedColor; private final int textColorOverdue; - @BindView(R.id.row) public ViewGroup row; - @BindView(R.id.due_date) public TextView dueDate; + + @BindView(R.id.row) + public ViewGroup row; + + @BindView(R.id.due_date) + public TextView dueDate; + public Task task; - @BindView(R.id.rowBody) ViewGroup rowBody; - @BindView(R.id.title) TextView nameView; - @BindView(R.id.completeBox) CheckableImageView completeBox; - @BindView(R.id.tag_block) TextView tagBlock; - @BindView(R.id.taskActionIcon) ImageView taskActionIcon; + + @BindView(R.id.rowBody) + ViewGroup rowBody; + + @BindView(R.id.title) + TextView nameView; + + @BindView(R.id.completeBox) + CheckableImageView completeBox; + + @BindView(R.id.tag_block) + TextView tagBlock; + + @BindView(R.id.taskActionIcon) + ImageView taskActionIcon; + private int indent; private boolean selected; private boolean moving; - ViewHolder(Context context, ViewGroup view, boolean showFullTaskTitle, int fontSize, - CheckBoxes checkBoxes, TagFormatter tagFormatter, - int textColorOverdue, int textColorSecondary, int textColorHint, TaskDao taskDao, - DialogBuilder dialogBuilder, ViewHolderCallbacks callback, - DisplayMetrics metrics, int background, int selectedColor, int rowPadding) { + ViewHolder( + Context context, + ViewGroup view, + boolean showFullTaskTitle, + int fontSize, + CheckBoxes checkBoxes, + TagFormatter tagFormatter, + int textColorOverdue, + int textColorSecondary, + int textColorHint, + TaskDao taskDao, + DialogBuilder dialogBuilder, + ViewHolderCallbacks callback, + DisplayMetrics metrics, + int background, + int selectedColor, + int rowPadding) { super(view); this.context = context; this.checkBoxes = checkBoxes; @@ -93,10 +121,10 @@ class ViewHolder extends RecyclerView.ViewHolder { if (atLeastKitKat()) { rowBody.setPadding(0, rowPadding, 0, rowPadding); } else { - ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) rowBody - .getLayoutParams(); - layoutParams - .setMargins(layoutParams.leftMargin, rowPadding, layoutParams.rightMargin, rowPadding); + ViewGroup.MarginLayoutParams layoutParams = + (ViewGroup.MarginLayoutParams) rowBody.getLayoutParams(); + layoutParams.setMargins( + layoutParams.leftMargin, rowPadding, layoutParams.rightMargin, rowPadding); } nameView.setTextSize(fontSize); @@ -134,8 +162,8 @@ class ViewHolder extends RecyclerView.ViewHolder { this.indent = indent; int indentSize = getIndentSize(indent); if (atLeastLollipop()) { - ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) row - .getLayoutParams(); + ViewGroup.MarginLayoutParams layoutParams = + (ViewGroup.MarginLayoutParams) row.getLayoutParams(); layoutParams.setMarginStart(indentSize); } else { rowBody.setPadding(indentSize, rowBody.getPaddingTop(), 0, rowBody.getPaddingBottom()); @@ -162,9 +190,7 @@ class ViewHolder extends RecyclerView.ViewHolder { setTaskAppearance(); } - /** - * Helper method to set the contents and visibility of each field - */ + /** Helper method to set the contents and visibility of each field */ private synchronized void setFieldContentsAndVisibility() { String nameValue = task.getTitle(); @@ -242,8 +268,8 @@ class ViewHolder extends RecyclerView.ViewHolder { dueDateView.setText(dateValue); dueDateView.setVisibility(View.VISIBLE); } else if (task.isCompleted()) { - String dateValue = DateUtilities - .getRelativeDateStringWithTime(context, task.getCompletionDate()); + String dateValue = + DateUtilities.getRelativeDateStringWithTime(context, task.getCompletionDate()); dueDateView.setText(context.getResources().getString(R.string.TAd_completed, dateValue)); dueDateView.setTextColor(textColorHint); dueDateView.setVisibility(View.VISIBLE); @@ -318,10 +344,12 @@ class ViewHolder extends RecyclerView.ViewHolder { } SpannableString description = new SpannableString(t.getNotes()); Linkify.addLinks(description, Linkify.ALL); - AlertDialog dialog = dialogBuilder.newDialog() - .setMessage(description) - .setPositiveButton(android.R.string.ok, null) - .show(); + AlertDialog dialog = + dialogBuilder + .newDialog() + .setMessage(description) + .setPositiveButton(android.R.string.ok, null) + .show(); View message = dialog.findViewById(android.R.id.message); if (message != null && message instanceof TextView) { ((TextView) message).setMovementMethod(LinkMovementMethod.getInstance()); @@ -330,10 +358,10 @@ class ViewHolder extends RecyclerView.ViewHolder { private void showFilesDialog(Task task) { // TODO: reimplement this -// FilesControlSet filesControlSet = new FilesControlSet(); -// filesControlSet.hideAddAttachmentButton(); -// filesControlSet.readFromTask(task); -// filesControlSet.getView().performClick(); + // FilesControlSet filesControlSet = new FilesControlSet(); + // filesControlSet.hideAddAttachmentButton(); + // filesControlSet.readFromTask(task); + // filesControlSet.getView().performClick(); } interface ViewHolderCallbacks { diff --git a/app/src/main/java/org/tasks/tasklist/ViewHolderFactory.java b/app/src/main/java/org/tasks/tasklist/ViewHolderFactory.java index 95a84797f..d6fa52404 100644 --- a/app/src/main/java/org/tasks/tasklist/ViewHolderFactory.java +++ b/app/src/main/java/org/tasks/tasklist/ViewHolderFactory.java @@ -34,8 +34,12 @@ public class ViewHolderFactory { private final int rowPadding; @Inject - public ViewHolderFactory(@ForActivity Context context, Preferences preferences, - CheckBoxes checkBoxes, TagFormatter tagFormatter, TaskDao taskDao, + public ViewHolderFactory( + @ForActivity Context context, + Preferences preferences, + CheckBoxes checkBoxes, + TagFormatter tagFormatter, + TaskDao taskDao, DialogBuilder dialogBuilder) { this.context = context; this.checkBoxes = checkBoxes; @@ -54,8 +58,22 @@ public class ViewHolderFactory { } ViewHolder newViewHolder(ViewGroup viewGroup, ViewHolder.ViewHolderCallbacks callbacks) { - return new ViewHolder(context, viewGroup, showFullTaskTitle, fontSize, checkBoxes, - tagFormatter, textColorOverdue, textColorSecondary, textColorHint, taskDao, - dialogBuilder, callbacks, metrics, background, selectedColor, rowPadding); + return new ViewHolder( + context, + viewGroup, + showFullTaskTitle, + fontSize, + checkBoxes, + tagFormatter, + textColorOverdue, + textColorSecondary, + textColorHint, + taskDao, + dialogBuilder, + callbacks, + metrics, + background, + selectedColor, + rowPadding); } } diff --git a/app/src/main/java/org/tasks/themes/ThemeAccent.java b/app/src/main/java/org/tasks/themes/ThemeAccent.java index 1e4d7f830..34fb8d8c7 100644 --- a/app/src/main/java/org/tasks/themes/ThemeAccent.java +++ b/app/src/main/java/org/tasks/themes/ThemeAccent.java @@ -7,36 +7,38 @@ import org.tasks.dialogs.ColorPickerDialog; public class ThemeAccent implements ColorPickerDialog.Pickable { - static final int[] ACCENTS = new int[]{ - R.style.BlueGreyAccent, - R.style.RedAccent, - R.style.PinkAccent, - R.style.PurpleAccent, - R.style.DeepPurpleAccent, - R.style.IndigoAccent, - R.style.BlueAccent, - R.style.LightBlueAccent, - R.style.CyanAccent, - R.style.TealAccent, - R.style.GreenAccent, - R.style.LightGreenAccent, - R.style.LimeAccent, - R.style.YellowAccent, - R.style.AmberAccent, - R.style.OrangeAccent, - R.style.DeepOrangeAccent - }; - public static Creator CREATOR = new Creator() { - @Override - public ThemeAccent createFromParcel(Parcel source) { - return new ThemeAccent(source); - } + static final int[] ACCENTS = + new int[] { + R.style.BlueGreyAccent, + R.style.RedAccent, + R.style.PinkAccent, + R.style.PurpleAccent, + R.style.DeepPurpleAccent, + R.style.IndigoAccent, + R.style.BlueAccent, + R.style.LightBlueAccent, + R.style.CyanAccent, + R.style.TealAccent, + R.style.GreenAccent, + R.style.LightGreenAccent, + R.style.LimeAccent, + R.style.YellowAccent, + R.style.AmberAccent, + R.style.OrangeAccent, + R.style.DeepOrangeAccent + }; + public static Creator CREATOR = + new Creator() { + @Override + public ThemeAccent createFromParcel(Parcel source) { + return new ThemeAccent(source); + } - @Override - public ThemeAccent[] newArray(int size) { - return new ThemeAccent[size]; - } - }; + @Override + public ThemeAccent[] newArray(int size) { + return new ThemeAccent[size]; + } + }; private final String name; private final int index; private final int style; diff --git a/app/src/main/java/org/tasks/themes/ThemeBase.java b/app/src/main/java/org/tasks/themes/ThemeBase.java index b27dd6ced..0b604ba59 100644 --- a/app/src/main/java/org/tasks/themes/ThemeBase.java +++ b/app/src/main/java/org/tasks/themes/ThemeBase.java @@ -11,24 +11,22 @@ import org.tasks.dialogs.ColorPickerDialog; public class ThemeBase implements ColorPickerDialog.Pickable { - private static final int[] THEMES = new int[]{ - R.style.Tasks, - R.style.ThemeBlack, - R.style.Tasks, - R.style.Wallpaper, - R.style.Tasks - }; - public static Creator CREATOR = new Creator() { - @Override - public ThemeBase createFromParcel(Parcel source) { - return new ThemeBase(source); - } - - @Override - public ThemeBase[] newArray(int size) { - return new ThemeBase[size]; - } - }; + private static final int[] THEMES = + new int[] { + R.style.Tasks, R.style.ThemeBlack, R.style.Tasks, R.style.Wallpaper, R.style.Tasks + }; + public static Creator CREATOR = + new Creator() { + @Override + public ThemeBase createFromParcel(Parcel source) { + return new ThemeBase(source); + } + + @Override + public ThemeBase[] newArray(int size) { + return new ThemeBase[size]; + } + }; private final String name; private final int index; private final int style; @@ -77,8 +75,9 @@ public class ThemeBase implements ColorPickerDialog.Pickable { public boolean isDarkTheme(Activity activity) { return index == 4 - ? Configuration.UI_MODE_NIGHT_YES == (activity.getResources().getConfiguration().uiMode - & Configuration.UI_MODE_NIGHT_MASK) + ? Configuration.UI_MODE_NIGHT_YES + == (activity.getResources().getConfiguration().uiMode + & Configuration.UI_MODE_NIGHT_MASK) : index > 0; } diff --git a/app/src/main/java/org/tasks/themes/ThemeCache.java b/app/src/main/java/org/tasks/themes/ThemeCache.java index bccaf25cc..a8acbc054 100644 --- a/app/src/main/java/org/tasks/themes/ThemeCache.java +++ b/app/src/main/java/org/tasks/themes/ThemeCache.java @@ -28,47 +28,72 @@ public class ThemeCache { public ThemeCache(@ForApplication Context context) { Resources resources = context.getResources(); - themes.add(new ThemeBase(context.getString(R.string.theme_light), 0, - getColor(context, R.color.grey_50), AppCompatDelegate.MODE_NIGHT_NO)); - themes.add(new ThemeBase(context.getString(R.string.theme_black), 1, - getColor(context, R.color.widget_background_black), AppCompatDelegate.MODE_NIGHT_YES)); - themes.add(new ThemeBase(context.getString(R.string.theme_dark), 2, - getColor(context, R.color.md_background_dark), AppCompatDelegate.MODE_NIGHT_YES)); - themes.add(new ThemeBase(context.getString(R.string.theme_wallpaper), 3, - getColor(context, R.color.black_38), AppCompatDelegate.MODE_NIGHT_YES)); - themes.add(new ThemeBase(context.getString(R.string.theme_day_night), 4, - getColor(context, R.color.grey_50), AppCompatDelegate.MODE_NIGHT_AUTO)); + themes.add( + new ThemeBase( + context.getString(R.string.theme_light), + 0, + getColor(context, R.color.grey_50), + AppCompatDelegate.MODE_NIGHT_NO)); + themes.add( + new ThemeBase( + context.getString(R.string.theme_black), + 1, + getColor(context, R.color.widget_background_black), + AppCompatDelegate.MODE_NIGHT_YES)); + themes.add( + new ThemeBase( + context.getString(R.string.theme_dark), + 2, + getColor(context, R.color.md_background_dark), + AppCompatDelegate.MODE_NIGHT_YES)); + themes.add( + new ThemeBase( + context.getString(R.string.theme_wallpaper), + 3, + getColor(context, R.color.black_38), + AppCompatDelegate.MODE_NIGHT_YES)); + themes.add( + new ThemeBase( + context.getString(R.string.theme_day_night), + 4, + getColor(context, R.color.grey_50), + AppCompatDelegate.MODE_NIGHT_AUTO)); String[] colorNames = resources.getStringArray(R.array.colors); for (int i = 0; i < ThemeColor.COLORS.length; i++) { Resources.Theme theme = new ContextThemeWrapper(context, ThemeColor.COLORS[i]).getTheme(); - colors.add(new ThemeColor( - colorNames[i], - i, - resolveAttribute(theme, R.attr.colorPrimary), - resolveAttribute(theme, R.attr.colorPrimaryDark), - resolveAttribute(theme, R.attr.actionBarPrimaryText), - resolveBoolean(theme, R.attr.dark_status_bar))); + colors.add( + new ThemeColor( + colorNames[i], + i, + resolveAttribute(theme, R.attr.colorPrimary), + resolveAttribute(theme, R.attr.colorPrimaryDark), + resolveAttribute(theme, R.attr.actionBarPrimaryText), + resolveBoolean(theme, R.attr.dark_status_bar))); } String[] accentNames = resources.getStringArray(R.array.accents); for (int i = 0; i < ThemeAccent.ACCENTS.length; i++) { Resources.Theme theme = new ContextThemeWrapper(context, ThemeAccent.ACCENTS[i]).getTheme(); - accents.add(new ThemeAccent( - accentNames[i], - i, - resolveAttribute(theme, R.attr.colorAccent))); + accents.add(new ThemeAccent(accentNames[i], i, resolveAttribute(theme, R.attr.colorAccent))); } String[] widgetBackgroundNames = resources.getStringArray(R.array.widget_background); for (int i = 0; i < WidgetTheme.BACKGROUNDS.length; i++) { - widgetThemes.add(new WidgetTheme( - widgetBackgroundNames[i], - i, - getColor(context, WidgetTheme.BACKGROUNDS[i]), - getColor(context, i == 0 ? R.color.black_87 : R.color.white_100), - getColor(context, i == 0 ? R.color.black_54 : R.color.white_70))); + widgetThemes.add( + new WidgetTheme( + widgetBackgroundNames[i], + i, + getColor(context, WidgetTheme.BACKGROUNDS[i]), + getColor(context, i == 0 ? R.color.black_87 : R.color.white_100), + getColor(context, i == 0 ? R.color.black_54 : R.color.white_70))); } - untaggedColor = new ThemeColor(null, 19, getColor(context, R.color.tag_color_none_background), - 0, getColor(context, R.color.black_87), false); + untaggedColor = + new ThemeColor( + null, + 19, + getColor(context, R.color.tag_color_none_background), + 0, + getColor(context, R.color.black_87), + false); } private static int resolveAttribute(Resources.Theme theme, int attribute) { diff --git a/app/src/main/java/org/tasks/themes/ThemeColor.java b/app/src/main/java/org/tasks/themes/ThemeColor.java index 1de9814a1..6c306051e 100644 --- a/app/src/main/java/org/tasks/themes/ThemeColor.java +++ b/app/src/main/java/org/tasks/themes/ThemeColor.java @@ -19,39 +19,41 @@ import org.tasks.ui.MenuColorizer; public class ThemeColor implements ColorPickerDialog.Pickable { - static final int[] COLORS = new int[]{ - R.style.BlueGrey, - R.style.DarkGrey, - R.style.Red, - R.style.Pink, - R.style.Purple, - R.style.DeepPurple, - R.style.Indigo, - R.style.Blue, - R.style.LightBlue, - R.style.Cyan, - R.style.Teal, - R.style.Green, - R.style.LightGreen, - R.style.Lime, - R.style.Yellow, - R.style.Amber, - R.style.Orange, - R.style.DeepOrange, - R.style.Brown, - R.style.Grey - }; - public static Creator CREATOR = new Creator() { - @Override - public ThemeColor createFromParcel(Parcel source) { - return new ThemeColor(source); - } - - @Override - public ThemeColor[] newArray(int size) { - return new ThemeColor[size]; - } - }; + static final int[] COLORS = + new int[] { + R.style.BlueGrey, + R.style.DarkGrey, + R.style.Red, + R.style.Pink, + R.style.Purple, + R.style.DeepPurple, + R.style.Indigo, + R.style.Blue, + R.style.LightBlue, + R.style.Cyan, + R.style.Teal, + R.style.Green, + R.style.LightGreen, + R.style.Lime, + R.style.Yellow, + R.style.Amber, + R.style.Orange, + R.style.DeepOrange, + R.style.Brown, + R.style.Grey + }; + public static Creator CREATOR = + new Creator() { + @Override + public ThemeColor createFromParcel(Parcel source) { + return new ThemeColor(source); + } + + @Override + public ThemeColor[] newArray(int size) { + return new ThemeColor[size]; + } + }; private final String name; private final int index; private final int actionBarTint; @@ -60,8 +62,13 @@ public class ThemeColor implements ColorPickerDialog.Pickable { private final int colorPrimaryDark; private final boolean isDark; - public ThemeColor(String name, int index, int colorPrimary, int colorPrimaryDark, - int actionBarTint, boolean isDark) { + public ThemeColor( + String name, + int index, + int colorPrimary, + int colorPrimaryDark, + int actionBarTint, + boolean isDark) { this.name = name; this.index = index; this.actionBarTint = actionBarTint; diff --git a/app/src/main/java/org/tasks/themes/WidgetTheme.java b/app/src/main/java/org/tasks/themes/WidgetTheme.java index 15d343e38..b16570410 100644 --- a/app/src/main/java/org/tasks/themes/WidgetTheme.java +++ b/app/src/main/java/org/tasks/themes/WidgetTheme.java @@ -6,30 +6,28 @@ import org.tasks.dialogs.ColorPickerDialog; public class WidgetTheme implements ColorPickerDialog.Pickable { - static final int[] BACKGROUNDS = new int[]{ - R.color.grey_50, - R.color.widget_background_black, - R.color.md_background_dark - }; - public static Creator CREATOR = new Creator() { - @Override - public WidgetTheme createFromParcel(Parcel source) { - return new WidgetTheme(source); - } + static final int[] BACKGROUNDS = + new int[] {R.color.grey_50, R.color.widget_background_black, R.color.md_background_dark}; + public static Creator CREATOR = + new Creator() { + @Override + public WidgetTheme createFromParcel(Parcel source) { + return new WidgetTheme(source); + } - @Override - public WidgetTheme[] newArray(int size) { - return new WidgetTheme[size]; - } - }; + @Override + public WidgetTheme[] newArray(int size) { + return new WidgetTheme[size]; + } + }; private final String name; private final int index; private final int backgroundColor; private final int textColorPrimary; private final int textColorSecondary; - public WidgetTheme(String name, int index, int backgroundColor, int textColorPrimary, - int textColorSecondary) { + public WidgetTheme( + String name, int index, int backgroundColor, int textColorPrimary, int textColorSecondary) { this.name = name; this.index = index; this.backgroundColor = backgroundColor; diff --git a/app/src/main/java/org/tasks/time/DateTime.java b/app/src/main/java/org/tasks/time/DateTime.java index 0c78198d3..867f7e2ab 100644 --- a/app/src/main/java/org/tasks/time/DateTime.java +++ b/app/src/main/java/org/tasks/time/DateTime.java @@ -46,7 +46,14 @@ public class DateTime { this(year, month, day, hour, minute, second, millisecond, TimeZone.getDefault()); } - public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, + public DateTime( + int year, + int month, + int day, + int hour, + int minute, + int second, + int millisecond, TimeZone timeZone) { GregorianCalendar gregorianCalendar = new GregorianCalendar(timeZone); gregorianCalendar.set(year, month - 1, day, hour, minute, second); @@ -153,10 +160,10 @@ public class DateTime { public int getMillisOfDay() { Calendar calendar = getCalendar(); long millisOfDay = - calendar.get(Calendar.MILLISECOND) + - TimeUnit.SECONDS.toMillis(calendar.get(Calendar.SECOND)) + - TimeUnit.MINUTES.toMillis(calendar.get(Calendar.MINUTE)) + - TimeUnit.HOURS.toMillis(calendar.get(Calendar.HOUR_OF_DAY)); + calendar.get(Calendar.MILLISECOND) + + TimeUnit.SECONDS.toMillis(calendar.get(Calendar.SECOND)) + + TimeUnit.MINUTES.toMillis(calendar.get(Calendar.MINUTE)) + + TimeUnit.HOURS.toMillis(calendar.get(Calendar.HOUR_OF_DAY)); return (int) millisOfDay; } @@ -310,9 +317,7 @@ public class DateTime { } public DateValue toDateValue() { - return timestamp == 0 - ? null - : new DateValueImpl(getYear(), getMonthOfYear(), getDayOfMonth()); + return timestamp == 0 ? null : new DateValueImpl(getYear(), getMonthOfYear(), getDayOfMonth()); } public int getDayOfWeekInMonth() { @@ -358,7 +363,6 @@ public class DateTime { return false; } return !(timeZone != null ? !timeZone.equals(dateTime.timeZone) : dateTime.timeZone != null); - } @Override @@ -370,8 +374,8 @@ public class DateTime { public String toString(String format) { Calendar calendar = getCalendar(); - SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format, - Locale.getInstance().getLocale()); + SimpleDateFormat simpleDateFormat = + new SimpleDateFormat(format, Locale.getInstance().getLocale()); simpleDateFormat.setCalendar(calendar); return simpleDateFormat.format(calendar.getTime()); } diff --git a/app/src/main/java/org/tasks/time/DateTimeUtils.java b/app/src/main/java/org/tasks/time/DateTimeUtils.java index 70b670a4f..e8eda4bbb 100644 --- a/app/src/main/java/org/tasks/time/DateTimeUtils.java +++ b/app/src/main/java/org/tasks/time/DateTimeUtils.java @@ -31,8 +31,6 @@ public class DateTimeUtils { } public static String printTimestamp(long timestamp) { - return BuildConfig.DEBUG - ? new Date(timestamp).toString() - : Long.toString(timestamp); + return BuildConfig.DEBUG ? new Date(timestamp).toString() : Long.toString(timestamp); } } diff --git a/app/src/main/java/org/tasks/ui/CalendarControlSet.java b/app/src/main/java/org/tasks/ui/CalendarControlSet.java index 1982cb09e..6ee06529f 100644 --- a/app/src/main/java/org/tasks/ui/CalendarControlSet.java +++ b/app/src/main/java/org/tasks/ui/CalendarControlSet.java @@ -51,8 +51,11 @@ public class CalendarControlSet extends TaskEditControlFragment { private static final String EXTRA_URI = "extra_uri"; private static final String EXTRA_ID = "extra_id"; - @BindView(R.id.clear) View cancelButton; - @BindView(R.id.calendar_display_which) TextView calendar; + @BindView(R.id.clear) + View cancelButton; + + @BindView(R.id.calendar_display_which) + TextView calendar; @Inject GCalHelper gcalHelper; @Inject CalendarProvider calendarProvider; @@ -70,8 +73,8 @@ public class CalendarControlSet extends TaskEditControlFragment { @Nullable @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = super.onCreateView(inflater, container, savedInstanceState); boolean canAccessCalendars = permissionChecker.canAccessCalendars(); if (savedInstanceState != null) { @@ -174,9 +177,11 @@ public class CalendarControlSet extends TaskEditControlFragment { task.setCalendarUri(uri.toString()); // pop up the new event Intent intent = new Intent(Intent.ACTION_VIEW, uri); - intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, + intent.putExtra( + CalendarContract.EXTRA_EVENT_BEGIN_TIME, values.getAsLong(CalendarContract.Events.DTSTART)); - intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, + intent.putExtra( + CalendarContract.EXTRA_EVENT_END_TIME, values.getAsLong(CalendarContract.Events.DTEND)); startActivity(intent); } @@ -199,12 +204,15 @@ public class CalendarControlSet extends TaskEditControlFragment { if (isNullOrEmpty(eventUri)) { clear(); } else { - dialogBuilder.newMessageDialog(R.string.delete_calendar_event_confirmation) - .setPositiveButton(R.string.delete, (dialog, which) -> { - if (permissionRequestor.requestCalendarPermissions(REQUEST_CODE_CLEAR_EVENT)) { - clear(); - } - }) + dialogBuilder + .newMessageDialog(R.string.delete_calendar_event_confirmation) + .setPositiveButton( + R.string.delete, + (dialog, which) -> { + if (permissionRequestor.requestCalendarPermissions(REQUEST_CODE_CLEAR_EVENT)) { + clear(); + } + }) .setNegativeButton(android.R.string.cancel, null) .show(); } @@ -233,9 +241,13 @@ public class CalendarControlSet extends TaskEditControlFragment { ContentResolver cr = getActivity().getContentResolver(); Uri uri = Uri.parse(eventUri); Intent intent = new Intent(Intent.ACTION_VIEW, uri); - Cursor cursor = cr - .query(uri, new String[]{CalendarContract.Events.DTSTART, CalendarContract.Events.DTEND}, - null, null, null); + Cursor cursor = + cr.query( + uri, + new String[] {CalendarContract.Events.DTSTART, CalendarContract.Events.DTEND}, + null, + null, + null); try { if (cursor.getCount() == 0) { // event no longer exists @@ -277,8 +289,8 @@ public class CalendarControlSet extends TaskEditControlFragment { } @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, - @NonNull int[] grantResults) { + public void onRequestPermissionsResult( + int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == REQUEST_CODE_OPEN_EVENT) { if (verifyPermissions(grantResults)) { openCalendarEvent(); @@ -313,8 +325,9 @@ public class CalendarControlSet extends TaskEditControlFragment { try { Uri uri = Uri.parse(eventUri); ContentResolver contentResolver = context.getContentResolver(); - Cursor cursor = contentResolver - .query(uri, new String[]{CalendarContract.Events.DTSTART}, null, null, null); + Cursor cursor = + contentResolver.query( + uri, new String[] {CalendarContract.Events.DTSTART}, null, null, null); try { if (cursor.getCount() != 0) { return true; diff --git a/app/src/main/java/org/tasks/ui/CheckBoxes.java b/app/src/main/java/org/tasks/ui/CheckBoxes.java index d5bc011d8..f3262c6a3 100644 --- a/app/src/main/java/org/tasks/ui/CheckBoxes.java +++ b/app/src/main/java/org/tasks/ui/CheckBoxes.java @@ -30,11 +30,12 @@ public class CheckBoxes { checkboxes = wrapDrawable(context, R.drawable.ic_check_box_outline_blank_24dp); repeatingCheckboxes = wrapDrawable(context, R.drawable.ic_repeat_24dp); completedCheckboxes = wrapDrawable(context, R.drawable.ic_check_box_24dp); - priorityColors = ImmutableList.of( - getColor(context, R.color.importance_1), - getColor(context, R.color.importance_2), - getColor(context, R.color.importance_3), - getColor(context, R.color.importance_4)); + priorityColors = + ImmutableList.of( + getColor(context, R.color.importance_1), + getColor(context, R.color.importance_2), + getColor(context, R.color.importance_3), + getColor(context, R.color.importance_4)); priorityColorsArray = Ints.toArray(priorityColors); } diff --git a/app/src/main/java/org/tasks/ui/DeadlineControlSet.java b/app/src/main/java/org/tasks/ui/DeadlineControlSet.java index 9e414981c..bb4b1afb0 100644 --- a/app/src/main/java/org/tasks/ui/DeadlineControlSet.java +++ b/app/src/main/java/org/tasks/ui/DeadlineControlSet.java @@ -51,9 +51,16 @@ public class DeadlineControlSet extends TaskEditControlFragment { @Inject Preferences preferences; @Inject @ForActivity Context context; @Inject ThemeBase themeBase; - @BindView(R.id.due_date) Spinner dueDateSpinner; - @BindView(R.id.due_time) Spinner dueTimeSpinner; - @BindView(R.id.clear) View clearButton; + + @BindView(R.id.due_date) + Spinner dueDateSpinner; + + @BindView(R.id.due_time) + Spinner dueTimeSpinner; + + @BindView(R.id.clear) + View clearButton; + private DueDateChangeListener callback; private List dueDateOptions = new ArrayList<>(); private List dueTimeOptions = new ArrayList<>(); @@ -84,13 +91,14 @@ public class DeadlineControlSet extends TaskEditControlFragment { dateShortcutAfternoon = preferences.getDateShortcutAfternoon(); dateShortcutEvening = preferences.getDateShortcutEvening(); dateShortcutNight = preferences.getDateShortcutNight(); - dueTimeHint = asList( - "", - "", - getTimeHint(dateShortcutMorning), - getTimeHint(dateShortcutAfternoon), - getTimeHint(dateShortcutEvening), - getTimeHint(dateShortcutNight)); + dueTimeHint = + asList( + "", + "", + getTimeHint(dateShortcutMorning), + getTimeHint(dateShortcutAfternoon), + getTimeHint(dateShortcutEvening), + getTimeHint(dateShortcutNight)); nightString = activity.getString(R.string.date_shortcut_night); eveningString = activity.getString(R.string.date_shortcut_evening); afternoonString = activity.getString(R.string.date_shortcut_afternoon); @@ -98,20 +106,17 @@ public class DeadlineControlSet extends TaskEditControlFragment { noTimeString = activity.getString(R.string.TEA_no_time); todayString = activity.getString(R.string.today); tomorrowString = activity.getString(R.string.tomorrow); - dueDateOptions = newArrayList( - "", - todayString, - tomorrowString, - "", - activity.getString(R.string.pick_a_date)); - dueTimeOptions = newArrayList( - "", - noTimeString, - morningString, - afternoonString, - eveningString, - nightString, - activity.getString(R.string.pick_a_time)); + dueDateOptions = + newArrayList("", todayString, tomorrowString, "", activity.getString(R.string.pick_a_date)); + dueTimeOptions = + newArrayList( + "", + noTimeString, + morningString, + afternoonString, + eveningString, + nightString, + activity.getString(R.string.pick_a_time)); } @Override @@ -121,8 +126,8 @@ public class DeadlineControlSet extends TaskEditControlFragment { @Nullable @Override - public View onCreateView(final LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = super.onCreateView(inflater, container, savedInstanceState); if (savedInstanceState == null) { if (task.hasDueDate()) { @@ -138,62 +143,64 @@ public class DeadlineControlSet extends TaskEditControlFragment { time = savedInstanceState.getInt(EXTRA_TIME); } final int overdueColor = getColor(context, R.color.overdue); - dueDateAdapter = new HiddenTopArrayAdapter(context, - android.R.layout.simple_spinner_item, dueDateOptions) { - @NonNull - @Override - public View getView(final int position, final View convertView, - @NonNull final ViewGroup parent) { - int selectedItemPosition = position; - if (parent instanceof AdapterView) { - selectedItemPosition = ((AdapterView) parent).getSelectedItemPosition(); - } - TextView tv = (TextView) inflater - .inflate(android.R.layout.simple_spinner_item, parent, false); - tv.setPadding(0, 0, 0, 0); - tv.setText(dueDateOptions.get(selectedItemPosition)); - int textColor; - if (date == 0) { - textColor = getColor(context, R.color.text_tertiary); - } else if (date < newDateTime().startOfDay().getMillis()) { - textColor = overdueColor; - } else { - textColor = getColor(context, R.color.text_primary); - } - dueDateSpinner.setBackgroundDrawable(getUnderline(textColor)); - tv.setTextColor(textColor); - return tv; - } - }; + dueDateAdapter = + new HiddenTopArrayAdapter( + context, android.R.layout.simple_spinner_item, dueDateOptions) { + @NonNull + @Override + public View getView( + final int position, final View convertView, @NonNull final ViewGroup parent) { + int selectedItemPosition = position; + if (parent instanceof AdapterView) { + selectedItemPosition = ((AdapterView) parent).getSelectedItemPosition(); + } + TextView tv = + (TextView) inflater.inflate(android.R.layout.simple_spinner_item, parent, false); + tv.setPadding(0, 0, 0, 0); + tv.setText(dueDateOptions.get(selectedItemPosition)); + int textColor; + if (date == 0) { + textColor = getColor(context, R.color.text_tertiary); + } else if (date < newDateTime().startOfDay().getMillis()) { + textColor = overdueColor; + } else { + textColor = getColor(context, R.color.text_primary); + } + dueDateSpinner.setBackgroundDrawable(getUnderline(textColor)); + tv.setTextColor(textColor); + return tv; + } + }; dueDateSpinner.setAdapter(dueDateAdapter); - dueTimeAdapter = new HiddenTopArrayAdapter(context, - android.R.layout.simple_spinner_item, dueTimeOptions, dueTimeHint) { - @NonNull - @Override - public View getView(final int position, final View convertView, - @NonNull final ViewGroup parent) { - int selectedItemPosition = position; - if (parent instanceof AdapterView) { - selectedItemPosition = ((AdapterView) parent).getSelectedItemPosition(); - } - TextView tv = (TextView) inflater - .inflate(android.R.layout.simple_spinner_item, parent, false); - tv.setPadding(0, 0, 0, 0); - tv.setText(dueTimeOptions.get(selectedItemPosition)); - int textColor; - if (time == -1) { - textColor = getColor(context, R.color.text_tertiary); - } else if (newDateTime(date).withMillisOfDay(time).isBeforeNow()) { - textColor = overdueColor; - } else { - textColor = getColor(context, R.color.text_primary); - } - tv.setTextColor(textColor); - dueTimeSpinner.setBackgroundDrawable(getUnderline(textColor)); - return tv; - } - }; + dueTimeAdapter = + new HiddenTopArrayAdapter( + context, android.R.layout.simple_spinner_item, dueTimeOptions, dueTimeHint) { + @NonNull + @Override + public View getView( + final int position, final View convertView, @NonNull final ViewGroup parent) { + int selectedItemPosition = position; + if (parent instanceof AdapterView) { + selectedItemPosition = ((AdapterView) parent).getSelectedItemPosition(); + } + TextView tv = + (TextView) inflater.inflate(android.R.layout.simple_spinner_item, parent, false); + tv.setPadding(0, 0, 0, 0); + tv.setText(dueTimeOptions.get(selectedItemPosition)); + int textColor; + if (time == -1) { + textColor = getColor(context, R.color.text_tertiary); + } else if (newDateTime(date).withMillisOfDay(time).isBeforeNow()) { + textColor = overdueColor; + } else { + textColor = getColor(context, R.color.text_primary); + } + tv.setTextColor(textColor); + dueTimeSpinner.setBackgroundDrawable(getUnderline(textColor)); + return tv; + } + }; dueTimeSpinner.setAdapter(dueTimeAdapter); refreshDisplayView(); @@ -319,8 +326,8 @@ public class DeadlineControlSet extends TaskEditControlFragment { private long getDueDateTime() { return time >= 0 - ? Task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, - newDateTime(date).withMillisOfDay(time).getMillis()) + ? Task.createDueDate( + Task.URGENCY_SPECIFIC_DAY_TIME, newDateTime(date).withMillisOfDay(time).getMillis()) : Task.createDueDate(Task.URGENCY_SPECIFIC_DAY, date); } @@ -368,11 +375,12 @@ public class DeadlineControlSet extends TaskEditControlFragment { if (time == -1) { dueTimeOptions.set(0, noTimeString); } else { - int compareTime = newDateTime() - .withMillisOfDay(time) - .withSecondOfMinute(0) - .withMillisOfSecond(0) - .getMillisOfDay(); + int compareTime = + newDateTime() + .withMillisOfDay(time) + .withSecondOfMinute(0) + .withMillisOfSecond(0) + .getMillisOfDay(); if (compareTime == dateShortcutMorning) { dueTimeOptions.set(0, morningString); } else if (compareTime == dateShortcutAfternoon) { @@ -382,8 +390,8 @@ public class DeadlineControlSet extends TaskEditControlFragment { } else if (compareTime == dateShortcutNight) { dueTimeOptions.set(0, nightString); } else { - dueTimeOptions - .set(0, DateUtilities.getTimeString(context, newDateTime().withMillisOfDay(time))); + dueTimeOptions.set( + 0, DateUtilities.getTimeString(context, newDateTime().withMillisOfDay(time))); } } dueTimeAdapter.notifyDataSetChanged(); @@ -391,8 +399,9 @@ public class DeadlineControlSet extends TaskEditControlFragment { } private Drawable getUnderline(int color) { - Drawable drawable = DrawableCompat - .wrap(ContextCompat.getDrawable(context, R.drawable.textfield_underline_black)); + Drawable drawable = + DrawableCompat.wrap( + ContextCompat.getDrawable(context, R.drawable.textfield_underline_black)); drawable.mutate(); DrawableCompat.setTint(drawable, color); return drawable; diff --git a/app/src/main/java/org/tasks/ui/DescriptionControlSet.java b/app/src/main/java/org/tasks/ui/DescriptionControlSet.java index 7490c13c2..d46c89148 100644 --- a/app/src/main/java/org/tasks/ui/DescriptionControlSet.java +++ b/app/src/main/java/org/tasks/ui/DescriptionControlSet.java @@ -19,14 +19,15 @@ public class DescriptionControlSet extends TaskEditControlFragment { public static final int TAG = R.string.TEA_ctrl_notes_pref; private static final String EXTRA_DESCRIPTION = "extra_description"; - @BindView(R.id.notes) EditText editText; + @BindView(R.id.notes) + EditText editText; private String description; @Nullable @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = super.onCreateView(inflater, container, savedInstanceState); if (savedInstanceState == null) { description = task.getNotes(); diff --git a/app/src/main/java/org/tasks/ui/EmptyTaskEditFragment.java b/app/src/main/java/org/tasks/ui/EmptyTaskEditFragment.java index 6b7d8a631..32c20f004 100644 --- a/app/src/main/java/org/tasks/ui/EmptyTaskEditFragment.java +++ b/app/src/main/java/org/tasks/ui/EmptyTaskEditFragment.java @@ -12,8 +12,8 @@ public class EmptyTaskEditFragment extends Fragment { @Nullable @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_task_edit_empty, container, false); } } diff --git a/app/src/main/java/org/tasks/ui/HiddenTopArrayAdapter.java b/app/src/main/java/org/tasks/ui/HiddenTopArrayAdapter.java index c23122c2f..421425b6c 100644 --- a/app/src/main/java/org/tasks/ui/HiddenTopArrayAdapter.java +++ b/app/src/main/java/org/tasks/ui/HiddenTopArrayAdapter.java @@ -25,8 +25,8 @@ public class HiddenTopArrayAdapter extends ArrayAdapter { } @Override - public View getDropDownView(final int position, final View convertView, - @NonNull final ViewGroup parent) { + public View getDropDownView( + final int position, final View convertView, @NonNull final ViewGroup parent) { View v; if (position == 0) { @@ -35,8 +35,10 @@ public class HiddenTopArrayAdapter extends ArrayAdapter { tv.setVisibility(View.GONE); v = tv; } else { - ViewGroup vg = (ViewGroup) LayoutInflater.from(getContext()) - .inflate(R.layout.simple_spinner_dropdown_item, parent, false); + ViewGroup vg = + (ViewGroup) + LayoutInflater.from(getContext()) + .inflate(R.layout.simple_spinner_dropdown_item, parent, false); ((TextView) vg.findViewById(R.id.text1)).setText(getItem(position).toString()); if (position < hints.size()) { ((TextView) vg.findViewById(R.id.text2)).setText(hints.get(position)); diff --git a/app/src/main/java/org/tasks/ui/MenuColorizer.java b/app/src/main/java/org/tasks/ui/MenuColorizer.java index 0660366ab..97506dfd8 100644 --- a/app/src/main/java/org/tasks/ui/MenuColorizer.java +++ b/app/src/main/java/org/tasks/ui/MenuColorizer.java @@ -27,9 +27,8 @@ import android.view.SubMenu; import org.tasks.R; /** - * Helper class to set the color and transparency for menu icons in an ActionBar/Toolbar.

    - * - * Example usage: + * Helper class to set the color and transparency for menu icons in an ActionBar/Toolbar. Example + * usage: * *
      * 
    @@ -48,8 +47,7 @@ import org.tasks.R;
      */
     public class MenuColorizer {
     
    -  private MenuColorizer() {
    -  }
    +  private MenuColorizer() {}
     
       public static void colorToolbar(Context context, Toolbar toolbar) {
         TypedValue typedValue = new TypedValue();
    @@ -69,9 +67,7 @@ public class MenuColorizer {
         colorMenu(menu, typedValue.data);
       }
     
    -  /**
    -   * Sets a color filter on all menu icons, including the overflow button (if it exists)
    -   */
    +  /** Sets a color filter on all menu icons, including the overflow button (if it exists) */
       private static void colorMenu(final Menu menu, final int color) {
         for (int i = 0, size = menu.size(); i < size; i++) {
           final MenuItem menuItem = menu.getItem(i);
    @@ -85,9 +81,7 @@ public class MenuColorizer {
         }
       }
     
    -  /**
    -   * Sets a color filter on a {@link MenuItem}
    -   */
    +  /** Sets a color filter on a {@link MenuItem} */
       private static void colorMenuItem(final MenuItem menuItem, final int color) {
         colorDrawable(menuItem.getIcon(), color);
       }
    diff --git a/app/src/main/java/org/tasks/ui/NavigationDrawerFragment.java b/app/src/main/java/org/tasks/ui/NavigationDrawerFragment.java
    index 74fbf5e43..a07bf3a4d 100644
    --- a/app/src/main/java/org/tasks/ui/NavigationDrawerFragment.java
    +++ b/app/src/main/java/org/tasks/ui/NavigationDrawerFragment.java
    @@ -34,14 +34,13 @@ public class NavigationDrawerFragment extends InjectingFragment {
       public static final int ACTIVITY_REQUEST_NEW_FILTER = 5;
       public static final int REQUEST_NEW_GTASK_LIST = 6;
       public static final int REQUEST_NEW_CALDAV_ACCOUNT = 7;
    -  private static final String TOKEN_LAST_SELECTED = "lastSelected"; //$NON-NLS-1$
    +  private static final String TOKEN_LAST_SELECTED = "lastSelected"; // $NON-NLS-1$
       private final RefreshReceiver refreshReceiver = new RefreshReceiver();
       @Inject LocalBroadcastManager localBroadcastManager;
       @Inject FilterAdapter adapter;
    -  /**
    -   * A pointer to the current callbacks instance (the Activity).
    -   */
    +  /** A pointer to the current callbacks instance (the Activity). */
       private OnFilterItemClickedListener mCallbacks;
    +
       private DrawerLayout mDrawerLayout;
       private ListView mDrawerListView;
       private View mFragmentContainerView;
    @@ -66,16 +65,17 @@ public class NavigationDrawerFragment extends InjectingFragment {
     
       @Override
       public void onActivityResult(int requestCode, int resultCode, Intent data) {
    -    if (requestCode == FilterAdapter.REQUEST_SETTINGS && resultCode == Activity.RESULT_OK
    +    if (requestCode == FilterAdapter.REQUEST_SETTINGS
    +        && resultCode == Activity.RESULT_OK
             && data != null) {
           if (data.getBooleanExtra(AppearancePreferences.EXTRA_RESTART, false)) {
             TaskListActivity activity = (TaskListActivity) getActivity();
             activity.restart();
           }
    -    } else if (requestCode == REQUEST_NEW_LIST ||
    -        requestCode == ACTIVITY_REQUEST_NEW_FILTER ||
    -        requestCode == REQUEST_NEW_GTASK_LIST ||
    -        requestCode == REQUEST_NEW_CALDAV_ACCOUNT) {
    +    } else if (requestCode == REQUEST_NEW_LIST
    +        || requestCode == ACTIVITY_REQUEST_NEW_FILTER
    +        || requestCode == REQUEST_NEW_GTASK_LIST
    +        || requestCode == REQUEST_NEW_CALDAV_ACCOUNT) {
           if (resultCode == RESULT_OK && data != null) {
             Filter newList = data.getParcelableExtra(TaskListActivity.OPEN_FILTER);
             if (newList != null) {
    @@ -88,24 +88,26 @@ public class NavigationDrawerFragment extends InjectingFragment {
       }
     
       @Override
    -  public View onCreateView(LayoutInflater inflater, ViewGroup container,
    -      Bundle savedInstanceState) {
    +  public View onCreateView(
    +      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
         View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
         if (atLeastLollipop()) {
           ((ScrimInsetsFrameLayout) layout.findViewById(R.id.scrim_layout))
               .setOnInsetsCallback(insets -> mDrawerListView.setPadding(0, insets.top, 0, 0));
         }
         mDrawerListView = layout.findViewById(android.R.id.list);
    -    mDrawerListView.setOnItemClickListener((parent, view, position, id) -> {
    -      mDrawerLayout.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
    -        @Override
    -        public void onDrawerClosed(View drawerView) {
    -          mDrawerLayout.removeDrawerListener(this);
    -          selectItem(position);
    -        }
    -      });
    -      close();
    -    });
    +    mDrawerListView.setOnItemClickListener(
    +        (parent, view, position, id) -> {
    +          mDrawerLayout.addDrawerListener(
    +              new DrawerLayout.SimpleDrawerListener() {
    +                @Override
    +                public void onDrawerClosed(View drawerView) {
    +                  mDrawerLayout.removeDrawerListener(this);
    +                  selectItem(position);
    +                }
    +              });
    +          close();
    +        });
     
         return layout;
       }
    diff --git a/app/src/main/java/org/tasks/ui/PriorityControlSet.java b/app/src/main/java/org/tasks/ui/PriorityControlSet.java
    index 3979681a6..7b00f22da 100644
    --- a/app/src/main/java/org/tasks/ui/PriorityControlSet.java
    +++ b/app/src/main/java/org/tasks/ui/PriorityControlSet.java
    @@ -24,10 +24,19 @@ public class PriorityControlSet extends TaskEditControlFragment {
       public static final int TAG = R.string.TEA_ctrl_importance_pref;
       private static final String EXTRA_PRIORITY = "extra_priority";
       @Inject CheckBoxes checkBoxes;
    -  @BindView(R.id.priority_high) AppCompatRadioButton priorityHigh;
    -  @BindView(R.id.priority_medium) AppCompatRadioButton priorityMedium;
    -  @BindView(R.id.priority_low) AppCompatRadioButton priorityLow;
    -  @BindView(R.id.priority_none) AppCompatRadioButton priorityNone;
    +
    +  @BindView(R.id.priority_high)
    +  AppCompatRadioButton priorityHigh;
    +
    +  @BindView(R.id.priority_medium)
    +  AppCompatRadioButton priorityMedium;
    +
    +  @BindView(R.id.priority_low)
    +  AppCompatRadioButton priorityLow;
    +
    +  @BindView(R.id.priority_none)
    +  AppCompatRadioButton priorityNone;
    +
       private OnPriorityChanged callback;
       private int priority;
     
    @@ -51,8 +60,8 @@ public class PriorityControlSet extends TaskEditControlFragment {
     
       @Nullable
       @Override
    -  public View onCreateView(LayoutInflater inflater, ViewGroup container,
    -      Bundle savedInstanceState) {
    +  public View onCreateView(
    +      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
         final View view = super.onCreateView(inflater, container, savedInstanceState);
         if (savedInstanceState == null) {
           priority = task.getImportance();
    @@ -111,9 +120,13 @@ public class PriorityControlSet extends TaskEditControlFragment {
     
       private void tintRadioButton(AppCompatRadioButton radioButton, int priority) {
         int color = checkBoxes.getPriorityColors().get(priority);
    -    CompoundButtonCompat.setButtonTintList(radioButton, new ColorStateList(new int[][]{
    -        new int[]{-android.R.attr.state_checked}, new int[]{android.R.attr.state_checked}},
    -        new int[]{color, color}));
    +    CompoundButtonCompat.setButtonTintList(
    +        radioButton,
    +        new ColorStateList(
    +            new int[][] {
    +              new int[] {-android.R.attr.state_checked}, new int[] {android.R.attr.state_checked}
    +            },
    +            new int[] {color, color}));
       }
     
       private int getPriority() {
    diff --git a/app/src/main/java/org/tasks/ui/RemoteListFragment.java b/app/src/main/java/org/tasks/ui/RemoteListFragment.java
    index f23697858..4053d5a36 100644
    --- a/app/src/main/java/org/tasks/ui/RemoteListFragment.java
    +++ b/app/src/main/java/org/tasks/ui/RemoteListFragment.java
    @@ -30,25 +30,26 @@ import org.tasks.preferences.DefaultFilterProvider;
     public class RemoteListFragment extends TaskEditControlFragment {
     
       public static final int TAG = R.string.TEA_ctrl_google_task_list;
    -  private static final String FRAG_TAG_GOOGLE_TASK_LIST_SELECTION = "frag_tag_google_task_list_selection";
    +  private static final String FRAG_TAG_GOOGLE_TASK_LIST_SELECTION =
    +      "frag_tag_google_task_list_selection";
       private static final String EXTRA_ORIGINAL_LIST = "extra_original_list";
       private static final String EXTRA_SELECTED_LIST = "extra_selected_list";
    -  @BindView(R.id.google_task_list) TextView textView;
    +
    +  @BindView(R.id.google_task_list)
    +  TextView textView;
     
       @Inject GtasksListService gtasksListService;
       @Inject GoogleTaskDao googleTaskDao;
       @Inject CaldavDao caldavDao;
       @Inject DefaultFilterProvider defaultFilterProvider;
     
    -  @Nullable
    -  private Filter originalList;
    -  @Nullable
    -  private Filter selectedList;
    +  @Nullable private Filter originalList;
    +  @Nullable private Filter selectedList;
     
       @Nullable
       @Override
    -  public View onCreateView(LayoutInflater inflater, ViewGroup container,
    -      Bundle savedInstanceState) {
    +  public View onCreateView(
    +      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
         View view = super.onCreateView(inflater, container, savedInstanceState);
         if (savedInstanceState != null) {
           originalList = savedInstanceState.getParcelable(EXTRA_ORIGINAL_LIST);
    @@ -56,8 +57,8 @@ public class RemoteListFragment extends TaskEditControlFragment {
         } else {
           if (task.isNew()) {
             if (task.hasTransitory(GoogleTask.KEY)) {
    -          originalList = new GtasksFilter(
    -              gtasksListService.getList(task.getTransitory(GoogleTask.KEY)));
    +          originalList =
    +              new GtasksFilter(gtasksListService.getList(task.getTransitory(GoogleTask.KEY)));
             } else if (task.hasTransitory(CaldavTask.KEY)) {
               originalList = new CaldavFilter(caldavDao.getByUuid(task.getTransitory(CaldavTask.KEY)));
             } else {
    @@ -116,13 +117,15 @@ public class RemoteListFragment extends TaskEditControlFragment {
       @Override
       public void apply(Task task) {
         GoogleTask googleTask = googleTaskDao.getByTaskId(task.getId());
    -    if (googleTask != null && selectedList instanceof GtasksFilter && googleTask.getListId()
    -        .equals(((GtasksFilter) selectedList).getRemoteId())) {
    +    if (googleTask != null
    +        && selectedList instanceof GtasksFilter
    +        && googleTask.getListId().equals(((GtasksFilter) selectedList).getRemoteId())) {
           return;
         }
         CaldavTask caldavTask = caldavDao.getTask(task.getId());
    -    if (caldavTask != null && selectedList instanceof CaldavFilter && caldavTask.getAccount()
    -        .equals(((CaldavFilter) selectedList).getUuid())) {
    +    if (caldavTask != null
    +        && selectedList instanceof CaldavFilter
    +        && caldavTask.getAccount().equals(((CaldavFilter) selectedList).getUuid())) {
           return;
         }
         task.putTransitory(SyncFlags.FORCE_SYNC, true);
    @@ -137,11 +140,12 @@ public class RemoteListFragment extends TaskEditControlFragment {
         }
     
         if (selectedList instanceof GtasksFilter) {
    -      googleTaskDao
    -          .insert(new GoogleTask(task.getId(), ((GtasksFilter) selectedList).getRemoteId()));
    +      googleTaskDao.insert(
    +          new GoogleTask(task.getId(), ((GtasksFilter) selectedList).getRemoteId()));
         } else if (selectedList instanceof CaldavFilter) {
    -      caldavDao.insert(new CaldavTask(task.getId(), ((CaldavFilter) selectedList).getUuid(),
    -          UUIDHelper.newUUID()));
    +      caldavDao.insert(
    +          new CaldavTask(
    +              task.getId(), ((CaldavFilter) selectedList).getUuid(), UUIDHelper.newUUID()));
         }
       }
     
    diff --git a/app/src/main/java/org/tasks/ui/ScrimInsetsFrameLayout.java b/app/src/main/java/org/tasks/ui/ScrimInsetsFrameLayout.java
    index 4de75d4d1..a764109ae 100644
    --- a/app/src/main/java/org/tasks/ui/ScrimInsetsFrameLayout.java
    +++ b/app/src/main/java/org/tasks/ui/ScrimInsetsFrameLayout.java
    @@ -53,8 +53,8 @@ public class ScrimInsetsFrameLayout extends FrameLayout {
       }
     
       private void init(Context context, AttributeSet attrs, int defStyle) {
    -    final TypedArray a = context.obtainStyledAttributes(attrs,
    -        R.styleable.ScrimInsetsFrameLayout, defStyle, 0);
    +    final TypedArray a =
    +        context.obtainStyledAttributes(attrs, R.styleable.ScrimInsetsFrameLayout, defStyle, 0);
         if (a == null) {
           return;
         }
    @@ -139,4 +139,4 @@ public class ScrimInsetsFrameLayout extends FrameLayout {
     
         void onInsetsChanged(Rect insets);
       }
    -}
    \ No newline at end of file
    +}
    diff --git a/app/src/main/java/org/tasks/ui/SingleCheckedArrayAdapter.java b/app/src/main/java/org/tasks/ui/SingleCheckedArrayAdapter.java
    index 5c1b98ac4..e883368d7 100644
    --- a/app/src/main/java/org/tasks/ui/SingleCheckedArrayAdapter.java
    +++ b/app/src/main/java/org/tasks/ui/SingleCheckedArrayAdapter.java
    @@ -23,14 +23,13 @@ import org.tasks.themes.ThemeAccent;
     
     public class SingleCheckedArrayAdapter extends ArrayAdapter {
     
    -  @NonNull
    -  private final Context context;
    +  @NonNull private final Context context;
       private final ThemeAccent accent;
       private final int alpha;
       private final int tint;
     
    -  public SingleCheckedArrayAdapter(@NonNull Context context, @NonNull List items,
    -      ThemeAccent accent) {
    +  public SingleCheckedArrayAdapter(
    +      @NonNull Context context, @NonNull List items, ThemeAccent accent) {
         super(context, R.layout.simple_list_item_single_choice_themed, items);
         this.context = context;
         this.accent = accent;
    @@ -43,11 +42,15 @@ public class SingleCheckedArrayAdapter extends ArrayAdapter {
       public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
         CheckedTextView view = (CheckedTextView) super.getView(position, convertView, parent);
         if (preLollipop()) {
    -      ColorStateList tintList = new ColorStateList(new int[][]{
    -          new int[]{-android.R.attr.state_checked}, new int[]{android.R.attr.state_checked}},
    -          new int[]{
    -              ResourcesCompat.getColor(context.getResources(), android.R.color.transparent, null),
    -              accent.getAccentColor()});
    +      ColorStateList tintList =
    +          new ColorStateList(
    +              new int[][] {
    +                new int[] {-android.R.attr.state_checked}, new int[] {android.R.attr.state_checked}
    +              },
    +              new int[] {
    +                ResourcesCompat.getColor(context.getResources(), android.R.color.transparent, null),
    +                accent.getAccentColor()
    +              });
           Drawable original = ContextCompat.getDrawable(context, R.drawable.ic_check_black_24dp);
           Drawable wrapped = DrawableCompat.wrap(original.mutate());
           DrawableCompat.setTintList(wrapped, tintList);
    diff --git a/app/src/main/java/org/tasks/ui/TaskEditControlFragment.java b/app/src/main/java/org/tasks/ui/TaskEditControlFragment.java
    index 1287613f3..69b5b5d80 100644
    --- a/app/src/main/java/org/tasks/ui/TaskEditControlFragment.java
    +++ b/app/src/main/java/org/tasks/ui/TaskEditControlFragment.java
    @@ -21,8 +21,8 @@ public abstract class TaskEditControlFragment extends InjectingFragment {
     
       @Nullable
       @Override
    -  public View onCreateView(LayoutInflater inflater, ViewGroup container,
    -      Bundle savedInstanceState) {
    +  public View onCreateView(
    +      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
         final View view = inflater.inflate(R.layout.control_set_template, null);
         LinearLayout content = view.findViewById(R.id.content);
         inflater.inflate(getLayout(), content);
    diff --git a/app/src/main/java/org/tasks/ui/TaskListViewModel.java b/app/src/main/java/org/tasks/ui/TaskListViewModel.java
    index d33dfb2d3..811469e1f 100644
    --- a/app/src/main/java/org/tasks/ui/TaskListViewModel.java
    +++ b/app/src/main/java/org/tasks/ui/TaskListViewModel.java
    @@ -48,43 +48,45 @@ public class TaskListViewModel extends ViewModel {
     
       private LiveData> getLiveData(Filter filter, Property[] properties) {
         return new LivePagedListBuilder<>(
    -        new LivePagedListProvider() {
    -          @Override
    -          protected LimitOffsetDataSource createDataSource() {
    -            latest = toDataSource(filter, properties);
    -            return latest;
    -          }
    -        }, 20)
    +            new LivePagedListProvider() {
    +              @Override
    +              protected LimitOffsetDataSource createDataSource() {
    +                latest = toDataSource(filter, properties);
    +                return latest;
    +              }
    +            },
    +            20)
             .build();
       }
     
       private LimitOffsetDataSource toDataSource(Filter filter, Property[] properties) {
    -    Criterion tagsJoinCriterion = Criterion.and(
    -        Task.ID.eq(Field.field(TAGS_METADATA_JOIN + ".task")));
    +    Criterion tagsJoinCriterion =
    +        Criterion.and(Task.ID.eq(Field.field(TAGS_METADATA_JOIN + ".task")));
     
         if (filter instanceof TagFilter) {
           String uuid = ((TagFilter) filter).getUuid();
    -      tagsJoinCriterion = Criterion
    -          .and(tagsJoinCriterion, Field.field(TAGS_METADATA_JOIN + ".tag_uid").neq(uuid));
    +      tagsJoinCriterion =
    +          Criterion.and(tagsJoinCriterion, Field.field(TAGS_METADATA_JOIN + ".tag_uid").neq(uuid));
         }
     
         // TODO: For now, we'll modify the query to join and include the things like tag data here.
    -    // Eventually, we might consider restructuring things so that this query is constructed elsewhere.
    +    // Eventually, we might consider restructuring things so that this query is constructed
    +    // elsewhere.
         String joinedQuery =
    -        Join.left(Tag.TABLE.as(TAGS_METADATA_JOIN),
    -            tagsJoinCriterion).toString() //$NON-NLS-1$
    -            + Join.left(TaskAttachment.TABLE.as(FILE_METADATA_JOIN),
    -            Task.UUID.eq(Field.field(FILE_METADATA_JOIN + ".task_id")))
    +        Join.left(Tag.TABLE.as(TAGS_METADATA_JOIN), tagsJoinCriterion).toString() // $NON-NLS-1$
    +            + Join.left(
    +                TaskAttachment.TABLE.as(FILE_METADATA_JOIN),
    +                Task.UUID.eq(Field.field(FILE_METADATA_JOIN + ".task_id")))
                 + filter.getSqlQuery();
     
    -    String query = SortHelper.adjustQueryForFlagsAndSort(
    -        preferences, joinedQuery, preferences.getSortMode());
    +    String query =
    +        SortHelper.adjustQueryForFlagsAndSort(preferences, joinedQuery, preferences.getSortMode());
     
         String groupedQuery;
         if (query.contains("GROUP BY")) {
           groupedQuery = query;
         } else if (query.contains("ORDER BY")) {
    -      groupedQuery = query.replace("ORDER BY", "GROUP BY " + Task.ID + " ORDER BY"); //$NON-NLS-1$
    +      groupedQuery = query.replace("ORDER BY", "GROUP BY " + Task.ID + " ORDER BY"); // $NON-NLS-1$
         } else {
           groupedQuery = query + " GROUP BY " + Task.ID;
         }
    diff --git a/app/src/main/java/org/tasks/ui/TimePreference.java b/app/src/main/java/org/tasks/ui/TimePreference.java
    index 34c4389fb..b1ec821de 100644
    --- a/app/src/main/java/org/tasks/ui/TimePreference.java
    +++ b/app/src/main/java/org/tasks/ui/TimePreference.java
    @@ -46,8 +46,8 @@ public class TimePreference extends Preference {
     
       private void setMillisOfDay(int millisOfDay) {
         this.millisOfDay = millisOfDay;
    -    String setting = DateUtilities
    -        .getTimeString(getContext(), new DateTime().withMillisOfDay(millisOfDay));
    +    String setting =
    +        DateUtilities.getTimeString(getContext(), new DateTime().withMillisOfDay(millisOfDay));
         setSummary(summary == null ? setting : String.format(summary, setting));
       }
     
    diff --git a/app/src/main/java/org/tasks/ui/WidgetCheckBoxes.java b/app/src/main/java/org/tasks/ui/WidgetCheckBoxes.java
    index 045b7a420..8cd58370e 100644
    --- a/app/src/main/java/org/tasks/ui/WidgetCheckBoxes.java
    +++ b/app/src/main/java/org/tasks/ui/WidgetCheckBoxes.java
    @@ -28,24 +28,30 @@ public class WidgetCheckBoxes {
       }
     
       private static List convertToBitmap(final List drawables) {
    -    return newArrayList(transform(drawables, drawable -> {
    -      if (drawable instanceof BitmapDrawable) {
    -        BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
    -        if (bitmapDrawable.getBitmap() != null) {
    -          return bitmapDrawable.getBitmap();
    -        }
    -      }
    -
    -      Bitmap bitmap = drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0
    -          ? Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888)
    -          : Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
    -              Bitmap.Config.ARGB_8888);
    -
    -      Canvas canvas = new Canvas(bitmap);
    -      drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    -      drawable.draw(canvas);
    -      return bitmap;
    -    }));
    +    return newArrayList(
    +        transform(
    +            drawables,
    +            drawable -> {
    +              if (drawable instanceof BitmapDrawable) {
    +                BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
    +                if (bitmapDrawable.getBitmap() != null) {
    +                  return bitmapDrawable.getBitmap();
    +                }
    +              }
    +
    +              Bitmap bitmap =
    +                  drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0
    +                      ? Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888)
    +                      : Bitmap.createBitmap(
    +                          drawable.getIntrinsicWidth(),
    +                          drawable.getIntrinsicHeight(),
    +                          Bitmap.Config.ARGB_8888);
    +
    +              Canvas canvas = new Canvas(bitmap);
    +              drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    +              drawable.draw(canvas);
    +              return bitmap;
    +            }));
       }
     
       public Bitmap getCompletedCheckbox(int importance) {
    diff --git a/app/src/main/java/org/tasks/widget/AppWidgetManager.java b/app/src/main/java/org/tasks/widget/AppWidgetManager.java
    index 306a56b06..7d72f1ff6 100644
    --- a/app/src/main/java/org/tasks/widget/AppWidgetManager.java
    +++ b/app/src/main/java/org/tasks/widget/AppWidgetManager.java
    @@ -18,8 +18,8 @@ public class AppWidgetManager {
       }
     
       public void updateWidgets() {
    -    int[] widgetIds = appWidgetManager
    -        .getAppWidgetIds(new ComponentName(context, TasksWidget.class));
    +    int[] widgetIds =
    +        appWidgetManager.getAppWidgetIds(new ComponentName(context, TasksWidget.class));
         appWidgetManager.notifyAppWidgetViewDataChanged(widgetIds, R.id.list_view);
       }
     }
    diff --git a/app/src/main/java/org/tasks/widget/ScrollableViewsFactory.java b/app/src/main/java/org/tasks/widget/ScrollableViewsFactory.java
    index 9b5cd45dd..57c78c04c 100644
    --- a/app/src/main/java/org/tasks/widget/ScrollableViewsFactory.java
    +++ b/app/src/main/java/org/tasks/widget/ScrollableViewsFactory.java
    @@ -151,8 +151,8 @@ class ScrollableViewsFactory implements RemoteViewsService.RemoteViewsFactory {
     
           if (task.isCompleted()) {
             textColorTitle = textColorSecondary;
    -        row.setInt(R.id.widget_text, "setPaintFlags",
    -            Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
    +        row.setInt(
    +            R.id.widget_text, "setPaintFlags", Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
           } else {
             row.setInt(R.id.widget_text, "setPaintFlags", Paint.ANTI_ALIAS_FLAG);
           }
    @@ -186,8 +186,8 @@ class ScrollableViewsFactory implements RemoteViewsService.RemoteViewsFactory {
           }
     
           if (atLeastJellybeanMR1()) {
    -        row.setInt(R.id.widget_row, "setLayoutDirection",
    -            Locale.getInstance(context).getDirectionality());
    +        row.setInt(
    +            R.id.widget_row, "setLayoutDirection", Locale.getInstance(context).getDirectionality());
           }
     
           return row;
    @@ -220,8 +220,9 @@ class ScrollableViewsFactory implements RemoteViewsService.RemoteViewsFactory {
           rv.setInt(R.id.widget, "setLayoutDirection", Locale.getInstance(context).getDirectionality());
         }
         appWidgetManager.partiallyUpdateAppWidget(widgetId, rv);
    -    String query = SortHelper.adjustQueryForFlagsAndSort(preferences, filter.getSqlQuery(), sort)
    -        .replaceAll("LIMIT \\d+", "");
    +    String query =
    +        SortHelper.adjustQueryForFlagsAndSort(preferences, filter.getSqlQuery(), sort)
    +            .replaceAll("LIMIT \\d+", "");
         return subtasksHelper.applySubtasksToWidgetFilter(filter, query);
       }
     
    @@ -229,12 +230,16 @@ class ScrollableViewsFactory implements RemoteViewsService.RemoteViewsFactory {
         if (task.hasDueDate()) {
           Resources resources = context.getResources();
           row.setViewVisibility(R.id.widget_due_date, View.VISIBLE);
    -      row.setTextViewText(R.id.widget_due_date, task.isCompleted()
    -          ? resources.getString(R.string.TAd_completed,
    -          DateUtilities.getRelativeDateStringWithTime(context, task.getCompletionDate()))
    -          : DateUtilities.getRelativeDateStringWithTime(context, task.getDueDate()));
    +      row.setTextViewText(
    +          R.id.widget_due_date,
    +          task.isCompleted()
    +              ? resources.getString(
    +                  R.string.TAd_completed,
    +                  DateUtilities.getRelativeDateStringWithTime(context, task.getCompletionDate()))
    +              : DateUtilities.getRelativeDateStringWithTime(context, task.getDueDate()));
           //noinspection ResourceAsColor
    -      row.setTextColor(R.id.widget_due_date,
    +      row.setTextColor(
    +          R.id.widget_due_date,
               task.isOverdue() ? getColor(context, R.color.overdue) : textColorSecondary);
           row.setFloat(R.id.widget_due_date, "setTextSize", dueDateTextSize);
         } else {
    diff --git a/app/src/main/java/org/tasks/widget/ScrollableWidgetUpdateService.java b/app/src/main/java/org/tasks/widget/ScrollableWidgetUpdateService.java
    index 79c8b7de2..fc7d6ff1b 100644
    --- a/app/src/main/java/org/tasks/widget/ScrollableWidgetUpdateService.java
    +++ b/app/src/main/java/org/tasks/widget/ScrollableWidgetUpdateService.java
    @@ -28,9 +28,7 @@ public class ScrollableWidgetUpdateService extends RemoteViewsService {
       public void onCreate() {
         super.onCreate();
     
    -    ((InjectingApplication) getApplication())
    -        .getComponent()
    -        .inject(this);
    +    ((InjectingApplication) getApplication()).getComponent().inject(this);
       }
     
       @Override
    @@ -52,8 +50,14 @@ public class ScrollableWidgetUpdateService extends RemoteViewsService {
         }
     
         int widgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID);
    -    return new ScrollableViewsFactory(subtasksHelper, preferences,
    +    return new ScrollableViewsFactory(
    +        subtasksHelper,
    +        preferences,
             locale.createConfigurationContext(getApplicationContext()),
    -        widgetId, taskDao, defaultFilterProvider, widgetCheckBoxes, themeCache);
    +        widgetId,
    +        taskDao,
    +        defaultFilterProvider,
    +        widgetCheckBoxes,
    +        themeCache);
       }
     }
    diff --git a/app/src/main/java/org/tasks/widget/ShortcutConfigActivity.java b/app/src/main/java/org/tasks/widget/ShortcutConfigActivity.java
    index a3333915f..928447e7e 100644
    --- a/app/src/main/java/org/tasks/widget/ShortcutConfigActivity.java
    +++ b/app/src/main/java/org/tasks/widget/ShortcutConfigActivity.java
    @@ -54,8 +54,10 @@ public class ShortcutConfigActivity extends InjectingAppCompatActivity {
             if (launcher instanceof BitmapDrawable) {
               intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, ((BitmapDrawable) launcher).getBitmap());
             } else if (atLeastOreo() && launcher instanceof AdaptiveIconDrawable) {
    -          Bitmap bitmap = Bitmap
    -              .createBitmap(launcher.getIntrinsicWidth(), launcher.getIntrinsicHeight(),
    +          Bitmap bitmap =
    +              Bitmap.createBitmap(
    +                  launcher.getIntrinsicWidth(),
    +                  launcher.getIntrinsicHeight(),
                       Bitmap.Config.ARGB_8888);
               Canvas canvas = new Canvas(bitmap);
               launcher.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    diff --git a/app/src/main/java/org/tasks/widget/TasksWidget.java b/app/src/main/java/org/tasks/widget/TasksWidget.java
    index 1035540c6..5454a8749 100644
    --- a/app/src/main/java/org/tasks/widget/TasksWidget.java
    +++ b/app/src/main/java/org/tasks/widget/TasksWidget.java
    @@ -38,7 +38,7 @@ public class TasksWidget extends InjectingAppWidgetProvider {
       public static final String COMPLETE_TASK = "COMPLETE_TASK";
       public static final String EDIT_TASK = "EDIT_TASK";
       public static final String EXTRA_FILTER_ID = "extra_filter_id";
    -  public static final String EXTRA_ID = "extra_id"; //$NON-NLS-1$
    +  public static final String EXTRA_ID = "extra_id"; // $NON-NLS-1$
       private static final int flags = FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TOP;
       @Inject Preferences preferences;
       @Inject DefaultFilterProvider defaultFilterProvider;
    @@ -48,7 +48,7 @@ public class TasksWidget extends InjectingAppWidgetProvider {
     
       private static Bitmap getSolidBackground(int bgColor) {
         Bitmap bitmap = Bitmap.createBitmap(2, 2, Bitmap.Config.ARGB_8888); // Create a Bitmap
    -    new Canvas(bitmap).drawColor(bgColor); //Set the color
    +    new Canvas(bitmap).drawColor(bgColor); // Set the color
         return bitmap;
       }
     
    @@ -113,9 +113,8 @@ public class TasksWidget extends InjectingAppWidgetProvider {
         }
         if (widgetPreferences.showHeader()) {
           remoteViews.setViewVisibility(R.id.widget_header, View.VISIBLE);
    -      remoteViews.setViewVisibility(R.id.widget_reconfigure, widgetPreferences.showSettings()
    -          ? View.VISIBLE
    -          : View.GONE);
    +      remoteViews.setViewVisibility(
    +          R.id.widget_reconfigure, widgetPreferences.showSettings() ? View.VISIBLE : View.GONE);
           remoteViews.setInt(R.id.widget_title, "setTextColor", color.getActionBarTint());
           remoteViews.setInt(R.id.widget_button, "setColorFilter", color.getActionBarTint());
           remoteViews.setInt(R.id.widget_reconfigure, "setColorFilter", color.getActionBarTint());
    @@ -124,10 +123,10 @@ public class TasksWidget extends InjectingAppWidgetProvider {
         }
         int opacityPercentage = widgetPreferences.getOpacity();
         int opacity = (int) ((opacityPercentage / 100.0) * 255.0);
    -    remoteViews.setImageViewBitmap(R.id.widget_background,
    -        getSolidBackground(theme.getBackgroundColor()));
    -    remoteViews.setImageViewBitmap(R.id.widget_header_background,
    -        getSolidBackground(color.getPrimaryColor()));
    +    remoteViews.setImageViewBitmap(
    +        R.id.widget_background, getSolidBackground(theme.getBackgroundColor()));
    +    remoteViews.setImageViewBitmap(
    +        R.id.widget_header_background, getSolidBackground(color.getPrimaryColor()));
         remoteViews.setInt(R.id.widget_background, "setAlpha", opacity);
         remoteViews.setInt(R.id.widget_header_background, "setAlpha", opacity);
     
    @@ -135,12 +134,12 @@ public class TasksWidget extends InjectingAppWidgetProvider {
         remoteViews.setTextViewText(R.id.widget_title, filter.listingTitle);
         remoteViews.setRemoteAdapter(R.id.list_view, rvIntent);
         remoteViews.setEmptyView(R.id.list_view, R.id.empty_view);
    -    remoteViews
    -        .setOnClickPendingIntent(R.id.widget_title, getOpenListIntent(context, filterId, id));
    -    remoteViews
    -        .setOnClickPendingIntent(R.id.widget_button, getNewTaskIntent(context, filterId, id));
    -    remoteViews
    -        .setOnClickPendingIntent(R.id.widget_reconfigure, getWidgetConfigIntent(context, id));
    +    remoteViews.setOnClickPendingIntent(
    +        R.id.widget_title, getOpenListIntent(context, filterId, id));
    +    remoteViews.setOnClickPendingIntent(
    +        R.id.widget_button, getNewTaskIntent(context, filterId, id));
    +    remoteViews.setOnClickPendingIntent(
    +        R.id.widget_reconfigure, getWidgetConfigIntent(context, id));
         remoteViews.setPendingIntentTemplate(R.id.list_view, getPendingIntentTemplate(context));
         return remoteViews;
       }
    diff --git a/app/src/main/java/org/tasks/widget/WidgetConfigActivity.java b/app/src/main/java/org/tasks/widget/WidgetConfigActivity.java
    index d0feb02ef..47a03acfd 100644
    --- a/app/src/main/java/org/tasks/widget/WidgetConfigActivity.java
    +++ b/app/src/main/java/org/tasks/widget/WidgetConfigActivity.java
    @@ -25,8 +25,8 @@ import org.tasks.themes.ThemeCache;
     import org.tasks.themes.ThemeColor;
     import org.tasks.themes.WidgetTheme;
     
    -public class WidgetConfigActivity extends InjectingPreferenceActivity implements
    -    SeekBarDialog.SeekBarCallback {
    +public class WidgetConfigActivity extends InjectingPreferenceActivity
    +    implements SeekBarDialog.SeekBarCallback {
     
       private static final String FRAG_TAG_OPACITY_SEEKBAR = "frag_tag_opacity_seekbar";
       private static final String FRAG_TAG_FONT_SIZE_SEEKBAR = "frag_tag_font_size_seekbar";
    @@ -54,8 +54,10 @@ public class WidgetConfigActivity extends InjectingPreferenceActivity implements
     
         addPreferencesFromResource(R.xml.preferences_widget);
     
    -    appWidgetId = getIntent()
    -        .getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
    +    appWidgetId =
    +        getIntent()
    +            .getIntExtra(
    +                AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
     
         // If they gave us an intent without the widget id, just bail.
         if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
    @@ -73,46 +75,66 @@ public class WidgetConfigActivity extends InjectingPreferenceActivity implements
         CheckBoxPreference showSettings = setupCheckbox(R.string.p_widget_show_settings);
         showSettings.setDependency(showHeader.getKey());
     
    -    findPreference(R.string.p_widget_filter).setOnPreferenceClickListener(preference -> {
    -      Intent intent = new Intent(WidgetConfigActivity.this, FilterSelectionActivity.class);
    -      intent.putExtra(FilterSelectionActivity.EXTRA_FILTER, getFilter());
    -      intent.putExtra(FilterSelectionActivity.EXTRA_RETURN_FILTER, true);
    -      startActivityForResult(intent, REQUEST_FILTER);
    -      return false;
    -    });
    -
    -    findPreference(R.string.p_widget_theme).setOnPreferenceClickListener(preference -> {
    -      Intent intent = new Intent(WidgetConfigActivity.this, ColorPickerActivity.class);
    -      intent.putExtra(ColorPickerActivity.EXTRA_PALETTE,
    -          ColorPickerActivity.ColorPalette.WIDGET_BACKGROUND);
    -      intent.putExtra(ColorPickerActivity.EXTRA_THEME_INDEX, widgetPreferences.getThemeIndex());
    -      startActivityForResult(intent, REQUEST_THEME_SELECTION);
    -      return false;
    -    });
    +    findPreference(R.string.p_widget_filter)
    +        .setOnPreferenceClickListener(
    +            preference -> {
    +              Intent intent = new Intent(WidgetConfigActivity.this, FilterSelectionActivity.class);
    +              intent.putExtra(FilterSelectionActivity.EXTRA_FILTER, getFilter());
    +              intent.putExtra(FilterSelectionActivity.EXTRA_RETURN_FILTER, true);
    +              startActivityForResult(intent, REQUEST_FILTER);
    +              return false;
    +            });
    +
    +    findPreference(R.string.p_widget_theme)
    +        .setOnPreferenceClickListener(
    +            preference -> {
    +              Intent intent = new Intent(WidgetConfigActivity.this, ColorPickerActivity.class);
    +              intent.putExtra(
    +                  ColorPickerActivity.EXTRA_PALETTE,
    +                  ColorPickerActivity.ColorPalette.WIDGET_BACKGROUND);
    +              intent.putExtra(
    +                  ColorPickerActivity.EXTRA_THEME_INDEX, widgetPreferences.getThemeIndex());
    +              startActivityForResult(intent, REQUEST_THEME_SELECTION);
    +              return false;
    +            });
     
         Preference colorPreference = findPreference(R.string.p_widget_color);
         colorPreference.setDependency(showHeader.getKey());
    -    colorPreference.setOnPreferenceClickListener(preference -> {
    -      Intent intent = new Intent(WidgetConfigActivity.this, ColorPickerActivity.class);
    -      intent.putExtra(ColorPickerActivity.EXTRA_PALETTE, ColorPickerActivity.ColorPalette.COLORS);
    -      intent.putExtra(ColorPickerActivity.EXTRA_THEME_INDEX, widgetPreferences.getColorIndex());
    -      startActivityForResult(intent, REQUEST_COLOR_SELECTION);
    -      return false;
    -    });
    -
    -    findPreference(R.string.p_widget_opacity).setOnPreferenceClickListener(preference -> {
    -      newSeekBarDialog(R.layout.dialog_opacity_seekbar, 0, 100, widgetPreferences.getOpacity(),
    -          REQUEST_OPACITY)
    -          .show(getFragmentManager(), FRAG_TAG_OPACITY_SEEKBAR);
    -      return false;
    -    });
    -
    -    findPreference(R.string.p_widget_font_size).setOnPreferenceClickListener(preference -> {
    -      newSeekBarDialog(R.layout.dialog_font_size_seekbar, 10, 22, widgetPreferences.getFontSize(),
    -          REQUEST_FONT_SIZE)
    -          .show(getFragmentManager(), FRAG_TAG_FONT_SIZE_SEEKBAR);
    -      return false;
    -    });
    +    colorPreference.setOnPreferenceClickListener(
    +        preference -> {
    +          Intent intent = new Intent(WidgetConfigActivity.this, ColorPickerActivity.class);
    +          intent.putExtra(
    +              ColorPickerActivity.EXTRA_PALETTE, ColorPickerActivity.ColorPalette.COLORS);
    +          intent.putExtra(ColorPickerActivity.EXTRA_THEME_INDEX, widgetPreferences.getColorIndex());
    +          startActivityForResult(intent, REQUEST_COLOR_SELECTION);
    +          return false;
    +        });
    +
    +    findPreference(R.string.p_widget_opacity)
    +        .setOnPreferenceClickListener(
    +            preference -> {
    +              newSeekBarDialog(
    +                      R.layout.dialog_opacity_seekbar,
    +                      0,
    +                      100,
    +                      widgetPreferences.getOpacity(),
    +                      REQUEST_OPACITY)
    +                  .show(getFragmentManager(), FRAG_TAG_OPACITY_SEEKBAR);
    +              return false;
    +            });
    +
    +    findPreference(R.string.p_widget_font_size)
    +        .setOnPreferenceClickListener(
    +            preference -> {
    +              newSeekBarDialog(
    +                      R.layout.dialog_font_size_seekbar,
    +                      10,
    +                      22,
    +                      widgetPreferences.getFontSize(),
    +                      REQUEST_FONT_SIZE)
    +                  .show(getFragmentManager(), FRAG_TAG_FONT_SIZE_SEEKBAR);
    +              return false;
    +            });
     
         updateFilter();
         updateOpacity();
    @@ -165,7 +187,7 @@ public class WidgetConfigActivity extends InjectingPreferenceActivity implements
         // force update after setting preferences
         Intent intent = new Intent(this, TasksWidget.class);
         intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
    -    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[]{appWidgetId});
    +    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] {appWidgetId});
         sendBroadcast(intent);
       }
     
    diff --git a/app/src/release/java/org/tasks/BaseApplication.java b/app/src/release/java/org/tasks/BaseApplication.java
    index 06c890c8a..b2f8d8cf4 100644
    --- a/app/src/release/java/org/tasks/BaseApplication.java
    +++ b/app/src/release/java/org/tasks/BaseApplication.java
    @@ -2,6 +2,4 @@ package org.tasks;
     
     import android.app.Application;
     
    -public abstract class BaseApplication extends Application {
    -
    -}
    +public abstract class BaseApplication extends Application {}
    diff --git a/app/src/release/java/org/tasks/BuildSetup.java b/app/src/release/java/org/tasks/BuildSetup.java
    index a4fc59e1a..56ec697d2 100644
    --- a/app/src/release/java/org/tasks/BuildSetup.java
    +++ b/app/src/release/java/org/tasks/BuildSetup.java
    @@ -7,9 +7,7 @@ import timber.log.Timber;
     public class BuildSetup {
     
       @Inject
    -  public BuildSetup() {
    -
    -  }
    +  public BuildSetup() {}
     
       public boolean setup() {
         Timber.plant(new ErrorReportingTree());