@Override public boolean onOptionsItemSelected(final MenuItem item) { long itemId; if (!isCurrentTaskListFragment()) { return false; } switch (item.getItemId()) { // --- context menu items case CONTEXT_MENU_EDIT_TASK_ID: itemId = item.getGroupId(); mListener.onTaskListItemClicked(itemId); return true; case CONTEXT_MENU_COPY_TASK_ID: itemId = item.getGroupId(); duplicateTask(itemId); return true; case CONTEXT_MENU_DELETE_TASK_ID: { itemId = item.getGroupId(); Task task = taskService.fetchById(itemId, Task.ID, Task.UUID); if (task != null) { deleteTask(task); } return true; } case CONTEXT_MENU_UNDELETE_TASK_ID: { itemId = item.getGroupId(); Task task = new Task(); task.setId(itemId); task.setDeletionDate(0L); taskService.save(task); loadTaskListContent(); return true; } case CONTEXT_MENU_PURGE_TASK_ID: { itemId = item.getGroupId(); Task task = new Task(); task.setId(itemId); TimerPlugin.updateTimer(notificationManager, taskService, getActivity(), task, false); taskDeleter.purge(itemId); loadTaskListContent(); return true; } default: return super.onOptionsItemSelected(item); } }
private synchronized void pushUpdated(GtasksInvoker invoker, SyncResultCallback callback) { TodorooCursor<Task> queued = taskService.query( Query.select(Task.PROPERTIES) .join( Join.left( Metadata.TABLE, Criterion.and( MetadataCriteria.withKey(GtasksMetadata.METADATA_KEY), Task.ID.eq(Metadata.TASK)))) .where( Criterion.or( Task.MODIFICATION_DATE.gt(GtasksMetadata.LAST_SYNC), Criterion.and( Task.USER_ID.neq(Task.USER_ID_SELF), GtasksMetadata.ID.isNotNull()), Metadata.KEY.isNull()))); callback.incrementMax(queued.getCount() * 10); try { Task task = new Task(); for (queued.moveToFirst(); !queued.isAfterLast(); queued.moveToNext()) { task.readFromCursor(queued); try { gtasksSyncService.pushTaskOnSave(task, task.getMergedValues(), invoker, false); } catch (GoogleTasksException e) { handler.handleException("gtasks-sync-io", e, e.getType()); // $NON-NLS-1$ } catch (IOException e) { handler.handleException("gtasks-sync-io", e, e.toString()); // $NON-NLS-1$ } finally { callback.incrementProgress(10); } } } finally { queued.close(); } }
private synchronized void synchronizeListHelper( StoreObject list, GtasksInvoker invoker, boolean manual, SyncExceptionHandler errorHandler, SyncResultCallback callback) { String listId = list.getValue(GtasksList.REMOTE_ID); long lastSyncDate; if (!manual && list.containsNonNullValue(GtasksList.LAST_SYNC)) { lastSyncDate = list.getValue(GtasksList.LAST_SYNC); } else { lastSyncDate = 0; } boolean includeDeletedAndHidden = lastSyncDate != 0; try { Tasks taskList = invoker.getAllGtasksFromListId( listId, includeDeletedAndHidden, includeDeletedAndHidden, lastSyncDate); List<com.google.api.services.tasks.model.Task> tasks = taskList.getItems(); if (tasks != null) { callback.incrementMax(tasks.size() * 10); HashSet<Long> localIds = new HashSet<Long>(tasks.size()); for (com.google.api.services.tasks.model.Task t : tasks) { GtasksTaskContainer container = parseRemoteTask(t, listId); gtasksMetadataService.findLocalMatch(container); container.gtaskMetadata.setValue( GtasksMetadata.GTASKS_ORDER, Long.parseLong(t.getPosition())); container.gtaskMetadata.setValue( GtasksMetadata.PARENT_TASK, gtasksMetadataService.localIdForGtasksId(t.getParent())); container.gtaskMetadata.setValue(GtasksMetadata.LAST_SYNC, DateUtilities.now() + 1000L); write(container); localIds.add(container.task.getId()); callback.incrementProgress(10); } list.setValue(GtasksList.LAST_SYNC, DateUtilities.now()); storeObjectDao.persist(list); if (lastSyncDate == 0) { Long[] localIdArray = localIds.toArray(new Long[localIds.size()]); Criterion delete = Criterion.and( Metadata.KEY.eq(GtasksMetadata.METADATA_KEY), GtasksMetadata.LIST_ID.eq(listId), Criterion.not(Metadata.TASK.in(localIdArray))); taskService.deleteWhere( Task.ID.in(Query.select(Metadata.TASK).from(Metadata.TABLE).where(delete))); metadataService.deleteWhere(delete); } gtasksTaskListUpdater.correctOrderAndIndentForList(listId); } } catch (GoogleTasksException e) { if (errorHandler != null) errorHandler.handleException("gtasks-sync-io", e, e.getType()); // $NON-NLS-1$ } catch (IOException e) { if (errorHandler != null) errorHandler.handleException("gtasks-sync-io", e, e.toString()); // $NON-NLS-1$ } }
@SuppressWarnings("nls") private TodorooCursor<Task> constructCursor() { String tagName = null; if (getActiveTagData() != null) tagName = getActiveTagData().getValue(TagData.NAME); String[] emergentTags = TagService.getInstance().getEmergentTags(); StringProperty tagProperty = new StringProperty(null, TAGS_METADATA_JOIN + "." + TagService.TAG.name); Criterion tagsJoinCriterion = Criterion.and( Field.field(TAGS_METADATA_JOIN + "." + Metadata.KEY.name) .eq(TagService.KEY), // $NON-NLS-1$ Task.ID.eq(Field.field(TAGS_METADATA_JOIN + "." + Metadata.TASK.name)), Criterion.not(tagProperty.in(emergentTags))); if (tagName != null) tagsJoinCriterion = Criterion.and( tagsJoinCriterion, Field.field(TAGS_METADATA_JOIN + "." + TagService.TAG.name).neq(tagName)); // TODO: For now, we'll modify the query to join and include the task rabbit and tag data here. // Eventually, we might consider restructuring things so that this query is constructed // elsewhere. String joinedQuery = Join.left( Metadata.TABLE.as(TR_METADATA_JOIN), Criterion.and( Field.field(TR_METADATA_JOIN + "." + Metadata.KEY.name) .eq(TaskRabbitMetadata.METADATA_KEY), // $NON-NLS-1$ Task.ID.eq(Field.field(TR_METADATA_JOIN + "." + Metadata.TASK.name)))) .toString() //$NON-NLS-1$ + Join.left(Metadata.TABLE.as(TAGS_METADATA_JOIN), tagsJoinCriterion) .toString() //$NON-NLS-1$ + filter.getSqlQuery(); sqlQueryTemplate.set(SortHelper.adjustQueryForFlagsAndSort(joinedQuery, sortFlags, sortSort)); String groupedQuery; if (sqlQueryTemplate.get().contains("GROUP BY")) groupedQuery = sqlQueryTemplate.get(); else if (sqlQueryTemplate.get().contains("ORDER BY")) // $NON-NLS-1$ groupedQuery = sqlQueryTemplate .get() .replace("ORDER BY", "GROUP BY " + Task.ID + " ORDER BY"); // $NON-NLS-1$ else groupedQuery = sqlQueryTemplate.get() + " GROUP BY " + Task.ID; sqlQueryTemplate.set(groupedQuery); // Peform query try { return taskService.fetchFiltered(sqlQueryTemplate.get(), null, taskProperties()); } catch (SQLiteException e) { // We don't show this error anymore--seems like this can get triggered // by a strange bug, but there seems to not be any negative side effect. // For now, we'll suppress the error // See http://astrid.com/home#tags-7tsoi/task-1119pk return null; } }
private TodorooCursor<Task> constructCursor() { String tagName = null; if (getActiveTagData() != null) { tagName = getActiveTagData().getName(); } Criterion tagsJoinCriterion = Criterion.and( Field.field(TAGS_METADATA_JOIN + "." + Metadata.KEY.name) .eq(TaskToTagMetadata.KEY), // $NON-NLS-1$ Field.field(TAGS_METADATA_JOIN + "." + Metadata.DELETION_DATE.name).eq(0), Task.ID.eq(Field.field(TAGS_METADATA_JOIN + "." + Metadata.TASK.name))); if (tagName != null) { tagsJoinCriterion = Criterion.and( tagsJoinCriterion, Field.field(TAGS_METADATA_JOIN + "." + TaskToTagMetadata.TAG_NAME.name).neq(tagName)); } // 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. String joinedQuery = Join.left(Metadata.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 + "." + TaskAttachment.TASK_UUID.name))) + filter.getSqlQuery(); sqlQueryTemplate.set(SortHelper.adjustQueryForFlagsAndSort(joinedQuery, sortFlags, sortSort)); String groupedQuery; if (sqlQueryTemplate.get().contains("GROUP BY")) { groupedQuery = sqlQueryTemplate.get(); } else if (sqlQueryTemplate.get().contains("ORDER BY")) // $NON-NLS-1$ { groupedQuery = sqlQueryTemplate .get() .replace("ORDER BY", "GROUP BY " + Task.ID + " ORDER BY"); // $NON-NLS-1$ } else { groupedQuery = sqlQueryTemplate.get() + " GROUP BY " + Task.ID; } sqlQueryTemplate.set(groupedQuery); // Peform query try { return taskService.fetchFiltered(sqlQueryTemplate.get(), null, taskProperties()); } catch (SQLiteException e) { // We don't show this error anymore--seems like this can get triggered // by a strange bug, but there seems to not be any negative side effect. // For now, we'll suppress the error // See http://astrid.com/home#tags-7tsoi/task-1119pk log.error(e.getMessage(), e); return null; } }
protected void duplicateTask(long itemId) { long cloneId = taskService.duplicateTask(itemId); Intent intent = new Intent(getActivity(), TaskEditActivity.class); intent.putExtra(TaskEditFragment.TOKEN_ID, cloneId); intent.putExtra(TOKEN_FILTER, filter); getActivity().startActivityForResult(intent, ACTIVITY_EDIT_TASK); transitionForTaskEdit(); }
private boolean shouldShowEula(Activity activity) { if (Preferences.getBoolean(PREFERENCE_EULA_ACCEPTED, false)) return false; SharedPreferences p = activity.getSharedPreferences("eula", Activity.MODE_PRIVATE); // $NON-NLS-1$ if (p.getBoolean(PREFERENCE_EULA_ACCEPTED, false)) return false; if (taskService.countTasks() > 0) return false; return true; }
/** Save task model from values in UI components */ private void save() { StringBuilder toast = new StringBuilder(); for (TaskEditControlSet controlSet : controls) { String toastText = controlSet.writeToModel(model); if (toastText != null) toast.append('\n').append(toastText); } if (title.getText().length() > 0) model.setValue(Task.DELETION_DATE, 0L); if (taskService.save(model) && title.getText().length() > 0) showSaveToast(toast.toString()); }
@Override public void finish() { super.finish(); // abandon editing and delete the newly created task if // no title was entered if (title.getText().length() == 0 && isNewTask && model.isSaved()) { taskService.delete(model); } }
protected void discardButtonClick() { shouldSaveState = false; // abandon editing in this case if (title.getText().length() == 0) { if (isNewTask) taskService.delete(model); } showCancelToast(); setResult(RESULT_CANCELED); finish(); }
private TodorooCursor<Task> getCursor() { String query = getQuery(context); return taskService.fetchFiltered( query, null, Task.ID, Task.TITLE, Task.DUE_DATE, Task.COMPLETION_DATE, Task.IMPORTANCE, Task.RECURRENCE); }
private void setCompletedForItemAndSubtasks(final Task item, final boolean completedState) { final long itemId = item.getId(); final Task model = new Task(); final long completionDate = completedState ? DateUtilities.now() : 0; if (!completedState) { ArrayList<Long> chained = chainedCompletions.get(itemId); if (chained != null) { for (Long taskId : chained) { model.setId(taskId); model.setValue(Task.COMPLETION_DATE, completionDate); taskService.save(model); model.clear(); taskAdapter.getCompletedItems().put(taskId, false); } taskAdapter.notifyDataSetInvalidated(); } return; } final ArrayList<Long> chained = new ArrayList<>(); final int parentIndent = item.getValue(updater.indentProperty()); updater.applyToChildren( list, itemId, new OrderedListNodeVisitor() { @Override public void visitNode(Node node) { Task childTask = taskService.fetchById(node.taskId, Task.RECURRENCE); if (!TextUtils.isEmpty(childTask.getValue(Task.RECURRENCE))) { Metadata metadata = updater.getTaskMetadata(node.taskId); metadata.setValue(updater.indentProperty(), parentIndent); metadataService.save(metadata); } model.setId(node.taskId); model.setValue(Task.COMPLETION_DATE, completionDate); taskService.save(model); model.clear(); taskAdapter.getCompletedItems().put(node.taskId, true); chained.add(node.taskId); } }); if (chained.size() > 0) { chainedCompletions.put(itemId, chained); taskAdapter.notifyDataSetInvalidated(); } }
public String getTaskEventUri(Task task) { String uri; if (!TextUtils.isEmpty(task.getCalendarURI())) { uri = task.getCalendarURI(); } else { task = taskService.fetchById(task.getId(), Task.CALENDAR_URI); if (task == null) { return null; } uri = task.getCalendarURI(); } return uri; }
@Override public void onReceive(Context context, Intent intent) { super.onReceive(context, intent); long taskId = intent.getLongExtra(AstridApiConstants.EXTRAS_TASK_ID, -1); if (taskId == -1) { return; } Task task = taskService.fetchById(taskId, Task.PROPERTIES); if (task == null || !task.isCompleted()) { return; } String recurrence = task.sanitizedRecurrence(); boolean repeatAfterCompletion = task.repeatAfterCompletion(); if (recurrence != null && recurrence.length() > 0) { long newDueDate; try { newDueDate = computeNextDueDate(task, recurrence, repeatAfterCompletion); if (newDueDate == -1) { return; } } catch (ParseException e) { log.error(e.getMessage(), e); return; } long oldDueDate = task.getDueDate(); long repeatUntil = task.getRepeatUntil(); if (repeatFinished(newDueDate, repeatUntil)) { return; } rescheduleTask(context, gcalHelper, taskService, task, newDueDate); // send a broadcast Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_EVENT_TASK_REPEATED); broadcastIntent.putExtra(AstridApiConstants.EXTRAS_TASK_ID, task.getId()); broadcastIntent.putExtra(AstridApiConstants.EXTRAS_OLD_DUE_DATE, oldDueDate); broadcastIntent.putExtra(AstridApiConstants.EXTRAS_NEW_DUE_DATE, newDueDate); context.sendOrderedBroadcast(broadcastIntent, null); Flags.set(Flags.REFRESH); } }
/** * Loads action item from the given intent * * @param intent */ @SuppressWarnings("nls") protected void loadItem(Intent intent) { if (model != null) { // came from bundle isNewTask = (model.getValue(Task.TITLE).length() == 0); return; } long idParam = intent.getLongExtra(TOKEN_ID, -1L); database.openForReading(); if (idParam > -1L) { model = taskService.fetchById(idParam, Task.PROPERTIES); } // not found by id or was never passed an id if (model == null) { String valuesAsString = intent.getStringExtra(TOKEN_VALUES); ContentValues values = null; try { if (valuesAsString != null) values = AndroidUtilities.contentValuesFromSerializedString(valuesAsString); } catch (Exception e) { // oops, can't serialize } model = TaskListActivity.createWithValues(values, null, taskService, metadataService); } if (model.getValue(Task.TITLE).length() == 0) { StatisticsService.reportEvent("create-task"); isNewTask = true; // set deletion date until task gets a title model.setValue(Task.DELETION_DATE, DateUtilities.now()); } else { StatisticsService.reportEvent("edit-task"); } if (model == null) { exceptionService.reportError("task-edit-no-task", new NullPointerException("model")); finish(); return; } // clear notification Notifications.cancelNotifications(model.getId()); }
@Override public void updatePreferences(final Preference preference, Object value) { final Resources r = getResources(); if (r.getString(R.string.p_showNotes).equals(preference.getKey())) { if (value != null && !(Boolean) value) preference.setSummary(R.string.EPr_showNotes_desc_disabled); else preference.setSummary(R.string.EPr_showNotes_desc_enabled); if ((Boolean) value != Preferences.getBoolean(preference.getKey(), false)) { taskService.clearDetails(Criterion.all); Flags.set(Flags.REFRESH); } } else if (r.getString(R.string.p_transparent).equals(preference.getKey())) { if (AndroidUtilities.getSdkVersion() < 5) { preference.setEnabled(false); preference.setSummary(R.string.EPr_transparent_desc_unsupported); } else if (value != null && !(Boolean) value) preference.setSummary(R.string.EPr_transparent_desc_disabled); else preference.setSummary(R.string.EPr_transparent_desc_enabled); } // statistics service else if (r.getString(R.string.p_statistics).equals(preference.getKey())) { if (value != null && !(Boolean) value) preference.setSummary(R.string.EPr_statistics_desc_disabled); else preference.setSummary(R.string.EPr_statistics_desc_enabled); } // voice input and output if (!addOnService.hasPowerPack()) return; if (r.getString(R.string.p_voiceInputEnabled).equals(preference.getKey())) { if (value != null && !(Boolean) value) preference.setSummary(R.string.EPr_voiceInputEnabled_desc_disabled); else preference.setSummary(R.string.EPr_voiceInputEnabled_desc_enabled); onVoiceInputStatusChanged(preference, (Boolean) value); } else if (r.getString(R.string.p_voiceRemindersEnabled).equals(preference.getKey())) { if (value != null && !(Boolean) value) preference.setSummary(R.string.EPr_voiceRemindersEnabled_desc_disabled); else preference.setSummary(R.string.EPr_voiceRemindersEnabled_desc_enabled); onVoiceReminderStatusChanged(preference, (Boolean) value); } else if (r.getString(R.string.p_voiceInputCreatesTask).equals(preference.getKey())) { if (value != null && !(Boolean) value) preference.setSummary(R.string.EPr_voiceInputCreatesTask_desc_disabled); else preference.setSummary(R.string.EPr_voiceInputCreatesTask_desc_enabled); } }
public static void rescheduleTask( Context context, GCalHelper gcalHelper, TaskService taskService, Task task, long newDueDate) { long hideUntil = task.getHideUntil(); if (hideUntil > 0 && task.getDueDate() > 0) { hideUntil += newDueDate - task.getDueDate(); } task.setReminderSnooze(0L); task.setCompletionDate(0L); task.setDueDate(newDueDate); task.setHideUntil(hideUntil); task.putTransitory(TaskService.TRANS_REPEAT_COMPLETE, true); ContentResolver cr = context.getContentResolver(); gcalHelper.rescheduleRepeatingTask(task, cr); taskService.save(task); }
/** * Cursor with the following columns * * <ol> * <li>task title, string * <li>task importance color, int android RGB color * <li>task due date (was: preferred due date), long millis since epoch * <li>task due date (was: absolute due date), long millis since epoch * <li>task importance, integer from 0 to 3 (0 => most important) * <li>task id, long * <li>task tags, string tags separated by | * </ol> * * @return cursor as described above */ public Cursor getTasks() { MatrixCursor ret = new MatrixCursor(TASK_FIELD_LIST); TodorooCursor<Task> cursor = taskService.query( Query.select(Task.ID, Task.TITLE, Task.IMPORTANCE, Task.DUE_DATE) .where(Criterion.and(TaskCriteria.isActive(), TaskCriteria.isVisible())) .orderBy(SortHelper.defaultTaskOrder()) .limit(MAX_NUMBER_OF_TASKS)); try { int[] importanceColors = Task.getImportanceColors(ctx.getResources()); Task task = new Task(); for (int i = 0; i < cursor.getCount(); i++) { cursor.moveToNext(); task.readFromCursor(cursor); StringBuilder taskTags = new StringBuilder(); TodorooCursor<Metadata> tagCursor = TagService.getInstance().getTags(task.getId()); try { for (tagCursor.moveToFirst(); !tagCursor.isAfterLast(); tagCursor.moveToNext()) taskTags.append(tagCursor.get(TagService.TAG)).append(TAG_SEPARATOR); } finally { tagCursor.close(); } Object[] values = new Object[7]; values[0] = task.getValue(Task.TITLE); values[1] = importanceColors[task.getValue(Task.IMPORTANCE)]; values[2] = task.getValue(Task.DUE_DATE); values[3] = task.getValue(Task.DUE_DATE); values[4] = task.getValue(Task.IMPORTANCE); values[5] = task.getId(); values[6] = taskTags.toString(); ret.addRow(values); } } finally { cursor.close(); } return ret; }
private void titleMatchWithActFm(Task task) { String title = task.getValue(Task.TITLE); TodorooCursor<Task> match = taskService.query( Query.select(Task.ID) .join( Join.left( Metadata.TABLE, Criterion.and( Metadata.KEY.eq(GtasksMetadata.METADATA_KEY), Metadata.TASK.eq(Task.ID)))) .where(Criterion.and(Task.TITLE.eq(title), GtasksMetadata.ID.isNull()))); try { if (match.getCount() > 0) { match.moveToFirst(); task.setId(match.get(Task.ID)); } } finally { match.close(); } }
private void serializeTasks() throws IOException { TodorooCursor<Task> cursor; cursor = taskService.query(Query.select(Task.PROPERTIES).orderBy(Order.asc(Task.ID))); try { int length = cursor.getCount(); for (int i = 0; i < length; i++) { cursor.moveToNext(); Task task = new Task(cursor); setProgress(i, length); xml.startTag(null, BackupConstants.TASK_TAG); serializeModel(task, Task.PROPERTIES, Task.ID); serializeMetadata(task); xml.endTag(null, BackupConstants.TASK_TAG); this.exportCount++; } } finally { cursor.close(); } }
public boolean deleteTaskEvent(Task task) { boolean eventDeleted = false; String uri; if (task.containsNonNullValue(Task.CALENDAR_URI)) { uri = task.getCalendarURI(); } else { task = taskService.fetchById(task.getId(), Task.CALENDAR_URI); if (task == null) { return false; } uri = task.getCalendarURI(); } if (!TextUtils.isEmpty(uri)) { try { Uri calendarUri = Uri.parse(uri); // try to load calendar ContentResolver cr = context.getContentResolver(); Cursor cursor = cr.query(calendarUri, new String[] {"dtstart"}, null, null, null); // $NON-NLS-1$ try { boolean alreadydeleted = cursor.getCount() == 0; if (!alreadydeleted) { cr.delete(calendarUri, null, null); eventDeleted = true; } } finally { cursor.close(); } task.setCalendarUri(""); } catch (Exception e) { log.error(e.getMessage(), e); } } return eventDeleted; }
@Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { if (LOGD) Log.d(TAG, "update"); switch (URI_MATCHER.match(uri)) { case URI_TASKS: Task task = new Task(); // map values if (values.containsKey(NAME)) task.setValue(Task.TITLE, values.getAsString(NAME)); if (values.containsKey(PREFERRED_DUE_DATE)) task.setValue(Task.DUE_DATE, values.getAsLong(PREFERRED_DUE_DATE)); if (values.containsKey(DEFINITE_DUE_DATE)) task.setValue(Task.DUE_DATE, values.getAsLong(DEFINITE_DUE_DATE)); if (values.containsKey(IMPORTANCE)) task.setValue(Task.IMPORTANCE, values.getAsInteger(IMPORTANCE)); if (values.containsKey(COMPLETED)) task.setValue( Task.COMPLETION_DATE, values.getAsBoolean(COMPLETED) ? DateUtilities.now() : 0); // map selection criteria String criteria = selection .replace(NAME, Task.TITLE.name) .replace(PREFERRED_DUE_DATE, Task.DUE_DATE.name) .replace(DEFINITE_DUE_DATE, Task.DUE_DATE.name) .replace(IDENTIFIER, Task.ID.name) .replace(ID, Task.ID.name) .replace(IMPORTANCE, Task.IMPORTANCE.name); return taskService.updateBySelection(criteria, selectionArgs, task); case URI_TAGS: throw new UnsupportedOperationException("tags updating: not yet"); default: throw new IllegalStateException("Unrecognized URI:" + uri); } }
/** * Select a custom task id in the list. If it doesn't exist, create a new custom filter * * @param withCustomId */ @SuppressWarnings("nls") public void selectCustomId(long withCustomId) { // if already in the list, select it TodorooCursor<Task> currentCursor = (TodorooCursor<Task>) taskAdapter.getCursor(); for (int i = 0; i < currentCursor.getCount(); i++) { currentCursor.moveToPosition(i); if (currentCursor.get(Task.ID) == withCustomId) { getListView().setSelection(i); return; } } // create a custom cursor if (!sqlQueryTemplate.get().contains("WHERE")) sqlQueryTemplate.set(sqlQueryTemplate.get() + " WHERE " + TaskCriteria.byId(withCustomId)); else sqlQueryTemplate.set( sqlQueryTemplate .get() .replace("WHERE ", "WHERE " + TaskCriteria.byId(withCustomId) + " OR ")); currentCursor = taskService.fetchFiltered(sqlQueryTemplate.get(), null, taskProperties()); getListView().setFilterText(""); taskAdapter.changeCursor(currentCursor); // update title if (getActivity() instanceof TaskListActivity) ((TaskListActivity) getActivity()).setListsTitle(getString(R.string.TLA_custom)); // try selecting again for (int i = 0; i < currentCursor.getCount(); i++) { currentCursor.moveToPosition(i); if (currentCursor.get(Task.ID) == withCustomId) { getListView().setSelection(i); break; } } }
private void verifyTreeModel(LIST list, Filter filter) { boolean changedThings = false; Set<String> keySet = idToNode.keySet(); Set<String> currentIds = new HashSet<>(); for (String id : keySet) { currentIds.add(id); } Set<String> idsInQuery = new HashSet<>(); String sql = filter.getSqlQuery().replaceAll("ORDER BY .*", ""); // $NON-NLS-1$//$NON-NLS-2$ sql = sql + String.format(" ORDER BY %s", Task.CREATION_DATE); // $NON-NLS-1$ TodorooCursor<Task> tasks = taskService.fetchFiltered(sql, null, Task.UUID); try { for (tasks.moveToFirst(); !tasks.isAfterLast(); tasks.moveToNext()) { String id = tasks.getString(0); idsInQuery.add(id); if (idToNode.containsKey(id)) { continue; } changedThings = true; Node newNode = new Node(id, treeRoot, 0); treeRoot.children.add(0, newNode); idToNode.put(id, newNode); } currentIds.removeAll(idsInQuery); if (currentIds.size() > 0) { removeNodes(currentIds); changedThings = true; } } finally { tasks.close(); } if (changedThings) { writeSerialization(list, serializeTree(), false); } }
/** * Fill in the Task List with current items * * @param withCustomId force task with given custom id to be part of list */ protected void setUpTaskList() { if (filter == null) return; // TODO: For now, we'll modify the query to join and include the task rabbit data here. // Eventually, we might consider restructuring things so that this query is constructed // elsewhere. String joinedTaskRabbitQuery = Join.left( Metadata.TABLE.as(TR_METADATA_JOIN), Criterion.and( Field.field(TR_METADATA_JOIN + "." + Metadata.KEY.name) .eq(TaskRabbitMetadata.METADATA_KEY), // $NON-NLS-1$ Task.ID.eq( Field.field(TR_METADATA_JOIN) + "." + Metadata.TASK.name))) // $NON-NLS-1$ + filter.getSqlQuery(); sqlQueryTemplate.set( SortHelper.adjustQueryForFlagsAndSort(joinedTaskRabbitQuery, sortFlags, sortSort)); // perform query TodorooCursor<Task> currentCursor; try { currentCursor = taskService.fetchFiltered(sqlQueryTemplate.get(), null, taskProperties()); } catch (SQLiteException e) { StartupService.handleSQLiteColumnMissing(getActivity(), e); return; } // set up list adapters taskAdapter = createTaskAdapter(currentCursor); setListAdapter(taskAdapter); getListView().setOnScrollListener(this); registerForContextMenu(getListView()); loadTaskListContent(true); }
/** * Called by the RefreshReceiver when the task list receives a refresh broadcast. Subclasses * should override this. */ protected void refresh() { if (taskAdapter != null) taskAdapter.flushCaches(); loadTaskListContent(true); taskService.cleanup(); }
/** * Save sharing settings * * @param toast toast to show after saving is finished * @return false if login is required & save should be halted */ @SuppressWarnings("nls") public boolean saveSharingSettings(String toast) { if (task == null) return false; saveToast = toast; boolean dirty = false; try { JSONObject userJson = null; TextView assignedView = null; if (assignedCustom.getVisibility() == View.VISIBLE) { userJson = PeopleContainer.createUserJson(assignedCustom); assignedView = assignedCustom; } else if (assignedSpinner.getSelectedItem() != null) { userJson = ((AssignedToUser) assignedSpinner.getSelectedItem()).user; } if (userJson != null && userJson.optString("email").indexOf('@') == -1) { throw new ParseSharedException( assignedView, activity.getString(R.string.actfm_EPA_invalid_email, userJson.optString("email"))); } if (userJson == null || userJson.optLong("id", -1) == 0) { dirty = task.getValue(Task.USER_ID) == 0L ? dirty : true; task.setValue(Task.USER_ID, 0L); if (!TextUtils.isEmpty(task.getValue(Task.USER))) task.setValue(Task.USER, "{}"); } else { String user = userJson.toString(); long taskUserId = -1; String taskUserEmail = ""; try { JSONObject taskUser = new JSONObject(task.getValue(Task.USER)); taskUserId = taskUser.optLong("id", -1); taskUserEmail = taskUser.optString("email"); } catch (JSONException e) { // sad times } long userId = userJson.optLong("id", -1); String userEmail = userJson.optString("email"); boolean match = (userId == taskUserId && userId != -1); match = match || (userEmail.equals(taskUserEmail) && !TextUtils.isEmpty(userEmail)); dirty = match ? dirty : true; task.setValue(Task.USER_ID, userJson.optLong("id", -1)); task.setValue(Task.USER, user); } JSONObject sharedWith = parseSharedWithAndTags(); dirty = dirty || sharedWith.has("p"); if (!TextUtils.isEmpty(task.getValue(Task.SHARED_WITH)) || sharedWith.length() != 0) task.setValue(Task.SHARED_WITH, sharedWith.toString()); if (dirty) taskService.save(task); if (dirty && !actFmPreferenceService.isLoggedIn()) { activity.startActivityForResult( new Intent(activity, ActFmLoginActivity.class), loginRequestCode); return false; } if (dirty) shareTask(sharedWith); else showSaveToast(); return true; } catch (JSONException e) { exceptionService.displayAndReportError(activity, "save-people", e); } catch (ParseSharedException e) { if (e.view != null) { e.view.setTextColor(Color.RED); e.view.requestFocus(); } DialogUtilities.okDialog(activity, e.message, null); } return false; }
@Override public void updatePreferences(final Preference preference, Object value) { final Resources r = getResources(); if (r.getString(R.string.p_showNotes).equals(preference.getKey())) { if (value != null && !(Boolean) value) preference.setSummary(R.string.EPr_showNotes_desc_disabled); else preference.setSummary(R.string.EPr_showNotes_desc_enabled); if ((Boolean) value != Preferences.getBoolean(preference.getKey(), false)) { taskService.clearDetails(Criterion.all); Flags.set(Flags.REFRESH); } } else if (r.getString(R.string.p_fullTaskTitle).equals(preference.getKey())) { if (value != null && (Boolean) value) preference.setSummary(R.string.EPr_fullTask_desc_enabled); else preference.setSummary(R.string.EPr_fullTask_desc_disabled); } else if (r.getString(R.string.p_theme).equals(preference.getKey())) { if (AndroidUtilities.getSdkVersion() < 5) { preference.setEnabled(false); preference.setSummary(R.string.EPr_theme_desc_unsupported); } else { int index = 0; if (value instanceof String && !TextUtils.isEmpty((String) value)) index = AndroidUtilities.indexOf( r.getStringArray(R.array.EPr_theme_settings), (String) value); if (index < 0) index = 0; preference.setSummary( getString(R.string.EPr_theme_desc, r.getStringArray(R.array.EPr_themes)[index])); } } else if (r.getString(R.string.p_theme_widget).equals(preference.getKey())) { if (AndroidUtilities.getSdkVersion() < 5) { preference.setEnabled(false); preference.setSummary(R.string.EPr_theme_desc_unsupported); } else { int index = 0; if (value instanceof String && !TextUtils.isEmpty((String) value)) index = AndroidUtilities.indexOf( r.getStringArray(R.array.EPr_theme_widget_settings), (String) value); if (index < 0) index = 0; preference.setSummary( getString(R.string.EPr_theme_desc, r.getStringArray(R.array.EPr_themes_widget)[index])); } } // pp preferences else if (booleanPreference( preference, value, R.string.p_statistics, R.string.EPr_statistics_desc_disabled, R.string.EPr_statistics_desc_enabled)) ; else if (booleanPreference( preference, value, R.string.p_autoIdea, R.string.EPr_ideaAuto_desc_disabled, R.string.EPr_ideaAuto_desc_enabled)) ; // voice input and output if (!addOnService.hasPowerPack()) return; if (r.getString(R.string.p_voiceInputEnabled).equals(preference.getKey())) { if (value != null && !(Boolean) value) preference.setSummary(R.string.EPr_voiceInputEnabled_desc_disabled); else preference.setSummary(R.string.EPr_voiceInputEnabled_desc_enabled); onVoiceInputStatusChanged(preference, (Boolean) value); } else if (r.getString(R.string.p_voiceRemindersEnabled).equals(preference.getKey())) { if (value != null && !(Boolean) value) preference.setSummary(R.string.EPr_voiceRemindersEnabled_desc_disabled); else preference.setSummary(R.string.EPr_voiceRemindersEnabled_desc_enabled); onVoiceReminderStatusChanged(preference, (Boolean) value); } else if (r.getString(R.string.p_voiceInputCreatesTask).equals(preference.getKey())) { if (value != null && !(Boolean) value) preference.setSummary(R.string.EPr_voiceInputCreatesTask_desc_disabled); else preference.setSummary(R.string.EPr_voiceInputCreatesTask_desc_enabled); } }
/** * Synchronize complete task with server * * @param task */ public void pushTask(long taskId) { Task task = taskService.fetchById(taskId, Task.PROPERTIES); pushTaskOnSave(task, task.getMergedValues()); }
/** Synchronize with server when data changes */ public void pushTaskOnSave(Task task, ContentValues values) { long remoteId; if (task.containsValue(Task.REMOTE_ID)) remoteId = task.getValue(Task.REMOTE_ID); else { Task taskForRemote = taskService.fetchById(task.getId(), Task.REMOTE_ID); if (taskForRemote == null) return; remoteId = taskForRemote.getValue(Task.REMOTE_ID); } boolean newlyCreated = remoteId == 0; ArrayList<Object> params = new ArrayList<Object>(); if (values.containsKey(Task.TITLE.name)) { params.add("title"); params.add(task.getValue(Task.TITLE)); } if (values.containsKey(Task.DUE_DATE.name)) { params.add("due"); params.add(task.getValue(Task.DUE_DATE) / 1000L); params.add("has_due_time"); params.add(task.hasDueTime() ? 1 : 0); } if (values.containsKey(Task.NOTES.name)) { params.add("notes"); params.add(task.getValue(Task.NOTES)); } if (values.containsKey(Task.DELETION_DATE.name)) { params.add("deleted_at"); params.add(task.getValue(Task.DELETION_DATE) / 1000L); } if (values.containsKey(Task.COMPLETION_DATE.name)) { params.add("completed"); params.add(task.getValue(Task.COMPLETION_DATE) / 1000L); } if (values.containsKey(Task.IMPORTANCE.name)) { params.add("importance"); params.add(task.getValue(Task.IMPORTANCE)); } if (values.containsKey(Task.RECURRENCE.name)) { params.add("repeat"); params.add(task.getValue(Task.RECURRENCE)); } if (values.containsKey(Task.USER_ID.name) && task.getValue(Task.USER_ID) >= 0) { params.add("user_id"); if (task.getValue(Task.USER_ID) == 0) params.add(ActFmPreferenceService.userId()); else params.add(task.getValue(Task.USER_ID)); } if (Flags.checkAndClear(Flags.TAGS_CHANGED) || newlyCreated) { TodorooCursor<Metadata> cursor = TagService.getInstance().getTags(task.getId()); try { if (cursor.getCount() == 0) { params.add("tags"); params.add(""); } else { Metadata metadata = new Metadata(); for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { metadata.readFromCursor(cursor); if (metadata.containsNonNullValue(TagService.REMOTE_ID) && metadata.getValue(TagService.REMOTE_ID) > 0) { params.add("tag_ids[]"); params.add(metadata.getValue(TagService.REMOTE_ID)); } else { params.add("tags[]"); params.add(metadata.getValue(TagService.TAG)); } } } } finally { cursor.close(); } } if (params.size() == 0 || !checkForToken()) return; System.err.println("PUSHN ON SAVE: " + task.getMergedValues()); System.err.println("SETVALUES: " + values); if (!newlyCreated) { params.add("id"); params.add(remoteId); } else if (!params.contains(Task.TITLE.name)) return; try { params.add("token"); params.add(token); JSONObject result = actFmInvoker.invoke("task_save", params.toArray(new Object[params.size()])); ArrayList<Metadata> metadata = new ArrayList<Metadata>(); JsonHelper.taskFromJson(result, task, metadata); task.setValue(Task.MODIFICATION_DATE, DateUtilities.now()); task.setValue(Task.LAST_SYNC, DateUtilities.now()); Flags.set(Flags.SUPPRESS_SYNC); taskDao.saveExisting(task); } catch (JSONException e) { handleException("task-save-json", e); } catch (IOException e) { handleException("task-save-io", e); } }