diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml index 5bec54801..d906e2642 100644 --- a/.idea/inspectionProfiles/Project_Default.xml +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -2,14 +2,22 @@ \ No newline at end of file diff --git a/.idea/scopes/Astrid.xml b/.idea/scopes/Astrid.xml index d6058e323..cf1e37295 100644 --- a/.idea/scopes/Astrid.xml +++ b/.idea/scopes/Astrid.xml @@ -1,3 +1,3 @@ - + \ No newline at end of file diff --git a/api/src/com/todoroo/andlib/data/AbstractDatabase.java b/api/src/com/todoroo/andlib/data/AbstractDatabase.java index 2ff93f9d7..d20f7a799 100644 --- a/api/src/com/todoroo/andlib/data/AbstractDatabase.java +++ b/api/src/com/todoroo/andlib/data/AbstractDatabase.java @@ -127,8 +127,9 @@ abstract public class AbstractDatabase { */ public final Table getTable(Class modelType) { for (Table table : getTables()) { - if (table.modelClass.equals(modelType)) + if (table.modelClass.equals(modelType)) { return table; + } } throw new UnsupportedOperationException("Unknown model class " + modelType); //$NON-NLS-1$ } @@ -151,8 +152,9 @@ abstract public class AbstractDatabase { protected synchronized final void initializeHelper() { if (helper == null) { - if (ContextManager.getContext() == null) + if (ContextManager.getContext() == null) { throw new NullPointerException("Null context creating database helper"); + } helper = new DatabaseHelper(ContextManager.getContext(), getName(), null, getVersion()); } @@ -165,8 +167,9 @@ abstract public class AbstractDatabase { public synchronized final void openForWriting() { initializeHelper(); - if (database != null && !database.isReadOnly() && database.isOpen()) + if (database != null && !database.isReadOnly() && database.isOpen()) { return; + } try { database = helper.getWritableDatabase(); @@ -193,8 +196,9 @@ abstract public class AbstractDatabase { */ public synchronized final void openForReading() { initializeHelper(); - if (database != null && database.isOpen()) + if (database != null && database.isOpen()) { return; + } database = helper.getReadableDatabase(); } @@ -305,8 +309,9 @@ abstract public class AbstractDatabase { sql.append("CREATE TABLE IF NOT EXISTS ").append(table.name).append('('). append(AbstractModel.ID_PROPERTY).append(" INTEGER PRIMARY KEY AUTOINCREMENT"); for (Property property : table.getProperties()) { - if (AbstractModel.ID_PROPERTY.name.equals(property.name)) + if (AbstractModel.ID_PROPERTY.name.equals(property.name)) { continue; + } sql.append(',').append(property.accept(sqlVisitor, null)); } sql.append(')'); diff --git a/api/src/com/todoroo/andlib/data/AbstractModel.java b/api/src/com/todoroo/andlib/data/AbstractModel.java index 1bfa6bccc..8775e7551 100644 --- a/api/src/com/todoroo/andlib/data/AbstractModel.java +++ b/api/src/com/todoroo/andlib/data/AbstractModel.java @@ -113,12 +113,15 @@ public abstract class AbstractModel implements Parcelable, Cloneable { ContentValues mergedValues = new ContentValues(); ContentValues defaultValues = getDefaultValues(); - if (defaultValues != null) + if (defaultValues != null) { mergedValues.putAll(defaultValues); - if (values != null) + } + if (values != null) { mergedValues.putAll(values); - if (setValues != null) + } + if (setValues != null) { mergedValues.putAll(setValues); + } return mergedValues; } @@ -136,10 +139,11 @@ public abstract class AbstractModel implements Parcelable, Cloneable { * saved - future saves will not need to write all the data as before. */ public void markSaved() { - if (values == null) + if (values == null) { values = setValues; - else if (setValues != null) + } else if (setValues != null) { values.putAll(setValues); + } setValues = null; } @@ -149,8 +153,9 @@ public abstract class AbstractModel implements Parcelable, Cloneable { */ @Override public boolean equals(Object other) { - if (other == null || other.getClass() != getClass()) + if (other == null || other.getClass() != getClass()) { return false; + } return getMergedValues().equals(((AbstractModel) other).getMergedValues()); } @@ -180,10 +185,12 @@ public abstract class AbstractModel implements Parcelable, Cloneable { } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } - if (setValues != null) + if (setValues != null) { clone.setValues = new ContentValues(setValues); - if (values != null) + } + if (values != null) { clone.values = new ContentValues(values); + } return clone; } @@ -200,8 +207,9 @@ public abstract class AbstractModel implements Parcelable, Cloneable { * Reads all properties from the supplied cursor and store */ public synchronized void readPropertiesFromCursor(TodorooCursor cursor) { - if (values == null) + if (values == null) { values = new ContentValues(); + } // clears user-set values setValues = null; @@ -221,29 +229,28 @@ public abstract class AbstractModel implements Parcelable, Cloneable { */ public synchronized TYPE getValue(Property property) { Object value; - if (setValues != null && setValues.containsKey(property.getColumnName())) + if (setValues != null && setValues.containsKey(property.getColumnName())) { value = setValues.get(property.getColumnName()); - - else if (values != null && values.containsKey(property.getColumnName())) + } else if (values != null && values.containsKey(property.getColumnName())) { value = values.get(property.getColumnName()); - - else if (getDefaultValues().containsKey(property.getColumnName())) + } else if (getDefaultValues().containsKey(property.getColumnName())) { value = getDefaultValues().get(property.getColumnName()); - - else + } else { throw new UnsupportedOperationException( "Model Error: Did not read property " + property.name); //$NON-NLS-1$ + } // resolve properties that were retrieved with a different type than accessed try { - if (value instanceof String && property instanceof LongProperty) + if (value instanceof String && property instanceof LongProperty) { return (TYPE) Long.valueOf((String) value); - else if (value instanceof String && property instanceof IntegerProperty) + } else if (value instanceof String && property instanceof IntegerProperty) { return (TYPE) Integer.valueOf((String) value); - else if (value instanceof String && property instanceof DoubleProperty) + } else if (value instanceof String && property instanceof DoubleProperty) { return (TYPE) Double.valueOf((String) value); - else if (value instanceof Integer && property instanceof LongProperty) + } else if (value instanceof Integer && property instanceof LongProperty) { return (TYPE) Long.valueOf(((Number) value).longValue()); + } return (TYPE) value; } catch (NumberFormatException e) { return (TYPE) getDefaultValues().get(property.name); @@ -258,22 +265,25 @@ public abstract class AbstractModel implements Parcelable, Cloneable { abstract public long getId(); protected long getIdHelper(LongProperty id) { - if (setValues != null && setValues.containsKey(id.name)) + if (setValues != null && setValues.containsKey(id.name)) { return setValues.getAsLong(id.name); - else if (values != null && values.containsKey(id.name)) + } else if (values != null && values.containsKey(id.name)) { return values.getAsLong(id.name); - else + } else { return NO_ID; + } } public void setId(long id) { - if (setValues == null) + if (setValues == null) { setValues = new ContentValues(); + } - if (id == NO_ID) + if (id == NO_ID) { clearValue(ID_PROPERTY); - else + } else { setValues.put(ID_PROPERTY_NAME, id); + } } /** @@ -288,10 +298,12 @@ public abstract class AbstractModel implements Parcelable, Cloneable { * @return true if setValues or values contains this property */ public boolean containsValue(Property property) { - if (setValues != null && setValues.containsKey(property.getColumnName())) + if (setValues != null && setValues.containsKey(property.getColumnName())) { return true; - if (values != null && values.containsKey(property.getColumnName())) + } + if (values != null && values.containsKey(property.getColumnName())) { return true; + } return false; } @@ -301,10 +313,12 @@ public abstract class AbstractModel implements Parcelable, Cloneable { * stored is not null */ public boolean containsNonNullValue(Property property) { - if (setValues != null && setValues.containsKey(property.getColumnName())) + if (setValues != null && setValues.containsKey(property.getColumnName())) { return setValues.get(property.getColumnName()) != null; - if (values != null && values.containsKey(property.getColumnName())) + } + if (values != null && values.containsKey(property.getColumnName())) { return values.get(property.getColumnName()) != null; + } return false; } @@ -318,17 +332,20 @@ public abstract class AbstractModel implements Parcelable, Cloneable { Property property, TYPE newValue) { // we've already decided to save it, so overwrite old value - if (setValues.containsKey(property.getColumnName())) + if (setValues.containsKey(property.getColumnName())) { return true; + } // values contains this key, we should check it out if (values != null && values.containsKey(property.getColumnName())) { TYPE value = getValue(property); if (value == null) { - if (newValue == null) + if (newValue == null) { return false; - } else if (value.equals(newValue)) + } + } else if (value.equals(newValue)) { return false; + } } // otherwise, good to save @@ -340,10 +357,12 @@ public abstract class AbstractModel implements Parcelable, Cloneable { */ public synchronized void setValue(Property property, TYPE value) { - if (setValues == null) + if (setValues == null) { setValues = new ContentValues(); - if (!shouldSaveValue(property, value)) + } + if (!shouldSaveValue(property, value)) { return; + } saver.save(property, setValues, value); } @@ -352,8 +371,9 @@ public abstract class AbstractModel implements Parcelable, Cloneable { * Merges content values with those coming from another source */ public synchronized void mergeWith(ContentValues other) { - if (setValues == null) + if (setValues == null) { setValues = new ContentValues(); + } setValues.putAll(other); } @@ -362,11 +382,13 @@ public abstract class AbstractModel implements Parcelable, Cloneable { * keeping the existing value if one already exists */ public synchronized void mergeWithoutReplacement(ContentValues other) { - if (setValues == null) + if (setValues == null) { setValues = new ContentValues(); + } for (Entry item : other.valueSet()) { - if (setValues.containsKey(item.getKey())) + if (setValues.containsKey(item.getKey())) { continue; + } AndroidUtilities.putInto(setValues, item.getKey(), item.getValue(), true); } } @@ -377,10 +399,12 @@ public abstract class AbstractModel implements Parcelable, Cloneable { * @param property */ public synchronized void clearValue(Property property) { - if (setValues != null && setValues.containsKey(property.getColumnName())) + if (setValues != null && setValues.containsKey(property.getColumnName())) { setValues.remove(property.getColumnName()); - if (values != null && values.containsKey(property.getColumnName())) + } + if (values != null && values.containsKey(property.getColumnName())) { values.remove(property.getColumnName()); + } } /** @@ -391,10 +415,11 @@ public abstract class AbstractModel implements Parcelable, Cloneable { * @param value */ public void setFlag(IntegerProperty property, int flag, boolean value) { - if (value) + if (value) { setValue(property, getValue(property) | flag); - else + } else { setValue(property, getValue(property) & ~flag); + } } /** @@ -412,26 +437,30 @@ public abstract class AbstractModel implements Parcelable, Cloneable { // --- setting and retrieving flags public synchronized void putTransitory(String key, Object value) { - if (transitoryData == null) + if (transitoryData == null) { transitoryData = new HashMap(); + } transitoryData.put(key, value); } public Object getTransitory(String key) { - if (transitoryData == null) + if (transitoryData == null) { return null; + } return transitoryData.get(key); } public Object clearTransitory(String key) { - if (transitoryData == null) + if (transitoryData == null) { return null; + } return transitoryData.remove(key); } public Set getAllTransitoryKeys() { - if (transitoryData == null) + if (transitoryData == null) { return null; + } return transitoryData.keySet(); } @@ -453,19 +482,23 @@ public abstract class AbstractModel implements Parcelable, Cloneable { */ protected static Property[] generateProperties(Class cls) { ArrayList> properties = new ArrayList>(); - if (cls.getSuperclass() != AbstractModel.class) + if (cls.getSuperclass() != AbstractModel.class) { properties.addAll(Arrays.asList(generateProperties( (Class) cls.getSuperclass()))); + } // a property is public, static & extends Property for (Field field : cls.getFields()) { - if ((field.getModifiers() & Modifier.STATIC) == 0) + if ((field.getModifiers() & Modifier.STATIC) == 0) { continue; - if (!Property.class.isAssignableFrom(field.getType())) + } + if (!Property.class.isAssignableFrom(field.getType())) { continue; + } try { - if (((Property) field.get(null)).table == null) + if (((Property) field.get(null)).table == null) { continue; + } properties.add((Property) field.get(null)); } catch (IllegalArgumentException e) { throw new RuntimeException(e); @@ -492,8 +525,9 @@ public abstract class AbstractModel implements Parcelable, Cloneable { // we don't allow null values, as they indicate unset properties // when the database was written - if (value != null) + if (value != null) { property.accept(this, value); + } } public Void visitDouble(Property property, Object value) { diff --git a/api/src/com/todoroo/andlib/data/ContentResolverDao.java b/api/src/com/todoroo/andlib/data/ContentResolverDao.java index df804bc2a..bbc4bbde8 100644 --- a/api/src/com/todoroo/andlib/data/ContentResolverDao.java +++ b/api/src/com/todoroo/andlib/data/ContentResolverDao.java @@ -52,8 +52,9 @@ public class ContentResolverDao { public ContentResolverDao(Class modelClass, Context context, Uri baseUri) { DependencyInjectionService.getInstance().inject(this); this.modelClass = modelClass; - if (debug == null) + if (debug == null) { debug = false; + } this.baseUri = baseUri; cr = context.getContentResolver(); @@ -96,8 +97,9 @@ public class ContentResolverDao { * @return */ public TodorooCursor query(Query query) { - if (debug) + if (debug) { Log.i("SQL-" + modelClass.getSimpleName(), query.toString()); //$NON-NLS-1$ + } Cursor cursor = query.queryContentResolver(cr, baseUri); return new TodorooCursor(cursor, query.getFields()); } @@ -111,10 +113,12 @@ public class ContentResolverDao { public boolean save(TYPE model) { writeTransitoriesToModelContentValues(model); if (model.isSaved()) { - if (model.getSetValues() == null) + if (model.getSetValues() == null) { return false; - if (cr.update(uriWithId(model.getId()), model.getSetValues(), null, null) != 0) + } + if (cr.update(uriWithId(model.getId()), model.getSetValues(), null, null) != 0) { return true; + } } Uri uri = cr.insert(baseUri, model.getMergedValues()); long id = Long.parseLong(uri.getLastPathSegment()); @@ -149,8 +153,9 @@ public class ContentResolverDao { TodorooCursor cursor = query( Query.select(properties).where(AbstractModel.ID_PROPERTY.eq(id))); try { - if (cursor.getCount() == 0) + if (cursor.getCount() == 0) { return null; + } cursor.moveToFirst(); Constructor constructor = modelClass.getConstructor(TodorooCursor.class); return constructor.newInstance(cursor); diff --git a/api/src/com/todoroo/andlib/data/DatabaseDao.java b/api/src/com/todoroo/andlib/data/DatabaseDao.java index 49a6d93a5..25b252ac3 100644 --- a/api/src/com/todoroo/andlib/data/DatabaseDao.java +++ b/api/src/com/todoroo/andlib/data/DatabaseDao.java @@ -52,8 +52,9 @@ public class DatabaseDao { public DatabaseDao(Class modelClass) { DependencyInjectionService.getInstance().inject(this); this.modelClass = modelClass; - if (debug == null) + if (debug == null) { debug = false; + } } public DatabaseDao(Class modelClass, AbstractDatabase database) { @@ -79,8 +80,9 @@ public class DatabaseDao { * @param database */ public void setDatabase(AbstractDatabase database) { - if (database == this.database) + if (database == this.database) { return; + } this.database = database; table = database.getTable(modelClass); outstandingTable = database.getOutstandingTable(modelClass); @@ -116,8 +118,9 @@ public class DatabaseDao { */ public TodorooCursor query(Query query) { query.from(table); - if (debug) + if (debug) { Log.i("SQL-" + modelClass.getSimpleName(), query.toString()); //$NON-NLS-1$ + } Cursor cursor = database.rawQuery(query.toString(), null); return new TodorooCursor(cursor, query.getFields()); } @@ -132,8 +135,9 @@ public class DatabaseDao { */ public TodorooCursor rawQuery(String selection, String[] selectionArgs, Property... properties) { String[] fields = new String[properties.length]; - for (int i = 0; i < properties.length; i++) + for (int i = 0; i < properties.length; i++) { fields[i] = properties[i].name; + } return new TodorooCursor(database.getDatabase().query(table.name, fields, selection, selectionArgs, null, null, null), properties); @@ -155,8 +159,9 @@ public class DatabaseDao { protected TYPE returnFetchResult(TodorooCursor cursor) { try { - if (cursor.getCount() == 0) + if (cursor.getCount() == 0) { return null; + } Constructor constructor = modelClass.getConstructor(TodorooCursor.class); return constructor.newInstance(cursor); } catch (SecurityException e) { @@ -230,8 +235,9 @@ public class DatabaseDao { toUpdate.close(); } - if (toUpdate.getCount() == 0) + if (toUpdate.getCount() == 0) { return 0; + } synchronized (database) { database.getDatabase().beginTransactionWithListener(new SQLiteTransactionListener() { @@ -281,7 +287,9 @@ public class DatabaseDao { ContentValues values = item.getSetValues(); if (values.size() == 0) // nothing changed + { return true; + } return saveExisting(item); } @@ -321,11 +329,15 @@ public class DatabaseDao { result.set(op.makeChange()); if (result.get()) { if (recordOutstanding && ((numOutstanding = createOutstandingEntries(item.getId(), values)) != -1)) // Create entries for setValues in outstanding table + { database.getDatabase().setTransactionSuccessful(); + } } } finally { if (recordOutstanding) // commit transaction + { database.getDatabase().endTransaction(); + } } if (result.get()) { onModelUpdated(item, recordOutstanding && numOutstanding > 0); @@ -352,8 +364,9 @@ public class DatabaseDao { long newRow = database.insert(table.name, AbstractModel.ID_PROPERTY.name, item.getMergedValues()); boolean result = newRow >= 0; - if (result) + if (result) { item.setId(newRow); + } return result; } }; @@ -371,7 +384,9 @@ public class DatabaseDao { public boolean saveExisting(final TYPE item) { final ContentValues values = item.getSetValues(); if (values == null || values.size() == 0) // nothing changed + { return true; + } DatabaseChangeOp update = new DatabaseChangeOp() { @Override public boolean makeChange() { diff --git a/api/src/com/todoroo/andlib/data/Property.java b/api/src/com/todoroo/andlib/data/Property.java index b773b5893..3163b382f 100644 --- a/api/src/com/todoroo/andlib/data/Property.java +++ b/api/src/com/todoroo/andlib/data/Property.java @@ -119,13 +119,15 @@ public abstract class Property extends Field implements Cloneable { */ public Property cloneAs(String tableAlias, String columnAlias) { Table aliasedTable = this.table; - if (!TextUtils.isEmpty(tableAlias)) + if (!TextUtils.isEmpty(tableAlias)) { aliasedTable = table.as(tableAlias); + } try { Property newInstance = this.getClass().getConstructor(Table.class, String.class).newInstance(aliasedTable, this.name); - if (!TextUtils.isEmpty(columnAlias)) + if (!TextUtils.isEmpty(columnAlias)) { return (Property) newInstance.as(columnAlias); + } return newInstance; } catch (Exception e) { throw new RuntimeException(e); @@ -311,8 +313,9 @@ public abstract class Property extends Field implements Cloneable { } public String getColumnName() { - if (hasAlias()) + if (hasAlias()) { return alias; + } return name; } diff --git a/api/src/com/todoroo/andlib/data/Table.java b/api/src/com/todoroo/andlib/data/Table.java index 26b9462f5..4defca0bf 100644 --- a/api/src/com/todoroo/andlib/data/Table.java +++ b/api/src/com/todoroo/andlib/data/Table.java @@ -67,21 +67,24 @@ public final class Table extends SqlTable { */ @SuppressWarnings("nls") public Field field(Property property) { - if (alias != null) + if (alias != null) { return Field.field(alias + "." + property.name); + } return Field.field(name + "." + property.name); } @Override public String toString() { - if (hasAlias()) + if (hasAlias()) { return expression + " AS " + alias; //$NON-NLS-1$ + } return expression; } public String name() { - if (hasAlias()) + if (hasAlias()) { return alias; + } return name; } } \ No newline at end of file diff --git a/api/src/com/todoroo/andlib/data/TodorooCursor.java b/api/src/com/todoroo/andlib/data/TodorooCursor.java index fc720a82e..5edd2159e 100644 --- a/api/src/com/todoroo/andlib/data/TodorooCursor.java +++ b/api/src/com/todoroo/andlib/data/TodorooCursor.java @@ -108,31 +108,35 @@ public class TodorooCursor extends CursorWrapper { public Object visitDouble(Property property, TodorooCursor cursor) { int column = columnIndex(property, cursor); - if (property.checkFlag(Property.PROP_FLAG_NULLABLE) && cursor.isNull(column)) + if (property.checkFlag(Property.PROP_FLAG_NULLABLE) && cursor.isNull(column)) { return null; + } return cursor.getDouble(column); } public Object visitInteger(Property property, TodorooCursor cursor) { int column = columnIndex(property, cursor); - if (property.checkFlag(Property.PROP_FLAG_NULLABLE) && cursor.isNull(column)) + if (property.checkFlag(Property.PROP_FLAG_NULLABLE) && cursor.isNull(column)) { return null; + } return cursor.getInt(column); } public Object visitLong(Property property, TodorooCursor cursor) { int column = columnIndex(property, cursor); - if (property.checkFlag(Property.PROP_FLAG_NULLABLE) && cursor.isNull(column)) + if (property.checkFlag(Property.PROP_FLAG_NULLABLE) && cursor.isNull(column)) { return null; + } return cursor.getLong(column); } public Object visitString(Property property, TodorooCursor cursor) { int column = columnIndex(property, cursor); - if (property.checkFlag(Property.PROP_FLAG_NULLABLE) && cursor.isNull(column)) + if (property.checkFlag(Property.PROP_FLAG_NULLABLE) && cursor.isNull(column)) { return null; + } return cursor.getString(column); } diff --git a/api/src/com/todoroo/andlib/service/ContextManager.java b/api/src/com/todoroo/andlib/service/ContextManager.java index f3714157b..49cec9f01 100644 --- a/api/src/com/todoroo/andlib/service/ContextManager.java +++ b/api/src/com/todoroo/andlib/service/ContextManager.java @@ -28,10 +28,12 @@ public final class ContextManager { * @param context */ public static void setContext(Context context) { - if (context == null || context.getApplicationContext() == null) + if (context == null || context.getApplicationContext() == null) { return; - if (ContextManager.context != null && !(context instanceof Activity)) + } + if (ContextManager.context != null && !(context instanceof Activity)) { return; + } ContextManager.context = context; } diff --git a/api/src/com/todoroo/andlib/service/DependencyInjectionService.java b/api/src/com/todoroo/andlib/service/DependencyInjectionService.java index 2d726d1b6..6a1747937 100644 --- a/api/src/com/todoroo/andlib/service/DependencyInjectionService.java +++ b/api/src/com/todoroo/andlib/service/DependencyInjectionService.java @@ -44,8 +44,9 @@ public class DependencyInjectionService { Class cls = caller.getClass(); while (cls != null) { String packageName = cls.getPackage().getName(); - if (!isQualifiedPackage(packageName)) + if (!isQualifiedPackage(packageName)) { break; + } for (Field field : cls.getDeclaredFields()) { if (field.getAnnotation(Autowired.class) != null) { @@ -71,12 +72,15 @@ public class DependencyInjectionService { @SuppressWarnings("nls") private boolean isQualifiedPackage(String packageName) { - if (packageName.startsWith("com.todoroo")) + if (packageName.startsWith("com.todoroo")) { return true; - if (packageName.startsWith("com.timsu")) + } + if (packageName.startsWith("com.timsu")) { return true; - if (packageName.startsWith("org.weloveastrid")) + } + if (packageName.startsWith("org.weloveastrid")) { return true; + } return false; } @@ -92,10 +96,11 @@ public class DependencyInjectionService { throws IllegalStateException, IllegalArgumentException, IllegalAccessException { - if (field.getType().isPrimitive()) + if (field.getType().isPrimitive()) { throw new IllegalStateException(String.format( "Tried to dependency-inject primative field '%s' of type '%s'", field.getName(), field.getType())); + } // field has already been processed, ignore if (field.get(caller) != null) { @@ -146,8 +151,9 @@ public class DependencyInjectionService { * @return */ public synchronized static DependencyInjectionService getInstance() { - if (instance == null) + if (instance == null) { instance = new DependencyInjectionService(); + } return instance; } diff --git a/api/src/com/todoroo/andlib/service/ExceptionService.java b/api/src/com/todoroo/andlib/service/ExceptionService.java index b022f2f23..e5aa065e0 100644 --- a/api/src/com/todoroo/andlib/service/ExceptionService.java +++ b/api/src/com/todoroo/andlib/service/ExceptionService.java @@ -42,8 +42,9 @@ public class ExceptionService { * @param error Exception encountered. Message will be displayed to user */ public void reportError(String name, Throwable error) { - if (errorReporters == null) + if (errorReporters == null) { return; + } for (ErrorReporter reporter : errorReporters) { try { @@ -66,10 +67,11 @@ public class ExceptionService { final String messageToDisplay; // pretty up the message when displaying to user - if (error == null) + if (error == null) { messageToDisplay = context.getString(R.string.DLG_error_generic); - else + } else { messageToDisplay = context.getString(R.string.DLG_error, error); + } ((Activity) context).runOnUiThread(new Runnable() { public void run() { @@ -125,13 +127,15 @@ public class ExceptionService { } } - if (tag == null) + if (tag == null) { tag = "unknown-" + name; //$NON-NLS-1$ + } - if (error == null) + if (error == null) { Log.e(tag, "Exception: " + name); //$NON-NLS-1$ - else + } else { Log.e(tag, error.toString(), error); + } } } @@ -153,8 +157,9 @@ public class ExceptionService { } public void uncaughtException(Thread thread, Throwable ex) { - if (exceptionService != null) + if (exceptionService != null) { exceptionService.reportError("uncaught", ex); //$NON-NLS-1$ + } defaultUEH.uncaughtException(thread, ex); } } diff --git a/api/src/com/todoroo/andlib/service/HttpRestClient.java b/api/src/com/todoroo/andlib/service/HttpRestClient.java index bcdf25584..3fde17306 100644 --- a/api/src/com/todoroo/andlib/service/HttpRestClient.java +++ b/api/src/com/todoroo/andlib/service/HttpRestClient.java @@ -106,8 +106,9 @@ public class HttpRestClient implements RestClient { public void process( final HttpRequest request, final HttpContext context) throws HttpException, IOException { - if (!request.containsHeader("Accept-Encoding")) + if (!request.containsHeader("Accept-Encoding")) { request.addHeader("Accept-Encoding", "gzip"); + } } }); @@ -191,8 +192,9 @@ public class HttpRestClient implements RestClient { * @throws IOException */ public synchronized String get(String url) throws IOException { - if (debug) + if (debug) { Log.d("http-rest-client-get", url); //$NON-NLS-1$ + } try { HttpGet httpGet = new HttpGet(url); @@ -216,14 +218,16 @@ public class HttpRestClient implements RestClient { * @throws IOException */ public synchronized String post(String url, HttpEntity data, Header... headers) throws IOException { - if (debug) + if (debug) { Log.d("http-rest-client-post", url + " | " + data); //$NON-NLS-1$ //$NON-NLS-2$ + } try { HttpPost httpPost = new HttpPost(url); httpPost.setEntity(data); - for (Header header : headers) + for (Header header : headers) { httpPost.addHeader(header); + } HttpResponse response = getClient().execute(httpPost); return processHttpResponse(response); diff --git a/api/src/com/todoroo/andlib/sql/DBObject.java b/api/src/com/todoroo/andlib/sql/DBObject.java index f95851003..99b0cefd8 100644 --- a/api/src/com/todoroo/andlib/sql/DBObject.java +++ b/api/src/com/todoroo/andlib/sql/DBObject.java @@ -32,14 +32,21 @@ public abstract class DBObject> implements Cloneable { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } DBObject dbObject = (DBObject) o; - if (alias != null ? !alias.equals(dbObject.alias) : dbObject.alias != null) return false; - if (expression != null ? !expression.equals(dbObject.expression) : dbObject.expression != null) + if (alias != null ? !alias.equals(dbObject.alias) : dbObject.alias != null) { return false; + } + if (expression != null ? !expression.equals(dbObject.expression) : dbObject.expression != null) { + return false; + } return true; } @@ -65,8 +72,9 @@ public abstract class DBObject> implements Cloneable { sb.append(SPACE).append(AS).append(SPACE).append(alias); } else { int pos = expression.indexOf('.'); - if (pos > 0) + if (pos > 0) { sb.append(SPACE).append(AS).append(SPACE).append(expression.substring(pos + 1)); + } } return sb.toString(); } diff --git a/api/src/com/todoroo/andlib/sql/Field.java b/api/src/com/todoroo/andlib/sql/Field.java index 6cfe2048e..4b722ff37 100644 --- a/api/src/com/todoroo/andlib/sql/Field.java +++ b/api/src/com/todoroo/andlib/sql/Field.java @@ -23,8 +23,9 @@ public class Field extends DBObject { } public Criterion eq(Object value) { - if (value == null) + if (value == null) { return UnaryCriterion.isNull(this); + } return UnaryCriterion.eq(this, value); } @@ -38,15 +39,17 @@ public class Field extends DBObject { */ @SuppressWarnings("nls") public Criterion eqCaseInsensitive(String value) { - if (value == null) + if (value == null) { return UnaryCriterion.isNull(this); + } String escaped = value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_"); return UnaryCriterion.like(this, escaped, "\\"); } public Criterion neq(Object value) { - if (value == null) + if (value == null) { return UnaryCriterion.isNotNull(this); + } return UnaryCriterion.neq(this, value); } diff --git a/api/src/com/todoroo/andlib/sql/Join.java b/api/src/com/todoroo/andlib/sql/Join.java index d532b8c43..b318bb005 100644 --- a/api/src/com/todoroo/andlib/sql/Join.java +++ b/api/src/com/todoroo/andlib/sql/Join.java @@ -44,8 +44,9 @@ public class Join { 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) + if (i < criterions.length - 1) { sb.append(SPACE).append(AND).append(SPACE); + } } sb.append(")"); return sb.toString(); diff --git a/api/src/com/todoroo/andlib/sql/Order.java b/api/src/com/todoroo/andlib/sql/Order.java index 9630ac8a1..b441f29b6 100644 --- a/api/src/com/todoroo/andlib/sql/Order.java +++ b/api/src/com/todoroo/andlib/sql/Order.java @@ -56,9 +56,10 @@ public class Order { } public Order reverse() { - if (orderType == OrderType.ASC) + if (orderType == OrderType.ASC) { return new Order(expression, OrderType.DESC); - else + } else { return new Order(expression, OrderType.ASC); + } } } diff --git a/api/src/com/todoroo/andlib/sql/Query.java b/api/src/com/todoroo/andlib/sql/Query.java index 77694d297..555ff7e20 100644 --- a/api/src/com/todoroo/andlib/sql/Query.java +++ b/api/src/com/todoroo/andlib/sql/Query.java @@ -125,8 +125,9 @@ public final class Query { visitLimitClause(sql); } else { if (groupBies.size() > 0 || orders.size() > 0 || - havings.size() > 0) + havings.size() > 0) { throw new IllegalStateException("Can't have extras AND query template"); //$NON-NLS-1$ + } sql.append(queryTemplate); } @@ -198,8 +199,9 @@ public final class Query { private void visitSelectClause(StringBuilder sql) { sql.append(SELECT).append(SPACE); - if (distinct) + if (distinct) { sql.append(DISTINCT).append(SPACE); + } if (fields.isEmpty()) { sql.append(ALL).append(SPACE); return; @@ -211,8 +213,9 @@ public final class Query { } private void visitLimitClause(StringBuilder sql) { - if (limits > -1) + if (limits > -1) { sql.append(LIMIT).append(SPACE).append(limits).append(SPACE); + } } public SqlTable as(String alias) { @@ -254,12 +257,14 @@ public final class Query { public Cursor queryContentResolver(ContentResolver cr, Uri baseUri) { Uri uri = baseUri; - if (joins.size() != 0) + if (joins.size() != 0) { throw new UnsupportedOperationException("can't perform join in content resolver query"); //$NON-NLS-1$ + } String[] projection = new String[fields.size()]; - for (int i = 0; i < projection.length; i++) + for (int i = 0; i < projection.length; i++) { projection[i] = fields.get(i).toString(); + } StringBuilder groupByClause = new StringBuilder(); StringBuilder selectionClause = new StringBuilder(); @@ -269,24 +274,30 @@ public final class Query { selectionClause, orderClause, groupByClause); } else { if (groupBies.size() > 0) { - for (Field groupBy : groupBies) + for (Field groupBy : groupBies) { groupByClause.append(SPACE).append(groupBy).append(COMMA); - if (groupByClause.length() > 0) + } + if (groupByClause.length() > 0) { groupByClause.deleteCharAt(groupByClause.length() - 1); + } } - for (Criterion criterion : criterions) + for (Criterion criterion : criterions) { selectionClause.append(criterion).append(SPACE); + } - for (Order order : orders) + for (Order order : orders) { orderClause.append(SPACE).append(order).append(COMMA); - if (orderClause.length() > 0) + } + if (orderClause.length() > 0) { orderClause.deleteCharAt(orderClause.length() - 1); + } } - if (groupByClause.length() > 0) + if (groupByClause.length() > 0) { uri = Uri.withAppendedPath(baseUri, AstridApiConstants.GROUP_BY_URI + groupByClause.toString().trim()); + } return cr.query(uri, projection, selectionClause.toString(), null, orderClause.toString()); } @@ -306,18 +317,21 @@ public final class Query { Pattern where = Pattern.compile("WHERE (.*?)(LIMIT|HAVING|GROUP|ORDER|\\Z)"); Matcher whereMatcher = where.matcher(queryTemplate); - if (whereMatcher.find()) + if (whereMatcher.find()) { selectionClause.append(whereMatcher.group(1).trim()); + } Pattern group = Pattern.compile("GROUP BY (.*?)(LIMIT|HAVING|ORDER|\\Z)"); Matcher groupMatcher = group.matcher(queryTemplate); - if (groupMatcher.find()) + if (groupMatcher.find()) { groupByClause.append(groupMatcher.group(1).trim()); + } Pattern order = Pattern.compile("ORDER BY (.*?)(LIMIT|HAVING|\\Z)"); Matcher orderMatcher = order.matcher(queryTemplate); - if (orderMatcher.find()) + if (orderMatcher.find()) { orderClause.append(orderMatcher.group(1).trim()); + } } } diff --git a/api/src/com/todoroo/andlib/sql/QueryTemplate.java b/api/src/com/todoroo/andlib/sql/QueryTemplate.java index 7abd50e42..cd34a2cb6 100644 --- a/api/src/com/todoroo/andlib/sql/QueryTemplate.java +++ b/api/src/com/todoroo/andlib/sql/QueryTemplate.java @@ -57,8 +57,9 @@ public final class QueryTemplate { visitWhereClause(sql); visitGroupByClause(sql); visitOrderByClause(sql); - if (limit != null) + if (limit != null) { sql.append(LIMIT).append(SPACE).append(limit); + } return sql.toString(); } diff --git a/api/src/com/todoroo/andlib/sql/UnaryCriterion.java b/api/src/com/todoroo/andlib/sql/UnaryCriterion.java index ff48d58c2..d0b6b5a9f 100644 --- a/api/src/com/todoroo/andlib/sql/UnaryCriterion.java +++ b/api/src/com/todoroo/andlib/sql/UnaryCriterion.java @@ -38,12 +38,13 @@ public class UnaryCriterion extends Criterion { @SuppressWarnings("nls") protected void afterPopulateOperator(StringBuilder sb) { - if (value == null) + if (value == null) { return; - else if (value instanceof String) + } else if (value instanceof String) { sb.append("'").append(sanitize((String) value)).append("'"); - else + } else { sb.append(value); + } } /** diff --git a/api/src/com/todoroo/andlib/utility/AndroidUtilities.java b/api/src/com/todoroo/andlib/utility/AndroidUtilities.java index 9274c0626..f18c58f99 100644 --- a/api/src/com/todoroo/andlib/utility/AndroidUtilities.java +++ b/api/src/com/todoroo/andlib/utility/AndroidUtilities.java @@ -94,10 +94,12 @@ public class AndroidUtilities { ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo(); - if (info == null) + if (info == null) { return false; - if (info.getState() != State.CONNECTED) + } + if (info.getState() != State.CONNECTED) { return false; + } return true; } @@ -118,8 +120,9 @@ public class AndroidUtilities { bis.close(); } } finally { - if (is != null) + if (is != null) { is.close(); + } } } @@ -157,10 +160,11 @@ public class AndroidUtilities { */ public static void startExternalIntent(Context context, Intent intent, int request) { try { - if (request > -1 && context instanceof Activity) + if (request > -1 && context instanceof Activity) { ((Activity) context).startActivityForResult(intent, request); - else + } else { context.startActivity(intent); + } } catch (Exception e) { getExceptionService().displayAndReportError(context, "start-external-intent-" + intent.toString(), //$NON-NLS-1$ @@ -194,25 +198,26 @@ public class AndroidUtilities { * @param value */ public static void putInto(ContentValues target, String key, Object value, boolean errorOnFail) { - if (value instanceof Boolean) + if (value instanceof Boolean) { target.put(key, (Boolean) value); - else if (value instanceof Byte) + } else if (value instanceof Byte) { target.put(key, (Byte) value); - else if (value instanceof Double) + } else if (value instanceof Double) { target.put(key, (Double) value); - else if (value instanceof Float) + } else if (value instanceof Float) { target.put(key, (Float) value); - else if (value instanceof Integer) + } else if (value instanceof Integer) { target.put(key, (Integer) value); - else if (value instanceof Long) + } else if (value instanceof Long) { target.put(key, (Long) value); - else if (value instanceof Short) + } else if (value instanceof Short) { target.put(key, (Short) value); - else if (value instanceof String) + } else if (value instanceof String) { target.put(key, (String) value); - else if (errorOnFail) + } else if (errorOnFail) { throw new UnsupportedOperationException("Could not handle type " + //$NON-NLS-1$ value.getClass()); + } } /** @@ -223,25 +228,26 @@ public class AndroidUtilities { * @param value */ public static void putInto(Bundle target, String key, Object value, boolean errorOnFail) { - if (value instanceof Boolean) + if (value instanceof Boolean) { target.putBoolean(key, (Boolean) value); - else if (value instanceof Byte) + } else if (value instanceof Byte) { target.putByte(key, (Byte) value); - else if (value instanceof Double) + } else if (value instanceof Double) { target.putDouble(key, (Double) value); - else if (value instanceof Float) + } else if (value instanceof Float) { target.putFloat(key, (Float) value); - else if (value instanceof Integer) + } else if (value instanceof Integer) { target.putInt(key, (Integer) value); - else if (value instanceof Long) + } else if (value instanceof Long) { target.putLong(key, (Long) value); - else if (value instanceof Short) + } else if (value instanceof Short) { target.putShort(key, (Short) value); - else if (value instanceof String) + } else if (value instanceof String) { target.putString(key, (String) value); - else if (errorOnFail) + } else if (errorOnFail) { throw new UnsupportedOperationException("Could not handle type " + //$NON-NLS-1$ value.getClass()); + } } // --- serialization @@ -267,9 +273,11 @@ public class AndroidUtilities { * @return */ public static int indexOf(TYPE[] array, TYPE value) { - for (int i = 0; i < array.length; i++) - if (array[i].equals(value)) + for (int i = 0; i < array.length; i++) { + if (array[i].equals(value)) { return i; + } + } return -1; } @@ -281,9 +289,11 @@ public class AndroidUtilities { * @return */ public static int indexOf(int[] array, int value) { - for (int i = 0; i < array.length; i++) - if (array[i] == value) + for (int i = 0; i < array.length; i++) { + if (array[i] == value) { return i; + } + } return -1; } @@ -305,18 +315,19 @@ public class AndroidUtilities { String key, Object value) { result.append(key.replace(SERIALIZATION_SEPARATOR, SEPARATOR_ESCAPE)).append( SERIALIZATION_SEPARATOR); - if (value instanceof Integer) + if (value instanceof Integer) { result.append('i').append(value); - else if (value instanceof Double) + } else if (value instanceof Double) { result.append('d').append(value); - else if (value instanceof Long) + } else if (value instanceof Long) { result.append('l').append(value); - else if (value instanceof String) + } else if (value instanceof String) { result.append('s').append(value.toString().replace(SERIALIZATION_SEPARATOR, SEPARATOR_ESCAPE)); - else if (value instanceof Boolean) + } else if (value instanceof Boolean) { result.append('b').append(value); - else + } else { throw new UnsupportedOperationException(value.getClass().toString()); + } result.append(SERIALIZATION_SEPARATOR); } @@ -325,8 +336,9 @@ public class AndroidUtilities { */ public static String bundleToSerializedString(Bundle source) { StringBuilder result = new StringBuilder(); - if (source == null) + if (source == null) { return null; + } for (String key : source.keySet()) { addSerialized(result, key, source.get(key)); @@ -341,8 +353,9 @@ public class AndroidUtilities { * @return */ public static ContentValues contentValuesFromSerializedString(String string) { - if (string == null) + if (string == null) { return new ContentValues(); + } ContentValues result = new ContentValues(); fromSerialized(string, result, new SerializedPut() { @@ -376,8 +389,9 @@ public class AndroidUtilities { * @return */ public static Bundle bundleFromSerializedString(String string) { - if (string == null) + if (string == null) { return new Bundle(); + } Bundle result = new Bundle(); fromSerialized(string, result, new SerializedPut() { @@ -436,8 +450,9 @@ public class AndroidUtilities { */ @SuppressWarnings("nls") public static ContentValues contentValuesFromString(String string) { - if (string == null) + if (string == null) { return null; + } String[] pairs = string.split("="); ContentValues result = new ContentValues(); @@ -451,8 +466,9 @@ public class AndroidUtilities { } else { newKey = pairs[i]; } - if (key != null) + if (key != null) { result.put(key.trim(), pairs[i].trim()); + } key = newKey; } return result; @@ -466,10 +482,12 @@ public class AndroidUtilities { * @return */ public static boolean equals(Object a, Object b) { - if (a == null && b == null) + if (a == null && b == null) { return true; - if (a == null) + } + if (a == null) { return false; + } return a.equals(b); } @@ -508,8 +526,9 @@ public class AndroidUtilities { while ((bytes = source.read(buffer)) != -1) { if (bytes == 0) { bytes = source.read(); - if (bytes < 0) + if (bytes < 0) { break; + } dest.write(bytes); dest.flush(); continue; @@ -528,16 +547,19 @@ public class AndroidUtilities { * @return first view (by DFS) if found, or null if none */ public static TYPE findViewByType(View view, Class type) { - if (view == null) + if (view == null) { return null; - if (type.isInstance(view)) + } + if (type.isInstance(view)) { return (TYPE) view; + } if (view instanceof ViewGroup) { ViewGroup group = (ViewGroup) view; for (int i = 0; i < group.getChildCount(); i++) { TYPE v = findViewByType(group.getChildAt(i), type); - if (v != null) + if (v != null) { return v; + } } } return null; @@ -557,8 +579,9 @@ public class AndroidUtilities { */ public static void copyDatabases(Context context, String folder) { File folderFile = new File(folder); - if (!folderFile.exists()) + if (!folderFile.exists()) { folderFile.mkdir(); + } for (String db : context.databaseList()) { File dbFile = context.getDatabasePath(db); try { @@ -592,8 +615,9 @@ public class AndroidUtilities { */ public static KEY findKeyInMap(Map map, VALUE value) { for (Entry entry : map.entrySet()) { - if (entry.getValue().equals(value)) + if (entry.getValue().equals(value)) { return entry.getKey(); + } } return null; } @@ -640,8 +664,9 @@ public class AndroidUtilities { */ public static Object callApiMethod(int minSdk, Object receiver, String methodName, Class[] params, Object... args) { - if (getSdkVersion() < minSdk) + if (getSdkVersion() < minSdk) { return null; + } return AndroidUtilities.callMethod(receiver.getClass(), receiver, methodName, params, args); @@ -660,8 +685,9 @@ public class AndroidUtilities { @SuppressWarnings("nls") public static Object callApiStaticMethod(int minSdk, String className, String methodName, Class[] params, Object... args) { - if (getSdkVersion() < minSdk) + if (getSdkVersion() < minSdk) { return null; + } try { return AndroidUtilities.callMethod(Class.forName(className), @@ -826,17 +852,20 @@ public class AndroidUtilities { originalListLength = list.length; length += list.length; } - if (newItems != null) + if (newItems != null) { length += newItems.length; + } T[] newList = (T[]) Array.newInstance(type, length); if (list != null) { - for (int i = 0; i < list.length; i++) + for (int i = 0; i < list.length; i++) { newList[i] = list[i]; + } } if (newItems != null) { - for (int i = 0; i < newItems.length; i++) + for (int i = 0; i < newItems.length; i++) { newList[originalListLength + i] = newItems[i]; + } } return newList; } @@ -846,11 +875,13 @@ public class AndroidUtilities { private static ExceptionService exceptionService = null; private static ExceptionService getExceptionService() { - if (exceptionService == null) + if (exceptionService == null) { synchronized (AndroidUtilities.class) { - if (exceptionService == null) + if (exceptionService == null) { exceptionService = new ExceptionService(); + } } + } return exceptionService; } @@ -863,11 +894,13 @@ public class AndroidUtilities { */ public static TYPE[] concat(TYPE[] dest, TYPE[] source, TYPE... additional) { int i = 0; - for (; i < Math.min(dest.length, source.length); i++) + for (; i < Math.min(dest.length, source.length); i++) { dest[i] = source[i]; + } int base = i; - for (; i < dest.length; i++) + for (; i < dest.length; i++) { dest[i] = additional[i - base]; + } return dest; } @@ -920,7 +953,9 @@ public class AndroidUtilities { */ public static boolean isTabletSized(Context context) { if (context.getPackageManager().hasSystemFeature("com.google.android.tv")) //$NON-NLS-1$ + { return true; + } int size = context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK; @@ -965,8 +1000,9 @@ public class AndroidUtilities { * @param popup */ public static void tryDismissPopup(Activity activity, final PopupWindow popup) { - if (popup == null) + if (popup == null) { return; + } try { popup.dismiss(); } catch (Exception e) { @@ -1008,8 +1044,9 @@ public class AndroidUtilities { String extension = ""; if (index > 0) { extension = file.substring(index + 1); - if (!extension.matches("\\w+")) + if (!extension.matches("\\w+")) { extension = ""; + } } return extension; } diff --git a/api/src/com/todoroo/andlib/utility/DateUtilities.java b/api/src/com/todoroo/andlib/utility/DateUtilities.java index 285bf5b2f..f2b712eac 100644 --- a/api/src/com/todoroo/andlib/utility/DateUtilities.java +++ b/api/src/com/todoroo/andlib/utility/DateUtilities.java @@ -29,8 +29,9 @@ public class DateUtilities { * Convert unixtime into date */ public static final Date unixtimeToDate(long millis) { - if (millis == 0) + if (millis == 0) { return null; + } return new Date(millis); } @@ -38,8 +39,9 @@ public class DateUtilities { * Convert date into unixtime */ public static final long dateToUnixtime(Date date) { - if (date == null) + if (date == null) { return 0; + } return date.getTime(); } @@ -101,8 +103,9 @@ public class DateUtilities { static Boolean is24HourOverride = null; public static boolean is24HourFormat(Context context) { - if (is24HourOverride != null) + if (is24HourOverride != null) { return is24HourOverride; + } return DateFormat.is24HourFormat(context); } @@ -149,12 +152,14 @@ public class DateUtilities { // united states, you are special Locale locale = Locale.getDefault(); if (arrayBinaryContains(locale.getLanguage(), "ja", "ko", "zh") - || arrayBinaryContains(locale.getCountry(), "BZ", "CA", "KE", "MN", "US")) + || arrayBinaryContains(locale.getCountry(), "BZ", "CA", "KE", "MN", "US")) { value = "'#' d'$'"; - else + } else { value = "d'$' '#'"; - if (includeYear) + } + if (includeYear) { value += ", yyyy"; + } if (arrayBinaryContains(locale.getLanguage(), "ja", "zh")) { standardDate = new SimpleDateFormat(value).format(date).replace("#", month).replace("$", "\u65E5"); //$NON-NLS-1$ } else if ("ko".equals(Locale.getDefault().getLanguage())) { @@ -182,20 +187,24 @@ public class DateUtilities { Locale locale = Locale.getDefault(); // united states, you are special if (arrayBinaryContains(locale.getLanguage(), "ja", "ko", "zh") - || arrayBinaryContains(locale.getCountry(), "BZ", "CA", "KE", "MN", "US")) + || arrayBinaryContains(locale.getCountry(), "BZ", "CA", "KE", "MN", "US")) { value = "'#' d"; - else + } else { value = "d '#'"; + } if (date.getYear() != (new Date()).getYear()) { value = value + "\nyyyy"; } if (arrayBinaryContains(locale.getLanguage(), "ja", "zh")) //$NON-NLS-1$ + { return new SimpleDateFormat(value).format(date).replace("#", month) + "\u65E5"; //$NON-NLS-1$ - else if ("ko".equals(Locale.getDefault().getLanguage())) //$NON-NLS-1$ + } else if ("ko".equals(Locale.getDefault().getLanguage())) //$NON-NLS-1$ + { return new SimpleDateFormat(value).format(date).replace("#", month) + "\uC77C"; //$NON-NLS-1$ - else + } else { return new SimpleDateFormat(value).format(date).replace("#", month); + } } /** @@ -247,33 +256,40 @@ public class DateUtilities { long today = clearTime(new Date()); long input = clearTime(new Date(date)); - if (today == input) + if (today == input) { return context.getString(R.string.today).toLowerCase(); + } - if (today + ONE_DAY == input) + if (today + ONE_DAY == input) { return context.getString(abbreviated ? R.string.tmrw : R.string.tomorrow).toLowerCase(); + } - if (today == input + ONE_DAY) + if (today == input + ONE_DAY) { return context.getString(abbreviated ? R.string.yest : R.string.yesterday).toLowerCase(); + } if (today + DateUtilities.ONE_WEEK >= input && - today - DateUtilities.ONE_WEEK <= input) + today - DateUtilities.ONE_WEEK <= input) { return abbreviated ? DateUtilities.getWeekdayShort(new Date(date)) : DateUtilities.getWeekday(new Date(date)); + } return DateUtilities.getDateStringHideYear(context, new Date(date)); } public static boolean isEndOfMonth(Date d) { int date = d.getDate(); - if (date < 28) + if (date < 28) { return false; + } int month = d.getMonth(); - if (month == Calendar.FEBRUARY) + if (month == Calendar.FEBRUARY) { return date >= 28; + } - if (month == Calendar.APRIL || month == Calendar.JUNE || month == Calendar.SEPTEMBER || month == Calendar.NOVEMBER) + if (month == Calendar.APRIL || month == Calendar.JUNE || month == Calendar.SEPTEMBER || month == Calendar.NOVEMBER) { return date >= 30; + } return date >= 31; } @@ -309,8 +325,9 @@ public class DateUtilities { } public static long parseIso8601(String iso8601String) throws ParseException { - if (iso8601String == null) + if (iso8601String == null) { return 0; + } String formatString; if (isoStringHasTime(iso8601String)) { // Time exists iso8601String = iso8601String.replace("Z", "+00:00"); //$NON-NLS-1$ //$NON-NLS-2$ @@ -330,12 +347,14 @@ public class DateUtilities { } public static String timeToIso8601(long time, boolean includeTime) { - if (time == 0) + if (time == 0) { return null; + } Date date = new Date(time); String formatString = "yyyy-MM-dd'T'HH:mm:ssZ"; //$NON-NLS-1$ - if (!includeTime) + if (!includeTime) { formatString = "yyyy-MM-dd"; //$NON-NLS-1$ + } return new SimpleDateFormat(formatString).format(date); } diff --git a/api/src/com/todoroo/andlib/utility/DialogUtilities.java b/api/src/com/todoroo/andlib/utility/DialogUtilities.java index 328124eea..6ef09ba03 100644 --- a/api/src/com/todoroo/andlib/utility/DialogUtilities.java +++ b/api/src/com/todoroo/andlib/utility/DialogUtilities.java @@ -29,8 +29,9 @@ public class DialogUtilities { public static void viewDialog(final Activity activity, final String text, final View view, final DialogInterface.OnClickListener okListener, final DialogInterface.OnClickListener cancelListener) { - if (activity.isFinishing()) + if (activity.isFinishing()) { return; + } tryOnUiThread(activity, new Runnable() { public void run() { @@ -76,8 +77,9 @@ public class DialogUtilities { */ public static void okDialog(final Activity activity, final String text, final DialogInterface.OnClickListener okListener) { - if (activity.isFinishing()) + if (activity.isFinishing()) { return; + } tryOnUiThread(activity, new Runnable() { public void run() { @@ -101,8 +103,9 @@ public class DialogUtilities { public static void okDialog(final Activity activity, final String title, final int icon, final CharSequence text, final DialogInterface.OnClickListener okListener) { - if (activity.isFinishing()) + if (activity.isFinishing()) { return; + } tryOnUiThread(activity, new Runnable() { public void run() { @@ -157,8 +160,9 @@ public class DialogUtilities { final int icon, final DialogInterface.OnClickListener okListener, final DialogInterface.OnClickListener cancelListener) { - if (activity.isFinishing()) + if (activity.isFinishing()) { return; + } tryOnUiThread(activity, new Runnable() { public void run() { @@ -220,8 +224,9 @@ public class DialogUtilities { * @param dialog */ public static void dismissDialog(Activity activity, final Dialog dialog) { - if (dialog == null) + if (dialog == null) { return; + } tryOnUiThread(activity, new Runnable() { public void run() { try { diff --git a/api/src/com/todoroo/andlib/utility/Pair.java b/api/src/com/todoroo/andlib/utility/Pair.java index a44618ec1..d933c9eb6 100644 --- a/api/src/com/todoroo/andlib/utility/Pair.java +++ b/api/src/com/todoroo/andlib/utility/Pair.java @@ -36,8 +36,9 @@ public class Pair { @Override public final boolean equals(Object o) { - if (!(o instanceof Pair)) + if (!(o instanceof Pair)) { return false; + } final Pair other = (Pair) o; return equal(getLeft(), other.getLeft()) && equal(getRight(), other.getRight()); diff --git a/api/src/com/todoroo/andlib/utility/Preferences.java b/api/src/com/todoroo/andlib/utility/Preferences.java index e5fa865da..2d3b2e42b 100644 --- a/api/src/com/todoroo/andlib/utility/Preferences.java +++ b/api/src/com/todoroo/andlib/utility/Preferences.java @@ -32,8 +32,9 @@ public class Preferences { */ public static void setIfUnset(SharedPreferences prefs, Editor editor, Resources r, int keyResource, int value) { String key = r.getString(keyResource); - if (!prefs.contains(key)) + if (!prefs.contains(key)) { editor.putString(key, Integer.toString(value)); + } } /** @@ -47,8 +48,9 @@ public class Preferences { */ public static void setIfUnset(SharedPreferences prefs, Editor editor, Resources r, int keyResource, boolean value) { String key = r.getString(keyResource); - if (!prefs.contains(key) || !(prefs.getAll().get(key) instanceof Boolean)) + if (!prefs.contains(key) || !(prefs.getAll().get(key) instanceof Boolean)) { editor.putBoolean(key, value); + } } /** @@ -62,8 +64,9 @@ public class Preferences { */ public static void setIfUnset(SharedPreferences prefs, Editor editor, Resources r, int keyResource, String value) { String key = r.getString(keyResource); - if (!prefs.contains(key) || !(prefs.getAll().get(key) instanceof String)) + if (!prefs.contains(key) || !(prefs.getAll().get(key) instanceof String)) { editor.putString(key, value); + } } /* ====================================================================== @@ -76,8 +79,9 @@ public class Preferences { * Get preferences object from the context */ public static SharedPreferences getPrefs(Context context) { - if (preferences != null) + if (preferences != null) { return preferences; + } context = context.getApplicationContext(); try { @@ -141,8 +145,9 @@ public class Preferences { Context context = ContextManager.getContext(); Resources r = context.getResources(); String value = getPrefs(context).getString(r.getString(keyResource), null); - if (value == null) + if (value == null) { return defaultValue; + } try { return Integer.parseInt(value); diff --git a/api/src/com/todoroo/andlib/utility/TodorooPreferenceActivity.java b/api/src/com/todoroo/andlib/utility/TodorooPreferenceActivity.java index 2f95518f9..fe99cb8bc 100644 --- a/api/src/com/todoroo/andlib/utility/TodorooPreferenceActivity.java +++ b/api/src/com/todoroo/andlib/utility/TodorooPreferenceActivity.java @@ -68,14 +68,15 @@ abstract public class TodorooPreferenceActivity extends PreferenceActivity { updatePreferences(group, null); } else { Object value = null; - if (preference instanceof ListPreference) + if (preference instanceof ListPreference) { value = ((ListPreference) preference).getValue(); - else if (preference instanceof CheckBoxPreference) + } else if (preference instanceof CheckBoxPreference) { value = ((CheckBoxPreference) preference).isChecked(); - else if (preference instanceof EditTextPreference) + } else if (preference instanceof EditTextPreference) { value = ((EditTextPreference) preference).getText(); - else if (preference instanceof RingtonePreference) + } else if (preference instanceof RingtonePreference) { value = getPreferenceManager().getSharedPreferences().getString(preference.getKey(), null); + } updatePreferences(preference, value); diff --git a/api/src/com/todoroo/astrid/api/Filter.java b/api/src/com/todoroo/astrid/api/Filter.java index 5a7637b3e..b20cd4d69 100644 --- a/api/src/com/todoroo/astrid/api/Filter.java +++ b/api/src/com/todoroo/astrid/api/Filter.java @@ -107,8 +107,9 @@ public class Filter extends FilterListItem { } public String getSqlQuery() { - if (filterOverride != null) + if (filterOverride != null) { return filterOverride; + } return sqlQuery; } @@ -150,23 +151,30 @@ public class Filter extends FilterListItem { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } Filter other = (Filter) obj; if (sqlQuery == null) { - if (other.sqlQuery != null) + if (other.sqlQuery != null) { return false; - } else if (!sqlQuery.equals(other.sqlQuery)) + } + } else if (!sqlQuery.equals(other.sqlQuery)) { return false; + } if (title == null) { - if (other.title != null) + if (other.title != null) { return false; - } else if (!title.equals(other.title)) + } + } else if (!title.equals(other.title)) { return false; + } return true; } diff --git a/api/src/com/todoroo/astrid/api/FilterCategory.java b/api/src/com/todoroo/astrid/api/FilterCategory.java index 3de203890..899766694 100644 --- a/api/src/com/todoroo/astrid/api/FilterCategory.java +++ b/api/src/com/todoroo/astrid/api/FilterCategory.java @@ -75,10 +75,11 @@ public class FilterCategory extends FilterListItem { FilterCategory.class.getClassLoader()); item.children = new Filter[parcelableChildren.length]; for (int i = 0; i < item.children.length; i++) { - if (parcelableChildren[i] instanceof FilterListItem) + if (parcelableChildren[i] instanceof FilterListItem) { item.children[i] = (Filter) parcelableChildren[i]; - else + } else { item.children[i] = null; + } } return item; diff --git a/api/src/com/todoroo/astrid/api/FilterCategoryWithNewButton.java b/api/src/com/todoroo/astrid/api/FilterCategoryWithNewButton.java index 31a4acf2b..ecf2f8f9c 100644 --- a/api/src/com/todoroo/astrid/api/FilterCategoryWithNewButton.java +++ b/api/src/com/todoroo/astrid/api/FilterCategoryWithNewButton.java @@ -83,10 +83,11 @@ public class FilterCategoryWithNewButton extends FilterCategory { FilterCategoryWithNewButton.class.getClassLoader()); item.children = new Filter[parcelableChildren.length]; for (int i = 0; i < item.children.length; i++) { - if (parcelableChildren[i] instanceof FilterListItem) + if (parcelableChildren[i] instanceof FilterListItem) { item.children[i] = (Filter) parcelableChildren[i]; - else + } else { item.children[i] = null; + } } item.intent = source.readParcelable(PendingIntent.class.getClassLoader()); diff --git a/api/src/com/todoroo/astrid/api/FilterWithCustomIntent.java b/api/src/com/todoroo/astrid/api/FilterWithCustomIntent.java index b3dbd6b48..3a43fb185 100644 --- a/api/src/com/todoroo/astrid/api/FilterWithCustomIntent.java +++ b/api/src/com/todoroo/astrid/api/FilterWithCustomIntent.java @@ -46,8 +46,9 @@ public class FilterWithCustomIntent extends Filter { Intent intent = new Intent(); intent.putExtra("filter", this); //$NON-NLS-1$ intent.setComponent(new ComponentName(AstridApiConstants.ASTRID_PACKAGE, "com.todoroo.astrid.activity.TaskListActivity")); //$NON-NLS-1$ - if (customExtras != null) + if (customExtras != null) { intent.putExtras(customExtras); + } return intent; } diff --git a/api/src/com/todoroo/astrid/api/PermaSql.java b/api/src/com/todoroo/astrid/api/PermaSql.java index 8bf52c6aa..7f6a6fd56 100644 --- a/api/src/com/todoroo/astrid/api/PermaSql.java +++ b/api/src/com/todoroo/astrid/api/PermaSql.java @@ -89,8 +89,9 @@ public final class PermaSql { * Replace placeholder strings with actual */ public static String replacePlaceholders(String value) { - if (value.contains(VALUE_NOW)) + if (value.contains(VALUE_NOW)) { value = value.replace(VALUE_NOW, Long.toString(DateUtilities.now())); + } if (value.contains(VALUE_EOD) || value.contains(VALUE_EOD_DAY_AFTER) || value.contains(VALUE_EOD_NEXT_WEEK) || value.contains(VALUE_EOD_TOMORROW) || value.contains(VALUE_EOD_YESTERDAY) || value.contains(VALUE_EOD_NEXT_MONTH)) { diff --git a/api/src/com/todoroo/astrid/api/SyncAction.java b/api/src/com/todoroo/astrid/api/SyncAction.java index 13ac0d382..1e237ad29 100644 --- a/api/src/com/todoroo/astrid/api/SyncAction.java +++ b/api/src/com/todoroo/astrid/api/SyncAction.java @@ -58,8 +58,9 @@ public class SyncAction implements Parcelable { */ @Override public boolean equals(Object o) { - if (!(o instanceof SyncAction)) + if (!(o instanceof SyncAction)) { return false; + } SyncAction other = (SyncAction) o; return label.equals(other.label) && intent.getTargetPackage().equals(other.intent.getTargetPackage()); } diff --git a/api/src/com/todoroo/astrid/core/SortHelper.java b/api/src/com/todoroo/astrid/core/SortHelper.java index 6bdf5b9f8..50881cfd5 100644 --- a/api/src/com/todoroo/astrid/core/SortHelper.java +++ b/api/src/com/todoroo/astrid/core/SortHelper.java @@ -52,26 +52,31 @@ public class SortHelper { @SuppressWarnings("nls") public static String adjustQueryForFlagsAndSort(String originalSql, int flags, int sort) { // sort - if (originalSql == null) + if (originalSql == null) { originalSql = ""; + } if (!originalSql.toUpperCase().contains("ORDER BY")) { Order order = orderForSortType(sort); - if ((flags & FLAG_REVERSE_SORT) > 0) + if ((flags & FLAG_REVERSE_SORT) > 0) { order = order.reverse(); + } originalSql += " ORDER BY " + order; } // flags - if ((flags & FLAG_SHOW_COMPLETED) > 0) + if ((flags & FLAG_SHOW_COMPLETED) > 0) { originalSql = originalSql.replace(Task.COMPLETION_DATE.eq(0).toString(), Criterion.all.toString()); - if ((flags & FLAG_SHOW_HIDDEN) > 0) + } + if ((flags & FLAG_SHOW_HIDDEN) > 0) { originalSql = originalSql.replace(TaskCriteria.isVisible().toString(), Criterion.all.toString()); - if ((flags & FLAG_SHOW_DELETED) > 0) + } + if ((flags & FLAG_SHOW_DELETED) > 0) { originalSql = originalSql.replace(Task.DELETION_DATE.eq(0).toString(), Criterion.all.toString()); + } return originalSql; } @@ -82,8 +87,9 @@ public class SortHelper { public static int setManualSort(int flags, boolean status) { flags = (flags & ~FLAG_DRAG_DROP); - if (status) + if (status) { flags |= FLAG_DRAG_DROP; + } return flags; } @@ -111,8 +117,9 @@ public class SortHelper { default: order = defaultTaskOrder(); } - if (sortType != SORT_ALPHA) + if (sortType != SORT_ALPHA) { order.addSecondaryExpression(Order.asc(Task.TITLE)); + } return order; } diff --git a/api/src/com/todoroo/astrid/data/RemoteModel.java b/api/src/com/todoroo/astrid/data/RemoteModel.java index c22de89cd..a3f58d7bc 100644 --- a/api/src/com/todoroo/astrid/data/RemoteModel.java +++ b/api/src/com/todoroo/astrid/data/RemoteModel.java @@ -96,22 +96,25 @@ abstract public class RemoteModel extends AbstractModel { abstract public String getUuid(); protected String getUuidHelper(StringProperty uuid) { - if (setValues != null && setValues.containsKey(uuid.name)) + if (setValues != null && setValues.containsKey(uuid.name)) { return setValues.getAsString(uuid.name); - else if (values != null && values.containsKey(uuid.name)) + } else if (values != null && values.containsKey(uuid.name)) { return values.getAsString(uuid.name); - else + } else { return NO_UUID; + } } public void setUuid(String uuid) { - if (setValues == null) + if (setValues == null) { setValues = new ContentValues(); + } - if (NO_UUID.equals(uuid)) + if (NO_UUID.equals(uuid)) { clearValue(UUID_PROPERTY); - else + } else { setValues.put(UUID_PROPERTY_NAME, uuid); + } } public static boolean isUuidEmpty(String uuid) { @@ -163,8 +166,9 @@ abstract public class RemoteModel extends AbstractModel { File dir = context.getExternalFilesDir(PICTURES_DIRECTORY); if (dir != null) { File file = new File(dir + File.separator + DateUtilities.now() + ".jpg"); - if (file.exists()) + if (file.exists()) { return null; + } try { FileOutputStream fos = new FileOutputStream(file); @@ -189,11 +193,14 @@ abstract public class RemoteModel extends AbstractModel { public static String getPictureUrl(String value, String size) { try { - if (value == null) + if (value == null) { return null; + } JSONObject pictureJson = new JSONObject(value); if (pictureJson.has("path")) // Unpushed encoded bitmap //$NON-NLS-1$ + { return null; + } return pictureJson.optString(size); } catch (JSONException e) { return value; @@ -203,8 +210,9 @@ abstract public class RemoteModel extends AbstractModel { @SuppressWarnings("nls") public static Bitmap getPictureBitmap(String value) { try { - if (value == null) + if (value == null) { return null; + } if (value.contains("path")) { JSONObject pictureJson = new JSONObject(value); if (pictureJson.has("path")) { diff --git a/api/src/com/todoroo/astrid/data/TagData.java b/api/src/com/todoroo/astrid/data/TagData.java index 3eea53ac6..1ff621420 100644 --- a/api/src/com/todoroo/astrid/data/TagData.java +++ b/api/src/com/todoroo/astrid/data/TagData.java @@ -329,10 +329,11 @@ public final class TagData extends RemoteModel { */ public boolean isDeleted() { // assume false if we didn't load deletion date - if (!containsValue(DELETION_DATE)) + if (!containsValue(DELETION_DATE)) { return false; - else + } else { return getValue(DELETION_DATE) > 0; + } } } diff --git a/api/src/com/todoroo/astrid/data/Task.java b/api/src/com/todoroo/astrid/data/Task.java index 5ef683e85..10d4397f0 100644 --- a/api/src/com/todoroo/astrid/data/Task.java +++ b/api/src/com/todoroo/astrid/data/Task.java @@ -301,8 +301,9 @@ public final class Task extends RemoteModel { public static final String USER_ID_SELF = "0"; public static boolean isRealUserId(String userId) { - if (userId == null) + if (userId == null) { return false; + } return !(Task.USER_ID_SELF.equals(userId) || Task.USER_ID_UNASSIGNED.equals(userId) || Task.USER_ID_EMAIL.equals(userId) || @@ -310,8 +311,9 @@ public final class Task extends RemoteModel { } public static boolean userIdIsEmail(String userId) { - if (userId == null) + if (userId == null) { return false; + } return userId.indexOf('@') >= 0; } @@ -469,10 +471,11 @@ public final class Task extends RemoteModel { */ public boolean isDeleted() { // assume false if we didn't load deletion date - if (!containsValue(DELETION_DATE)) + if (!containsValue(DELETION_DATE)) { return false; - else + } else { return getValue(DELETION_DATE) > 0; + } } /** @@ -555,8 +558,9 @@ public final class Task extends RemoteModel { throw new IllegalArgumentException("Unknown setting " + setting); } - if (date <= 0) + if (date <= 0) { return date; + } Date dueDate = new Date(date / 1000L * 1000L); // get rid of millis if (setting != URGENCY_SPECIFIC_DAY_TIME) { @@ -600,8 +604,9 @@ public final class Task extends RemoteModel { throw new IllegalArgumentException("Unknown setting " + setting); } - if (date <= 0) + if (date <= 0) { return date; + } Date hideUntil = new Date(date / 1000L * 1000L); // get rid of millis if (setting != HIDE_UNTIL_SPECIFIC_DAY_TIME && setting != HIDE_UNTIL_DUE_TIME) { @@ -618,8 +623,9 @@ public final class Task extends RemoteModel { * Checks whether this due date has a due time or only a date */ public boolean hasDueTime() { - if (!hasDueDate()) + if (!hasDueDate()) { return false; + } return hasDueTime(getValue(Task.DUE_DATE)); } diff --git a/api/src/com/todoroo/astrid/data/TaskApiDao.java b/api/src/com/todoroo/astrid/data/TaskApiDao.java index 74f082ad8..6b50b98f1 100644 --- a/api/src/com/todoroo/astrid/data/TaskApiDao.java +++ b/api/src/com/todoroo/astrid/data/TaskApiDao.java @@ -188,24 +188,29 @@ public class TaskApiDao extends ContentResolverDao { * @return true if task change shouldn't be broadcast */ public static boolean insignificantChange(ContentValues values) { - if (values == null || values.size() == 0) + if (values == null || values.size() == 0) { return true; + } if (values.containsKey(Task.DETAILS_DATE.name) && - values.size() <= 3) + values.size() <= 3) { return true; + } if (values.containsKey(Task.REMINDER_LAST.name) && - values.size() <= 2) + values.size() <= 2) { return true; + } if (values.containsKey(Task.REMINDER_SNOOZE.name) && - values.size() <= 2) + values.size() <= 2) { return true; + } if (values.containsKey(Task.TIMER_START.name) && - values.size() <= 2) + values.size() <= 2) { return true; + } return false; } diff --git a/api/src/com/todoroo/astrid/data/User.java b/api/src/com/todoroo/astrid/data/User.java index c910c5240..876943e36 100644 --- a/api/src/com/todoroo/astrid/data/User.java +++ b/api/src/com/todoroo/astrid/data/User.java @@ -182,19 +182,23 @@ public final class User extends RemoteModel { public String getDisplayName(StringProperty nameProperty, StringProperty firstNameProperty, StringProperty lastNameProperty) { String name = getCheckedString(nameProperty); - if (!(TextUtils.isEmpty(name) || "null".equals(name))) + if (!(TextUtils.isEmpty(name) || "null".equals(name))) { return name; + } String firstName = getCheckedString(firstNameProperty); boolean firstNameEmpty = TextUtils.isEmpty(firstName) || "null".equals(firstName); String lastName = getCheckedString(lastNameProperty); boolean lastNameEmpty = TextUtils.isEmpty(lastName) || "null".equals(lastName); - if (firstNameEmpty && lastNameEmpty) + if (firstNameEmpty && lastNameEmpty) { return getCheckedString(EMAIL); + } StringBuilder nameBuilder = new StringBuilder(); - if (!firstNameEmpty) + if (!firstNameEmpty) { nameBuilder.append(firstName).append(" "); - if (!lastNameEmpty) + } + if (!lastNameEmpty) { nameBuilder.append(lastName); + } return nameBuilder.toString().trim(); } diff --git a/api/src/com/todoroo/astrid/sync/SyncBackgroundService.java b/api/src/com/todoroo/astrid/sync/SyncBackgroundService.java index 0319362d3..32ac0af12 100644 --- a/api/src/com/todoroo/astrid/sync/SyncBackgroundService.java +++ b/api/src/com/todoroo/astrid/sync/SyncBackgroundService.java @@ -74,13 +74,15 @@ abstract public class SyncBackgroundService extends Service { * Start the actual synchronization */ private void startSynchronization(Context context) { - if (context == null || context.getResources() == null) + if (context == null || context.getResources() == null) { return; + } ContextManager.setContext(context); - if (!getSyncUtilities().isLoggedIn()) + if (!getSyncUtilities().isLoggedIn()) { return; + } getSyncProvider().synchronize(context); } @@ -162,10 +164,11 @@ abstract public class SyncBackgroundService extends Service { long lastSyncDate = getSyncUtilities().getLastSyncDate(); // if user never synchronized, give them a full offset period before bg sync - if (lastSyncDate != 0) + if (lastSyncDate != 0) { return Math.max(0, lastSyncDate + interval - DateUtilities.now()); - else + } else { return interval; + } } diff --git a/api/src/com/todoroo/astrid/sync/SyncContainer.java b/api/src/com/todoroo/astrid/sync/SyncContainer.java index c742df94c..e24532006 100644 --- a/api/src/com/todoroo/astrid/sync/SyncContainer.java +++ b/api/src/com/todoroo/astrid/sync/SyncContainer.java @@ -30,8 +30,9 @@ public class SyncContainer { */ public Metadata findMetadata(String key) { for (Metadata item : metadata) { - if (AndroidUtilities.equals(key, item.getValue(Metadata.KEY))) + if (AndroidUtilities.equals(key, item.getValue(Metadata.KEY))) { return item; + } } return null; } diff --git a/api/src/com/todoroo/astrid/sync/SyncProvider.java b/api/src/com/todoroo/astrid/sync/SyncProvider.java index a82933418..0a6993caa 100644 --- a/api/src/com/todoroo/astrid/sync/SyncProvider.java +++ b/api/src/com/todoroo/astrid/sync/SyncProvider.java @@ -168,8 +168,9 @@ public abstract class SyncProvider { ((Activity) context).runOnUiThread(new Runnable() { @Override public void run() { - if (showSyncToast) + if (showSyncToast) { makeSyncToast(context); + } } }); } @@ -221,8 +222,9 @@ public abstract class SyncProvider { length = data.remoteUpdated.size(); for (int i = 0; i < length; i++) { TYPE remote = data.remoteUpdated.get(i); - if (remote.task.getId() != Task.NO_ID) + if (remote.task.getId() != Task.NO_ID) { continue; + } remoteNewTaskNameMap.put(remote.task.getValue(Task.TITLE), i); } @@ -239,10 +241,11 @@ public abstract class SyncProvider { @SuppressWarnings("nls") protected String getFinalSyncStatus() { if (getUtilities().getLastError() != null || getUtilities().getLastAttemptedSyncDate() != 0) { - if (getUtilities().getLastAttemptedSyncDate() == 0) + if (getUtilities().getLastAttemptedSyncDate() == 0) { return "errors"; - else + } else { return "failed"; + } } else { return "success"; } @@ -261,22 +264,25 @@ public abstract class SyncProvider { private final int check(TYPE o1, TYPE o2, LongProperty property) { long o1Property = o1.task.getValue(property); long o2Property = o2.task.getValue(property); - if (o1Property != 0 && o2Property != 0) + if (o1Property != 0 && o2Property != 0) { return 0; - else if (o1Property != 0) + } else if (o1Property != 0) { return -1; - else if (o2Property != 0) + } else if (o2Property != 0) { return 1; + } return SENTINEL; } public int compare(TYPE o1, TYPE o2) { int comparison = check(o1, o2, Task.DELETION_DATE); - if (comparison != SENTINEL) + if (comparison != SENTINEL) { return comparison; + } comparison = check(o1, o2, Task.COMPLETION_DATE); - if (comparison != SENTINEL) + if (comparison != SENTINEL) { return comparison; + } return 0; } }); @@ -286,8 +292,9 @@ public abstract class SyncProvider { TYPE remote = data.remoteUpdated.get(i); // don't synchronize new & deleted tasks - if (!remote.task.isSaved() && (remote.task.isDeleted())) + if (!remote.task.isSaved() && (remote.task.isDeleted())) { continue; + } try { write(remote); @@ -304,8 +311,9 @@ public abstract class SyncProvider { data.localUpdated.moveToNext(); TYPE local = read(data.localUpdated); try { - if (local.task == null) + if (local.task == null) { continue; + } // if there is a conflict, merge int remoteIndex = matchTask((ArrayList) data.remoteUpdated, local); diff --git a/api/src/com/todoroo/astrid/sync/SyncProviderPreferences.java b/api/src/com/todoroo/astrid/sync/SyncProviderPreferences.java index 700261524..2191b8b0c 100644 --- a/api/src/com/todoroo/astrid/sync/SyncProviderPreferences.java +++ b/api/src/com/todoroo/astrid/sync/SyncProviderPreferences.java @@ -86,8 +86,9 @@ abstract public class SyncProviderPreferences extends TodorooPreferenceActivity @Override public void onChildViewAdded(View parent, View child) { View view = findViewById(R.id.status); - if (view != null) + if (view != null) { view.setBackgroundColor(statusColor); + } } }); } @@ -105,12 +106,13 @@ abstract public class SyncProviderPreferences extends TodorooPreferenceActivity int index = AndroidUtilities.indexOf( r.getStringArray(R.array.sync_SPr_interval_values), (String) value); - if (index <= 0) + if (index <= 0) { preference.setSummary(R.string.sync_SPr_interval_desc_disabled); - else + } else { preference.setSummary(r.getString( R.string.sync_SPr_interval_desc, r.getStringArray(R.array.sync_SPr_interval_entries)[index])); + } } // status @@ -171,8 +173,9 @@ abstract public class SyncProviderPreferences extends TodorooPreferenceActivity }); View view = findViewById(R.id.status); - if (view != null) + if (view != null) { view.setBackgroundColor(statusColor); + } } else if (r.getString(R.string.sync_SPr_key_last_error).equals(preference.getKey())) { if (getUtilities().getLastError() != null) { // Display error @@ -266,8 +269,9 @@ abstract public class SyncProviderPreferences extends TodorooPreferenceActivity break; } } - if (resource == null) + if (resource == null) { return lastError; + } return r.getString(resource.intValue(), service); } diff --git a/api/src/com/todoroo/astrid/sync/SyncProviderUtilities.java b/api/src/com/todoroo/astrid/sync/SyncProviderUtilities.java index 6c8332265..83d009e8f 100644 --- a/api/src/com/todoroo/astrid/sync/SyncProviderUtilities.java +++ b/api/src/com/todoroo/astrid/sync/SyncProviderUtilities.java @@ -194,8 +194,9 @@ abstract public class SyncProviderUtilities { String value = getPrefs().getString( ContextManager.getContext().getString( getSyncIntervalKey()), null); - if (value == null) + if (value == null) { return 0; + } try { return Integer.parseInt(value); } catch (Exception e) { diff --git a/api/src/com/todoroo/astrid/sync/SyncV2BackgroundService.java b/api/src/com/todoroo/astrid/sync/SyncV2BackgroundService.java index d46c9c1f6..13b86585d 100644 --- a/api/src/com/todoroo/astrid/sync/SyncV2BackgroundService.java +++ b/api/src/com/todoroo/astrid/sync/SyncV2BackgroundService.java @@ -75,16 +75,18 @@ abstract public class SyncV2BackgroundService extends Service { * Start the actual synchronization */ private void startSynchronization(final Context context) { - if (context == null || context.getResources() == null) + if (context == null || context.getResources() == null) { return; + } ContextManager.setContext(context); - if (!getSyncUtilities().isLoggedIn()) + if (!getSyncUtilities().isLoggedIn()) { return; + } SyncV2Provider provider = getSyncProvider(); - if (provider.isActive()) + if (provider.isActive()) { provider.synchronizeActiveTasks(false, new SyncResultCallbackAdapter() { @Override public void finished() { @@ -92,6 +94,7 @@ abstract public class SyncV2BackgroundService extends Service { context.sendBroadcast(new Intent(AstridApiConstants.BROADCAST_EVENT_REFRESH)); } }); + } } @Override @@ -171,10 +174,11 @@ abstract public class SyncV2BackgroundService extends Service { long lastSyncDate = getSyncUtilities().getLastSyncDate(); // if user never synchronized, give them a full offset period before bg sync - if (lastSyncDate != 0) + if (lastSyncDate != 0) { return Math.max(0, lastSyncDate + interval - DateUtilities.now()); - else + } else { return interval; + } } diff --git a/api/src/com/todoroo/astrid/sync/SyncV2Provider.java b/api/src/com/todoroo/astrid/sync/SyncV2Provider.java index 45f0632a2..d35b53ffe 100644 --- a/api/src/com/todoroo/astrid/sync/SyncV2Provider.java +++ b/api/src/com/todoroo/astrid/sync/SyncV2Provider.java @@ -90,8 +90,9 @@ abstract public class SyncV2Provider { utilities.recordSuccessfulSync(); utilities.reportLastError(); utilities.stopOngoing(); - if (callback != null) + if (callback != null) { callback.finished(); + } } @Override diff --git a/astrid/common-src/com/commonsware/cwac/tlv/TouchListView.java b/astrid/common-src/com/commonsware/cwac/tlv/TouchListView.java index 8b30a41e5..3ba2532cf 100644 --- a/astrid/common-src/com/commonsware/cwac/tlv/TouchListView.java +++ b/astrid/common-src/com/commonsware/cwac/tlv/TouchListView.java @@ -419,8 +419,9 @@ public class TouchListView extends ErrorCatchingListView { private final Runnable longPressRunnable = new Runnable() { public void run() { AndroidUtilities.sleepDeep(1000L); - if (Thread.currentThread().isInterrupted()) + if (Thread.currentThread().isInterrupted()) { return; + } if (mDragView != null && mDragPos == mFirstDragPos && Math.abs(mDragCurrentX - mDragStartX) < 10) { @@ -473,10 +474,11 @@ public class TouchListView extends ErrorCatchingListView { if (mDragPos == mFirstDragPos && Math.abs(mDragCurrentX - mDragStartX) < 10) { long pressTime = System.currentTimeMillis() - mDragStartTime; - if (pressTime < 1000) + if (pressTime < 1000) { mClickListener.onClick(mOriginalView); - else + } else { mClickListener.onLongClick(mOriginalView); + } } } } diff --git a/astrid/plugin-src/com/timsu/astrid/GCMIntentService.java b/astrid/plugin-src/com/timsu/astrid/GCMIntentService.java index dd562e226..93f31559e 100644 --- a/astrid/plugin-src/com/timsu/astrid/GCMIntentService.java +++ b/astrid/plugin-src/com/timsu/astrid/GCMIntentService.java @@ -67,8 +67,9 @@ public class GCMIntentService extends GCMBaseIntentService { if (AndroidUtilities.getSdkVersion() > 8) { //Gingerbread and above //the following uses relection to get android.os.Build.SERIAL to avoid having to build with Gingerbread try { - if (!Build.UNKNOWN.equals(Build.SERIAL)) + if (!Build.UNKNOWN.equals(Build.SERIAL)) { id = Build.SERIAL; + } } catch (Exception e) { // Ah well } @@ -120,13 +121,15 @@ public class GCMIntentService extends GCMBaseIntentService { @Override protected void onMessage(Context context, Intent intent) { if (actFmPreferenceService.isLoggedIn()) { - if (intent.hasExtra("web_update")) - if (DateUtilities.now() - actFmPreferenceService.getLastSyncDate() > MIN_MILLIS_BETWEEN_FULL_SYNCS && !actFmPreferenceService.isOngoing()) + if (intent.hasExtra("web_update")) { + if (DateUtilities.now() - actFmPreferenceService.getLastSyncDate() > MIN_MILLIS_BETWEEN_FULL_SYNCS && !actFmPreferenceService.isOngoing()) { new ActFmSyncV2Provider().synchronizeActiveTasks(false, refreshOnlyCallback); - else + } else { handleWebUpdate(intent); - else + } + } else { handleMessage(intent); + } } } @@ -179,12 +182,14 @@ public class GCMIntentService extends GCMBaseIntentService { private void handleMessage(Intent intent) { String message = intent.getStringExtra("alert"); Context context = ContextManager.getContext(); - if (TextUtils.isEmpty(message)) + if (TextUtils.isEmpty(message)) { return; + } long lastNotification = Preferences.getLong(PREF_LAST_GCM, 0); - if (DateUtilities.now() - lastNotification < 5000L) + if (DateUtilities.now() - lastNotification < 5000L) { return; + } Preferences.setLong(PREF_LAST_GCM, DateUtilities.now()); Intent notifyIntent = null; int notifId; @@ -218,8 +223,9 @@ public class GCMIntentService extends GCMBaseIntentService { return; } - if (notifyIntent == null) + if (notifyIntent == null) { return; + } notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); notifyIntent.putExtra(TaskListActivity.TOKEN_SOURCE, Constants.SOURCE_C2DM); @@ -233,10 +239,11 @@ public class GCMIntentService extends GCMBaseIntentService { Notification notification = new Notification(icon, message, System.currentTimeMillis()); String title; - if (intent.hasExtra("title")) + if (intent.hasExtra("title")) { title = "Astrid: " + intent.getStringExtra("title"); - else + } else { title = ContextManager.getString(R.string.app_name); + } notification.setLatestEventInfo(ContextManager.getContext(), title, message, pendingIntent); notification.flags |= Notification.FLAG_AUTO_CANCEL; @@ -259,20 +266,26 @@ public class GCMIntentService extends GCMBaseIntentService { private int calculateIcon(Intent intent) { if (intent.hasExtra("type")) { String type = intent.getStringExtra("type"); - if ("f".equals(type)) + if ("f".equals(type)) { return R.drawable.notif_c2dm_done; - if ("s".equals(type)) + } + if ("s".equals(type)) { return R.drawable.notif_c2dm_assign; - if ("l".equals(type)) + } + if ("l".equals(type)) { return R.drawable.notif_c2dm_assign; + } } else { String message = intent.getStringExtra("alert"); - if (message.contains(" finished ")) + if (message.contains(" finished ")) { return R.drawable.notif_c2dm_done; - if (message.contains(" invited you to ")) + } + if (message.contains(" invited you to ")) { return R.drawable.notif_c2dm_assign; - if (message.contains(" sent you ")) + } + if (message.contains(" sent you ")) { return R.drawable.notif_c2dm_assign; + } } return R.drawable.notif_c2dm_msg; } @@ -339,8 +352,9 @@ public class GCMIntentService extends GCMBaseIntentService { update.setValue(UserActivity.ACTION, "tag_comment"); update.setValue(UserActivity.TARGET_NAME, intent.getStringExtra("title")); String message = intent.getStringExtra("alert"); - if (message.contains(":")) + if (message.contains(":")) { message = message.substring(message.indexOf(':') + 2); + } update.setValue(UserActivity.MESSAGE, message); update.setValue(UserActivity.CREATED_AT, DateUtilities.now()); update.setValue(UserActivity.TARGET_ID, intent.getStringExtra("tag_id")); @@ -366,14 +380,26 @@ public class GCMIntentService extends GCMBaseIntentService { private boolean shouldLaunchActivity(Intent intent) { if (intent.hasExtra("type")) { String type = intent.getStringExtra("type"); - if ("f".equals(type)) return true; - if ("s".equals(type)) return false; - if ("l".equals(type)) return false; + if ("f".equals(type)) { + return true; + } + if ("s".equals(type)) { + return false; + } + if ("l".equals(type)) { + return false; + } } else { String message = intent.getStringExtra("alert"); - if (message.contains(" finished ")) return true; - if (message.contains(" invited you to ")) return false; - if (message.contains(" sent you ")) return false; + if (message.contains(" finished ")) { + return true; + } + if (message.contains(" invited you to ")) { + return false; + } + if (message.contains(" sent you ")) { + return false; + } } return true; } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmCameraModule.java b/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmCameraModule.java index cb4416b7b..646bf65f6 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmCameraModule.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmCameraModule.java @@ -44,12 +44,14 @@ public class ActFmCameraModule { PackageManager pm = activity.getPackageManager(); final boolean cameraAvailable = pm.queryIntentActivities(cameraIntent, 0).size() > 0; - if (cameraAvailable) + if (cameraAvailable) { options.add(activity.getString(R.string.actfm_picture_camera)); + } options.add(activity.getString(R.string.actfm_picture_gallery)); - if (clearImageOption != null) + if (clearImageOption != null) { options.add(activity.getString(R.string.actfm_picture_clear)); + } ArrayAdapter adapter = new ArrayAdapter(activity, android.R.layout.simple_spinner_dropdown_item, options.toArray(new String[options.size()])); @@ -71,8 +73,9 @@ public class ActFmCameraModule { activity.startActivityForResult(Intent.createChooser(intent, activity.getString(R.string.actfm_TVA_tag_picture)), REQUEST_CODE_PICTURE); } else { - if (clearImageOption != null) + if (clearImageOption != null) { clearImageOption.clearImage(); + } } } }; @@ -90,13 +93,15 @@ public class ActFmCameraModule { final Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); PackageManager pm = fragment.getActivity().getPackageManager(); final boolean cameraAvailable = pm.queryIntentActivities(cameraIntent, 0).size() > 0; - if (cameraAvailable) + if (cameraAvailable) { options.add(fragment.getString(R.string.actfm_picture_camera)); + } options.add(fragment.getString(R.string.actfm_picture_gallery)); - if (clearImageOption != null) + if (clearImageOption != null) { options.add(fragment.getString(R.string.actfm_picture_clear)); + } ArrayAdapter adapter = new ArrayAdapter(fragment.getActivity(), android.R.layout.simple_spinner_dropdown_item, options.toArray(new String[options.size()])); @@ -107,8 +112,9 @@ public class ActFmCameraModule { public void onClick(DialogInterface d, int which) { if (which == 0 && cameraAvailable) { lastTempFile = getTempFile(fragment.getActivity()); - if (lastTempFile != null) + if (lastTempFile != null) { cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(lastTempFile)); + } fragment.startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA); } else if ((which == 1 && cameraAvailable) || (which == 0 && !cameraAvailable)) { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); @@ -116,8 +122,9 @@ public class ActFmCameraModule { fragment.startActivityForResult(Intent.createChooser(intent, fragment.getString(R.string.actfm_TVA_tag_picture)), REQUEST_CODE_PICTURE); } else { - if (clearImageOption != null) + if (clearImageOption != null) { clearImageOption.clearImage(); + } } } }; @@ -173,10 +180,12 @@ public class ActFmCameraModule { bitmap = bitmapFromUri(activity, Uri.fromFile(lastTempFile)); lastTempFile.deleteOnExit(); lastTempFile = null; - } else + } else { bitmap = null; - } else + } + } else { bitmap = data.getParcelableExtra("data"); //$NON-NLS-1$ + } if (bitmap != null) { activity.setResult(Activity.RESULT_OK); cameraResult.handleCameraResult(bitmap); diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmGoogleAuthActivity.java b/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmGoogleAuthActivity.java index 427f4f4f3..38db535ac 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmGoogleAuthActivity.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmGoogleAuthActivity.java @@ -72,8 +72,9 @@ public class ActFmGoogleAuthActivity extends ListActivity { accountManager = new GoogleAccountManager(this); Account[] accounts = accountManager.getAccounts(); ArrayList accountNames = new ArrayList(); - for (Account a : accounts) + for (Account a : accounts) { accountNames.add(a.name); + } nameArray = accountNames.toArray(new String[accountNames.size()]); setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, nameArray)); @@ -132,8 +133,9 @@ public class ActFmGoogleAuthActivity extends ListActivity { } }); } finally { - if (dismissDialog) + if (dismissDialog) { DialogUtilities.dismissDialog(ActFmGoogleAuthActivity.this, pd); + } } } }.start(); diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmLoginActivity.java b/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmLoginActivity.java index 3ea766d00..b43950bdb 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmLoginActivity.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmLoginActivity.java @@ -196,11 +196,13 @@ public class ActFmLoginActivity extends SherlockFragmentActivity { ContextManager.setContext(this); setContentView(getContentViewResource()); - if (getTitleResource() != 0) + if (getTitleResource() != 0) { setTitle(getTitleResource()); + } - if (getSupportActionBar() != null) + if (getSupportActionBar() != null) { getSupportActionBar().hide(); + } rand = new Random(DateUtilities.now()); @@ -298,14 +300,16 @@ public class ActFmLoginActivity extends SherlockFragmentActivity { protected void initializeUI() { errors = (TextView) findViewById(R.id.error); LoginButton loginButton = (LoginButton) findViewById(R.id.fb_login); - if (loginButton == null) + if (loginButton == null) { return; + } loginButton.setReadPermissions(Arrays.asList("email", "offline_access")); View googleLogin = findViewById(R.id.gg_login); - if (AmazonMarketStrategy.isKindleFire()) + if (AmazonMarketStrategy.isKindleFire()) { googleLogin.setVisibility(View.GONE); + } googleLogin.setOnClickListener(googleListener); View fbLogin = findViewById(R.id.fb_login_dummy); @@ -371,8 +375,9 @@ public class ActFmLoginActivity extends SherlockFragmentActivity { getCredentials(new OnGetCredentials() { @Override public void getCredentials(String[] accounts) { - if (accounts != null && accounts.length > 0) + if (accounts != null && accounts.length > 0) { email.setText(accounts[0]); + } } }); @@ -415,8 +420,9 @@ public class ActFmLoginActivity extends SherlockFragmentActivity { getCredentials(new OnGetCredentials() { @Override public void getCredentials(String[] accounts) { - if (accounts != null && accounts.length > 0) + if (accounts != null && accounts.length > 0) { email.setText(accounts[0]); + } } }); @@ -494,8 +500,9 @@ public class ActFmLoginActivity extends SherlockFragmentActivity { char last = 'a'; for (int i = 0; i < chars.length; i++) { char r = acceptable.charAt(rand.nextInt(acceptable.length())); - while (!checkSimilar(last, r)) + while (!checkSimilar(last, r)) { r = acceptable.charAt(rand.nextInt(acceptable.length())); + } last = r; chars[i] = r; } @@ -512,8 +519,9 @@ public class ActFmLoginActivity extends SherlockFragmentActivity { || (oSimilar.indexOf(last) > 0 && oSimilar.indexOf(check) > 0) || (puncSimilar.indexOf(last) > 0 && puncSimilar.indexOf(check) > 0); - if (match) + if (match) { return false; + } return true; } @@ -572,9 +580,10 @@ public class ActFmLoginActivity extends SherlockFragmentActivity { @SuppressWarnings("nls") public void authenticate(final String email, final String firstName, final String lastName, final String provider, final String secret) { - if (progressDialog == null) + if (progressDialog == null) { progressDialog = DialogUtilities.progressDialog(this, getString(R.string.DLG_please_wait)); + } new Thread() { @Override @@ -851,8 +860,9 @@ public class ActFmLoginActivity extends SherlockFragmentActivity { Preferences.setString(ActFmPreferenceService.PREF_PICTURE, result.optString("picture")); - if (!result.optBoolean("new")) + if (!result.optBoolean("new")) { Toast.makeText(this, R.string.actfm_ALA_user_exists_sync_alert, Toast.LENGTH_LONG).show(); + } ActFmPreferenceService.reloadThisUser(); @@ -887,12 +897,13 @@ public class ActFmLoginActivity extends SherlockFragmentActivity { JSONObject result = ae.result; if (result != null && result.has("code")) { String code = result.optString("code"); - if ("user_exists".equals(code)) + if ("user_exists".equals(code)) { message = getString(R.string.actfm_ALA_error_user_exists); - else if ("incorrect_password".equals(code)) + } else if ("incorrect_password".equals(code)) { message = getString(R.string.actfm_ALA_error_wrong_password); - else if ("user_not_found".equals(code) || "missing_param".equals(code)) + } else if ("user_not_found".equals(code) || "missing_param".equals(code)) { message = getString(R.string.actfm_ALA_error_user_not_found); + } } } errors.setText(message); @@ -909,8 +920,9 @@ public class ActFmLoginActivity extends SherlockFragmentActivity { super.onActivityResult(requestCode, resultCode, data); uiHelper.onActivityResult(requestCode, resultCode, data); - if (resultCode == RESULT_CANCELED) + if (resultCode == RESULT_CANCELED) { return; + } if (requestCode == REQUEST_CODE_GOOGLE_ACCOUNTS && data != null && credentialsListener != null) { String accounts[] = data.getStringArrayExtra( @@ -937,8 +949,9 @@ public class ActFmLoginActivity extends SherlockFragmentActivity { // errors.setVisibility(View.GONE); // } else if (requestCode == REQUEST_CODE_GOOGLE) { - if (data == null) + if (data == null) { return; + } String email = data.getStringExtra(ActFmGoogleAuthActivity.RESULT_EMAIL); String token = data.getStringExtra(ActFmGoogleAuthActivity.RESULT_TOKEN); authenticate(email, email, "", "google", token); @@ -953,11 +966,12 @@ public class ActFmLoginActivity extends SherlockFragmentActivity { public void getCredentials(OnGetCredentials onGetCredentials) { credentialsListener = onGetCredentials; - if (Integer.parseInt(Build.VERSION.SDK) >= 7) + if (Integer.parseInt(Build.VERSION.SDK) >= 7) { credentialsListener.getCredentials(ModernAuthManager.getAccounts(this)); - else + } else { GoogleLoginServiceHelper.getAccount(this, REQUEST_CODE_GOOGLE_ACCOUNTS, false); + } } } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmPreferences.java b/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmPreferences.java index f9afeeb6b..afa969cba 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmPreferences.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmPreferences.java @@ -78,9 +78,9 @@ public class ActFmPreferences extends SyncProviderPreferences { PreferenceScreen screen = getPreferenceScreen(); Preference inAppBilling = findPreference(getString(R.string.actfm_inapp_billing)); - if (Constants.ASTRID_LITE || Preferences.getBoolean(PremiumUnlockService.PREF_KILL_SWITCH, false)) + if (Constants.ASTRID_LITE || Preferences.getBoolean(PremiumUnlockService.PREF_KILL_SWITCH, false)) { screen.removePreference(inAppBilling); - else + } else { inAppBilling.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { @@ -88,6 +88,7 @@ public class ActFmPreferences extends SyncProviderPreferences { return true; } }); + } findPreference(getString(R.string.actfm_account_type)).setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override @@ -141,19 +142,22 @@ public class ActFmPreferences extends SyncProviderPreferences { String title = actFmPreferenceService.getLoggedInUserName(); String email = Preferences.getStringValue(ActFmPreferenceService.PREF_EMAIL); if (!TextUtils.isEmpty(email)) { - if (!TextUtils.isEmpty(title)) + if (!TextUtils.isEmpty(title)) { title += "\n"; //$NON-NLS-1$ + } title += email; } status.setTitle(getString(R.string.actfm_status_title_logged_in, title)); - } else + } else { status.setTitle(R.string.sync_SPr_group_status); + } if (r.getString(R.string.actfm_https_key).equals(preference.getKey())) { - if ((Boolean) value) + if ((Boolean) value) { preference.setSummary(R.string.actfm_https_enabled); - else + } else { preference.setSummary(R.string.actfm_https_disabled); + } } else if (r.getString(R.string.actfm_account_type).equals(preference.getKey())) { if (ActFmPreferenceService.isPremiumUser()) { // Premium user diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmSyncActionExposer.java b/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmSyncActionExposer.java index bcbe524f8..fc9207d1f 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmSyncActionExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/ActFmSyncActionExposer.java @@ -36,8 +36,9 @@ public class ActFmSyncActionExposer extends BroadcastReceiver { DependencyInjectionService.getInstance().inject(this); // if we aren't logged in, don't expose sync action - if (!actFmPreferenceService.isLoggedIn()) + if (!actFmPreferenceService.isLoggedIn()) { return; + } SyncAction syncAction = new SyncAction(context.getString(R.string.actfm_APr_header), null); diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/CommentsFragment.java b/astrid/plugin-src/com/todoroo/astrid/actfm/CommentsFragment.java index 939fc9200..5f53927de 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/CommentsFragment.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/CommentsFragment.java @@ -217,10 +217,11 @@ public abstract class CommentsFragment extends SherlockListFragment { pictureButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - if (picture != null) + if (picture != null) { ActFmCameraModule.showPictureLauncher(CommentsFragment.this, clearImage); - else + } else { ActFmCameraModule.showPictureLauncher(CommentsFragment.this, null); + } } }); @@ -235,8 +236,9 @@ public abstract class CommentsFragment extends SherlockListFragment { protected void refreshUpdatesList() { Activity activity = getActivity(); View view = getView(); - if (activity == null || view == null) + if (activity == null || view == null) { return; + } Cursor cursor = null; ListView listView = ((ListView) view.findViewById(android.R.id.list)); @@ -287,8 +289,9 @@ public abstract class CommentsFragment extends SherlockListFragment { listView.setVisibility(View.VISIBLE); } - if (activity instanceof CommentsActivity) + if (activity instanceof CommentsActivity) { setLastViewed(); + } } @@ -305,8 +308,9 @@ public abstract class CommentsFragment extends SherlockListFragment { int historyCount = 0; Cursor c = updateAdapter.getCursor(); for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { - if (NameMaps.TABLE_ID_HISTORY.equals(c.getString(UpdateAdapter.TYPE_PROPERTY_INDEX))) + if (NameMaps.TABLE_ID_HISTORY.equals(c.getString(UpdateAdapter.TYPE_PROPERTY_INDEX))) { historyCount++; + } } loadMoreHistory(historyCount, doneRunnable); } @@ -327,7 +331,7 @@ public abstract class CommentsFragment extends SherlockListFragment { public void runOnSuccess() { synchronized (this) { Activity activity = getActivity(); - if (activity != null) + if (activity != null) { activity.runOnUiThread(new Runnable() { @Override public void run() { @@ -335,6 +339,7 @@ public abstract class CommentsFragment extends SherlockListFragment { refreshUpdatesList(); } }); + } } } @@ -354,8 +359,9 @@ public abstract class CommentsFragment extends SherlockListFragment { @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - if (menu.size() > 0) + if (menu.size() > 0) { return; + } MenuItem item; boolean showCommentsRefresh = actFmPreferenceService.isLoggedIn(); diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/EditPeopleControlSet.java b/astrid/plugin-src/com/todoroo/astrid/actfm/EditPeopleControlSet.java index d4bf272d7..9c873f9a1 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/EditPeopleControlSet.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/EditPeopleControlSet.java @@ -164,8 +164,9 @@ public class EditPeopleControlSet extends PopupControlSet { @Override public void readFromTask(Task sourceTask) { setTask(sourceTask); - if (!dontClearAssignedCustom) + if (!dontClearAssignedCustom) { assignedCustom.setText(""); //$NON-NLS-1$ + } dontClearAssignedCustom = false; setUpData(task, null); } @@ -303,8 +304,9 @@ public class EditPeopleControlSet extends PopupControlSet { .put(CONTACT_CHOOSER_USER, true)); int contactsIndex = addUnassigned ? 2 : 1; boolean addContactPicker = Preferences.getBoolean(R.string.p_use_contact_picker, true) && contactPickerAvailable(); - if (addContactPicker) + if (addContactPicker) { coreUsers.add(contactsIndex, contactPickerUser); + } if (assignedIndex == 0) { assignedIndex = findAssignedIndex(t, coreUsers, listUsers, astridUsers); @@ -354,8 +356,9 @@ public class EditPeopleControlSet extends PopupControlSet { return Long.toString(value); } catch (JSONException e) { String value = obj.optString("id"); //$NON-NLS-1$ - if (TextUtils.isEmpty(value)) + if (TextUtils.isEmpty(value)) { value = defaultValue; + } return value; } } @@ -366,23 +369,28 @@ public class EditPeopleControlSet extends PopupControlSet { ArrayList users = new ArrayList(); for (int i = 0; i < jsonUsers.size(); i++) { JSONObject person = jsonUsers.get(i); - if (person == null) + if (person == null) { continue; + } String id = getLongOrStringId(person, Task.USER_ID_EMAIL); - if (ActFmPreferenceService.userId().equals(id) || ((Task.USER_ID_UNASSIGNED.equals(id) || Task.isRealUserId(id)) && userIds.contains(id))) + if (ActFmPreferenceService.userId().equals(id) || ((Task.USER_ID_UNASSIGNED.equals(id) || Task.isRealUserId(id)) && userIds.contains(id))) { continue; + } userIds.add(id); String email = person.optString("email"); - if (!TextUtils.isEmpty(email) && emails.contains(email)) + if (!TextUtils.isEmpty(email) && emails.contains(email)) { continue; + } emails.add(email); String name = person.optString("name"); - if (Task.USER_ID_SELF.equals(id)) + if (Task.USER_ID_SELF.equals(id)) { name = activity.getString(R.string.actfm_EPA_assign_me); - if (Task.USER_ID_UNASSIGNED.equals(id)) + } + if (Task.USER_ID_UNASSIGNED.equals(id)) { name = activity.getString(R.string.actfm_EPA_unassigned); + } AssignedToUser atu = new AssignedToUser(name, person); users.add(atu); @@ -392,15 +400,18 @@ public class EditPeopleControlSet extends PopupControlSet { user.label += " (" + user.user.optString("email") + ")"; names.put(name, null); } - if (!TextUtils.isEmpty(email)) + if (!TextUtils.isEmpty(email)) { atu.label += " (" + email + ")"; + } } else if (TextUtils.isEmpty(name) || "null".equals(name)) { - if (!TextUtils.isEmpty(email)) + if (!TextUtils.isEmpty(email)) { atu.label = email; - else + } else { users.remove(atu); - } else + } + } else { names.put(name, atu); + } } return users; } @@ -445,8 +456,9 @@ public class EditPeopleControlSet extends PopupControlSet { } if (getLongOrStringId(user, Task.USER_ID_EMAIL).equals(assignedId) || (user.optString("email").equals(assignedEmail) && - !(TextUtils.isEmpty(assignedEmail)))) + !(TextUtils.isEmpty(assignedEmail)))) { return index; + } } index++; } @@ -490,8 +502,9 @@ public class EditPeopleControlSet extends PopupControlSet { @SuppressWarnings("nls") @Override public View getView(int position, View convertView, ViewGroup parent) { - if (convertView == null) + if (convertView == null) { convertView = activity.getLayoutInflater().inflate(R.layout.assigned_adapter_row, parent, false); + } CheckedTextView ctv = (CheckedTextView) convertView.findViewById(android.R.id.text1); super.getView(position, ctv, parent); if (assignedList.getCheckedItemPosition() == position + positionOffset) { @@ -581,8 +594,9 @@ public class EditPeopleControlSet extends PopupControlSet { @Override public String writeToModel(Task t) { - if (initialized && dialog != null) + if (initialized && dialog != null) { dialog.dismiss(); + } // do nothing else, we use a separate method return null; } @@ -610,8 +624,9 @@ public class EditPeopleControlSet extends PopupControlSet { */ @SuppressWarnings("nls") public boolean saveSharingSettings(String toast) { - if (task == null) + if (task == null) { return false; + } boolean dirty = false; try { @@ -621,8 +636,9 @@ public class EditPeopleControlSet extends PopupControlSet { userJson = PeopleContainer.createUserJson(assignedCustom); assignedView = assignedCustom; } else { - if (!loadedUI || assignedList.getCheckedItemPosition() == ListView.INVALID_POSITION) + if (!loadedUI || assignedList.getCheckedItemPosition() == ListView.INVALID_POSITION) { return true; + } AssignedToUser item = (AssignedToUser) assignedList.getAdapter().getItem(assignedList.getCheckedItemPosition()); if (item != null) { if (item.equals(contactPickerUser)) { //don't want to ever set the user as the fake contact picker user @@ -634,9 +650,10 @@ public class EditPeopleControlSet extends PopupControlSet { if (userJson != null) { String email = userJson.optString("email"); - if (!TextUtils.isEmpty(email) && email.indexOf('@') == -1) + if (!TextUtils.isEmpty(email) && email.indexOf('@') == -1) { throw new ParseSharedException(assignedView, activity.getString(R.string.actfm_EPA_invalid_email, userJson.optString("email"))); + } } if (userJson == null || Task.USER_ID_SELF.equals(getLongOrStringId(userJson, Task.USER_ID_EMAIL))) { @@ -659,8 +676,9 @@ public class EditPeopleControlSet extends PopupControlSet { } catch (JSONException e) { // sad times taskUserId = task.getValue(Task.USER_ID); - if (Task.userIdIsEmail(taskUserId)) + if (Task.userIdIsEmail(taskUserId)) { taskUserEmail = taskUserId; + } } String userId = getLongOrStringId(userJson, Task.USER_ID_EMAIL); String userEmail = userJson.optString("email"); @@ -671,8 +689,9 @@ public class EditPeopleControlSet extends PopupControlSet { dirty = match ? dirty : true; String willAssignToId = getLongOrStringId(userJson, Task.USER_ID_EMAIL); task.setValue(Task.USER_ID, willAssignToId); - if (Task.USER_ID_EMAIL.equals(task.getValue(Task.USER_ID))) + if (Task.USER_ID_EMAIL.equals(task.getValue(Task.USER_ID))) { task.setValue(Task.USER_ID, userEmail); + } task.setValue(Task.USER, ""); } @@ -702,10 +721,11 @@ public class EditPeopleControlSet extends PopupControlSet { task.putTransitory(TaskService.TRANS_ASSIGNED, true); - if (assignedView == assignedCustom) + if (assignedView == assignedCustom) { StatisticsService.reportEvent(StatisticsConstants.TASK_ASSIGNED_EMAIL); - else if (task.getValue(Task.USER_ID) != Task.USER_ID_SELF) + } else if (task.getValue(Task.USER_ID) != Task.USER_ID_SELF) { StatisticsService.reportEvent(StatisticsConstants.TASK_ASSIGNED_PICKER); + } return true; } catch (ParseSharedException e) { @@ -740,14 +760,16 @@ public class EditPeopleControlSet extends PopupControlSet { userJson = PeopleContainer.createUserJson(assignedCustom); } else { if (!hasLoadedUI() || assignedList.getCheckedItemPosition() == ListView.INVALID_POSITION) { - if (task != null) + if (task != null) { return task.getValue(Task.USER_ID) == Task.USER_ID_SELF; - else + } else { return true; + } } AssignedToUser item = (AssignedToUser) assignedList.getAdapter().getItem(assignedList.getCheckedItemPosition()); - if (item != null) + if (item != null) { userJson = item.user; + } } if (userJson == null || Task.USER_ID_SELF.equals(getLongOrStringId(userJson, Task.USER_ID_EMAIL))) { @@ -800,8 +822,9 @@ public class EditPeopleControlSet extends PopupControlSet { assignedCustom.setText(email); dontClearAssignedCustom = true; refreshDisplayView(); - if (dialog != null) + if (dialog != null) { dialog.dismiss(); + } } else { DialogUtilities.okDialog(activity, activity.getString(R.string.TEA_contact_error), null); } @@ -819,8 +842,9 @@ public class EditPeopleControlSet extends PopupControlSet { displayString = activity.getString(R.string.TEA_assigned_to, assignedCustom.getText()); } else { AssignedToUser user = (AssignedToUser) assignedList.getAdapter().getItem(assignedList.getCheckedItemPosition()); - if (user == null) + if (user == null) { user = (AssignedToUser) assignedList.getAdapter().getItem(0); + } String id = getLongOrStringId(user.user, Task.USER_ID_IGNORE); if (Task.USER_ID_UNASSIGNED.equals(id)) { @@ -828,8 +852,9 @@ public class EditPeopleControlSet extends PopupControlSet { displayString = activity.getString(R.string.actfm_EPA_unassigned); } else { String userString = user.toString(); - if (Task.USER_ID_SELF.equals(id)) + if (Task.USER_ID_SELF.equals(id)) { userString = userString.toLowerCase(); + } displayString = activity.getString(R.string.TEA_assigned_to, userString); } @@ -838,10 +863,11 @@ public class EditPeopleControlSet extends PopupControlSet { assignedDisplay.setTextColor(unassigned ? unsetColor : themeColor); assignedDisplay.setText(displayString); - if (unassigned) + if (unassigned) { image.setImageResource(R.drawable.tea_icn_assign_gray); - else + } else { image.setImageResource(ThemeService.getTaskEditDrawable(R.drawable.tea_icn_assign, R.drawable.tea_icn_assign_lightblue)); + } } @Override diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/TagCommentsFragment.java b/astrid/plugin-src/com/todoroo/astrid/actfm/TagCommentsFragment.java index 5ed009453..8987bf146 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/TagCommentsFragment.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/TagCommentsFragment.java @@ -66,8 +66,9 @@ public class TagCommentsFragment extends CommentsFragment { protected void loadModelFromIntent(Intent intent) { if (tagData == null) { long id = intent.getLongExtra(TagViewFragment.EXTRA_TAG_DATA, 0); - if (id > 0) + if (id > 0) { tagData = tagDataService.fetchById(id, TagData.PROPERTIES); + } } } @@ -120,7 +121,9 @@ public class TagCommentsFragment extends CommentsFragment { @Override protected void populateListHeader(ViewGroup header) { - if (header == null) return; + if (header == null) { + return; + } TextView tagTitle = (TextView) header.findViewById(R.id.tag_title); String tagName = tagData.getValue(TagData.NAME); tagTitle.setText(tagName); @@ -138,12 +141,14 @@ public class TagCommentsFragment extends CommentsFragment { imageView.setDefaultImageDrawable(ResourceDrawableCache.getImageDrawableFromId(getResources(), TagService.getDefaultImageIDForTag(tagData.getUuid()))); String imageUrl = tagData.getPictureUrl(TagData.PICTURE, RemoteModel.PICTURE_MEDIUM); Bitmap imageBitmap = null; - if (TextUtils.isEmpty(imageUrl)) + if (TextUtils.isEmpty(imageUrl)) { imageBitmap = tagData.getPictureBitmap(TagData.PICTURE); - if (imageBitmap != null) + } + if (imageBitmap != null) { imageView.setImageBitmap(imageBitmap); - else + } else { imageView.setUrl(imageUrl); + } } @Override @@ -177,8 +182,9 @@ public class TagCommentsFragment extends CommentsFragment { if (tagData != null && RemoteModel.isValidUuid(tagData.getValue(TagData.UUID))) { Preferences.setLong(UPDATES_LAST_VIEWED + tagData.getValue(TagData.UUID), DateUtilities.now()); Activity activity = getActivity(); - if (activity instanceof TaskListActivity) + if (activity instanceof TaskListActivity) { ((TaskListActivity) activity).setCommentsCount(0); + } } } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/TagSettingsActivity.java b/astrid/plugin-src/com/todoroo/astrid/actfm/TagSettingsActivity.java index cc9ffe0e4..8ce570ae2 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/TagSettingsActivity.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/TagSettingsActivity.java @@ -141,10 +141,11 @@ public class TagSettingsActivity extends SherlockFragmentActivity { params.height = LayoutParams.WRAP_CONTENT; DisplayMetrics metrics = getResources().getDisplayMetrics(); - if ((metrics.widthPixels / metrics.density) >= AndroidUtilities.MIN_TABLET_HEIGHT) + if ((metrics.widthPixels / metrics.density) >= AndroidUtilities.MIN_TABLET_HEIGHT) { params.width = (3 * metrics.widthPixels) / 5; - else if ((metrics.widthPixels / metrics.density) >= AndroidUtilities.MIN_TABLET_WIDTH) + } else if ((metrics.widthPixels / metrics.density) >= AndroidUtilities.MIN_TABLET_WIDTH) { params.width = (4 * metrics.widthPixels) / 5; + } getWindow().setAttributes((android.view.WindowManager.LayoutParams) params); } @@ -188,16 +189,18 @@ public class TagSettingsActivity extends SherlockFragmentActivity { isDialog = AstridPreferences.useTabletLayout(this); if (isDialog) { setTheme(ThemeService.getDialogTheme()); - if (AndroidUtilities.getSdkVersion() < 14) + if (AndroidUtilities.getSdkVersion() < 14) { requestWindowFeature(Window.FEATURE_NO_TITLE); + } } else { ThemeService.applyTheme(this); ActionBar actionBar = getSupportActionBar(); if (Preferences.getBoolean(R.string.p_save_and_cancel, false)) { - if (ThemeService.getTheme() == R.style.Theme_White_Alt) + if (ThemeService.getTheme() == R.style.Theme_White_Alt) { actionBar.setLogo(R.drawable.ic_menu_save_blue_alt); - else + } else { actionBar.setLogo(R.drawable.ic_menu_save); + } } else { actionBar.setLogo(null); } @@ -324,8 +327,9 @@ public class TagSettingsActivity extends SherlockFragmentActivity { if (setBitmap != null) { JSONObject pictureJson = RemoteModel.PictureHelper.savePictureJson(this, setBitmap); - if (pictureJson != null) + if (pictureJson != null) { tagData.setValue(TagData.PICTURE, pictureJson.toString()); + } } JSONArray members; @@ -342,8 +346,9 @@ public class TagSettingsActivity extends SherlockFragmentActivity { DialogUtilities.okDialog(this, e.message, null); return; } - if (members == null) + if (members == null) { members = new JSONArray(); + } if (members.length() > 0 && !actFmPreferenceService.isLoggedIn()) { if (newName.length() > 0 && oldName.length() == 0) { @@ -400,7 +405,9 @@ public class TagSettingsActivity extends SherlockFragmentActivity { } private void saveTagPictureLocally(Bitmap bitmap) { - if (bitmap == null) return; + if (bitmap == null) { + return; + } try { String tagPicture = RemoteModel.PictureHelper.getPictureHash(tagData); imageCache.put(tagPicture, bitmap); @@ -443,13 +450,15 @@ public class TagSettingsActivity extends SherlockFragmentActivity { String imageUrl = tagData.getPictureUrl(TagData.PICTURE, RemoteModel.PICTURE_MEDIUM); Bitmap imageBitmap = null; - if (TextUtils.isEmpty(imageUrl)) + if (TextUtils.isEmpty(imageUrl)) { imageBitmap = tagData.getPictureBitmap(TagData.PICTURE); + } - if (imageBitmap != null) + if (imageBitmap != null) { picture.setImageBitmap(imageBitmap); - else + } else { picture.setUrl(imageUrl); + } if (!isNewTag) { ImageView shortcut = (ImageView) findViewById(R.id.create_shortcut); shortcut.setImageBitmap(FilterListFragment.superImposeListIcon(this, picture.getImageBitmap(), tagData.getUuid())); @@ -604,22 +613,25 @@ public class TagSettingsActivity extends SherlockFragmentActivity { break; case android.R.id.home: saveSettings(); - if (!isFinishing()) + if (!isFinishing()) { finish(); + } break; } return super.onOptionsItemSelected(item); } protected void showDeleteDialog(TagData td) { - if (td == null) + if (td == null) { return; + } int string; - if (td.getValue(TagData.MEMBER_COUNT) > 0) + if (td.getValue(TagData.MEMBER_COUNT) > 0) { string = R.string.DLG_leave_this_shared_tag_question; - else + } else { string = R.string.DLG_delete_this_tag_question; + } DialogUtilities.okCancelDialog(this, getString(string, td.getValue(TagData.NAME)), diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/TagViewFragment.java b/astrid/plugin-src/com/todoroo/astrid/actfm/TagViewFragment.java index 25e3157d2..21969bed5 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/TagViewFragment.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/TagViewFragment.java @@ -174,8 +174,9 @@ public class TagViewFragment extends TaskListFragment { ((EditText) getView().findViewById(R.id.quickAddText)).setOnTouchListener(onTouch); View membersEdit = getView().findViewById(R.id.members_edit); - if (membersEdit != null) + if (membersEdit != null) { membersEdit.setOnClickListener(settingsListener); + } originalFilter = filter; } @@ -213,14 +214,16 @@ public class TagViewFragment extends TaskListFragment { } private void showListSettingsPopover() { - if (!AstridPreferences.canShowPopover()) + if (!AstridPreferences.canShowPopover()) { return; + } if (!Preferences.getBoolean(R.string.p_showed_list_settings_help, false)) { Preferences.setBoolean(R.string.p_showed_list_settings_help, true); View tabView = getView().findViewById(R.id.members_edit); - if (tabView != null) + if (tabView != null) { HelpInfoPopover.showPopover(getActivity(), tabView, R.string.help_popover_list_settings, null); + } } } @@ -249,22 +252,26 @@ public class TagViewFragment extends TaskListFragment { @Override protected void initializeData() { synchronized (this) { - if (dataLoaded) + if (dataLoaded) { return; + } dataLoaded = true; } TaskListActivity activity = (TaskListActivity) getActivity(); String tag = extras.getString(EXTRA_TAG_NAME); String uuid = RemoteModel.NO_UUID; - if (extras.containsKey(EXTRA_TAG_UUID)) + if (extras.containsKey(EXTRA_TAG_UUID)) { uuid = extras.getString(EXTRA_TAG_UUID); - else if (extras.containsKey(EXTRA_TAG_REMOTE_ID)) // For legacy support with shortcuts, widgets, etc. + } else if (extras.containsKey(EXTRA_TAG_REMOTE_ID)) // For legacy support with shortcuts, widgets, etc. + { uuid = Long.toString(extras.getLong(EXTRA_TAG_REMOTE_ID)); + } - if (tag == null && RemoteModel.NO_UUID.equals(uuid)) + if (tag == null && RemoteModel.NO_UUID.equals(uuid)) { return; + } TodorooCursor cursor; if (!RemoteModel.isUuidEmpty(uuid)) { @@ -305,8 +312,9 @@ public class TagViewFragment extends TaskListFragment { @Override public void loadTaskListContent(boolean requery) { super.loadTaskListContent(requery); - if (taskAdapter == null || taskAdapter.getCursor() == null) + if (taskAdapter == null || taskAdapter.getCursor() == null) { return; + } int count = taskAdapter.getCursor().getCount(); @@ -336,8 +344,9 @@ public class TagViewFragment extends TaskListFragment { } TaskListActivity tla = (TaskListActivity) getActivity(); - if (tla != null) + if (tla != null) { tla.setCommentsCount(unreadCount); + } } } @@ -346,8 +355,9 @@ public class TagViewFragment extends TaskListFragment { @Override protected void initiateAutomaticSyncImpl() { - if (!isCurrentTaskListFragment()) + if (!isCurrentTaskListFragment()) { return; + } if (tagData != null) { long lastAutosync = tagData.getValue(TagData.LAST_AUTOSYNC); if (DateUtilities.now() - lastAutosync > AUTOSYNC_INTERVAL) { @@ -478,8 +488,9 @@ public class TagViewFragment extends TaskListFragment { getView().findViewById(R.id.members_header).setVisibility(View.GONE); return; } - if (tagData == null) + if (tagData == null) { return; + } LinearLayout membersView = (LinearLayout) getView().findViewById(R.id.shared_with); membersView.setOnClickListener(settingsListener); boolean addedMembers = false; @@ -567,8 +578,9 @@ public class TagViewFragment extends TaskListFragment { } else { owner = ActFmPreferenceService.thisUser(); } - if (owner != null) + if (owner != null) { addImageForMember(membersView, owner); + } JSONObject unassigned = new JSONObject(); unassigned.put("id", Task.USER_ID_UNASSIGNED); //$NON-NLS-1$ @@ -585,13 +597,14 @@ public class TagViewFragment extends TaskListFragment { } View filterAssigned = getView().findViewById(R.id.filter_assigned); - if (filterAssigned != null) + if (filterAssigned != null) { filterAssigned.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { resetAssignedFilter(); } }); + } } @SuppressWarnings("nls") @@ -604,14 +617,16 @@ public class TagViewFragment extends TaskListFragment { image.setDefaultImageDrawable(ResourceDrawableCache.getImageDrawableFromId(resources, R.drawable.icn_default_person_image)); - if (Task.USER_ID_UNASSIGNED.equals(Long.toString(member.optLong("id", 0)))) + if (Task.USER_ID_UNASSIGNED.equals(Long.toString(member.optLong("id", 0)))) { image.setDefaultImageDrawable(ResourceDrawableCache.getImageDrawableFromId(resources, R.drawable.icn_anyone)); + } image.setScaleType(ImageView.ScaleType.FIT_CENTER); try { final String id = Long.toString(member.optLong("id", -2)); - if (ActFmPreferenceService.userId().equals(id)) + if (ActFmPreferenceService.userId().equals(id)) { member = ActFmPreferenceService.thisUser(); + } final JSONObject memberToUse = member; final String memberName = displayName(memberToUse); @@ -641,21 +656,23 @@ public class TagViewFragment extends TaskListFragment { // New filter currentId = id; Criterion assignedCriterion; - if (ActFmPreferenceService.userId().equals(currentId)) + if (ActFmPreferenceService.userId().equals(currentId)) { assignedCriterion = Criterion.or(Task.USER_ID.eq(0), Task.USER_ID.eq(id)); - else if (Task.userIdIsEmail(currentId) && !TextUtils.isEmpty(email)) + } else if (Task.userIdIsEmail(currentId) && !TextUtils.isEmpty(email)) { assignedCriterion = Criterion.or(Task.USER_ID.eq(email), Task.USER.like("%" + email + "%")); //$NON-NLS-1$ //$NON-NLS-2$ // Deprecated field OK for backwards compatibility - else + } else { assignedCriterion = Task.USER_ID.eq(id); + } Criterion assigned = Criterion.and(TaskCriteria.activeAndVisible(), assignedCriterion); filter = TagFilterExposer.filterFromTag(getActivity(), new Tag(tagData), assigned); TextView filterByAssigned = (TextView) getView().findViewById(R.id.filter_assigned); if (filterByAssigned != null) { filterByAssigned.setVisibility(View.VISIBLE); - if (id == Task.USER_ID_UNASSIGNED) + if (id == Task.USER_ID_UNASSIGNED) { filterByAssigned.setText(getString(R.string.actfm_TVA_filter_by_unassigned)); - else + } else { filterByAssigned.setText(getString(R.string.actfm_TVA_filtered_by_assign, displayName)); + } } isBeingFiltered.set(true); setUpTaskList(); @@ -669,8 +686,9 @@ public class TagViewFragment extends TaskListFragment { isBeingFiltered.set(false); filter = originalFilter; View filterAssigned = getView().findViewById(R.id.filter_assigned); - if (filterAssigned != null) + if (filterAssigned != null) { filterAssigned.setVisibility(View.GONE); + } setUpTaskList(); } @@ -703,10 +721,12 @@ public class TagViewFragment extends TaskListFragment { @SuppressWarnings("nls") @Override public void onReceive(Context context, Intent intent) { - if (!intent.hasExtra("tag_id")) + if (!intent.hasExtra("tag_id")) { return; - if (tagData == null || !tagData.getValue(TagData.UUID).toString().equals(intent.getStringExtra("tag_id"))) + } + if (tagData == null || !tagData.getValue(TagData.UUID).toString().equals(intent.getStringExtra("tag_id"))) { return; + } getActivity().runOnUiThread(new Runnable() { @Override @@ -775,10 +795,11 @@ public class TagViewFragment extends TaskListFragment { ((TaskListActivity) activity).setListsTitle(filter.title); FilterListFragment flf = ((TaskListActivity) activity).getFilterListFragment(); if (flf != null) { - if (!onActivityResult) + if (!onActivityResult) { flf.refresh(); - else + } else { flf.clear(); + } } } taskAdapter = null; @@ -818,9 +839,9 @@ public class TagViewFragment extends TaskListFragment { protected void toggleDragDrop(boolean newState) { Class customComponent; - if (newState) + if (newState) { customComponent = SubtasksTagListFragment.class; - else { + } else { filter.setFilterQueryOverride(null); customComponent = TagViewFragment.class; } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/WaitingOnMeFragment.java b/astrid/plugin-src/com/todoroo/astrid/actfm/WaitingOnMeFragment.java index 3ea74d394..e82257030 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/WaitingOnMeFragment.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/WaitingOnMeFragment.java @@ -42,8 +42,9 @@ public class WaitingOnMeFragment extends TaskListFragment { new OnCompletedTaskListener() { @Override public void onCompletedTask(Task item, boolean newState) { - if (newState == true) + if (newState == true) { onTaskCompleted(item); + } } }); } @@ -61,10 +62,11 @@ public class WaitingOnMeFragment extends TaskListFragment { super.setTaskAppearance(viewHolder, task); TextView nameView = viewHolder.nameView; - if (task.getValue(WaitingOnMe.READ_AT) == 0 && task.getValue(WaitingOnMe.ACKNOWLEDGED) == 0) + if (task.getValue(WaitingOnMe.READ_AT) == 0 && task.getValue(WaitingOnMe.ACKNOWLEDGED) == 0) { nameView.setTypeface(null, Typeface.BOLD); - else + } else { nameView.setTypeface(null, 0); + } } } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmInvoker.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmInvoker.java index 95804a0e7..196329a0f 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmInvoker.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmInvoker.java @@ -132,16 +132,19 @@ public class ActFmInvoker { try { String request = createFetchUrl(api, method, getParameters); - if (SYNC_DEBUG) + if (SYNC_DEBUG) { Log.e("act-fm-invoke", request); + } String response = restClient.get(request); JSONObject object = new JSONObject(response); - if (SYNC_DEBUG) + if (SYNC_DEBUG) { AndroidUtilities.logJSONObject("act-fm-invoke-response", object); - if (object.getString("status").equals("error")) + } + if (object.getString("status").equals("error")) { throw new ActFmServiceException(object.getString("message"), object); + } return object; } catch (JSONException e) { throw new IOException(e.getMessage()); @@ -163,17 +166,20 @@ public class ActFmInvoker { try { String request = createFetchUrl(null, method, getParameters); - if (SYNC_DEBUG) + if (SYNC_DEBUG) { Log.e("act-fm-post", request); + } String response = restClient.post(request, data); JSONObject object = new JSONObject(response); - if (SYNC_DEBUG) + if (SYNC_DEBUG) { AndroidUtilities.logJSONObject("act-fm-post-response", object); + } - if (object.getString("status").equals("error")) + if (object.getString("status").equals("error")) { throw new ActFmServiceException(object.getString("message"), object); + } return object; } catch (JSONException e) { throw new IOException(e.getMessage()); @@ -199,8 +205,9 @@ public class ActFmInvoker { } String request = createFetchUrl("api/" + API_VERSION, "synchronize", params); - if (SYNC_DEBUG) + if (SYNC_DEBUG) { Log.e("act-fm-post", request); + } Charset chars; try { chars = Charset.forName("UTF-8"); @@ -215,11 +222,13 @@ public class ActFmInvoker { String response = restClient.post(request, entity); JSONObject object = new JSONObject(response); - if (SYNC_DEBUG) + if (SYNC_DEBUG) { AndroidUtilities.logJSONObject("act-fm-post-response", object); + } - if (object.getString("status").equals("error")) + if (object.getString("status").equals("error")) { throw new ActFmServiceException(object.getString("message"), object); + } return object; } catch (JSONException e) { throw new IOException(e.getMessage()); @@ -242,17 +251,20 @@ public class ActFmInvoker { for (int i = 0; i < getParameters.length; i += 2) { if (getParameters[i + 1] instanceof ArrayList) { ArrayList list = (ArrayList) getParameters[i + 1]; - for (int j = 0; j < list.size(); j++) + for (int j = 0; j < list.size(); j++) { params.add(new Pair(getParameters[i].toString() + "[]", list.get(j))); - } else + } + } else { params.add(new Pair(getParameters[i].toString(), getParameters[i + 1])); + } } params.add(new Pair("app_id", APP_ID)); boolean syncMethod = "synchronize".equals(method); - if (!syncMethod) + if (!syncMethod) { params.add(new Pair("time", System.currentTimeMillis() / 1000L)); + } if (token != null) { boolean foundTokenKey = false; for (Pair curr : params) { @@ -261,8 +273,9 @@ public class ActFmInvoker { break; } } - if (!foundTokenKey) + if (!foundTokenKey) { params.add(new Pair("token", token)); + } } Collections.sort(params, new Comparator>() { @@ -270,8 +283,9 @@ public class ActFmInvoker { public int compare(Pair object1, Pair object2) { int result = object1.getLeft().compareTo(object2.getLeft()); - if (result == 0) + if (result == 0) { return object1.getRight().toString().compareTo(object2.getRight().toString()); + } return result; } }); @@ -282,26 +296,30 @@ public class ActFmInvoker { customApi = true; url = url.replace("api", api); } - if (Preferences.getBoolean(R.string.actfm_https_key, false)) + if (Preferences.getBoolean(R.string.actfm_https_key, false)) { url = "https:" + url; - else + } else { url = "http:" + url; + } StringBuilder requestBuilder = new StringBuilder(url); - if (!customApi) + if (!customApi) { requestBuilder.append(API_VERSION).append("/"); + } requestBuilder.append(method).append('?'); StringBuilder sigBuilder = new StringBuilder(method); for (Pair entry : params) { - if (entry.getRight() == null) + if (entry.getRight() == null) { continue; + } String key = entry.getLeft(); String value = entry.getRight().toString(); String encoded = URLEncoder.encode(value, "UTF-8"); - if (!syncMethod || "app_id".equals(key)) + if (!syncMethod || "app_id".equals(key)) { requestBuilder.append(key).append('=').append(encoded).append('&'); + } sigBuilder.append(key).append(value); } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmPreferenceService.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmPreferenceService.java index 1b8c581ff..1dcfdd377 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmPreferenceService.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmPreferenceService.java @@ -51,8 +51,9 @@ public class ActFmPreferenceService extends SyncProviderUtilities { @Override public boolean shouldShowToast() { - if (Preferences.getBoolean(AstridPreferences.P_FIRST_TASK, true)) + if (Preferences.getBoolean(AstridPreferences.P_FIRST_TASK, true)) { return false; + } return super.shouldShowToast(); } @@ -61,10 +62,11 @@ public class ActFmPreferenceService extends SyncProviderUtilities { @Override public void setToken(String setting) { super.setToken(setting); - if (TextUtils.isEmpty(setting)) + if (TextUtils.isEmpty(setting)) { RemoteModelDao.setOutstandingEntryFlags(RemoteModelDao.OUTSTANDING_FLAG_UNINITIALIZED); - else + } else { RemoteModelDao.setOutstandingEntryFlags(RemoteModelDao.OUTSTANDING_ENTRY_FLAG_ENQUEUE_MESSAGES | RemoteModelDao.OUTSTANDING_ENTRY_FLAG_RECORD_OUTSTANDING); + } } /** @@ -80,8 +82,9 @@ public class ActFmPreferenceService extends SyncProviderUtilities { public static String userId() { try { String value = Preferences.getStringValue(PREF_USER_ID); - if (value == null) + if (value == null) { return Long.toString(Preferences.getLong(PREF_USER_ID, -2L)); + } return value; } catch (Exception e) { return Long.toString(Preferences.getLong(PREF_USER_ID, -2L)); @@ -149,8 +152,9 @@ public class ActFmPreferenceService extends SyncProviderUtilities { } public synchronized static void reloadThisUser() { - if (user == null) + if (user == null) { return; + } populateUser(); } @@ -170,8 +174,9 @@ public class ActFmPreferenceService extends SyncProviderUtilities { } public static boolean isPremiumUser() { - if (Preferences.getBoolean(PremiumUnlockService.PREF_KILL_SWITCH, false)) + if (Preferences.getBoolean(PremiumUnlockService.PREF_KILL_SWITCH, false)) { return true; + } if (Preferences.getBoolean(BillingConstants.PREF_NEEDS_SERVER_UPDATE, false)) { return Preferences.getBoolean(PREF_LOCAL_PREMIUM, false); @@ -190,18 +195,21 @@ public class ActFmPreferenceService extends SyncProviderUtilities { String name = Preferences.getStringValue(PREF_NAME); if (TextUtils.isEmpty(name)) { String firstName = Preferences.getStringValue(PREF_FIRST_NAME); - if (!TextUtils.isEmpty(firstName)) + if (!TextUtils.isEmpty(firstName)) { name = firstName; + } String lastName = Preferences.getStringValue(PREF_FIRST_NAME); if (!TextUtils.isEmpty(lastName)) { - if (!TextUtils.isEmpty(name)) + if (!TextUtils.isEmpty(name)) { name += " "; //$NON-NLS-1$ + } name += lastName; } - if (name == null) + if (name == null) { name = ""; //$NON-NLS-1$ + } } return name; } @@ -211,19 +219,23 @@ public class ActFmPreferenceService extends SyncProviderUtilities { JSONObject thisUser = thisUser(); String name = thisUser.optString("name"); - if (!(TextUtils.isEmpty(name) || "null".equals(name))) + if (!(TextUtils.isEmpty(name) || "null".equals(name))) { return name; + } String firstName = thisUser.optString("first_name"); boolean firstNameEmpty = TextUtils.isEmpty(firstName) || "null".equals(firstName); String lastName = thisUser.optString("last_name"); boolean lastNameEmpty = TextUtils.isEmpty(lastName) || "null".equals(lastName); - if (firstNameEmpty && lastNameEmpty) + if (firstNameEmpty && lastNameEmpty) { return thisUser.optString("email"); + } StringBuilder nameBuilder = new StringBuilder(); - if (!firstNameEmpty) + if (!firstNameEmpty) { nameBuilder.append(firstName).append(" "); - if (!lastNameEmpty) + } + if (!lastNameEmpty) { nameBuilder.append(lastName); + } return nameBuilder.toString().trim(); } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncService.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncService.java index 8a77726d0..9882e1059 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncService.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncService.java @@ -67,13 +67,15 @@ public final class ActFmSyncService { // --- data fetch methods public int fetchFeaturedLists(int serverTime) throws JSONException, IOException { - if (!checkForToken()) + if (!checkForToken()) { return 0; + } JSONObject result = actFmInvoker.invoke("featured_lists", "token", token, "modified_after", serverTime); JSONArray featuredLists = result.getJSONArray("list"); - if (featuredLists.length() > 0) + if (featuredLists.length() > 0) { Preferences.setBoolean(FeaturedListFilterExposer.PREF_SHOULD_SHOW_FEATURED_LISTS, true); + } for (int i = 0; i < featuredLists.length(); i++) { JSONObject featObject = featuredLists.getJSONObject(i); @@ -87,8 +89,9 @@ public final class ActFmSyncService { String purchaseToken = Preferences.getStringValue(BillingConstants.PREF_PURCHASE_TOKEN); String productId = Preferences.getStringValue(BillingConstants.PREF_PRODUCT_ID); try { - if (!checkForToken()) + if (!checkForToken()) { throw new ActFmServiceException("Not logged in", null); + } ArrayList params = new ArrayList(); params.add("purchase_token"); @@ -101,8 +104,9 @@ public final class ActFmSyncService { actFmInvoker.invoke("premium_update_android", params.toArray(new Object[params.size()])); Preferences.setBoolean(BillingConstants.PREF_NEEDS_SERVER_UPDATE, false); - if (onSuccess != null) + if (onSuccess != null) { onSuccess.run(); + } } catch (Exception e) { if (e instanceof ActFmServiceException) { ActFmServiceException ae = (ActFmServiceException) e; @@ -110,15 +114,17 @@ public final class ActFmSyncService { if (ae.result.optString("code").equals("invalid_purchase_token")) { // Not a valid purchase--expired or duolicate Preferences.setBoolean(ActFmPreferenceService.PREF_LOCAL_PREMIUM, false); Preferences.setBoolean(BillingConstants.PREF_NEEDS_SERVER_UPDATE, false); - if (onInvalidToken != null) + if (onInvalidToken != null) { onInvalidToken.run(); + } return; } } } Preferences.setBoolean(BillingConstants.PREF_NEEDS_SERVER_UPDATE, true); - if (onRecoverableError != null) + if (onRecoverableError != null) { onRecoverableError.run(); + } } } @@ -158,13 +164,15 @@ public final class ActFmSyncService { */ public JSONObject invoke(String method, Object... getParameters) throws IOException, ActFmServiceException { - if (!checkForToken()) + if (!checkForToken()) { throw new ActFmServiceException("not logged in", null); + } Object[] parameters = new Object[getParameters.length + 2]; parameters[0] = "token"; parameters[1] = token; - for (int i = 0; i < getParameters.length; i++) + for (int i = 0; i < getParameters.length; i++) { parameters[i + 2] = getParameters[i]; + } return actFmInvoker.invoke(method, parameters); } @@ -173,8 +181,9 @@ public final class ActFmSyncService { } private boolean checkForToken() { - if (!actFmPreferenceService.isLoggedIn()) + if (!actFmPreferenceService.isLoggedIn()) { return false; + } token = actFmPreferenceService.getToken(); return true; } @@ -207,19 +216,24 @@ public final class ActFmSyncService { model.setValue(TagData.UUID, Long.toString(json.getLong("id"))); model.setValue(TagData.NAME, json.getString("name")); - if (featuredList) + if (featuredList) { model.setFlag(TagData.FLAGS, TagData.FLAG_FEATURED, true); + } - if (json.has("picture")) + if (json.has("picture")) { model.setValue(TagData.PICTURE, json.optString("picture", "")); - if (json.has("thumb")) + } + if (json.has("thumb")) { model.setValue(TagData.THUMB, json.optString("thumb", "")); + } - if (json.has("is_silent")) + if (json.has("is_silent")) { model.setFlag(TagData.FLAGS, TagData.FLAG_SILENT, json.getBoolean("is_silent")); + } - if (!json.isNull("description")) + if (!json.isNull("description")) { model.setValue(TagData.TAG_DESCRIPTION, json.getString("description")); + } if (json.has("members")) { JSONArray members = json.getJSONArray("members"); @@ -227,11 +241,13 @@ public final class ActFmSyncService { model.setValue(TagData.MEMBER_COUNT, members.length()); } - if (json.has("deleted_at")) + if (json.has("deleted_at")) { model.setValue(TagData.DELETION_DATE, readDate(json, "deleted_at")); + } - if (json.has("tasks")) + if (json.has("tasks")) { model.setValue(TagData.TASK_COUNT, json.getInt("tasks")); + } } } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncThread.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncThread.java index 64f739d55..41a1de104 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncThread.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncThread.java @@ -209,17 +209,20 @@ public class ActFmSyncThread { public static void clearTablePushedAtValues() { String[] pushedAtPrefs = new String[]{NameMaps.PUSHED_AT_TASKS, NameMaps.PUSHED_AT_TAGS, NameMaps.PUSHED_AT_ACTIVITY, NameMaps.PUSHED_AT_USERS, NameMaps.PUSHED_AT_TASK_LIST_METADATA, NameMaps.PUSHED_AT_WAITING_ON_ME}; - for (String key : pushedAtPrefs) + for (String key : pushedAtPrefs) { Preferences.clear(key); + } } public synchronized void enqueueMessage(ClientToServerMessage message, SyncMessageCallback callback) { - if (!RemoteModelDao.getOutstandingEntryFlag(RemoteModelDao.OUTSTANDING_ENTRY_FLAG_ENQUEUE_MESSAGES)) + if (!RemoteModelDao.getOutstandingEntryFlag(RemoteModelDao.OUTSTANDING_ENTRY_FLAG_ENQUEUE_MESSAGES)) { return; + } if (!pendingMessages.contains(message)) { pendingMessages.add(message); - if (callback != null) + if (callback != null) { pendingCallbacks.put(message, callback); + } synchronized (monitor) { monitor.notifyAll(); } @@ -228,10 +231,11 @@ public class ActFmSyncThread { public synchronized void setTimeForBackgroundSync(boolean isTimeForBackgroundSync) { this.isTimeForBackgroundSync = isTimeForBackgroundSync; - if (isTimeForBackgroundSync) + if (isTimeForBackgroundSync) { synchronized (monitor) { monitor.notifyAll(); } + } } public static final SyncMessageCallback DEFAULT_REFRESH_RUNNABLE = new SyncMessageCallback() { @@ -261,8 +265,9 @@ public class ActFmSyncThread { monitor.wait(); AndroidUtilities.sleepDeep(500L); // Wait briefly for large database operations to finish (e.g. adding a task with several tags may trigger a message before all saves are done--fix this?) - if (!syncMigration) + if (!syncMigration) { syncMigration = Preferences.getBoolean(AstridNewSyncMigrator.PREF_SYNC_MIGRATION, false); + } } catch (InterruptedException e) { // Ignored } @@ -282,8 +287,9 @@ public class ActFmSyncThread { while (messageBatch.size() < batchSize && !pendingMessages.isEmpty()) { ClientToServerMessage message = pendingMessages.remove(0); - if (message != null) + if (message != null) { messageBatch.add(message); + } } if (!messageBatch.isEmpty() && checkForToken()) { @@ -294,8 +300,9 @@ public class ActFmSyncThread { ClientToServerMessage message = messageBatch.get(i); boolean success = payload.addMessage(message, entity); if (success) { - if (message instanceof ChangesHappened) + if (message instanceof ChangesHappened) { containsChangesHappened = true; + } } else { messageBatch.remove(i); i--; @@ -356,10 +363,11 @@ public class ActFmSyncThread { SyncMessageCallback r = pendingCallbacks.remove(message); if (r != null && !callbacksExecutedThisLoop.contains(r)) { List errorList = errorMap.get(i); - if (errorList == null || errorList.isEmpty()) + if (errorList == null || errorList.isEmpty()) { r.runOnSuccess(); - else + } else { r.runOnErrors(errorList); + } callbacksExecutedThisLoop.add(r); } @@ -499,15 +507,17 @@ public class ActFmSyncThread { } private boolean checkForToken() { - if (!actFmPreferenceService.isLoggedIn()) + if (!actFmPreferenceService.isLoggedIn()) { return false; + } token = actFmPreferenceService.getToken(); return true; } public static void syncLog(String message) { - if (ActFmInvoker.SYNC_DEBUG) + if (ActFmInvoker.SYNC_DEBUG) { Log.e(ERROR_TAG, message); + } } public static class NetworkStateChangedReceiver extends BroadcastReceiver { diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncV2Provider.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncV2Provider.java index 5d2229006..7274e51a7 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncV2Provider.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncV2Provider.java @@ -122,20 +122,27 @@ public class ActFmSyncV2Provider extends SyncV2Provider { try { JSONObject status = actFmSyncService.invoke("user_status"); //$NON-NLS-1$ - if (status.has("id")) + if (status.has("id")) { Preferences.setString(ActFmPreferenceService.PREF_USER_ID, Long.toString(status.optLong("id"))); - if (status.has("name")) + } + if (status.has("name")) { Preferences.setString(ActFmPreferenceService.PREF_NAME, status.optString("name")); - if (status.has("first_name")) + } + if (status.has("first_name")) { Preferences.setString(ActFmPreferenceService.PREF_FIRST_NAME, status.optString("first_name")); - if (status.has("last_name")) + } + if (status.has("last_name")) { Preferences.setString(ActFmPreferenceService.PREF_LAST_NAME, status.optString("last_name")); - if (status.has("premium") && !Preferences.getBoolean(BillingConstants.PREF_NEEDS_SERVER_UPDATE, false)) + } + if (status.has("premium") && !Preferences.getBoolean(BillingConstants.PREF_NEEDS_SERVER_UPDATE, false)) { Preferences.setBoolean(ActFmPreferenceService.PREF_PREMIUM, status.optBoolean("premium")); - if (status.has("email")) + } + if (status.has("email")) { Preferences.setString(ActFmPreferenceService.PREF_EMAIL, status.optString("email")); - if (status.has("picture")) + } + if (status.has("picture")) { Preferences.setString(ActFmPreferenceService.PREF_PICTURE, status.optString("picture")); + } ActFmPreferenceService.reloadThisUser(); } catch (IOException e) { diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncWaitingPool.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncWaitingPool.java index c0f2505ba..fc758b46f 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncWaitingPool.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/ActFmSyncWaitingPool.java @@ -31,8 +31,9 @@ public class ActFmSyncWaitingPool { private final Runnable delayMessageRunnable = new Runnable() { @Override public void run() { - if (pendingMessages.isEmpty()) + if (pendingMessages.isEmpty()) { return; + } AndroidUtilities.sleepDeep(WAIT_TIME); while (!pendingMessages.isEmpty()) { ActFmSyncThread.getInstance().enqueueMessage(pendingMessages.remove(0), ActFmSyncThread.DEFAULT_REFRESH_RUNNABLE); diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/AstridNewSyncMigrator.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/AstridNewSyncMigrator.java index c16ee806f..d8b935593 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/AstridNewSyncMigrator.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/AstridNewSyncMigrator.java @@ -89,8 +89,9 @@ public class AstridNewSyncMigrator { @SuppressWarnings("deprecation") public void performMigration() { - if (Preferences.getBoolean(PREF_SYNC_MIGRATION, false)) + if (Preferences.getBoolean(PREF_SYNC_MIGRATION, false)) { return; + } // -------------- // First ensure that a TagData object exists for each tag metadata @@ -111,8 +112,9 @@ public class AstridNewSyncMigrator { tag.clear(); tag.readFromCursor(noTagData); - if (ActFmInvoker.SYNC_DEBUG) + if (ActFmInvoker.SYNC_DEBUG) { Log.w(LOG_TAG, "CREATING TAG DATA " + tag.getValue(TaskToTagMetadata.TAG_NAME)); + } newTagData.setValue(TagData.NAME, tag.getValue(TaskToTagMetadata.TAG_NAME)); tagDataService.save(newTagData); @@ -125,8 +127,9 @@ public class AstridNewSyncMigrator { Log.e(LOG_TAG, "Error creating tag data", e); Crittercism.logHandledException(e); } finally { - if (noTagData != null) + if (noTagData != null) { noTagData.close(); + } } // -------------- @@ -142,8 +145,9 @@ public class AstridNewSyncMigrator { td.readFromCursor(emergentTags); String name = td.getValue(TagData.NAME); tagDataDao.delete(td.getId()); - if (!TextUtils.isEmpty(name)) + if (!TextUtils.isEmpty(name)) { metadataService.deleteWhere(Criterion.and(MetadataCriteria.withKey(TaskToTagMetadata.KEY), TaskToTagMetadata.TAG_NAME.eq(name))); + } } catch (Exception e) { Log.e(LOG_TAG, "Error clearing emergent tags"); Crittercism.logHandledException(e); @@ -152,8 +156,9 @@ public class AstridNewSyncMigrator { } catch (Exception e) { Crittercism.logHandledException(e); } finally { - if (emergentTags != null) + if (emergentTags != null) { emergentTags.close(); + } } // -------------- @@ -182,16 +187,18 @@ public class AstridNewSyncMigrator { assertUUIDsExist(tasksQuery, new Task(), taskDao, taskOutstandingDao, new TaskOutstanding(), NameMaps.syncableProperties(NameMaps.TABLE_ID_TASKS), new UUIDAssertionExtras() { @Override public boolean shouldCreateOutstandingEntries(Task instance) { - if (!instance.containsNonNullValue(Task.MODIFICATION_DATE) || instance.getValue(Task.LAST_SYNC) == 0) + if (!instance.containsNonNullValue(Task.MODIFICATION_DATE) || instance.getValue(Task.LAST_SYNC) == 0) { return RemoteModelDao.getOutstandingEntryFlag(RemoteModelDao.OUTSTANDING_ENTRY_FLAG_RECORD_OUTSTANDING); + } return (instance.getValue(Task.LAST_SYNC) < instance.getValue(Task.MODIFICATION_DATE)) && RemoteModelDao.getOutstandingEntryFlag(RemoteModelDao.OUTSTANDING_ENTRY_FLAG_RECORD_OUTSTANDING); } @Override public void afterSave(Task instance, boolean createdOutstanding) { - if (createdOutstanding) + if (createdOutstanding) { tasksThatNeedTagSync.add(instance.getId()); + } } }); } catch (Exception e) { @@ -231,10 +238,11 @@ public class AstridNewSyncMigrator { template.setFlag(Task.FLAGS, Task.FLAG_REPEAT_AFTER_COMPLETION, false); recurrence = recurrence.replaceAll("BYDAY=;", ""); - if (fromCompletion.equals(recurrence)) + if (fromCompletion.equals(recurrence)) { recurrence = ""; - else if (repeatAfterCompletion) + } else if (repeatAfterCompletion) { recurrence = recurrence + fromCompletion; + } template.setValue(Task.RECURRENCE, recurrence); template.putTransitory(SyncFlags.GTASKS_SUPPRESS_SYNC, true); @@ -249,8 +257,9 @@ public class AstridNewSyncMigrator { Log.e(LOG_TAG, "Error migrating recurrence", e); Crittercism.logHandledException(e); } finally { - if (tasksWithRecurrence != null) + if (tasksWithRecurrence != null) { tasksWithRecurrence.close(); + } } // -------------- @@ -275,10 +284,11 @@ public class AstridNewSyncMigrator { userActivity.setValue(UserActivity.TARGET_ID, update.getValue(Update.TASK).toString()); } else if (update.getValue(Update.TASK_LOCAL) > 0) { Task local = taskDao.fetch(update.getValue(Update.TASK_LOCAL), Task.UUID); - if (local != null && !RemoteModel.isUuidEmpty(local.getUuid())) + if (local != null && !RemoteModel.isUuidEmpty(local.getUuid())) { userActivity.setValue(UserActivity.TARGET_ID, local.getUuid()); - else + } else { setTarget = false; + } } else { setTarget = false; } @@ -300,8 +310,9 @@ public class AstridNewSyncMigrator { Log.e(LOG_TAG, "Error migrating updates", e); Crittercism.logHandledException(e); } finally { - if (updates != null) + if (updates != null) { updates.close(); + } } @@ -331,8 +342,9 @@ public class AstridNewSyncMigrator { m.readFromCursor(fmCursor); Task task = taskDao.fetch(m.getValue(Metadata.TASK), Task.UUID); - if (task == null || !RemoteModel.isValidUuid(task.getUuid())) + if (task == null || !RemoteModel.isValidUuid(task.getUuid())) { continue; + } Long oldRemoteId = m.getValue(FileMetadata.REMOTE_ID); boolean synced = false; @@ -341,23 +353,29 @@ public class AstridNewSyncMigrator { attachment.setValue(TaskAttachment.UUID, Long.toString(oldRemoteId)); } attachment.setValue(TaskAttachment.TASK_UUID, task.getUuid()); - if (m.containsNonNullValue(FileMetadata.NAME)) + if (m.containsNonNullValue(FileMetadata.NAME)) { attachment.setValue(TaskAttachment.NAME, m.getValue(FileMetadata.NAME)); - if (m.containsNonNullValue(FileMetadata.URL)) + } + if (m.containsNonNullValue(FileMetadata.URL)) { attachment.setValue(TaskAttachment.URL, m.getValue(FileMetadata.URL)); - if (m.containsNonNullValue(FileMetadata.FILE_PATH)) + } + if (m.containsNonNullValue(FileMetadata.FILE_PATH)) { attachment.setValue(TaskAttachment.FILE_PATH, m.getValue(FileMetadata.FILE_PATH)); - if (m.containsNonNullValue(FileMetadata.FILE_TYPE)) + } + if (m.containsNonNullValue(FileMetadata.FILE_TYPE)) { attachment.setValue(TaskAttachment.CONTENT_TYPE, m.getValue(FileMetadata.FILE_TYPE)); - if (m.containsNonNullValue(FileMetadata.DELETION_DATE)) + } + if (m.containsNonNullValue(FileMetadata.DELETION_DATE)) { attachment.setValue(TaskAttachment.DELETED_AT, m.getValue(FileMetadata.DELETION_DATE)); + } if (synced) { attachment.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true); } - if (!ActFmPreferenceService.isPremiumUser()) + if (!ActFmPreferenceService.isPremiumUser()) { attachment.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true); + } taskAttachmentDao.createNew(attachment); } catch (Exception e) { Log.e(LOG_TAG, "Error migrating task attachment metadata", e); @@ -369,8 +387,9 @@ public class AstridNewSyncMigrator { Log.e(LOG_TAG, "Error migrating task attachment metadata", e); Crittercism.logHandledException(e); } finally { - if (fmCursor != null) + if (fmCursor != null) { fmCursor.close(); + } } // -------------- @@ -379,8 +398,9 @@ public class AstridNewSyncMigrator { TaskListMetadata tlm = new TaskListMetadata(); try { String activeTasksOrder = Preferences.getStringValue(SubtasksUpdater.ACTIVE_TASKS_ORDER); - if (TextUtils.isEmpty(activeTasksOrder)) + if (TextUtils.isEmpty(activeTasksOrder)) { activeTasksOrder = "[]"; + } activeTasksOrder = SubtasksHelper.convertTreeToRemoteIds(activeTasksOrder); @@ -397,8 +417,9 @@ public class AstridNewSyncMigrator { try { tlm.clear(); String todayTasksOrder = Preferences.getStringValue(SubtasksUpdater.TODAY_TASKS_ORDER); - if (TextUtils.isEmpty(todayTasksOrder)) + if (TextUtils.isEmpty(todayTasksOrder)) { todayTasksOrder = "[]"; + } todayTasksOrder = SubtasksHelper.convertTreeToRemoteIds(todayTasksOrder); @@ -437,8 +458,9 @@ public class AstridNewSyncMigrator { Log.e(LOG_TAG, "Error migrating tag ordering", e); Crittercism.logHandledException(e); } finally { - if (allTagData != null) + if (allTagData != null) { allTagData.close(); + } } // -------------- @@ -458,23 +480,27 @@ public class AstridNewSyncMigrator { m.clear(); // Need this since some properties may be null m.readFromCursor(incompleteMetadata); - if (ActFmInvoker.SYNC_DEBUG) + if (ActFmInvoker.SYNC_DEBUG) { Log.w(LOG_TAG, "Incomplete linking task " + m.getValue(Metadata.TASK) + " to " + m.getValue(TaskToTagMetadata.TAG_NAME)); + } if (!m.containsNonNullValue(TaskToTagMetadata.TASK_UUID) || RemoteModel.isUuidEmpty(m.getValue(TaskToTagMetadata.TASK_UUID))) { - if (ActFmInvoker.SYNC_DEBUG) + if (ActFmInvoker.SYNC_DEBUG) { Log.w(LOG_TAG, "No task uuid"); + } updateTaskUuid(m); } if (!m.containsNonNullValue(TaskToTagMetadata.TAG_UUID) || RemoteModel.isUuidEmpty(m.getValue(TaskToTagMetadata.TAG_UUID))) { - if (ActFmInvoker.SYNC_DEBUG) + if (ActFmInvoker.SYNC_DEBUG) { Log.w(LOG_TAG, "No tag uuid"); + } updateTagUuid(m); } - if (m.getSetValues() != null && m.getSetValues().size() > 0) + if (m.getSetValues() != null && m.getSetValues().size() > 0) { metadataService.save(m); + } } catch (Exception e) { Log.e(LOG_TAG, "Error validating task to tag metadata", e); @@ -486,8 +512,9 @@ public class AstridNewSyncMigrator { Log.e(LOG_TAG, "Error validating task to tag metadata", e); Crittercism.logHandledException(e); } finally { - if (incompleteMetadata != null) + if (incompleteMetadata != null) { incompleteMetadata.close(); + } } // -------------- @@ -516,15 +543,17 @@ public class AstridNewSyncMigrator { m.readFromCursor(tagsAdded); Long deletionDate = m.getValue(Metadata.DELETION_DATE); String tagUuid = m.getValue(TaskToTagMetadata.TAG_UUID); - if (!RemoteModel.isValidUuid(tagUuid)) + if (!RemoteModel.isValidUuid(tagUuid)) { continue; + } TaskOutstanding to = new TaskOutstanding(); to.setValue(OutstandingEntry.ENTITY_ID_PROPERTY, m.getValue(Metadata.TASK)); to.setValue(OutstandingEntry.CREATED_AT_PROPERTY, DateUtilities.now()); String addedOrRemoved = NameMaps.TAG_ADDED_COLUMN; - if (deletionDate != null && deletionDate > 0) + if (deletionDate != null && deletionDate > 0) { addedOrRemoved = NameMaps.TAG_REMOVED_COLUMN; + } to.setValue(OutstandingEntry.COLUMN_STRING_PROPERTY, addedOrRemoved); to.setValue(OutstandingEntry.VALUE_STRING_PROPERTY, tagUuid); @@ -538,8 +567,9 @@ public class AstridNewSyncMigrator { Log.e(LOG_TAG, "Error creating tag_added outstanding entries", e); Crittercism.logHandledException(e); } finally { - if (tagsAdded != null) + if (tagsAdded != null) { tagsAdded.close(); + } } Preferences.setBoolean(PREF_SYNC_MIGRATION, true); @@ -579,8 +609,9 @@ public class AstridNewSyncMigrator { createdOutstanding = true; createOutstandingEntries(instance.getId(), dao, oeDao, oe, propertiesForOutstanding); } - if (extras != null) + if (extras != null) { extras.afterSave(instance, createdOutstanding); + } } catch (Exception e) { Log.e(LOG_TAG, "Error asserting UUIDs", e); Crittercism.logHandledException(e); @@ -590,8 +621,9 @@ public class AstridNewSyncMigrator { Log.e(LOG_TAG, "Error asserting UUIDs", e); Crittercism.logHandledException(e); } finally { - if (cursor != null) + if (cursor != null) { cursor.close(); + } } } @@ -603,8 +635,9 @@ public class AstridNewSyncMigrator { oe.setValue(OutstandingEntry.ENTITY_ID_PROPERTY, id); oe.setValue(OutstandingEntry.COLUMN_STRING_PROPERTY, property.name); Object value = instance.getValue(property); - if (value == null) + if (value == null) { value = ""; + } oe.setValue(OutstandingEntry.VALUE_STRING_PROPERTY, value.toString()); oe.setValue(OutstandingEntry.CREATED_AT_PROPERTY, now); oeDao.createNew(oe); @@ -615,12 +648,14 @@ public class AstridNewSyncMigrator { long taskId = m.getValue(Metadata.TASK); Task task = taskDao.fetch(taskId, Task.UUID); if (task != null) { - if (ActFmInvoker.SYNC_DEBUG) + if (ActFmInvoker.SYNC_DEBUG) { Log.w(LOG_TAG, "Linking with task uuid " + task.getValue(Task.UUID)); + } m.setValue(TaskToTagMetadata.TASK_UUID, task.getValue(Task.UUID)); } else { - if (ActFmInvoker.SYNC_DEBUG) + if (ActFmInvoker.SYNC_DEBUG) { Log.w(LOG_TAG, "Task not found, deleting link"); + } m.setValue(Metadata.DELETION_DATE, DateUtilities.now()); } } @@ -629,12 +664,14 @@ public class AstridNewSyncMigrator { String tag = m.getValue(TaskToTagMetadata.TAG_NAME); TagData tagData = tagDataService.getTagByName(tag, TagData.UUID); if (tagData != null) { - if (ActFmInvoker.SYNC_DEBUG) + if (ActFmInvoker.SYNC_DEBUG) { Log.w(LOG_TAG, "Linking with tag uuid " + tagData.getValue(TagData.UUID)); + } m.setValue(TaskToTagMetadata.TAG_UUID, tagData.getValue(TagData.UUID)); } else { - if (ActFmInvoker.SYNC_DEBUG) + if (ActFmInvoker.SYNC_DEBUG) { Log.w(LOG_TAG, "Tag not found, deleting link"); + } m.setValue(Metadata.DELETION_DATE, DateUtilities.now()); } } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/EmptyTitleOutstandingEntryMigration.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/EmptyTitleOutstandingEntryMigration.java index 1c360d8bb..c42936c32 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/EmptyTitleOutstandingEntryMigration.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/EmptyTitleOutstandingEntryMigration.java @@ -67,8 +67,9 @@ public class EmptyTitleOutstandingEntryMigration { } catch (Exception e) { Log.e(ERROR_TAG, "Unhandled exception", e); //$NON-NLS-1$ } finally { - if (outstandingWithTitle != null) + if (outstandingWithTitle != null) { outstandingWithTitle.close(); + } } } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/SyncUpgradePrompt.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/SyncUpgradePrompt.java index c8ab87543..8cfdd62ce 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/SyncUpgradePrompt.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/SyncUpgradePrompt.java @@ -22,8 +22,9 @@ public class SyncUpgradePrompt { private static long lastPromptDate = -1; public static void showSyncUpgradePrompt(final Activity activity) { - if (lastPromptDate == -1) + if (lastPromptDate == -1) { lastPromptDate = Preferences.getLong(P_SYNC_UPGRADE_PROMPT, 0L); + } Dialog d = null; if (DateUtilities.now() - lastPromptDate > DateUtilities.ONE_WEEK * 3) { @@ -69,8 +70,9 @@ public class SyncUpgradePrompt { } } - if (d != null) + if (d != null) { d.show(); + } } private static void setLastPromptDate(long date) { @@ -103,8 +105,9 @@ public class SyncUpgradePrompt { @Override public void onClick(View v) { d.dismiss(); - if (listener1 != null) + if (listener1 != null) { listener1.run(); + } } }); b1.setBackgroundColor(activity.getResources().getColor(tv.data)); @@ -120,8 +123,9 @@ public class SyncUpgradePrompt { @Override public void onClick(View v) { d.dismiss(); - if (listener2 != null) + if (listener2 != null) { listener2.run(); + } } }); b2.setBackgroundColor(activity.getResources().getColor(tv.data)); diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/TaskListMetadataSyncDatabaseListener.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/TaskListMetadataSyncDatabaseListener.java index ae7015fb8..e810e40cf 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/TaskListMetadataSyncDatabaseListener.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/TaskListMetadataSyncDatabaseListener.java @@ -15,10 +15,11 @@ public class TaskListMetadataSyncDatabaseListener extends SyncDatabaseListener message) { - if (model.getSetValues().containsKey(TaskListMetadata.TASK_IDS.name)) + if (model.getSetValues().containsKey(TaskListMetadata.TASK_IDS.name)) { waitingPool.enqueueMessage(message); - else + } else { actFmSyncThread.enqueueMessage(message, ActFmSyncThread.DEFAULT_REFRESH_RUNNABLE); + } } } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/AcknowledgeChange.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/AcknowledgeChange.java index 2f85ab47e..51e194838 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/AcknowledgeChange.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/AcknowledgeChange.java @@ -21,20 +21,21 @@ public class AcknowledgeChange extends ServerToClientMessage { public AcknowledgeChange(JSONObject json) { super(json); String table = json.optString("table"); //$NON-NLS-1$ - if (NameMaps.TABLE_ID_TASKS.equals(table)) + if (NameMaps.TABLE_ID_TASKS.equals(table)) { dao = PluginServices.getTaskOutstandingDao(); - else if (NameMaps.TABLE_ID_TAGS.equals(table)) + } else if (NameMaps.TABLE_ID_TAGS.equals(table)) { dao = PluginServices.getTagOutstandingDao(); - else if (NameMaps.TABLE_ID_USER_ACTIVITY.equals(table)) + } else if (NameMaps.TABLE_ID_USER_ACTIVITY.equals(table)) { dao = PluginServices.getUserActivityOutstandingDao(); - else if (NameMaps.TABLE_ID_ATTACHMENTS.equals(table)) + } else if (NameMaps.TABLE_ID_ATTACHMENTS.equals(table)) { dao = PluginServices.getTaskAttachmentOutstandingDao(); - else if (NameMaps.TABLE_ID_TASK_LIST_METADATA.equals(table)) + } else if (NameMaps.TABLE_ID_TASK_LIST_METADATA.equals(table)) { dao = PluginServices.getTaskListMetadataOutstandingDao(); - else if (NameMaps.TABLE_ID_WAITING_ON_ME.equals(table)) + } else if (NameMaps.TABLE_ID_WAITING_ON_ME.equals(table)) { dao = PluginServices.getWaitingOnMeOutstandingDao(); - else + } else { dao = null; + } } @Override @@ -45,8 +46,9 @@ public class AcknowledgeChange extends ServerToClientMessage { for (int i = 0; i < idsArray.length(); i++) { try { Long id = idsArray.getLong(i); - if (id <= 0) + if (id <= 0) { continue; + } idsList.add(id); } catch (JSONException e) { diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ChangesHappened.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ChangesHappened.java index 092cfc711..47a2a0458 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ChangesHappened.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ChangesHappened.java @@ -86,15 +86,18 @@ public class ChangesHappened(); if (!foundEntity) // Stop sending changes for entities that don't exist anymore + { outstandingDao.deleteWhere(OutstandingEntry.ENTITY_ID_PROPERTY.eq(id)); + } } @Override protected boolean serializeExtrasToJSON(JSONObject serializeTo, MultipartEntity entity) throws JSONException { // Process changes list and serialize to JSON JSONArray changesJson = changesToJSON(entity); - if (changesJson == null || changesJson.length() == 0) + if (changesJson == null || changesJson.length() == 0) { return false; + } serializeTo.put(CHANGES_KEY, changesJson); return true; } @@ -109,8 +112,9 @@ public class ChangesHappened localProperty = NameMaps.localColumnNameToProperty(table, localColumn); - if (localProperty == null) + if (localProperty == null) { throw new RuntimeException("No local property found for local column " + localColumn + " in table " + table); + } serverColumn = NameMaps.localColumnNameToServerColumnName(table, localColumn); - if (serverColumn == null) + if (serverColumn == null) { throw new RuntimeException("No server column found for local column " + localColumn + " in table " + table); + } Object value = localProperty.accept(visitor, change); - if (!validateValue(localProperty, value)) + if (!validateValue(localProperty, value)) { return null; + } - if (value == null) + if (value == null) { changeJson.put("value", JSONObject.NULL); - else { + } else { if (localProperty.checkFlag(Property.PROP_FLAG_PICTURE) && value instanceof JSONObject) { JSONObject json = (JSONObject) value; String name = addToEntityFromFileJson(entity, json, uploadCounter); - if (name != null) + if (name != null) { changeJson.put("value", name); + } } else { changeJson.put("value", value); } @@ -223,8 +231,9 @@ public class ChangesHappened property, Object value) { if (Task.TITLE.equals(property)) { - if (!(value instanceof String) || TextUtils.isEmpty((String) value)) + if (!(value instanceof String) || TextUtils.isEmpty((String) value)) { return false; + } } return true; } @@ -233,11 +242,13 @@ public class ChangesHappened property, OE data) { Integer i = data.getMergedValues().getAsInteger(OutstandingEntry.VALUE_STRING_PROPERTY.name); if (i != null) { - if (property.checkFlag(Property.PROP_FLAG_BOOLEAN)) + if (property.checkFlag(Property.PROP_FLAG_BOOLEAN)) { return i > 0; + } return i; } else { return getAsString(data); @@ -269,8 +281,9 @@ public class ChangesHappened property, OE data) { String value = getAsString(data); - if (RemoteModel.NO_UUID.equals(value) && property.checkFlag(Property.PROP_FLAG_USER_ID)) + if (RemoteModel.NO_UUID.equals(value) && property.checkFlag(Property.PROP_FLAG_USER_ID)) { return ActFmPreferenceService.userId(); + } if (property.checkFlag(Property.PROP_FLAG_JSON)) { - if (TextUtils.isEmpty(value)) + if (TextUtils.isEmpty(value)) { return null; + } try { - if (value != null && value.startsWith("[")) + if (value != null && value.startsWith("[")) { return new JSONArray(value); - else + } else { return new JSONObject(value); + } } catch (JSONException e) { return null; } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ClientToServerMessage.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ClientToServerMessage.java index 5b39f0051..beed230b2 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ClientToServerMessage.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ClientToServerMessage.java @@ -74,10 +74,11 @@ public abstract class ClientToServerMessage { json.put(UUID_KEY, uuid); String dateValue = DateUtilities.timeToIso8601(pushedAt, true); json.put(PUSHED_AT_KEY, dateValue != null ? dateValue : 0); - if (serializeExtrasToJSON(json, entity)) + if (serializeExtrasToJSON(json, entity)) { return json; - else + } else { return null; + } } catch (JSONException e) { Crittercism.logHandledException(e); return null; @@ -95,23 +96,30 @@ public abstract class ClientToServerMessage { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } ClientToServerMessage other = (ClientToServerMessage) obj; if (table == null) { - if (other.table != null) + if (other.table != null) { return false; - } else if (!table.equals(other.table)) + } + } else if (!table.equals(other.table)) { return false; + } if (uuid == null) { - if (other.uuid != null) + if (other.uuid != null) { return false; - } else if (!uuid.equals(other.uuid)) + } + } else if (!uuid.equals(other.uuid)) { return false; + } return true; } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ConstructOutstandingTableFromMasterTable.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ConstructOutstandingTableFromMasterTable.java index 35f7c1e56..b215bde8a 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ConstructOutstandingTableFromMasterTable.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ConstructOutstandingTableFromMasterTable.java @@ -46,18 +46,20 @@ public class ConstructOutstandingTableFromMasterTable p : syncableProperties) { oe.clear(); oe.setValue(OutstandingEntry.ENTITY_ID_PROPERTY, itemId); oe.setValue(OutstandingEntry.COLUMN_STRING_PROPERTY, p.name); Object value = items.get(p); - if (value == null) + if (value == null) { continue; + } oe.setValue(OutstandingEntry.VALUE_STRING_PROPERTY, value.toString()); oe.setValue(OutstandingEntry.CREATED_AT_PROPERTY, createdAt); diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/Debug.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/Debug.java index 843840628..32d6e249e 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/Debug.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/Debug.java @@ -15,8 +15,9 @@ public class Debug extends ServerToClientMessage { @SuppressWarnings("nls") public void processMessage(String serverTime) { String message = json.optString("message"); - if (!TextUtils.isEmpty(message)) + if (!TextUtils.isEmpty(message)) { Log.w("actfm-debug-message", message); + } } } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/FetchHistory.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/FetchHistory.java index dcffa4459..955702ce8 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/FetchHistory.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/FetchHistory.java @@ -71,16 +71,18 @@ public class FetchHistory { @Override public void run() { String token = actFmPreferenceService.getToken(); - if (TextUtils.isEmpty(token) || TextUtils.isEmpty(uuid)) + if (TextUtils.isEmpty(token) || TextUtils.isEmpty(uuid)) { return; + } ArrayList params = new ArrayList(); - if (NameMaps.TABLE_ID_TASKS.equals(table)) + if (NameMaps.TABLE_ID_TASKS.equals(table)) { params.add("task_id"); - else if (NameMaps.TABLE_ID_TAGS.equals(table)) + } else if (NameMaps.TABLE_ID_TAGS.equals(table)) { params.add("tag_id"); - else + } else { return; + } params.add(uuid); @@ -114,8 +116,9 @@ public class FetchHistory { history.setValue(History.UUID, historyJson.optString("id") + ":" + uuid); String userId = historyJson.optString("user_id"); - if (userId.equals(ActFmPreferenceService.userId())) + if (userId.equals(ActFmPreferenceService.userId())) { userId = Task.USER_ID_SELF; + } history.setValue(History.USER_UUID, historyJson.optString("user_id")); history.setValue(History.COLUMN, historyJson.optString("column")); history.setValue(History.OLD_VALUE, historyJson.optString("prev")); @@ -148,8 +151,9 @@ public class FetchHistory { try { template = dao.getModelClass().newInstance(); template.setValue(historyTimeProperty, time); - if (modifiedAfter == 0 || hasMore) + if (modifiedAfter == 0 || hasMore) { template.setValue(historyHasMoreProperty, hasMore ? 1 : 0); + } dao.update(RemoteModel.UUID_PROPERTY.eq(uuid), template); } catch (InstantiationException e) { Log.e(ERROR_TAG, "Error instantiating model for recording time", e); @@ -167,8 +171,9 @@ public class FetchHistory { JSONObject userObj = users.optJSONObject(key); if (userObj != null) { String userUuid = userObj.optString("id"); - if (RemoteModel.isUuidEmpty(uuid)) + if (RemoteModel.isUuidEmpty(uuid)) { continue; + } User user = new User(); user.setValue(User.FIRST_NAME, userObj.optString("first_name")); @@ -188,8 +193,9 @@ public class FetchHistory { Log.e(ERROR_TAG, "Error getting model history", e); } - if (done != null) + if (done != null) { done.runOnSuccess(); + } } }).start(); } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/JSONChangeToPropertyVisitor.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/JSONChangeToPropertyVisitor.java index bea292df8..f1b4f8e91 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/JSONChangeToPropertyVisitor.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/JSONChangeToPropertyVisitor.java @@ -87,19 +87,22 @@ public class JSONChangeToPropertyVisitor implements PropertyVisitor property, String key) { try { String value = data.getString(key); - if ("null".equals(value)) + if ("null".equals(value)) { value = ""; - else if (property.checkFlag(Property.PROP_FLAG_USER_ID) && ActFmPreferenceService.userId().equals(value)) + } else if (property.checkFlag(Property.PROP_FLAG_USER_ID) && ActFmPreferenceService.userId().equals(value)) { value = Task.USER_ID_SELF; - if (property.equals(Task.USER_ID)) + } + if (property.equals(Task.USER_ID)) { model.setValue(Task.USER, ""); // Clear this value for migration purposes + } model.setValue((StringProperty) property, value); } catch (JSONException e) { try { JSONObject object = data.getJSONObject(key); - if (object != null) + if (object != null) { model.setValue((StringProperty) property, object.toString()); + } } catch (JSONException e2) { Log.e(ERROR_TAG, "Error reading JSON value with key " + key + " from JSON " + data, e); } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/JSONPayloadBuilder.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/JSONPayloadBuilder.java index c6fe81f94..76565093a 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/JSONPayloadBuilder.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/JSONPayloadBuilder.java @@ -46,8 +46,9 @@ public class JSONPayloadBuilder { } public String closeAndReturnString() { - if (messageCount > 0) + if (messageCount > 0) { sb.deleteCharAt(sb.length() - 1); // Remove final comma + } sb.append("]"); //$NON-NLS-1$ return sb.toString(); } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/MakeChanges.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/MakeChanges.java index 73263e2be..da494fd8c 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/MakeChanges.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/MakeChanges.java @@ -71,13 +71,15 @@ public class MakeChanges extends ServerToClientMessage private static void saveOrUpdateModelAfterChanges(RemoteModelDao dao, T model, String oldUuid, String uuid, String serverTime, Criterion orCriterion) { Criterion uuidCriterion; - if (oldUuid == null) + if (oldUuid == null) { uuidCriterion = RemoteModel.UUID_PROPERTY.eq(uuid); - else + } else { uuidCriterion = RemoteModel.UUID_PROPERTY.eq(oldUuid); + } - if (orCriterion != null) + if (orCriterion != null) { uuidCriterion = Criterion.or(uuidCriterion, orCriterion); + } if (model.getSetValues() != null && model.getSetValues().size() > 0) { long pushedAt; @@ -87,8 +89,9 @@ public class MakeChanges extends ServerToClientMessage pushedAt = 0; } - if (pushedAt > 0) + if (pushedAt > 0) { model.setValue(RemoteModel.PUSHED_AT_PROPERTY, pushedAt); + } model.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true); if (dao.update(uuidCriterion, model) <= 0) { // If update doesn't update rows. create a new model @@ -116,8 +119,9 @@ public class MakeChanges extends ServerToClientMessage beforeSaveChanges(changes, model, uuid); - if (model.getSetValues() != null && !model.getSetValues().containsKey(uuidProperty.name)) + if (model.getSetValues() != null && !model.getSetValues().containsKey(uuidProperty.name)) { model.setValue(uuidProperty, uuid); + } saveOrUpdateModelAfterChanges(dao, model, oldUuid, uuid, serverTime, getMatchCriterion(model)); afterSaveChanges(changes, model, uuid, oldUuid); @@ -133,36 +137,41 @@ public class MakeChanges extends ServerToClientMessage private Criterion getMatchCriterion(TYPE model) { if (NameMaps.TABLE_ID_TASK_LIST_METADATA.equals(table)) { - if (model.getSetValues().containsKey(TaskListMetadata.FILTER.name)) + if (model.getSetValues().containsKey(TaskListMetadata.FILTER.name)) { return TaskListMetadata.FILTER.eq(model.getSetValues().getAsString(TaskListMetadata.FILTER.name)); - else if (model.getSetValues().containsKey(TaskListMetadata.TAG_UUID.name)) + } else if (model.getSetValues().containsKey(TaskListMetadata.TAG_UUID.name)) { return TaskListMetadata.TAG_UUID.eq(model.getSetValues().getAsString(TaskListMetadata.TAG_UUID.name)); + } } return null; } private void beforeSaveChanges(JSONObject changes, TYPE model, String uuid) { ChangeHooks beforeSaveChanges = null; - if (NameMaps.TABLE_ID_TASKS.equals(table)) + if (NameMaps.TABLE_ID_TASKS.equals(table)) { beforeSaveChanges = new BeforeSaveTaskChanges(model, changes, uuid); - else if (NameMaps.TABLE_ID_TAGS.equals(table)) + } else if (NameMaps.TABLE_ID_TAGS.equals(table)) { beforeSaveChanges = new BeforeSaveTagChanges(model, changes, uuid); + } - if (beforeSaveChanges != null) + if (beforeSaveChanges != null) { beforeSaveChanges.performChanges(); + } } private void afterSaveChanges(JSONObject changes, TYPE model, String uuid, String oldUuid) { ChangeHooks afterSaveChanges = null; - if (NameMaps.TABLE_ID_TASKS.equals(table)) + if (NameMaps.TABLE_ID_TASKS.equals(table)) { afterSaveChanges = new AfterSaveTaskChanges(model, changes, uuid, oldUuid); - else if (NameMaps.TABLE_ID_TAGS.equals(table)) + } else if (NameMaps.TABLE_ID_TAGS.equals(table)) { afterSaveChanges = new AfterSaveTagChanges(model, changes, uuid, oldUuid); - else if (NameMaps.TABLE_ID_USERS.equals(table)) + } else if (NameMaps.TABLE_ID_USERS.equals(table)) { afterSaveChanges = new AfterSaveUserChanges(model, changes, uuid); + } - if (afterSaveChanges != null) + if (afterSaveChanges != null) { afterSaveChanges.performChanges(); + } } private abstract class ChangeHooks { @@ -213,8 +222,9 @@ public class MakeChanges extends ServerToClientMessage public void performChanges() { JSONArray addMembers = changes.optJSONArray("member_added"); boolean membersAdded = (addMembers != null && addMembers.length() > 0); - if (membersAdded) + if (membersAdded) { model.setValue(TagData.MEMBERS, ""); // Clear this value for migration purposes + } } } @@ -238,8 +248,9 @@ public class MakeChanges extends ServerToClientMessage changes.has(NameMaps.localPropertyToServerColumnName(NameMaps.TABLE_ID_TASKS, Task.COMPLETION_DATE))) { Task t = PluginServices.getTaskDao().fetch(uuid, ReminderService.NOTIFICATION_PROPERTIES); if (t != null) { - if ((changes.has("task_repeated") && t.getValue(Task.DUE_DATE) > DateUtilities.now()) || t.getValue(Task.COMPLETION_DATE) > 0) + if ((changes.has("task_repeated") && t.getValue(Task.DUE_DATE) > DateUtilities.now()) || t.getValue(Task.COMPLETION_DATE) > 0) { Notifications.cancelNotifications(t.getId()); + } ReminderService.getInstance().scheduleAlarm(t); } } @@ -248,12 +259,14 @@ public class MakeChanges extends ServerToClientMessage JSONArray removeTags = changes.optJSONArray("tag_removed"); boolean tagsAdded = (addTags != null && addTags.length() > 0); boolean tagsRemoved = (removeTags != null && removeTags.length() > 0); - if (!tagsAdded && !tagsRemoved) + if (!tagsAdded && !tagsRemoved) { return; + } long localId = AbstractModel.NO_ID; - if (tagsAdded || tagsRemoved) + if (tagsAdded || tagsRemoved) { localId = getLocalId(); + } if (tagsAdded) { if (model.isSaved()) { @@ -284,8 +297,9 @@ public class MakeChanges extends ServerToClientMessage } private void uuidChanged(String fromUuid, String toUuid) { - if (ActFmInvoker.SYNC_DEBUG) + if (ActFmInvoker.SYNC_DEBUG) { Log.e(ERROR_TAG, "Task UUID collision -- old uuid: " + fromUuid + ", new uuid: " + toUuid); + } // Update reference from UserActivity to task uuid UserActivityDao activityDao = PluginServices.getUserActivityDao(); @@ -359,8 +373,9 @@ public class MakeChanges extends ServerToClientMessage boolean membersRemoved = (removeMembers != null && removeMembers.length() > 0); long localId = AbstractModel.NO_ID; - if (membersAdded || membersRemoved) + if (membersAdded || membersRemoved) { localId = getLocalId(); + } if (membersAdded) { for (int i = 0; i < addMembers.length(); i++) { @@ -388,8 +403,9 @@ public class MakeChanges extends ServerToClientMessage } private void uuidChanged(String fromUuid, String toUuid) { - if (ActFmInvoker.SYNC_DEBUG) + if (ActFmInvoker.SYNC_DEBUG) { Log.e(ERROR_TAG, "Tag UUID collision -- old uuid: " + fromUuid + ", new uuid: " + toUuid); + } UserActivityDao activityDao = PluginServices.getUserActivityDao(); UserActivity activityTemplate = new UserActivity(); diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/NameMaps.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/NameMaps.java index 590e3048c..83f0ce4f4 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/NameMaps.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/NameMaps.java @@ -78,31 +78,34 @@ public class NameMaps { propertyMap.put(property, serverName); localNameMap.put(property.name, property); serverNameMap.put(property.name, serverName); - if (!writeable && excludedFromOutstandingSet != null) + if (!writeable && excludedFromOutstandingSet != null) { excludedFromOutstandingSet.add(property.name); + } } public static Property[] syncableProperties(String table) { - if (TABLE_ID_TASKS.equals(table)) + if (TABLE_ID_TASKS.equals(table)) { return computeSyncableProperties(TASK_PROPERTIES_LOCAL_TO_SERVER.keySet(), TASK_PROPERTIES_EXCLUDED); - else if (TABLE_ID_TAGS.equals(table)) + } else if (TABLE_ID_TAGS.equals(table)) { return computeSyncableProperties(TAG_DATA_PROPERTIES_LOCAL_TO_SERVER.keySet(), TAG_PROPERTIES_EXCLUDED); - else if (TABLE_ID_USER_ACTIVITY.equals(table)) + } else if (TABLE_ID_USER_ACTIVITY.equals(table)) { return computeSyncableProperties(USER_ACTIVITY_PROPERTIES_LOCAL_TO_SERVER.keySet(), USER_ACTIVITY_PROPERTIES_EXCLUDED); - else if (TABLE_ID_ATTACHMENTS.equals(table)) + } else if (TABLE_ID_ATTACHMENTS.equals(table)) { return computeSyncableProperties(TASK_ATTACHMENT_PROPERTIES_LOCAL_TO_SERVER.keySet(), TASK_ATTACHMENT_PROPERTIES_EXCLUDED); - else if (TABLE_ID_TASK_LIST_METADATA.equals(table)) + } else if (TABLE_ID_TASK_LIST_METADATA.equals(table)) { return computeSyncableProperties(TASK_LIST_METADATA_PROPERTIES_LOCAL_TO_SERVER.keySet(), TASK_LIST_METADATA_PROPERTIES_EXCLUDED); - else if (TABLE_ID_WAITING_ON_ME.equals(table)) + } else if (TABLE_ID_WAITING_ON_ME.equals(table)) { return computeSyncableProperties(WAITING_ON_ME_PROPERTIES_LOCAL_TO_SERVER.keySet(), WAITING_ON_ME_PROPERTIES_EXCLUDED); + } return null; } private static Property[] computeSyncableProperties(Set> baseSet, Set excluded) { Set> result = new HashSet>(); for (Property elem : baseSet) { - if (!excluded.contains(elem.name)) + if (!excluded.contains(elem.name)) { result.add(elem); + } } return result.toArray(new Property[result.size()]); } @@ -371,49 +374,58 @@ public class NameMaps { private static B mapColumnName(String table, A col, Map taskMap, Map tagMap, Map userMap, Map userActivityMap, Map taskAttachmentMap, Map taskListMetadataMap, Map waitingOnMeMap) { Map map = null; - if (TABLE_ID_TASKS.equals(table)) + if (TABLE_ID_TASKS.equals(table)) { map = taskMap; - else if (TABLE_ID_TAGS.equals(table)) + } else if (TABLE_ID_TAGS.equals(table)) { map = tagMap; - else if (TABLE_ID_USERS.equals(table)) + } else if (TABLE_ID_USERS.equals(table)) { map = userMap; - else if (TABLE_ID_USER_ACTIVITY.equals(table)) + } else if (TABLE_ID_USER_ACTIVITY.equals(table)) { map = userActivityMap; - else if (TABLE_ID_ATTACHMENTS.equals(table)) + } else if (TABLE_ID_ATTACHMENTS.equals(table)) { map = taskAttachmentMap; - else if (TABLE_ID_TASK_LIST_METADATA.equals(table)) + } else if (TABLE_ID_TASK_LIST_METADATA.equals(table)) { map = taskListMetadataMap; - else if (TABLE_ID_WAITING_ON_ME.equals(table)) + } else if (TABLE_ID_WAITING_ON_ME.equals(table)) { map = waitingOnMeMap; + } - if (map == null) + if (map == null) { return null; + } return map.get(col); } public static boolean shouldRecordOutstandingColumnForTable(String table, String column) { if (TABLE_ID_TASKS.equals(table)) { - if (TASK_COLUMN_NAMES_TO_PROPERTIES.containsKey(column)) + if (TASK_COLUMN_NAMES_TO_PROPERTIES.containsKey(column)) { return !TASK_PROPERTIES_EXCLUDED.contains(column); + } } else if (TABLE_ID_TAGS.equals(table)) { - if (TAG_DATA_COLUMN_NAMES_TO_PROPERTIES.containsKey(column)) + if (TAG_DATA_COLUMN_NAMES_TO_PROPERTIES.containsKey(column)) { return !TAG_PROPERTIES_EXCLUDED.contains(column); + } } else if (TABLE_ID_USER_ACTIVITY.equals(table)) { - if (USER_ACTIVITY_COLUMN_NAMES_TO_PROPERTIES.containsKey(column)) + if (USER_ACTIVITY_COLUMN_NAMES_TO_PROPERTIES.containsKey(column)) { return !USER_ACTIVITY_PROPERTIES_EXCLUDED.contains(column); + } } else if (TABLE_ID_USERS.equals(table)) { - if (USER_COLUMN_NAMES_TO_PROPERTIES.containsKey(column)) + if (USER_COLUMN_NAMES_TO_PROPERTIES.containsKey(column)) { return !USER_PROPERTIES_EXCLUDED.contains(column); + } } else if (TABLE_ID_ATTACHMENTS.equals(table)) { - if (TASK_ATTACHMENT_COLUMN_NAMES_TO_PROPERTIES.containsKey(column)) + if (TASK_ATTACHMENT_COLUMN_NAMES_TO_PROPERTIES.containsKey(column)) { return !TASK_ATTACHMENT_PROPERTIES_EXCLUDED.contains(column); + } } else if (TABLE_ID_TASK_LIST_METADATA.equals(table)) { - if (TASK_LIST_METADATA_COLUMN_NAMES_TO_PROPERTIES.containsKey(column)) + if (TASK_LIST_METADATA_COLUMN_NAMES_TO_PROPERTIES.containsKey(column)) { return !TASK_LIST_METADATA_PROPERTIES_EXCLUDED.contains(column); + } } else if (TABLE_ID_WAITING_ON_ME.equals(table)) { - if (WAITING_ON_ME_COLUMN_NAMES_TO_PROPERTIES.containsKey(column)) + if (WAITING_ON_ME_COLUMN_NAMES_TO_PROPERTIES.containsKey(column)) { return !WAITING_ON_ME_PROPERTIES_EXCLUDED.contains(column); + } } return false; } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/NowBriefed.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/NowBriefed.java index 378a683bc..a11b83968 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/NowBriefed.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/NowBriefed.java @@ -50,25 +50,30 @@ public class NowBriefed extends ServerToClientMessage if (TextUtils.isEmpty(uuid)) { if (!TextUtils.isEmpty(taskId)) { Task template = new Task(); - if (NameMaps.TABLE_ID_ATTACHMENTS.equals(table)) + if (NameMaps.TABLE_ID_ATTACHMENTS.equals(table)) { template.setValue(Task.ATTACHMENTS_PUSHED_AT, pushedAt); - else if (NameMaps.TABLE_ID_USER_ACTIVITY.equals(table)) + } else if (NameMaps.TABLE_ID_USER_ACTIVITY.equals(table)) { template.setValue(Task.USER_ACTIVITIES_PUSHED_AT, pushedAt); + } - if (template.getSetValues() != null) + if (template.getSetValues() != null) { PluginServices.getTaskDao().update(Task.UUID.eq(taskId), template); + } } else if (!TextUtils.isEmpty(tagId)) { TagData template = new TagData(); - if (NameMaps.TABLE_ID_TASKS.equals(table)) + if (NameMaps.TABLE_ID_TASKS.equals(table)) { template.setValue(TagData.TASKS_PUSHED_AT, pushedAt); - if (NameMaps.TABLE_ID_TASK_LIST_METADATA.equals(table)) + } + if (NameMaps.TABLE_ID_TASK_LIST_METADATA.equals(table)) { template.setValue(TagData.METADATA_PUSHED_AT, pushedAt); - else if (NameMaps.TABLE_ID_USER_ACTIVITY.equals(table)) + } else if (NameMaps.TABLE_ID_USER_ACTIVITY.equals(table)) { template.setValue(TagData.USER_ACTIVITIES_PUSHED_AT, pushedAt); + } - if (template.getSetValues() != null) + if (template.getSetValues() != null) { PluginServices.getTagDataDao().update(TagData.UUID.eq(tagId), template); + } } else if (!TextUtils.isEmpty(userId)) { if (NameMaps.TABLE_ID_TASKS.equals(table)) { @@ -78,21 +83,23 @@ public class NowBriefed extends ServerToClientMessage } } else { String pushedAtKey = null; - if (NameMaps.TABLE_ID_TASKS.equals(table)) + if (NameMaps.TABLE_ID_TASKS.equals(table)) { pushedAtKey = NameMaps.PUSHED_AT_TASKS; - else if (NameMaps.TABLE_ID_TAGS.equals(table)) + } else if (NameMaps.TABLE_ID_TAGS.equals(table)) { pushedAtKey = NameMaps.PUSHED_AT_TAGS; - else if (NameMaps.TABLE_ID_USER_ACTIVITY.equals(table)) + } else if (NameMaps.TABLE_ID_USER_ACTIVITY.equals(table)) { pushedAtKey = NameMaps.PUSHED_AT_ACTIVITY; - else if (NameMaps.TABLE_ID_USERS.equals(table)) + } else if (NameMaps.TABLE_ID_USERS.equals(table)) { pushedAtKey = NameMaps.PUSHED_AT_USERS; - else if (NameMaps.TABLE_ID_TASK_LIST_METADATA.equals(table)) + } else if (NameMaps.TABLE_ID_TASK_LIST_METADATA.equals(table)) { pushedAtKey = NameMaps.PUSHED_AT_TASK_LIST_METADATA; - else if (NameMaps.TABLE_ID_WAITING_ON_ME.equals(table)) + } else if (NameMaps.TABLE_ID_WAITING_ON_ME.equals(table)) { pushedAtKey = NameMaps.PUSHED_AT_WAITING_ON_ME; + } - if (pushedAtKey != null) + if (pushedAtKey != null) { Preferences.setLong(pushedAtKey, pushedAt); + } } } else { diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ReplayOutstandingEntries.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ReplayOutstandingEntries.java index c5e215e79..e16dea6a4 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ReplayOutstandingEntries.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ReplayOutstandingEntries.java @@ -72,14 +72,16 @@ public class ReplayOutstandingEntries property = NameMaps.localColumnNameToProperty(table, column); // set values to model - if (property != null) + if (property != null) { property.accept(visitor, instance); + } } model.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true); @@ -110,24 +112,27 @@ public class ReplayOutstandingEntries property, OE data) { Integer i = data.getMergedValues().getAsInteger(OutstandingEntry.VALUE_STRING_PROPERTY.name); - if (i != null) + if (i != null) { model.setValue(property, i); + } return null; } @Override public Void visitLong(Property property, OE data) { Long l = data.getMergedValues().getAsLong(OutstandingEntry.VALUE_STRING_PROPERTY.name); - if (l != null) + if (l != null) { model.setValue(property, l); + } return null; } @Override public Void visitDouble(Property property, OE data) { Double d = data.getMergedValues().getAsDouble(OutstandingEntry.VALUE_STRING_PROPERTY.name); - if (d != null) + if (d != null) { model.setValue(property, d); + } return null; } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ReplayTaskListMetadataOutstanding.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ReplayTaskListMetadataOutstanding.java index 7f3f96b70..14b95648c 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ReplayTaskListMetadataOutstanding.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ReplayTaskListMetadataOutstanding.java @@ -14,8 +14,9 @@ public class ReplayTaskListMetadataOutstanding extends ReplayOutstandingEntries< @Override protected boolean shouldSaveModel(TaskListMetadata model) { if (model.containsNonNullValue(TaskListMetadata.TASK_IDS) && - TaskListMetadata.taskIdsIsEmpty(model.getValue(TaskListMetadata.TASK_IDS))) + TaskListMetadata.taskIdsIsEmpty(model.getValue(TaskListMetadata.TASK_IDS))) { return false; + } return true; } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ServerToClientMessage.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ServerToClientMessage.java index fa6444089..428bf7737 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ServerToClientMessage.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ServerToClientMessage.java @@ -32,62 +32,65 @@ public abstract class ServerToClientMessage { public static ServerToClientMessage instantiateMessage(JSONObject json) { String type = json.optString("type"); - if (TYPE_MAKE_CHANGES.equals(type)) + if (TYPE_MAKE_CHANGES.equals(type)) { return instantiateMakeChanges(json); - else if (TYPE_NOW_BRIEFED.equals(type)) + } else if (TYPE_NOW_BRIEFED.equals(type)) { return instantiateNowBriefed(json); - else if (TYPE_ACKNOWLEDGE_CHANGE.equals(type)) + } else if (TYPE_ACKNOWLEDGE_CHANGE.equals(type)) { return new AcknowledgeChange(json); - else if (TYPE_USER_DATA.equals(type)) + } else if (TYPE_USER_DATA.equals(type)) { return new UserData(json); - else if (TYPE_DOUBLE_CHECK.equals(type)) + } else if (TYPE_DOUBLE_CHECK.equals(type)) { return new DoubleCheck(json); - else if (TYPE_USER_MIGRATED.equals(type)) + } else if (TYPE_USER_MIGRATED.equals(type)) { return new UserMigrated(json); - else if (TYPE_DEBUG.equals(type)) + } else if (TYPE_DEBUG.equals(type)) { return new Debug(json); + } return null; } private static MakeChanges instantiateMakeChanges(JSONObject json) { String table = json.optString("table"); - if (NameMaps.TABLE_ID_TASKS.equals(table)) + if (NameMaps.TABLE_ID_TASKS.equals(table)) { return new MakeChanges(json, PluginServices.getTaskDao()); - else if (NameMaps.TABLE_ID_TAGS.equals(table)) + } else if (NameMaps.TABLE_ID_TAGS.equals(table)) { return new MakeChanges(json, PluginServices.getTagDataDao()); - else if (NameMaps.TABLE_ID_USERS.equals(table)) + } else if (NameMaps.TABLE_ID_USERS.equals(table)) { return new MakeChanges(json, PluginServices.getUserDao()); - else if (NameMaps.TABLE_ID_USER_ACTIVITY.equals(table)) + } else if (NameMaps.TABLE_ID_USER_ACTIVITY.equals(table)) { return new MakeChanges(json, PluginServices.getUserActivityDao()); - else if (NameMaps.TABLE_ID_ATTACHMENTS.equals(table)) + } else if (NameMaps.TABLE_ID_ATTACHMENTS.equals(table)) { return new MakeChanges(json, PluginServices.getTaskAttachmentDao()); - else if (NameMaps.TABLE_ID_TASK_LIST_METADATA.equals(table)) + } else if (NameMaps.TABLE_ID_TASK_LIST_METADATA.equals(table)) { return new MakeChanges(json, PluginServices.getTaskListMetadataDao()); - else if (NameMaps.TABLE_ID_WAITING_ON_ME.equals(table)) + } else if (NameMaps.TABLE_ID_WAITING_ON_ME.equals(table)) { return new MakeChanges(json, PluginServices.getWaitingOnMeDao()); - else + } else { return null; + } } private static NowBriefed instantiateNowBriefed(JSONObject json) { String table = json.optString("table"); - if (NameMaps.TABLE_ID_TASKS.equals(table)) + if (NameMaps.TABLE_ID_TASKS.equals(table)) { return new NowBriefed(json, PluginServices.getTaskDao()); - else if (NameMaps.TABLE_ID_TAGS.equals(table)) + } else if (NameMaps.TABLE_ID_TAGS.equals(table)) { return new NowBriefed(json, PluginServices.getTagDataDao()); - else if (NameMaps.TABLE_ID_USER_ACTIVITY.equals(table)) + } else if (NameMaps.TABLE_ID_USER_ACTIVITY.equals(table)) { return new NowBriefed(json, PluginServices.getUserActivityDao()); - else if (NameMaps.TABLE_ID_USERS.equals(table)) + } else if (NameMaps.TABLE_ID_USERS.equals(table)) { return new NowBriefed(json, PluginServices.getUserDao()); - else if (NameMaps.TABLE_ID_ATTACHMENTS.equals(table)) + } else if (NameMaps.TABLE_ID_ATTACHMENTS.equals(table)) { return new NowBriefed(json, PluginServices.getTaskAttachmentDao()); - else if (NameMaps.TABLE_ID_TASK_LIST_METADATA.equals(table)) + } else if (NameMaps.TABLE_ID_TASK_LIST_METADATA.equals(table)) { return new NowBriefed(json, PluginServices.getTaskListMetadataDao()); - else if (NameMaps.TABLE_ID_WAITING_ON_ME.equals(table)) + } else if (NameMaps.TABLE_ID_WAITING_ON_ME.equals(table)) { return new NowBriefed(json, PluginServices.getWaitingOnMeDao()); - else + } else { return null; + } } } diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/UserData.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/UserData.java index 3653b67f4..b3e04b799 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/UserData.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/UserData.java @@ -24,8 +24,9 @@ public class UserData extends ServerToClientMessage { String uuid = json.optString("uuid"); String email = json.optString("email"); - if (TextUtils.isEmpty(uuid)) + if (TextUtils.isEmpty(uuid)) { return; + } Task taskTemplate = new Task(); taskTemplate.setValue(Task.USER_ID, uuid); diff --git a/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmControlSet.java b/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmControlSet.java index 859d719ff..0d435318e 100644 --- a/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmControlSet.java +++ b/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmControlSet.java @@ -47,8 +47,9 @@ public final class AlarmControlSet extends TaskEditControlSet { alertsContainer.removeAllViews(); TodorooCursor cursor = AlarmService.getInstance().getAlarms(model.getId()); try { - for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) + for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { addAlarm(new Date(cursor.get(AlarmFields.TIME))); + } } finally { cursor.close(); } @@ -70,8 +71,9 @@ public final class AlarmControlSet extends TaskEditControlSet { @Override public String writeToModel(Task task) { - if (initialized && pickerDialog != null) + if (initialized && pickerDialog != null) { pickerDialog.dismiss(); + } return super.writeToModel(task); } @@ -80,13 +82,15 @@ public final class AlarmControlSet extends TaskEditControlSet { LinkedHashSet alarms = new LinkedHashSet(); for (int i = 0; i < alertsContainer.getChildCount(); i++) { Long dateValue = (Long) alertsContainer.getChildAt(i).getTag(); - if (dateValue == null) + if (dateValue == null) { continue; + } alarms.add(dateValue); } - if (AlarmService.getInstance().synchronizeAlarms(task.getId(), alarms)) + if (AlarmService.getInstance().synchronizeAlarms(task.getId(), alarms)) { task.setValue(Task.MODIFICATION_DATE, DateUtilities.now()); + } return null; } diff --git a/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmDetailExposer.java b/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmDetailExposer.java index 72ad0e65a..7655761a6 100644 --- a/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmDetailExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmDetailExposer.java @@ -30,12 +30,14 @@ public class AlarmDetailExposer extends BroadcastReceiver { ContextManager.setContext(context); // get tags associated with this task long taskId = intent.getLongExtra(AstridApiConstants.EXTRAS_TASK_ID, -1); - if (taskId == -1) + if (taskId == -1) { return; + } String taskDetail = getTaskDetails(context, taskId); - if (taskDetail == null) + if (taskDetail == null) { return; + } // transmit Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_SEND_DETAILS); @@ -57,15 +59,18 @@ public class AlarmDetailExposer extends BroadcastReceiver { } } - if (nextTime == -1) + if (nextTime == -1) { return null; + } int flags = DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_SHOW_TIME; Date today = new Date(); Date alarm = new Date(nextTime); - if (today.getYear() == alarm.getYear()) + if (today.getYear() == alarm.getYear()) { flags |= DateUtils.FORMAT_NO_YEAR; - if (alarm.getTime() - today.getTime() > DateUtilities.ONE_DAY) + } + if (alarm.getTime() - today.getTime() > DateUtilities.ONE_DAY) { flags |= DateUtils.FORMAT_SHOW_DATE; + } CharSequence durationString = DateUtils.formatDateTime(context, nextTime, flags); return " " + durationString; //$NON-NLS-1$ diff --git a/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmService.java b/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmService.java index 4dd5a4ec1..6f46d973d 100644 --- a/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmService.java +++ b/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmService.java @@ -45,8 +45,9 @@ public class AlarmService { private static AlarmService instance = null; public static synchronized AlarmService getInstance() { - if (instance == null) + if (instance == null) { instance = new AlarmService(); + } return instance; } @@ -96,8 +97,9 @@ public class AlarmService { } }, true); - if (changed) + if (changed) { scheduleAlarms(taskId); + } return changed; } @@ -186,8 +188,9 @@ public class AlarmService { */ @SuppressWarnings("nls") private void scheduleAlarm(Metadata alarm) { - if (alarm == null) + if (alarm == null) { return; + } long taskId = alarm.getValue(Metadata.TASK); @@ -196,12 +199,13 @@ public class AlarmService { PendingIntent pendingIntent = pendingIntentForAlarm(alarm, taskId); long time = alarm.getValue(AlarmFields.TIME); - if (time == 0 || time == NO_ALARM) + if (time == 0 || time == NO_ALARM) { am.cancel(pendingIntent); - else if (time > DateUtilities.now()) { - if (Constants.DEBUG) + } else if (time > DateUtilities.now()) { + if (Constants.DEBUG) { Log.e("Astrid", "Alarm (" + taskId + ", " + ReminderService.TYPE_ALARM + ", " + alarm.getId() + ") set for " + new Date(time)); + } am.set(AlarmManager.RTC_WAKEUP, time, pendingIntent); } } diff --git a/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmTaskRepeatListener.java b/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmTaskRepeatListener.java index e0ecb8cf9..4cbf13bc2 100644 --- a/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmTaskRepeatListener.java +++ b/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmTaskRepeatListener.java @@ -23,20 +23,24 @@ public class AlarmTaskRepeatListener extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { ContextManager.setContext(context); long taskId = intent.getLongExtra(AstridApiConstants.EXTRAS_TASK_ID, -1); - if (taskId == -1) + if (taskId == -1) { return; + } long oldDueDate = intent.getLongExtra(AstridApiConstants.EXTRAS_OLD_DUE_DATE, 0); - if (oldDueDate == 0) + if (oldDueDate == 0) { oldDueDate = DateUtilities.now(); + } long newDueDate = intent.getLongExtra(AstridApiConstants.EXTRAS_NEW_DUE_DATE, -1); - if (newDueDate <= 0 || newDueDate <= oldDueDate) + if (newDueDate <= 0 || newDueDate <= oldDueDate) { return; + } TodorooCursor cursor = AlarmService.getInstance().getAlarms(taskId); try { - if (cursor.getCount() == 0) + if (cursor.getCount() == 0) { return; + } Metadata metadata = new Metadata(); LinkedHashSet alarms = new LinkedHashSet(cursor.getCount()); diff --git a/astrid/plugin-src/com/todoroo/astrid/backup/BackupPreferences.java b/astrid/plugin-src/com/todoroo/astrid/backup/BackupPreferences.java index f55319021..8abbc339d 100644 --- a/astrid/plugin-src/com/todoroo/astrid/backup/BackupPreferences.java +++ b/astrid/plugin-src/com/todoroo/astrid/backup/BackupPreferences.java @@ -62,8 +62,9 @@ public class BackupPreferences extends TodorooPreferenceActivity { @Override public void onChildViewAdded(View parent, View child) { View view = findViewById(R.id.status); - if (view != null) + if (view != null) { view.setBackgroundColor(statusColor); + } } }); @@ -101,10 +102,11 @@ public class BackupPreferences extends TodorooPreferenceActivity { // auto if (r.getString(R.string.backup_BPr_auto_key).equals( preference.getKey())) { - if (value != null && !(Boolean) value) + if (value != null && !(Boolean) value) { preference.setSummary(R.string.backup_BPr_auto_disabled); - else + } else { preference.setSummary(R.string.backup_BPr_auto_enabled); + } } // status @@ -140,8 +142,9 @@ public class BackupPreferences extends TodorooPreferenceActivity { preference.setSummary(subtitle); View view = findViewById(R.id.status); - if (view != null) + if (view != null) { view.setBackgroundColor(statusColor); + } } } diff --git a/astrid/plugin-src/com/todoroo/astrid/backup/BackupService.java b/astrid/plugin-src/com/todoroo/astrid/backup/BackupService.java index 113ed9b2c..3ccf04d77 100644 --- a/astrid/plugin-src/com/todoroo/astrid/backup/BackupService.java +++ b/astrid/plugin-src/com/todoroo/astrid/backup/BackupService.java @@ -128,13 +128,15 @@ public class BackupService extends Service { } }; File astridDir = backupDirectorySetting.getBackupDirectory(); - if (astridDir == null) + if (astridDir == null) { return; + } // grab all backup files, sort by modified date, delete old ones File[] files = astridDir.listFiles(backupFileFilter); - if (files == null) + if (files == null) { return; + } Arrays.sort(files, new Comparator() { @Override @@ -143,8 +145,9 @@ public class BackupService extends Service { } }); for (int i = DAYS_TO_KEEP_BACKUP; i < files.length; i++) { - if (!files[i].delete()) + if (!files[i].delete()) { Log.i("astrid-backups", "Unable to delete: " + files[i]); //$NON-NLS-1$ //$NON-NLS-2$ + } } } diff --git a/astrid/plugin-src/com/todoroo/astrid/backup/FilePickerBuilder.java b/astrid/plugin-src/com/todoroo/astrid/backup/FilePickerBuilder.java index 7a0b8ae48..890e24c07 100644 --- a/astrid/plugin-src/com/todoroo/astrid/backup/FilePickerBuilder.java +++ b/astrid/plugin-src/com/todoroo/astrid/backup/FilePickerBuilder.java @@ -54,8 +54,9 @@ public class FilePickerBuilder extends AlertDialog.Builder implements DialogInte AndroidUtilities.sortFilesByDateDesc(filesAsFile); files = new String[filesAsFile.length]; - for (int i = 0; i < files.length; i++) + for (int i = 0; i < files.length; i++) { files[i] = filesAsFile[i].getName(); + } setItems(files, this); } else { diff --git a/astrid/plugin-src/com/todoroo/astrid/backup/TasksXmlExporter.java b/astrid/plugin-src/com/todoroo/astrid/backup/TasksXmlExporter.java index 493c960ce..927699261 100644 --- a/astrid/plugin-src/com/todoroo/astrid/backup/TasksXmlExporter.java +++ b/astrid/plugin-src/com/todoroo/astrid/backup/TasksXmlExporter.java @@ -107,8 +107,9 @@ public class TasksXmlExporter { progressDialog.setCancelable(false); progressDialog.setIndeterminate(false); progressDialog.show(); - if (context instanceof Activity) + if (context instanceof Activity) { progressDialog.setOwnerActivity((Activity) context); + } } new Thread(new Runnable() { @@ -119,15 +120,17 @@ public class TasksXmlExporter { exportType); int tasks = taskService.countTasks(); - if (tasks > 0) + if (tasks > 0) { doTasksExport(output); + } Preferences.setLong(BackupPreferences.PREF_BACKUP_LAST_DATE, DateUtilities.now()); Preferences.setString(BackupPreferences.PREF_BACKUP_LAST_ERROR, null); - if (exportType == ExportType.EXPORT_TYPE_MANUAL) + if (exportType == ExportType.EXPORT_TYPE_MANUAL) { onFinishExport(output); + } } catch (IOException e) { switch (exportType) { case EXPORT_TYPE_MANUAL: @@ -144,8 +147,9 @@ public class TasksXmlExporter { break; } } finally { - if (runAfterExport != null) + if (runAfterExport != null) { runAfterExport.run(); + } } } }).start(); @@ -226,9 +230,11 @@ public class TasksXmlExporter { private void serializeModel(AbstractModel model, Property[] properties, Property... excludes) { outer: for (Property property : properties) { - for (Property exclude : excludes) - if (property.name.equals(exclude.name)) + for (Property exclude : excludes) { + if (property.name.equals(exclude.name)) { continue outer; + } + } try { property.accept(xmlWritingVisitor, model); @@ -303,8 +309,9 @@ public class TasksXmlExporter { public Void visitString(Property property, AbstractModel data) { try { String value = data.getValue(property); - if (value == null) + if (value == null) { return null; + } xml.attribute(null, property.name, value); } catch (UnsupportedOperationException e) { // didn't read this value, do nothing @@ -324,15 +331,16 @@ public class TasksXmlExporter { @Override public void run() { - if (exportCount == 0) + if (exportCount == 0) { Toast.makeText(context, context.getString(R.string.export_toast_no_tasks), Toast.LENGTH_LONG).show(); - else { + } else { CharSequence text = String.format(context.getString(R.string.export_toast), context.getResources().getQuantityString(R.plurals.Ntasks, exportCount, exportCount), outputFile); Toast.makeText(context, text, Toast.LENGTH_LONG).show(); - if (progressDialog.isShowing() && context instanceof Activity) + if (progressDialog.isShowing() && context instanceof Activity) { DialogUtilities.dismissDialog((Activity) context, progressDialog); + } } } }); diff --git a/astrid/plugin-src/com/todoroo/astrid/backup/TasksXmlImporter.java b/astrid/plugin-src/com/todoroo/astrid/backup/TasksXmlImporter.java index a46b0c5cb..37a3efb77 100644 --- a/astrid/plugin-src/com/todoroo/astrid/backup/TasksXmlImporter.java +++ b/astrid/plugin-src/com/todoroo/astrid/backup/TasksXmlImporter.java @@ -109,8 +109,9 @@ public class TasksXmlImporter { progressDialog.setIndeterminate(true); try { progressDialog.show(); - if (context instanceof Activity) + if (context instanceof Activity) { progressDialog.setOwnerActivity((Activity) context); + } } catch (BadTokenException e) { // Running from a unit test or some such thing } @@ -148,14 +149,15 @@ public class TasksXmlImporter { // Process if (tag.equals(BackupConstants.ASTRID_TAG)) { String format = xpp.getAttributeValue(null, BackupConstants.ASTRID_ATTR_FORMAT); - if (TextUtils.equals(format, FORMAT1)) + if (TextUtils.equals(format, FORMAT1)) { new Format1TaskImporter(xpp); - else if (TextUtils.equals(format, FORMAT2)) + } else if (TextUtils.equals(format, FORMAT2)) { new Format2TaskImporter(xpp); - else + } else { throw new UnsupportedOperationException( "Did not know how to import tasks with xml format '" + format + "'"); + } } } } @@ -165,8 +167,9 @@ public class TasksXmlImporter { handler.post(new Runnable() { @Override public void run() { - if (progressDialog.isShowing() && context instanceof Activity) + if (progressDialog.isShowing() && context instanceof Activity) { DialogUtilities.dismissDialog((Activity) context, progressDialog); + } showSummary(); } }); @@ -222,8 +225,9 @@ public class TasksXmlImporter { while (xpp.next() != XmlPullParser.END_DOCUMENT) { String tag = xpp.getName(); - if (tag == null || xpp.getEventType() == XmlPullParser.END_TAG) + if (tag == null || xpp.getEventType() == XmlPullParser.END_TAG) { continue; + } try { if (tag.equals(BackupConstants.TASK_TAG)) { @@ -272,12 +276,14 @@ public class TasksXmlImporter { // fix for failed migration in 4.0.6 if (version < UpgradeService.V4_0_6) { if (!completionDate.equals("0") && - !completionDate.equals(Long.toString(cursor.get(Task.COMPLETION_DATE)))) + !completionDate.equals(Long.toString(cursor.get(Task.COMPLETION_DATE)))) { existingTask = cursor.get(Task.ID); + } if (!deletionDate.equals("0") && - !deletionDate.equals(Long.toString(cursor.get(Task.DELETION_DATE)))) + !deletionDate.equals(Long.toString(cursor.get(Task.DELETION_DATE)))) { existingTask = cursor.get(Task.ID); + } } if (existingTask == 0) { @@ -291,13 +297,15 @@ public class TasksXmlImporter { // else, make a new task model and add away. deserializeModel(currentTask, Task.PROPERTIES); - if (version < UpgradeService.V4_0_6) + if (version < UpgradeService.V4_0_6) { adjustDueDateScheme(currentTask); + } - if (existingTask > 0) + if (existingTask > 0) { currentTask.setId(existingTask); - else + } else { currentTask.setId(Task.NO_ID); + } // Save the task to the database. taskService.save(currentTask); @@ -321,8 +329,9 @@ public class TasksXmlImporter { } private void parseMetadata() { - if (!currentTask.isSaved()) + if (!currentTask.isSaved()) { return; + } metadata.clear(); deserializeModel(metadata, Metadata.PROPERTIES); metadata.setId(Metadata.NO_ID); @@ -355,18 +364,20 @@ public class TasksXmlImporter { public Void visitInteger(Property property, AbstractModel data) { String value = xpp.getAttributeValue(null, property.name); - if (value != null) + if (value != null) { data.setValue(property, TasksXmlExporter.XML_NULL.equals(value) ? null : Integer.parseInt(value)); + } return null; } @Override public Void visitLong(Property property, AbstractModel data) { String value = xpp.getAttributeValue(null, property.name); - if (value != null) + if (value != null) { data.setValue(property, TasksXmlExporter.XML_NULL.equals(value) ? null : Long.parseLong(value)); + } return null; } @@ -374,9 +385,10 @@ public class TasksXmlImporter { public Void visitDouble(Property property, AbstractModel data) { String value = xpp.getAttributeValue(null, property.name); - if (value != null) + if (value != null) { data.setValue(property, TasksXmlExporter.XML_NULL.equals(value) ? null : Double.parseDouble(value)); + } return null; } @@ -384,8 +396,9 @@ public class TasksXmlImporter { public Void visitString(Property property, AbstractModel data) { String value = xpp.getAttributeValue(null, property.name); - if (value != null) + if (value != null) { data.setValue(property, value); + } return null; } @@ -412,11 +425,11 @@ public class TasksXmlImporter { String tag = xpp.getName(); try { - if (BackupConstants.TASK_TAG.equals(tag) && xpp.getEventType() == XmlPullParser.END_TAG) + if (BackupConstants.TASK_TAG.equals(tag) && xpp.getEventType() == XmlPullParser.END_TAG) { saveTags(); - else if (tag == null || xpp.getEventType() == XmlPullParser.END_TAG) + } else if (tag == null || xpp.getEventType() == XmlPullParser.END_TAG) { continue; - else if (tag.equals(BackupConstants.TASK_TAG)) { + } else if (tag.equals(BackupConstants.TASK_TAG)) { // Parse currentTask = parseTask(); } else if (currentTask != null) { @@ -527,10 +540,11 @@ public class TasksXmlImporter { } if (upgradeNotes != null) { - if (task.containsValue(Task.NOTES) && task.getValue(Task.NOTES).length() > 0) + if (task.containsValue(Task.NOTES) && task.getValue(Task.NOTES).length() > 0) { task.setValue(Task.NOTES, task.getValue(Task.NOTES) + "\n" + upgradeNotes); - else + } else { task.setValue(Task.NOTES, upgradeNotes); + } upgradeNotes = null; } @@ -574,11 +588,12 @@ public class TasksXmlImporter { BackupDateUtilities.getTaskDueDateFromIso8601String(value).getTime()); } else if (field.equals(LegacyTaskModel.PREFERRED_DUE_DATE)) { String definite = xpp.getAttributeValue(null, LegacyTaskModel.DEFINITE_DUE_DATE); - if (definite != null) + if (definite != null) { ; // handled above - else + } else { task.setValue(Task.DUE_DATE, BackupDateUtilities.getTaskDueDateFromIso8601String(value).getTime()); + } } else if (field.equals(LegacyTaskModel.HIDDEN_UNTIL)) { task.setValue(Task.HIDE_UNTIL, BackupDateUtilities.getDateFromIso8601String(value).getTime()); @@ -614,8 +629,9 @@ public class TasksXmlImporter { task.setValue(Task.RECURRENCE, rrule.toIcal()); } } else if (field.equals(LegacyTaskModel.FLAGS)) { - if (Integer.parseInt(value) == LegacyTaskModel.FLAG_SYNC_ON_COMPLETE) + if (Integer.parseInt(value) == LegacyTaskModel.FLAG_SYNC_ON_COMPLETE) { syncOnComplete = true; + } } else { return false; } diff --git a/astrid/plugin-src/com/todoroo/astrid/calls/PhoneStateChangedReceiver.java b/astrid/plugin-src/com/todoroo/astrid/calls/PhoneStateChangedReceiver.java index 8ddc03788..6a498b464 100644 --- a/astrid/plugin-src/com/todoroo/astrid/calls/PhoneStateChangedReceiver.java +++ b/astrid/plugin-src/com/todoroo/astrid/calls/PhoneStateChangedReceiver.java @@ -41,8 +41,9 @@ public class PhoneStateChangedReceiver extends BroadcastReceiver { if (TelephonyManager.EXTRA_STATE_RINGING.equals(state)) { String number = digitsOnly(intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER)); - if (TextUtils.isEmpty(number)) + if (TextUtils.isEmpty(number)) { return; + } Preferences.setString(PREF_LAST_INCOMING_NUMBER, number); } else if (TelephonyManager.EXTRA_STATE_IDLE.equals(state)) { @@ -81,8 +82,9 @@ public class PhoneStateChangedReceiver extends BroadcastReceiver { } } try { - if (calls == null) + if (calls == null) { return; + } if (calls.moveToFirst()) { int numberIndex = calls.getColumnIndex(Calls.NUMBER); String number = calls.getString(numberIndex); @@ -121,8 +123,9 @@ public class PhoneStateChangedReceiver extends BroadcastReceiver { } catch (Exception e) { Log.e("phone-state", "Unexpected exception in PhoneStateChangedReceiver", e); } finally { - if (calls != null) + if (calls != null) { calls.close(); + } } } }.start(); @@ -130,13 +133,15 @@ public class PhoneStateChangedReceiver extends BroadcastReceiver { } private String digitsOnly(String number) { - if (number == null) + if (number == null) { return ""; + } StringBuilder builder = new StringBuilder(); for (int i = 0; i < number.length(); i++) { char c = number.charAt(i); - if (Character.isDigit(c)) + if (Character.isDigit(c)) { builder.append(c); + } } return builder.toString(); } diff --git a/astrid/plugin-src/com/todoroo/astrid/core/CoreFilterExposer.java b/astrid/plugin-src/com/todoroo/astrid/core/CoreFilterExposer.java index ed406f9f5..f24126b90 100644 --- a/astrid/plugin-src/com/todoroo/astrid/core/CoreFilterExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/core/CoreFilterExposer.java @@ -63,13 +63,15 @@ public final class CoreFilterExposer extends BroadcastReceiver implements Astrid List filters = new ArrayList(3); filters.add(buildInboxFilter(r)); - if (Preferences.getBoolean(R.string.p_show_today_filter, true)) + if (Preferences.getBoolean(R.string.p_show_today_filter, true)) { filters.add(getTodayFilter(r)); + } if (Preferences.getBoolean(R.string.p_show_waiting_on_me_filter, true) && PluginServices.getWaitingOnMeDao().count(Query.select(WaitingOnMe.ID).where(Criterion.and(WaitingOnMe.DELETED_AT.eq(0), - Criterion.or(WaitingOnMe.ACKNOWLEDGED.isNull(), WaitingOnMe.ACKNOWLEDGED.neq(1))))) > 0) + Criterion.or(WaitingOnMe.ACKNOWLEDGED.isNull(), WaitingOnMe.ACKNOWLEDGED.neq(1))))) > 0) { filters.add(getWaitingOnMeFilter(r)); + } // transmit filter list return filters.toArray(new FilterListItem[filters.size()]); @@ -141,8 +143,9 @@ public final class CoreFilterExposer extends BroadcastReceiver implements Astrid @Override public FilterListItem[] getFilters() { - if (ContextManager.getContext() == null || ContextManager.getContext().getResources() == null) + if (ContextManager.getContext() == null || ContextManager.getContext().getResources() == null) { return null; + } Resources r = ContextManager.getContext().getResources(); return prepareFilters(r); diff --git a/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterActivity.java b/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterActivity.java index 93f1c39bc..1c2fb183f 100644 --- a/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterActivity.java +++ b/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterActivity.java @@ -119,16 +119,18 @@ public class CustomFilterActivity extends SherlockFragmentActivity { } return criterion.text; } else if (criterion instanceof TextInputCriterion) { - if (selectedText == null) + if (selectedText == null) { return criterion.text; + } return criterion.text.replace("?", selectedText); } throw new UnsupportedOperationException("Unknown criterion type"); //$NON-NLS-1$ } public String getValueFromCriterion() { - if (type == TYPE_UNIVERSE) + if (type == TYPE_UNIVERSE) { return null; + } if (criterion instanceof MultipleSelectCriterion) { if (selectedIndex >= 0 && ((MultipleSelectCriterion) criterion).entryValues != null && selectedIndex < ((MultipleSelectCriterion) criterion).entryValues.length) { @@ -163,8 +165,9 @@ public class CustomFilterActivity extends SherlockFragmentActivity { ContextManager.setContext(this); ActionBar ab = getSupportActionBar(); - if (ab != null) + if (ab != null) { ab.setDisplayHomeAsUpEnabled(true); + } setContentView(R.layout.custom_filter_activity); setTitle(R.string.FLA_new_filter); @@ -187,10 +190,11 @@ public class CustomFilterActivity extends SherlockFragmentActivity { private void setupForDialogOrFullscreen() { isDialog = AstridPreferences.useTabletLayout(this); - if (isDialog) + if (isDialog) { setTheme(ThemeService.getDialogTheme()); - else + } else { ThemeService.applyTheme(this); + } } /** @@ -378,8 +382,9 @@ public class CustomFilterActivity extends SherlockFragmentActivity { @Override public void finish() { super.finish(); - if (!AstridPreferences.useTabletLayout(this)) + if (!AstridPreferences.useTabletLayout(this)) { AndroidUtilities.callOverridePendingTransition(this, R.anim.slide_right_in, R.anim.slide_right_out); + } } @@ -387,8 +392,9 @@ public class CustomFilterActivity extends SherlockFragmentActivity { @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { - if (menu.size() > 0) + if (menu.size() > 0) { menu.clear(); + } // view holder if (v.getTag() != null) { @@ -404,8 +410,9 @@ public class CustomFilterActivity extends SherlockFragmentActivity { for (int i = 0; i < adapter.getCount(); i++) { CriterionInstance instance = adapter.getItem(i); String value = instance.getValueFromCriterion(); - if (value == null && instance.criterion.sql != null && instance.criterion.sql.contains("?")) + if (value == null && instance.criterion.sql != null && instance.criterion.sql.contains("?")) { value = ""; + } String title = instance.getTitleFromCriterion(); @@ -429,9 +436,9 @@ public class CustomFilterActivity extends SherlockFragmentActivity { // special code for all tasks universe - if (instance.criterion.sql == null) + if (instance.criterion.sql == null) { sql.append(TaskCriteria.activeVisibleMine()).append(' '); - else { + } else { String subSql = instance.criterion.sql.replace("?", UnaryCriterion.sanitize(value)); sql.append(Task.ID).append(" IN (").append(subSql).append(") "); } @@ -474,8 +481,9 @@ public class CustomFilterActivity extends SherlockFragmentActivity { for (int i = 0; i < adapter.getCount(); i++) { CriterionInstance instance = adapter.getItem(i); String value = instance.getValueFromCriterion(); - if (value == null && instance.criterion.sql != null && instance.criterion.sql.contains("?")) + if (value == null && instance.criterion.sql != null && instance.criterion.sql.contains("?")) { value = ""; + } switch (instance.type) { case CriterionInstance.TYPE_ADD: @@ -491,9 +499,9 @@ public class CustomFilterActivity extends SherlockFragmentActivity { } // special code for all tasks universe - if (instance.criterion.sql == null) + if (instance.criterion.sql == null) { sql.append(TaskCriteria.activeVisibleMine()).append(' '); - else { + } else { String subSql = instance.criterion.sql.replace("?", UnaryCriterion.sanitize(value)); subSql = PermaSql.replacePlaceholders(subSql); sql.append(Task.ID).append(" IN (").append(subSql).append(") "); @@ -523,7 +531,9 @@ public class CustomFilterActivity extends SherlockFragmentActivity { private V getNth(int index, Map map) { int i = 0; for (V v : map.values()) { - if (i == index) return v; + if (i == index) { + return v; + } i++; } throw new IllegalArgumentException("out of bounds"); diff --git a/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterAdapter.java b/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterAdapter.java index 9cc800db7..1924950f0 100644 --- a/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterAdapter.java +++ b/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterAdapter.java @@ -51,10 +51,12 @@ public class CustomFilterAdapter extends ArrayAdapter { @Override public void onClick(View v) { ViewHolder viewHolder = (ViewHolder) v.getTag(); - if (viewHolder == null) + if (viewHolder == null) { return; - if (viewHolder.item.type == CriterionInstance.TYPE_UNIVERSE) + } + if (viewHolder.item.type == CriterionInstance.TYPE_UNIVERSE) { return; + } showOptionsFor(viewHolder.item, new Runnable() { @Override @@ -69,14 +71,16 @@ public class CustomFilterAdapter extends ArrayAdapter { public void onCreateContextMenu(ContextMenu menu, View v) { // view holder ViewHolder viewHolder = (ViewHolder) v.getTag(); - if (viewHolder == null || viewHolder.item.type == CriterionInstance.TYPE_UNIVERSE) + if (viewHolder == null || viewHolder.item.type == CriterionInstance.TYPE_UNIVERSE) { return; + } int index = getPosition(viewHolder.item); menu.setHeaderTitle(viewHolder.name.getText()); - if (viewHolder.icon.getVisibility() == View.VISIBLE) + if (viewHolder.icon.getVisibility() == View.VISIBLE) { menu.setHeaderIcon(viewHolder.icon.getDrawable()); + } MenuItem item = menu.add(CustomFilterActivity.MENU_GROUP_CONTEXT_TYPE, CriterionInstance.TYPE_INTERSECT, index, @@ -116,8 +120,9 @@ public class CustomFilterAdapter extends ArrayAdapter { @Override public void onClick(DialogInterface click, int which) { item.selectedIndex = which; - if (onComplete != null) + if (onComplete != null) { onComplete.run(); + } } }; dialog.setAdapter(adapter, listener); @@ -136,8 +141,9 @@ public class CustomFilterAdapter extends ArrayAdapter { @Override public void onClick(DialogInterface dialogInterface, int which) { item.selectedText = editText.getText().toString(); - if (onComplete != null) + if (onComplete != null) { onComplete.run(); + } } }); } @@ -203,8 +209,9 @@ public class CustomFilterAdapter extends ArrayAdapter { viewHolder.icon.setVisibility(item.criterion.icon == null ? View.GONE : View.VISIBLE); - if (item.criterion.icon != null) + if (item.criterion.icon != null) { viewHolder.icon.setImageBitmap(item.criterion.icon); + } viewHolder.name.setText(title); diff --git a/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterExposer.java b/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterExposer.java index 690dcdc2a..a499293a3 100644 --- a/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterExposer.java @@ -80,9 +80,10 @@ public final class CustomFilterExposer extends BroadcastReceiver implements Astr boolean useCustomFilters = Preferences.getBoolean(R.string.p_use_filters, true); StoreObjectDao dao = PluginServices.getStoreObjectDao(); TodorooCursor cursor = null; - if (useCustomFilters) + if (useCustomFilters) { cursor = dao.query(Query.select(StoreObject.PROPERTIES).where( StoreObject.TYPE.eq(SavedFilter.TYPE)).orderBy(Order.asc(SavedFilter.NAME))); + } try { ArrayList list = new ArrayList(); @@ -100,8 +101,9 @@ public final class CustomFilterExposer extends BroadcastReceiver implements Astr list.add(recent); } - if (Preferences.getBoolean(R.string.p_show_ive_assigned_filter, true)) + if (Preferences.getBoolean(R.string.p_show_ive_assigned_filter, true)) { list.add(getAssignedByMeFilter(r)); + } if (useCustomFilters && cursor != null) { StoreObject savedFilter = new StoreObject(); @@ -122,8 +124,9 @@ public final class CustomFilterExposer extends BroadcastReceiver implements Astr return list.toArray(new Filter[list.size()]); } finally { - if (cursor != null) + if (cursor != null) { cursor.close(); + } } } @@ -184,8 +187,9 @@ public final class CustomFilterExposer extends BroadcastReceiver implements Astr @Override public FilterListItem[] getFilters() { - if (ContextManager.getContext() == null) + if (ContextManager.getContext() == null) { return null; + } return prepareFilters(ContextManager.getContext()); } diff --git a/astrid/plugin-src/com/todoroo/astrid/core/DefaultsPreferences.java b/astrid/plugin-src/com/todoroo/astrid/core/DefaultsPreferences.java index b64101fc5..cb30ae250 100644 --- a/astrid/plugin-src/com/todoroo/astrid/core/DefaultsPreferences.java +++ b/astrid/plugin-src/com/todoroo/astrid/core/DefaultsPreferences.java @@ -62,27 +62,28 @@ public class DefaultsPreferences extends TodorooPreferenceActivity { R.array.EPr_default_reminders_mode_values, R.string.EPr_default_reminders_mode_desc); } else if (r.getString(R.string.p_rmd_default_random_hours).equals(preference.getKey())) { int index = AndroidUtilities.indexOf(r.getStringArray(R.array.EPr_reminder_random_hours), (String) value); - if (index <= 0) + if (index <= 0) { preference.setSummary(r.getString(R.string.rmd_EPr_defaultRemind_desc_disabled)); - else { + } else { String setting = r.getStringArray(R.array.EPr_reminder_random)[index]; preference.setSummary(r.getString(R.string.rmd_EPr_defaultRemind_desc, setting)); } } else if (r.getString(R.string.gcal_p_default).equals(preference.getKey())) { ListPreference listPreference = (ListPreference) preference; int index = AndroidUtilities.indexOf(listPreference.getEntryValues(), (String) value); - if (index <= 0) + if (index <= 0) { preference.setSummary(r.getString(R.string.EPr_default_addtocalendar_desc_disabled)); - else { + } else { String setting = listPreference.getEntries()[index].toString(); preference.setSummary(r.getString(R.string.EPr_default_addtocalendar_desc, setting)); } } else if (r.getString(R.string.p_voiceInputCreatesTask).equals(preference.getKey())) { preference.setEnabled(Preferences.getBoolean(R.string.p_voiceInputEnabled, false)); - if (value != null && !(Boolean) value) + if (value != null && !(Boolean) value) { preference.setSummary(R.string.EPr_voiceInputCreatesTask_desc_disabled); - else + } else { preference.setSummary(R.string.EPr_voiceInputCreatesTask_desc_enabled); + } } } diff --git a/astrid/plugin-src/com/todoroo/astrid/core/LinkActionExposer.java b/astrid/plugin-src/com/todoroo/astrid/core/LinkActionExposer.java index 6f5aa76b9..4a07e49bf 100644 --- a/astrid/plugin-src/com/todoroo/astrid/core/LinkActionExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/core/LinkActionExposer.java @@ -37,15 +37,18 @@ import java.util.List; public class LinkActionExposer { public static TaskAction getActionsForTask(Context context, Task task, boolean hasAttachments, boolean hasNotes) { - if (task == null) return null; + if (task == null) { + return null; + } Spannable titleSpan = Spannable.Factory.getInstance().newSpannable(task.getValue(Task.TITLE)); Linkify.addLinks(titleSpan, Linkify.ALL); URLSpan[] urlSpans = titleSpan.getSpans(0, titleSpan.length(), URLSpan.class); if (urlSpans.length == 0 && !hasNotes && - !hasAttachments) + !hasAttachments) { return null; + } PackageManager pm = context.getPackageManager(); @@ -55,8 +58,9 @@ public class LinkActionExposer { int end = titleSpan.getSpanEnd(urlSpan); String text = titleSpan.subSequence(start, end).toString(); TaskAction taskAction = createLinkAction(context, task.getId(), url, text, pm); - if (taskAction != null) + if (taskAction != null) { return taskAction; + } } Resources r = context.getResources(); @@ -94,8 +98,9 @@ public class LinkActionExposer { } // no intents -> no item - else + else { return null; + } Resources r = context.getResources(); Drawable icon; @@ -107,8 +112,9 @@ public class LinkActionExposer { icon = getBitmapDrawable(R.drawable.action_web, r); } - if (text.length() > 15) + if (text.length() > 15) { text = text.substring(0, 12) + "..."; //$NON-NLS-1$ + } TaskAction action = new TaskAction(text, PendingIntent.getActivity(context, (int) id, actionIntent, 0), (BitmapDrawable) icon); @@ -118,9 +124,9 @@ public class LinkActionExposer { private static final HashMap IMAGE_CACHE = new HashMap(); private static BitmapDrawable getBitmapDrawable(int resId, Resources resources) { - if (IMAGE_CACHE.containsKey(resId)) + if (IMAGE_CACHE.containsKey(resId)) { return IMAGE_CACHE.get(resId); - else { + } else { BitmapDrawable b = (BitmapDrawable) resources.getDrawable(resId); IMAGE_CACHE.put(resId, b); return b; diff --git a/astrid/plugin-src/com/todoroo/astrid/core/OldTaskPreferences.java b/astrid/plugin-src/com/todoroo/astrid/core/OldTaskPreferences.java index dc1dadb4a..aa6d68f9c 100644 --- a/astrid/plugin-src/com/todoroo/astrid/core/OldTaskPreferences.java +++ b/astrid/plugin-src/com/todoroo/astrid/core/OldTaskPreferences.java @@ -255,8 +255,9 @@ public class OldTaskPreferences extends TodorooPreferenceActivity { for (int i = 0; i < length; i++) { cursor.moveToNext(); task.readFromCursor(cursor); - if (GCalHelper.deleteTaskEvent(task)) + if (GCalHelper.deleteTaskEvent(task)) { deletedEventCount++; + } } } finally { cursor.close(); @@ -298,8 +299,9 @@ public class OldTaskPreferences extends TodorooPreferenceActivity { for (int i = 0; i < length; i++) { cursor.moveToNext(); task.readFromCursor(cursor); - if (GCalHelper.deleteTaskEvent(task)) + if (GCalHelper.deleteTaskEvent(task)) { deletedEventCount++; + } } } finally { cursor.close(); diff --git a/astrid/plugin-src/com/todoroo/astrid/core/PluginServices.java b/astrid/plugin-src/com/todoroo/astrid/core/PluginServices.java index 531b60bcb..8789a6af2 100644 --- a/astrid/plugin-src/com/todoroo/astrid/core/PluginServices.java +++ b/astrid/plugin-src/com/todoroo/astrid/core/PluginServices.java @@ -129,8 +129,9 @@ public final class PluginServices { private static PluginServices getInstance() { if (instance == null) { synchronized (PluginServices.class) { - if (instance == null) + if (instance == null) { instance = new PluginServices(); + } } } return instance; @@ -247,8 +248,9 @@ public final class PluginServices { if (cursor.getCount() > 0) { cursor.moveToNext(); return new Metadata(cursor); - } else + } else { return null; + } } finally { cursor.close(); } diff --git a/astrid/plugin-src/com/todoroo/astrid/core/SavedFilter.java b/astrid/plugin-src/com/todoroo/astrid/core/SavedFilter.java index 52edea76e..79ab7cb47 100644 --- a/astrid/plugin-src/com/todoroo/astrid/core/SavedFilter.java +++ b/astrid/plugin-src/com/todoroo/astrid/core/SavedFilter.java @@ -66,8 +66,9 @@ public class SavedFilter { public static void persist(CustomFilterAdapter adapter, String title, String sql, ContentValues values) { - if (title == null || title.length() == 0) + if (title == null || title.length() == 0) { return; + } // if filter of this name exists, edit it StoreObjectDao dao = PluginServices.getStoreObjectDao(); @@ -87,10 +88,11 @@ public class SavedFilter { storeObject.setValue(NAME, title); storeObject.setValue(SQL, sql); - if (values == null) + if (values == null) { storeObject.setValue(VALUES, ""); //$NON-NLS-1$ - else + } else { storeObject.setValue(VALUES, AndroidUtilities.contentValuesToSerializedString(values)); + } String filters = serializeFilters(adapter); storeObject.setValue(FILTERS, filters); @@ -114,8 +116,9 @@ public class SavedFilter { values.append(escape(item.getValueFromCriterion())).append(AndroidUtilities.SERIALIZATION_SEPARATOR); values.append(escape(item.criterion.text)).append(AndroidUtilities.SERIALIZATION_SEPARATOR); values.append(item.type).append(AndroidUtilities.SERIALIZATION_SEPARATOR); - if (item.criterion.sql != null) + if (item.criterion.sql != null) { values.append(item.criterion.sql); + } values.append('\n'); } @@ -123,8 +126,9 @@ public class SavedFilter { } private static String escape(String item) { - if (item == null) + if (item == null) { return ""; //$NON-NLS-1$ + } return item.replace(AndroidUtilities.SERIALIZATION_SEPARATOR, AndroidUtilities.SEPARATOR_ESCAPE); } @@ -141,8 +145,9 @@ public class SavedFilter { String values = savedFilter.getValue(VALUES); ContentValues contentValues = null; - if (!TextUtils.isEmpty(values)) + if (!TextUtils.isEmpty(values)) { contentValues = AndroidUtilities.contentValuesFromSerializedString(values); + } return new Filter(title, title, sql, contentValues); } diff --git a/astrid/plugin-src/com/todoroo/astrid/files/AACRecordingActivity.java b/astrid/plugin-src/com/todoroo/astrid/files/AACRecordingActivity.java index 071d557f4..5c1b0c7fc 100644 --- a/astrid/plugin-src/com/todoroo/astrid/files/AACRecordingActivity.java +++ b/astrid/plugin-src/com/todoroo/astrid/files/AACRecordingActivity.java @@ -100,8 +100,9 @@ public class AACRecordingActivity extends Activity implements AACRecorderCallbac e.printStackTrace(); Toast.makeText(this, R.string.audio_err_encoding, Toast.LENGTH_LONG).show(); } - if (pd != null) + if (pd != null) { pd.dismiss(); + } } } diff --git a/astrid/plugin-src/com/todoroo/astrid/files/FileExplore.java b/astrid/plugin-src/com/todoroo/astrid/files/FileExplore.java index 9d493344d..1499b0573 100644 --- a/astrid/plugin-src/com/todoroo/astrid/files/FileExplore.java +++ b/astrid/plugin-src/com/todoroo/astrid/files/FileExplore.java @@ -63,10 +63,11 @@ public class FileExplore extends Activity { super.onCreate(savedInstanceState); - if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) + if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { path = new File(Environment.getExternalStorageDirectory().toString()); - else + } else { path = Environment.getRootDirectory(); + } loadFileList(); diff --git a/astrid/plugin-src/com/todoroo/astrid/files/FileUtilities.java b/astrid/plugin-src/com/todoroo/astrid/files/FileUtilities.java index 58f1a7e16..1e1272160 100644 --- a/astrid/plugin-src/com/todoroo/astrid/files/FileUtilities.java +++ b/astrid/plugin-src/com/todoroo/astrid/files/FileUtilities.java @@ -60,8 +60,9 @@ public class FileUtilities { filePathBuilder.append(dir) .append(File.separator) .append(name); - if (nameReference != null) + if (nameReference != null) { nameReference.set(name); + } return filePathBuilder.toString(); } @@ -69,11 +70,13 @@ public class FileUtilities { public static File getAttachmentsDirectory(Context context) { File directory = null; String customDir = Preferences.getStringValue(TaskAttachment.FILES_DIRECTORY_PREF); - if (!TextUtils.isEmpty(customDir)) + if (!TextUtils.isEmpty(customDir)) { directory = new File(customDir); + } - if (directory == null || !directory.exists()) + if (directory == null || !directory.exists()) { directory = context.getExternalFilesDir(TaskAttachment.FILES_DIRECTORY_DEFAULT); + } return directory; } diff --git a/astrid/plugin-src/com/todoroo/astrid/files/FilesControlSet.java b/astrid/plugin-src/com/todoroo/astrid/files/FilesControlSet.java index 0d947322f..ee446fa4c 100644 --- a/astrid/plugin-src/com/todoroo/astrid/files/FilesControlSet.java +++ b/astrid/plugin-src/com/todoroo/astrid/files/FilesControlSet.java @@ -112,8 +112,9 @@ public class FilesControlSet extends PopupControlSet { cursor.close(); } validateFiles(); - if (initialized) + if (initialized) { afterInflate(); + } } } @@ -258,8 +259,9 @@ public class FilesControlSet extends PopupControlSet { MimeTypeMap map = MimeTypeMap.getSingleton(); String guessedType = map.getMimeTypeFromExtension(extension); - if (!TextUtils.isEmpty(guessedType)) + if (!TextUtils.isEmpty(guessedType)) { useType = guessedType; + } if (useType != guessedType) { m.setValue(TaskAttachment.CONTENT_TYPE, useType); m.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true); @@ -300,8 +302,9 @@ public class FilesControlSet extends PopupControlSet { public void onClick(DialogInterface d, int which) { Intent marketIntent = Constants.MARKET_STRATEGY.generateMarketLink(packageName); try { - if (marketIntent == null) + if (marketIntent == null) { throw new ActivityNotFoundException("No market link supplied"); //$NON-NLS-1$ + } activity.startActivity(marketIntent); } catch (ActivityNotFoundException anf) { DialogUtilities.okDialog(activity, @@ -414,10 +417,11 @@ public class FilesControlSet extends PopupControlSet { String type = getTypeString(m.getValue(TaskAttachment.NAME)); nameView.setText(name); - if (TextUtils.isEmpty(type)) + if (TextUtils.isEmpty(type)) { typeView.setVisibility(View.GONE); - else + } else { typeView.setText(type); + } parent.addView(row, lp); } @@ -425,16 +429,18 @@ public class FilesControlSet extends PopupControlSet { private String getNameString(TaskAttachment metadata) { String name = metadata.getValue(TaskAttachment.NAME); int extension = name.lastIndexOf('.'); - if (extension < 0) + if (extension < 0) { return name; + } return name.substring(0, extension); } @SuppressWarnings("nls") private String getTypeString(String name) { int extension = name.lastIndexOf('.'); - if (extension < 0 || extension + 1 >= name.length()) + if (extension < 0 || extension + 1 >= name.length()) { return ""; + } return name.substring(extension + 1).toUpperCase(); } diff --git a/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarAlarmListCreator.java b/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarAlarmListCreator.java index 60dbf3925..5f9ce5617 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarAlarmListCreator.java +++ b/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarAlarmListCreator.java @@ -196,10 +196,11 @@ public class CalendarAlarmListCreator extends Activity { String displayName2 = getDisplayName(1); int extras = emails.size() - 2; - if (extras > 0) + if (extras > 0) { return getString(R.string.CRA_many_attendees, displayName1, displayName2, extras); - else + } else { return getString(R.string.CRA_two_attendees, displayName1, displayName2); + } } } @@ -220,14 +221,16 @@ public class CalendarAlarmListCreator extends Activity { private String getDisplayName(int index) { String name = names.get(index); - if (!TextUtils.isEmpty(name)) + if (!TextUtils.isEmpty(name)) { return name; + } String email = emails.get(index); if (emailsToUsers.containsKey(email)) { User u = emailsToUsers.get(email); String userName = u.getDisplayName(); - if (!TextUtils.isEmpty(userName)) + if (!TextUtils.isEmpty(userName)) { return userName; + } } return email; } diff --git a/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarAlarmReceiver.java b/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarAlarmReceiver.java index 371ea4403..c73ae6942 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarAlarmReceiver.java +++ b/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarAlarmReceiver.java @@ -41,18 +41,22 @@ public class CalendarAlarmReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { - if (!Preferences.getBoolean(R.string.p_calendar_reminders, true)) + if (!Preferences.getBoolean(R.string.p_calendar_reminders, true)) { return; + } try { Uri data = intent.getData(); - if (data == null) + if (data == null) { return; + } String uriString = data.toString(); int pathIndex = uriString.indexOf("://"); - if (pathIndex > 0) + if (pathIndex > 0) { pathIndex += 3; - else return; + } else { + return; + } long eventId = Long.parseLong(uriString.substring(pathIndex)); boolean fromPostpone = CalendarAlarmScheduler.URI_PREFIX_POSTPONE.equals(data.getScheme()); if (eventId > 0) { @@ -68,8 +72,9 @@ public class CalendarAlarmReceiver extends BroadcastReceiver { ContentResolver cr = context.getContentResolver(); Uri eventUri = Calendars.getCalendarContentUri(Calendars.CALENDAR_CONTENT_EVENTS); - if (AndroidUtilities.getSdkVersion() <= 7) + if (AndroidUtilities.getSdkVersion() <= 7) { return; + } String[] eventArg = new String[]{Long.toString(eventId)}; Cursor event = cr.query(eventUri, @@ -118,8 +123,9 @@ public class CalendarAlarmReceiver extends BroadcastReceiver { } String astridUser = ActFmPreferenceService.thisUser().optString("email"); - if (!TextUtils.isEmpty(astridUser)) + if (!TextUtils.isEmpty(astridUser)) { phoneAccounts.add(astridUser); + } boolean includesMe = false; for (attendees.moveToFirst(); !attendees.isAfterLast(); attendees.moveToNext()) { @@ -130,8 +136,9 @@ public class CalendarAlarmReceiver extends BroadcastReceiver { includesMe = true; continue; } - if (Constants.DEBUG) + if (Constants.DEBUG) { Log.w(CalendarAlarmScheduler.TAG, "Attendee: " + name + ", email: " + email); + } names.add(name); emails.add(email); } diff --git a/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarAlarmScheduler.java b/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarAlarmScheduler.java index 4ff675d6d..9796b5332 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarAlarmScheduler.java +++ b/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarAlarmScheduler.java @@ -25,8 +25,9 @@ public class CalendarAlarmScheduler { public static final String URI_PREFIX_POSTPONE = "cal-postpone"; public static void scheduleAllCalendarAlarms(Context context) { - if (!Preferences.getBoolean(R.string.p_calendar_reminders, true)) + if (!Preferences.getBoolean(R.string.p_calendar_reminders, true)) { return; + } ContentResolver cr = context.getContentResolver(); @@ -60,8 +61,9 @@ public class CalendarAlarmScheduler { long alarmTime = start - DateUtilities.ONE_MINUTE * 15; am.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent); - if (Constants.DEBUG) + if (Constants.DEBUG) { Log.w(TAG, "Scheduling calendar alarm for " + new Date(alarmTime)); + } } } @@ -73,8 +75,9 @@ public class CalendarAlarmScheduler { am.cancel(pendingReschedule); am.set(AlarmManager.RTC, DateUtilities.now() + DateUtilities.ONE_HOUR * 12, pendingReschedule); } finally { - if (events != null) + if (events != null) { events.close(); + } } } diff --git a/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarReminderActivity.java b/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarReminderActivity.java index 78c993917..c7e918495 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarReminderActivity.java +++ b/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarReminderActivity.java @@ -141,17 +141,19 @@ public class CalendarReminderActivity extends Activity { TextView dialogView = (TextView) findViewById(R.id.reminder_message); String speechText; - if (fromPostpone) + if (fromPostpone) { speechText = getString(R.string.CRA_speech_bubble_end, eventName); - else + } else { speechText = getString(R.string.CRA_speech_bubble_start, eventName); + } dialogView.setText(speechText); createListButton.setBackgroundColor(getResources().getColor(ThemeService.getThemeColor())); - if (fromPostpone) + if (fromPostpone) { postponeButton.setVisibility(View.GONE); + } } private void addListeners() { @@ -167,13 +169,14 @@ public class CalendarReminderActivity extends Activity { } }); - if (!fromPostpone) + if (!fromPostpone) { postponeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { postpone(); } }); + } createListButton.setOnClickListener(new OnClickListener() { @Override @@ -242,8 +245,9 @@ public class CalendarReminderActivity extends Activity { am.cancel(pendingIntent); long alarmTime = endTime + DateUtilities.ONE_MINUTE * 5; - if (Constants.DEBUG) + if (Constants.DEBUG) { Log.w(CalendarAlarmScheduler.TAG, "Scheduling calendar alarm for " + new Date(alarmTime)); + } am.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent); dismissButton.performClick(); } diff --git a/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarStartupReceiver.java b/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarStartupReceiver.java index aa1fa3250..aad714676 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarStartupReceiver.java +++ b/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarStartupReceiver.java @@ -20,8 +20,9 @@ public class CalendarStartupReceiver extends BroadcastReceiver { } public static void scheduleCalendarAlarms(final Context context, boolean force) { - if (!Preferences.getBoolean(R.string.p_calendar_reminders, true) && !force) + if (!Preferences.getBoolean(R.string.p_calendar_reminders, true) && !force) { return; + } new Thread(new Runnable() { @Override public void run() { diff --git a/astrid/plugin-src/com/todoroo/astrid/gcal/Calendars.java b/astrid/plugin-src/com/todoroo/astrid/gcal/Calendars.java index 9357fecd0..21596e920 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gcal/Calendars.java +++ b/astrid/plugin-src/com/todoroo/astrid/gcal/Calendars.java @@ -65,19 +65,21 @@ public class Calendars { return getIcsUri(table); } - if (AndroidUtilities.getSdkVersion() >= 8) + if (AndroidUtilities.getSdkVersion() >= 8) { return Uri.parse("content://com.android.calendar/" + table); - else + } else { return Uri.parse("content://calendar/" + table); + } } private static Uri getIcsUri(String table) { - if (CALENDAR_CONTENT_CALENDARS.equals(table)) + if (CALENDAR_CONTENT_CALENDARS.equals(table)) { return CalendarContract.Calendars.CONTENT_URI; - else if (CALENDAR_CONTENT_EVENTS.equals(table)) + } else if (CALENDAR_CONTENT_EVENTS.equals(table)) { return CalendarContract.Events.CONTENT_URI; - else if (CALENDAR_CONTENT_ATTENDEES.equals(table)) + } else if (CALENDAR_CONTENT_ATTENDEES.equals(table)) { return CalendarContract.Attendees.CONTENT_URI; + } return null; } @@ -85,10 +87,11 @@ public class Calendars { * Return calendar package name */ public static String getCalendarPackage() { - if (AndroidUtilities.getSdkVersion() >= 8) + if (AndroidUtilities.getSdkVersion() >= 8) { return "com.google.android.calendar"; - else + } else { return "com.android.calendar"; + } } // --- helper data structure @@ -172,8 +175,9 @@ public class Calendars { return result; } finally { - if (c != null) + if (c != null) { c.close(); + } } } diff --git a/astrid/plugin-src/com/todoroo/astrid/gcal/GCalControlSet.java b/astrid/plugin-src/com/todoroo/astrid/gcal/GCalControlSet.java index bdd21f51a..1b320fe0a 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gcal/GCalControlSet.java +++ b/astrid/plugin-src/com/todoroo/astrid/gcal/GCalControlSet.java @@ -132,15 +132,17 @@ public class GCalControlSet extends PopupControlSet { } public void resetCalendarSelector() { - if (calendarSelector != null) + if (calendarSelector != null) { calendarSelector.setSelection(calendars.defaultIndex + 1); // plus 1 for the no selection item + } } @SuppressWarnings("nls") @Override protected String writeToModelAfterInitialized(Task task) { - if (!task.hasDueDate()) + if (!task.hasDueDate()) { return null; + } boolean gcalCreateEventEnabled = Preferences.getStringValue(R.string.gcal_p_default) != null && !Preferences.getStringValue(R.string.gcal_p_default).equals("-1"); @@ -178,16 +180,20 @@ public class GCalControlSet extends PopupControlSet { // check if we need to update the item ContentValues setValues = task.getSetValues(); - if (setValues.containsKey(Task.TITLE.name)) + if (setValues.containsKey(Task.TITLE.name)) { updateValues.put("title", task.getValue(Task.TITLE)); - if (setValues.containsKey(Task.NOTES.name)) + } + if (setValues.containsKey(Task.NOTES.name)) { updateValues.put("description", task.getValue(Task.NOTES)); - if (setValues.containsKey(Task.DUE_DATE.name) || setValues.containsKey(Task.ESTIMATED_SECONDS.name)) + } + if (setValues.containsKey(Task.DUE_DATE.name) || setValues.containsKey(Task.ESTIMATED_SECONDS.name)) { GCalHelper.createStartAndEndDate(task, updateValues); + } ContentResolver cr = activity.getContentResolver(); - if (cr.update(calendarUri, updateValues, null, null) > 0) + if (cr.update(calendarUri, updateValues, null, null) > 0) { return activity.getString(R.string.gcal_TEA_calendar_updated); + } } catch (Exception e) { exceptionService.reportError("unable-to-update-calendar: " + //$NON-NLS-1$ task.getValue(Task.CALENDAR_URI), e); @@ -199,8 +205,9 @@ public class GCalControlSet extends PopupControlSet { @SuppressWarnings("nls") private void viewCalendarEvent() { - if (calendarUri == null) + if (calendarUri == null) { return; + } ContentResolver cr = activity.getContentResolver(); Intent intent = new Intent(Intent.ACTION_EDIT, calendarUri); @@ -261,8 +268,9 @@ public class GCalControlSet extends PopupControlSet { return new OnClickListener() { @Override public void onClick(View v) { - if (calendarSelector == null) + if (calendarSelector == null) { getView(); // Force load + } if (!hasEvent) { calendarSelector.performClick(); } else { diff --git a/astrid/plugin-src/com/todoroo/astrid/gcal/GCalHelper.java b/astrid/plugin-src/com/todoroo/astrid/gcal/GCalHelper.java index 19627caa2..9c9df2388 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gcal/GCalHelper.java +++ b/astrid/plugin-src/com/todoroo/astrid/gcal/GCalHelper.java @@ -34,12 +34,13 @@ public class GCalHelper { public static String getTaskEventUri(Task task) { String uri; - if (!TextUtils.isEmpty(task.getValue(Task.CALENDAR_URI))) + if (!TextUtils.isEmpty(task.getValue(Task.CALENDAR_URI))) { uri = task.getValue(Task.CALENDAR_URI); - else { + } else { task = PluginServices.getTaskService().fetchById(task.getId(), Task.CALENDAR_URI); - if (task == null) + if (task == null) { return null; + } uri = task.getValue(Task.CALENDAR_URI); } @@ -47,8 +48,9 @@ public class GCalHelper { } public static void createTaskEventIfEnabled(Task t) { - if (!t.hasDueDate()) + if (!t.hasDueDate()) { return; + } createTaskEventIfEnabled(t, true); } @@ -58,8 +60,9 @@ public class GCalHelper { if (gcalCreateEventEnabled) { ContentResolver cr = ContextManager.getContext().getContentResolver(); Uri calendarUri = GCalHelper.createTaskEvent(t, cr, new ContentValues(), deleteEventIfExists); - if (calendarUri != null) + if (calendarUri != null) { t.setValue(Task.CALENDAR_URI, calendarUri.toString()); + } } } @@ -111,8 +114,9 @@ public class GCalHelper { public static void rescheduleRepeatingTask(Task task, ContentResolver cr) { String taskUri = getTaskEventUri(task); - if (TextUtils.isEmpty(taskUri)) + if (TextUtils.isEmpty(taskUri)) { return; + } Uri eventUri = Uri.parse(taskUri); String calendarId = getCalendarId(eventUri, cr); @@ -143,12 +147,13 @@ public class GCalHelper { public static boolean deleteTaskEvent(Task task) { boolean eventDeleted = false; String uri; - if (task.containsNonNullValue(Task.CALENDAR_URI)) + if (task.containsNonNullValue(Task.CALENDAR_URI)) { uri = task.getValue(Task.CALENDAR_URI); - else { + } else { task = PluginServices.getTaskService().fetchById(task.getId(), Task.CALENDAR_URI); - if (task == null) + if (task == null) { return false; + } uri = task.getValue(Task.CALENDAR_URI); } @@ -188,8 +193,9 @@ public class GCalHelper { if (task.hasDueDate()) { if (task.hasDueTime()) { long estimatedTime = task.getValue(Task.ESTIMATED_SECONDS) * 1000; - if (estimatedTime <= 0) + if (estimatedTime <= 0) { estimatedTime = DEFAULT_CAL_TIME; + } if (Preferences.getBoolean(R.string.p_end_at_deadline, true)) { values.put("dtstart", dueDate); values.put("dtend", dueDate + estimatedTime); diff --git a/astrid/plugin-src/com/todoroo/astrid/gcal/GCalTaskCompleteListener.java b/astrid/plugin-src/com/todoroo/astrid/gcal/GCalTaskCompleteListener.java index 2989fe322..62ed0a71a 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gcal/GCalTaskCompleteListener.java +++ b/astrid/plugin-src/com/todoroo/astrid/gcal/GCalTaskCompleteListener.java @@ -27,12 +27,14 @@ public class GCalTaskCompleteListener extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { ContextManager.setContext(context); long taskId = intent.getLongExtra(AstridApiConstants.EXTRAS_TASK_ID, -1); - if (taskId == -1) + if (taskId == -1) { return; + } Task task = PluginServices.getTaskService().fetchById(taskId, Task.ID, Task.TITLE, Task.CALENDAR_URI); - if (task == null) + if (task == null) { return; + } String calendarUri = task.getValue(Task.CALENDAR_URI); if (!TextUtils.isEmpty(calendarUri)) { diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksBackgroundService.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksBackgroundService.java index 2e8cfcaed..8ebf84659 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksBackgroundService.java +++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksBackgroundService.java @@ -25,8 +25,9 @@ public class GtasksBackgroundService extends SyncV2BackgroundService { @Override protected SyncProviderUtilities getSyncUtilities() { - if (gtasksPreferenceService == null) + if (gtasksPreferenceService == null) { DependencyInjectionService.getInstance().inject(this); + } return gtasksPreferenceService; } diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksCustomFilterCriteriaExposer.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksCustomFilterCriteriaExposer.java index 06e381dea..3957ccf07 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksCustomFilterCriteriaExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksCustomFilterCriteriaExposer.java @@ -49,8 +49,9 @@ public class GtasksCustomFilterCriteriaExposer extends BroadcastReceiver { DependencyInjectionService.getInstance().inject(this); // if we aren't logged in, don't expose sync action - if (!gtasksPreferenceService.isLoggedIn()) + if (!gtasksPreferenceService.isLoggedIn()) { return; + } Resources r = context.getResources(); diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksDetailExposer.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksDetailExposer.java index 60ff0310a..3206a4054 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksDetailExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksDetailExposer.java @@ -47,16 +47,19 @@ public class GtasksDetailExposer extends BroadcastReceiver { ContextManager.setContext(context); // if we aren't logged in, don't expose features - if (!gtasksPreferenceService.isLoggedIn()) + if (!gtasksPreferenceService.isLoggedIn()) { return; + } long taskId = intent.getLongExtra(AstridApiConstants.EXTRAS_TASK_ID, -1); - if (taskId == -1) + if (taskId == -1) { return; + } String taskDetail = getTaskDetails(taskId); - if (taskDetail == null) + if (taskDetail == null) { return; + } Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_SEND_DETAILS); broadcastIntent.putExtra(AstridApiConstants.EXTRAS_ADDON, GtasksPreferenceService.IDENTIFIER); @@ -67,17 +70,20 @@ public class GtasksDetailExposer extends BroadcastReceiver { public String getTaskDetails(long id) { Metadata metadata = gtasksMetadataService.getTaskMetadata(id); - if (metadata == null) + if (metadata == null) { return null; + } StringBuilder builder = new StringBuilder(); String listId = metadata.getValue(GtasksMetadata.LIST_ID); - if (listId == null || listId.equals(Preferences.getStringValue(GtasksPreferenceService.PREF_DEFAULT_LIST))) + if (listId == null || listId.equals(Preferences.getStringValue(GtasksPreferenceService.PREF_DEFAULT_LIST))) { return null; + } String listName = gtasksListService.getListName(listId); - if (listName == GtasksListService.LIST_NOT_FOUND) + if (listName == GtasksListService.LIST_NOT_FOUND) { return null; + } builder.append(" ").append(listName); //$NON-NLS-1$ diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksFilterExposer.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksFilterExposer.java index 568c4a2c4..5626d800d 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksFilterExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksFilterExposer.java @@ -97,18 +97,21 @@ public class GtasksFilterExposer extends BroadcastReceiver implements AstridFilt DependencyInjectionService.getInstance().inject(this); // if we aren't logged in (or we are logged in to astrid.com), don't expose features - if (!gtasksPreferenceService.isLoggedIn() || actFmPreferenceService.isLoggedIn()) + if (!gtasksPreferenceService.isLoggedIn() || actFmPreferenceService.isLoggedIn()) { return null; + } lists = gtasksListService.getLists(); // If user does not have any lists, don't show this section at all - if (noListsToShow()) + if (noListsToShow()) { return null; + } Filter[] listFilters = new Filter[lists.length]; - for (int i = 0; i < lists.length; i++) + for (int i = 0; i < lists.length; i++) { listFilters[i] = filterFromList(context, lists[i]); + } FilterCategoryWithNewButton listsCategory = new FilterCategoryWithNewButton(context.getString(R.string.gtasks_FEx_header), listFilters); @@ -127,8 +130,9 @@ public class GtasksFilterExposer extends BroadcastReceiver implements AstridFilt @Override public FilterListItem[] getFilters() { - if (ContextManager.getContext() == null) + if (ContextManager.getContext() == null) { return null; + } return prepareFilters(ContextManager.getContext()); } diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksListAdder.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksListAdder.java index 2b87821cc..7111ee2e1 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksListAdder.java +++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksListAdder.java @@ -61,7 +61,9 @@ public class GtasksListAdder extends Activity { GtasksInvoker service = new GtasksInvoker(token); String title = editText.getText().toString(); if (TextUtils.isEmpty(title)) //Don't create a list without a title + { return; + } StoreObject newList = gtasksListService.addNewList(service.createGtaskList(title)); if (newList != null) { FilterWithCustomIntent listFilter = (FilterWithCustomIntent) GtasksFilterExposer.filterFromList(activity, newList); diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksListFragment.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksListFragment.java index d3e4a085f..717c746ac 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksListFragment.java +++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksListFragment.java @@ -85,8 +85,9 @@ public class GtasksListFragment extends SubtasksListFragment { @Override protected void initiateAutomaticSyncImpl() { - if (!isCurrentTaskListFragment()) + if (!isCurrentTaskListFragment()) { return; + } if (list != null && DateUtilities.now() - list.getValue(GtasksList.LAST_SYNC) > DateUtilities.ONE_MINUTE * 10) { refreshData(false); } @@ -99,10 +100,11 @@ public class GtasksListFragment extends SubtasksListFragment { R.id.progressBar, new Runnable() { @Override public void run() { - if (manual) + if (manual) { ContextManager.getContext().sendBroadcast(new Intent(AstridApiConstants.BROADCAST_EVENT_REFRESH)); - else + } else { refresh(); + } ((TextView) getView().findViewById(android.R.id.empty)).setText(R.string.TLA_no_items); } })); diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksListService.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksListService.java index e4cbe3113..56fd542b6 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksListService.java +++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksListService.java @@ -64,8 +64,9 @@ public class GtasksListService { */ public String getListName(String listId) { StoreObject list = getList(listId); - if (list != LIST_NOT_FOUND_OBJECT) + if (list != LIST_NOT_FOUND_OBJECT) { return list.getValue(GtasksList.NAME); + } return LIST_NOT_FOUND; } @@ -94,8 +95,9 @@ public class GtasksListService { readLists(); HashSet previousLists = new HashSet(lists.length); - for (StoreObject list : lists) + for (StoreObject list : lists) { previousLists.add(list.getId()); + } List items = remoteLists.getItems(); StoreObject[] newLists = new StoreObject[items.size()]; @@ -111,8 +113,9 @@ public class GtasksListService { } } - if (local == null) + if (local == null) { local = new StoreObject(); + } local.setValue(StoreObject.TYPE, GtasksList.TYPE); local.setValue(GtasksList.REMOTE_ID, id); @@ -136,7 +139,9 @@ public class GtasksListService { if (lists != null) { for (StoreObject list : lists) { if (list.getValue(GtasksList.REMOTE_ID).equals(newList.getId())) //Sanity check--make sure it's actually a new list + { return null; + } } } StoreObject local = new StoreObject(); @@ -160,9 +165,11 @@ public class GtasksListService { public StoreObject getList(String listId) { readLists(); - for (StoreObject list : lists) - if (list != null && list.getValue(GtasksList.REMOTE_ID).equals(listId)) + for (StoreObject list : lists) { + if (list != null && list.getValue(GtasksList.REMOTE_ID).equals(listId)) { return list; + } + } return LIST_NOT_FOUND_OBJECT; } diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksMetadata.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksMetadata.java index ffc5cab2d..2a69860ec 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksMetadata.java +++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksMetadata.java @@ -66,15 +66,17 @@ public class GtasksMetadata { metadata.setValue(ID, ""); //$NON-NLS-1$ String defaultList = Preferences.getStringValue(GtasksPreferenceService.PREF_DEFAULT_LIST); - if (defaultList == null) + if (defaultList == null) { defaultList = "@default"; //$NON-NLS-1$ + } metadata.setValue(LIST_ID, defaultList); metadata.setValue(PARENT_TASK, AbstractModel.NO_ID); metadata.setValue(INDENT, 0); metadata.setValue(ORDER, DateUtilities.now()); - if (taskId > AbstractModel.NO_ID) + if (taskId > AbstractModel.NO_ID) { metadata.setValue(Metadata.TASK, taskId); + } return metadata; } diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksMetadataService.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksMetadataService.java index 0d308d60e..8ea15d22c 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksMetadataService.java +++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/GtasksMetadataService.java @@ -81,14 +81,16 @@ public final class GtasksMetadataService extends SyncMetadataService cursor = metadataDao.query(Query.select(Metadata.PROPERTIES). where(Criterion.and(MetadataCriteria.withKey(getMetadataKey()), getLocalMatchCriteria(remoteTask)))); try { - if (cursor.getCount() == 0) + if (cursor.getCount() == 0) { return; + } cursor.moveToFirst(); remoteTask.task.setId(cursor.get(Metadata.TASK)); remoteTask.task.setUuid(taskDao.uuidFromLocalId(remoteTask.task.getId())); @@ -116,14 +118,16 @@ public final class GtasksMetadataService extends SyncMetadataService filterLocallyUpdated(TodorooCursor tasks, long lastSyncDate) { HashSet taskIds = new HashSet(); - for (tasks.moveToFirst(); !tasks.isAfterLast(); tasks.moveToNext()) + for (tasks.moveToFirst(); !tasks.isAfterLast(); tasks.moveToNext()) { taskIds.add(tasks.get(Task.ID)); + } TodorooCursor metadata = metadataDao.query(Query.select(Metadata.TASK).where( Criterion.and(MetadataCriteria.withKey(GtasksMetadata.METADATA_KEY), GtasksMetadata.LAST_SYNC.gt(lastSyncDate)))); - for (metadata.moveToFirst(); !metadata.isAfterLast(); metadata.moveToNext()) + for (metadata.moveToFirst(); !metadata.isAfterLast(); metadata.moveToNext()) { taskIds.remove(metadata.get(Metadata.TASK)); + } return taskDao.query(Query.select(Task.ID).where( Task.ID.in(taskIds.toArray(new Long[taskIds.size()])))); @@ -154,8 +158,9 @@ public final class GtasksMetadataService extends SyncMetadataService previousIndent.get() + 1) + if (indent > previousIndent.get() + 1) { indent = previousIndent.get() + 1; + } metadata.setValue(GtasksMetadata.INDENT, indent); Long parent = parents.get(taskId); - if (parent == null || parent < 0) + if (parent == null || parent < 0) { parent = Task.NO_ID; + } metadata.setValue(GtasksMetadata.PARENT_TASK, parent); PluginServices.getMetadataService().save(metadata); @@ -164,8 +167,9 @@ public class GtasksTaskListUpdater extends OrderedMetadataListUpdater future = accountManager.manager.getAuthToken(a, GtasksInvoker.AUTH_TOKEN_TYPE, false, null, null); token = getTokenFromFuture(c, future); - if (TOKEN_INTENT_RECEIVED.equals(token)) + if (TOKEN_INTENT_RECEIVED.equals(token)) { return null; - else if (token != null && testToken(token)) + } else if (token != null && testToken(token)) { return token; + } } @@ -82,8 +84,9 @@ public class GtasksTokenValidator { Bundle result; try { result = future.getResult(); - if (result == null) + if (result == null) { throw new NullPointerException("Future result was null."); //$NON-NLS-1$ + } } catch (Exception e) { throw new GoogleTasksException(e.getLocalizedMessage(), "future-error"); } @@ -94,10 +97,11 @@ public class GtasksTokenValidator { token = result.getString(AccountManager.KEY_AUTHTOKEN); } else if (result.containsKey(AccountManager.KEY_INTENT)) { Intent intent = (Intent) result.get(AccountManager.KEY_INTENT); - if (c instanceof Activity) + if (c instanceof Activity) { c.startActivity(intent); - else + } else { throw new GoogleTasksException(c.getString(R.string.gtasks_error_background_sync_auth), "background-auth-error"); + } return TOKEN_INTENT_RECEIVED; } else { throw new GoogleTasksException(c.getString(R.string.gtasks_error_accountManager), "account-manager-error"); diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/sync/GtasksLegacyMigrator.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/sync/GtasksLegacyMigrator.java index 9d24c0df5..3c1fc7e5f 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gtasks/sync/GtasksLegacyMigrator.java +++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/sync/GtasksLegacyMigrator.java @@ -121,8 +121,9 @@ public class GtasksLegacyMigrator { // save the new id of the current list // if it matches the listname of the current task - if (list.getTitle() != null && list.getTitle().equals(originalListName)) + if (list.getTitle() != null && list.getTitle().equals(originalListName)) { originalListId = list.getId(); + } if (taskAndListTitlesToRemoteTaskIds.containsKey(expectedKey)) { foundMatch = true; diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/sync/GtasksSyncService.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/sync/GtasksSyncService.java index 4c337f1a8..31de24c1d 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gtasks/sync/GtasksSyncService.java +++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/sync/GtasksSyncService.java @@ -72,8 +72,9 @@ public final class GtasksSyncService { @Override public void op(GtasksInvoker invoker) throws IOException { - if (DateUtilities.now() - creationDate < 1000) + if (DateUtilities.now() - creationDate < 1000) { AndroidUtilities.sleepDeep(1000 - (DateUtilities.now() - creationDate)); + } pushTaskOnSave(model, model.getMergedValues(), invoker, false); } } @@ -110,17 +111,24 @@ public final class GtasksSyncService { taskDao.addListener(new ModelUpdateListener() { public void onModelUpdated(final Task model, boolean outstandingEntries) { - if (model.checkAndClearTransitory(SyncFlags.GTASKS_SUPPRESS_SYNC)) + if (model.checkAndClearTransitory(SyncFlags.GTASKS_SUPPRESS_SYNC)) { return; - if (actFmPreferenceService.isLoggedIn()) + } + if (actFmPreferenceService.isLoggedIn()) { return; + } if (gtasksPreferenceService.isOngoing() && !model.checkTransitory(TaskService.TRANS_REPEAT_COMPLETE)) //Don't try and sync changes that occur during a normal sync + { return; + } final ContentValues setValues = model.getSetValues(); - if (setValues == null || !checkForToken()) + if (setValues == null || !checkForToken()) { return; + } if (!checkValuesForProperties(setValues, TASK_PROPERTIES)) //None of the properties we sync were updated + { return; + } Task toPush = taskDao.fetch(model.getId(), TASK_PROPERTIES); operationQueue.offer(new TaskPushOp(toPush)); @@ -177,26 +185,35 @@ public final class GtasksSyncService { */ private boolean checkValuesForProperties(ContentValues values, Property[] properties) { for (Property property : properties) { - if (property != Task.ID && values.containsKey(property.name)) + if (property != Task.ID && values.containsKey(property.name)) { return true; + } } return false; } public void triggerMoveForMetadata(final Metadata metadata) { - if (metadata == null) + if (metadata == null) { return; - if (metadata.checkAndClearTransitory(SyncFlags.GTASKS_SUPPRESS_SYNC)) + } + if (metadata.checkAndClearTransitory(SyncFlags.GTASKS_SUPPRESS_SYNC)) { return; - if (actFmPreferenceService.isLoggedIn()) + } + if (actFmPreferenceService.isLoggedIn()) { return; + } if (!metadata.getValue(Metadata.KEY).equals(GtasksMetadata.METADATA_KEY)) //Don't care about non-gtasks metadata + { return; + } if (gtasksPreferenceService.isOngoing()) //Don't try and sync changes that occur during a normal sync + { return; - if (!checkForToken()) + } + if (!checkForToken()) { return; + } operationQueue.offer(new MoveOp(metadata)); } @@ -205,11 +222,13 @@ public final class GtasksSyncService { * Synchronize with server when data changes */ public void pushTaskOnSave(Task task, ContentValues values, GtasksInvoker invoker, boolean sleep) throws IOException { - if (actFmPreferenceService.isLoggedIn()) + if (actFmPreferenceService.isLoggedIn()) { return; + } - if (sleep) + if (sleep) { AndroidUtilities.sleepDeep(1000L); //Wait for metadata to be saved + } Metadata gtasksMetadata = gtasksMetadataService.getTaskMetadata(task.getId()); com.google.api.services.tasks.model.Task remoteModel = null; @@ -302,7 +321,9 @@ public final class GtasksSyncService { //Update the metadata for the newly created task gtasksMetadata.setValue(GtasksMetadata.ID, created.getId()); gtasksMetadata.setValue(GtasksMetadata.LIST_ID, listId); - } else return; + } else { + return; + } } task.setValue(Task.MODIFICATION_DATE, DateUtilities.now()); @@ -313,8 +334,9 @@ public final class GtasksSyncService { } public void pushMetadataOnSave(Metadata model, GtasksInvoker invoker) throws IOException { - if (actFmPreferenceService.isLoggedIn()) + if (actFmPreferenceService.isLoggedIn()) { return; + } AndroidUtilities.sleepDeep(1000L); String taskId = model.getValue(GtasksMetadata.ID); @@ -333,8 +355,9 @@ public final class GtasksSyncService { } private boolean checkForToken() { - if (!gtasksPreferenceService.isLoggedIn()) + if (!gtasksPreferenceService.isLoggedIn()) { return false; + } return true; } } diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/sync/GtasksSyncV2Provider.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/sync/GtasksSyncV2Provider.java index b55924e97..de6d750f5 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gtasks/sync/GtasksSyncV2Provider.java +++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/sync/GtasksSyncV2Provider.java @@ -102,8 +102,9 @@ public class GtasksSyncV2Provider extends SyncV2Provider { } public synchronized static GtasksSyncV2Provider getInstance() { - if (instance == null) + if (instance == null) { instance = new GtasksSyncV2Provider(); + } return instance; } @@ -156,8 +157,9 @@ public class GtasksSyncV2Provider extends SyncV2Provider { public void synchronizeActiveTasks(final boolean manual, final SyncResultCallback callback) { // TODO: Improve this logic. Should only be able to import from settings or something. final boolean isImport = actFmPreferenceService.isLoggedIn(); - if (isImport && !manual) + if (isImport && !manual) { return; + } callback.started(); callback.incrementMax(100); @@ -193,10 +195,11 @@ public class GtasksSyncV2Provider extends SyncV2Provider { synchronizeListHelper(list, invoker, manual, handler, callback, isImport); callback.incrementProgress(25); if (finisher.decrementAndGet() == 0) { - if (!isImport) + if (!isImport) { pushUpdated(invoker, callback); - else + } else { finishImport(callback); + } finishSync(callback); } } @@ -236,11 +239,13 @@ public class GtasksSyncV2Provider extends SyncV2Provider { @Override public void synchronizeList(Object list, final boolean manual, final SyncResultCallback callback) { - if (!(list instanceof StoreObject)) + if (!(list instanceof StoreObject)) { return; + } final StoreObject gtasksList = (StoreObject) list; - if (!GtasksList.TYPE.equals(gtasksList.getValue(StoreObject.TYPE))) + if (!GtasksList.TYPE.equals(gtasksList.getValue(StoreObject.TYPE))) { return; + } final boolean isImport = actFmPreferenceService.isLoggedIn(); @@ -269,8 +274,9 @@ public class GtasksSyncV2Provider extends SyncV2Provider { String authToken = gtasksPreferenceService.getToken(); try { authToken = GtasksTokenValidator.validateAuthToken(ContextManager.getContext(), authToken); - if (authToken != null) + if (authToken != null) { gtasksPreferenceService.setToken(authToken); + } } catch (GoogleTasksException e) { authToken = null; } @@ -325,11 +331,13 @@ public class GtasksSyncV2Provider extends SyncV2Provider { gtasksTaskListUpdater.correctOrderAndIndentForList(listId); } } catch (GoogleTasksException e) { - if (errorHandler != null) + if (errorHandler != null) { errorHandler.handleException("gtasks-sync-io", e, e.getType()); //$NON-NLS-1$ + } } catch (IOException e) { - if (errorHandler != null) + if (errorHandler != null) { errorHandler.handleException("gtasks-sync-io", e, e.toString()); //$NON-NLS-1$ + } } } @@ -346,12 +354,14 @@ public class GtasksSyncV2Provider extends SyncV2Provider { task.setValue(Task.TITLE, remoteTask.getTitle()); task.setValue(Task.CREATION_DATE, DateUtilities.now()); task.setValue(Task.COMPLETION_DATE, GtasksApiUtilities.gtasksCompletedTimeToUnixTime(remoteTask.getCompleted(), 0)); - if (remoteTask.getDeleted() == null || !remoteTask.getDeleted().booleanValue()) + if (remoteTask.getDeleted() == null || !remoteTask.getDeleted().booleanValue()) { task.setValue(Task.DELETION_DATE, 0L); - else if (remoteTask.getDeleted().booleanValue()) + } else if (remoteTask.getDeleted().booleanValue()) { task.setValue(Task.DELETION_DATE, DateUtilities.now()); - if (remoteTask.getHidden() != null && remoteTask.getHidden().booleanValue()) + } + if (remoteTask.getHidden() != null && remoteTask.getHidden().booleanValue()) { task.setValue(Task.DELETION_DATE, DateUtilities.now()); + } long dueDate = GtasksApiUtilities.gtasksDueTimeToUnixTime(remoteTask.getDue(), 0); long createdDate = Task.createDueDate(Task.URGENCY_SPECIFIC_DAY, dueDate); @@ -369,8 +379,9 @@ public class GtasksSyncV2Provider extends SyncV2Provider { private void write(GtasksTaskContainer task) throws IOException { // merge astrid dates with google dates - if (!task.task.isSaved() && actFmPreferenceService.isLoggedIn()) + if (!task.task.isSaved() && actFmPreferenceService.isLoggedIn()) { titleMatchWithActFm(task.task); + } if (task.task.isSaved()) { Task local = PluginServices.getTaskService().fetchById(task.task.getId(), Task.DUE_DATE, Task.COMPLETION_DATE); @@ -379,8 +390,9 @@ public class GtasksSyncV2Provider extends SyncV2Provider { task.task.clearValue(Task.UUID); } else { mergeDates(task.task, local); - if (task.task.isCompleted() && !local.isCompleted()) + if (task.task.isCompleted() && !local.isCompleted()) { StatisticsService.reportEvent(StatisticsConstants.GTASKS_TASK_COMPLETED); + } } } else { // Set default importance and reminders for remotely created tasks task.task.setValue(Task.IMPORTANCE, Preferences.getIntegerFromString( @@ -429,8 +441,9 @@ public class GtasksSyncV2Provider extends SyncV2Provider { .where(MetadataCriteria.withKey(GtasksMetadata.METADATA_KEY))); GtasksImportCallback gtCallback = null; - if (callback instanceof GtasksImportCallback) + if (callback instanceof GtasksImportCallback) { gtCallback = (GtasksImportCallback) callback; + } try { for (tasks.moveToFirst(); !tasks.isAfterLast(); tasks.moveToNext()) { @@ -453,8 +466,9 @@ public class GtasksSyncV2Provider extends SyncV2Provider { tuple.tagUuid = tagUuid; tuple.tagName = listName; - if (gtCallback != null) + if (gtCallback != null) { gtCallback.addImportConflict(tuple); + } continue; } else if (taskIsInTag) { diff --git a/astrid/plugin-src/com/todoroo/astrid/locale/LocaleEditAlerts.java b/astrid/plugin-src/com/todoroo/astrid/locale/LocaleEditAlerts.java index d1fd26b6e..7d08877de 100644 --- a/astrid/plugin-src/com/todoroo/astrid/locale/LocaleEditAlerts.java +++ b/astrid/plugin-src/com/todoroo/astrid/locale/LocaleEditAlerts.java @@ -123,9 +123,10 @@ public final class LocaleEditAlerts extends ListActivity { * robust and re-usable */ final String breadcrumbString = getIntent().getStringExtra(com.twofortyfouram.Intent.EXTRA_STRING_BREADCRUMB); - if (breadcrumbString != null) + if (breadcrumbString != null) { setTitle(String.format("%s%s%s", breadcrumbString, com.twofortyfouram.Intent.BREADCRUMB_SEPARATOR, //$NON-NLS-1$ getString(R.string.locale_edit_alerts_title))); + } /* * Load the Locale background frame from Locale @@ -171,20 +172,24 @@ public final class LocaleEditAlerts extends ListActivity { adapter = new FilterAdapter(this, getListView(), R.layout.filter_adapter_row, true) { @Override public void onReceiveFilter(FilterListItem item) { - if (adapter.getSelection() != null || finalSelection == null) + if (adapter.getSelection() != null || finalSelection == null) { return; + } if (item instanceof Filter) { - if (finalSelection.equals(((Filter) item).getSqlQuery())) + if (finalSelection.equals(((Filter) item).getSqlQuery())) { adapter.setSelection(item); + } } else if (item instanceof FilterCategory) { Filter[] filters = ((FilterCategory) item).children; - if (filters == null) + if (filters == null) { return; - for (Filter filter : filters) + } + for (Filter filter : filters) { if (finalSelection.equals(filter.getSqlQuery())) { adapter.setSelection(filter); break; } + } } } }; @@ -220,11 +225,11 @@ public final class LocaleEditAlerts extends ListActivity { */ @Override public void finish() { - if (isRemoved) + if (isRemoved) { setResult(com.twofortyfouram.Intent.RESULT_REMOVE); - else if (isCancelled) + } else if (isCancelled) { setResult(RESULT_CANCELED); - else { + } else { final FilterListItem selected = adapter.getSelection(); final int intervalIndex = interval.getSelectedItemPosition(); @@ -250,8 +255,9 @@ public final class LocaleEditAlerts extends ListActivity { Filter filterItem = (Filter) selected; storeAndForwardExtras.putString(KEY_FILTER_TITLE, filterItem.title); storeAndForwardExtras.putString(KEY_SQL, filterItem.getSqlQuery()); - if (filterItem.valuesForNewTasks != null) + if (filterItem.valuesForNewTasks != null) { storeAndForwardExtras.putString(KEY_VALUES, AndroidUtilities.contentValuesToSerializedString(filterItem.valuesForNewTasks)); + } storeAndForwardExtras.putInt(KEY_INTERVAL, INTERVALS[intervalIndex]); returnIntent.putExtra(com.twofortyfouram.Intent.EXTRA_BUNDLE, storeAndForwardExtras); @@ -259,10 +265,11 @@ public final class LocaleEditAlerts extends ListActivity { /* * This is the blurb concisely describing what your setting's state is. This is simply used for display in the UI. */ - if (filterItem.title != null && filterItem.title.length() > com.twofortyfouram.Intent.MAXIMUM_BLURB_LENGTH) + if (filterItem.title != null && filterItem.title.length() > com.twofortyfouram.Intent.MAXIMUM_BLURB_LENGTH) { returnIntent.putExtra(com.twofortyfouram.Intent.EXTRA_STRING_BLURB, filterItem.title.substring(0, com.twofortyfouram.Intent.MAXIMUM_BLURB_LENGTH)); - else + } else { returnIntent.putExtra(com.twofortyfouram.Intent.EXTRA_STRING_BLURB, filterItem.title); + } setResult(RESULT_OK, returnIntent); } diff --git a/astrid/plugin-src/com/todoroo/astrid/locale/LocaleReceiver.java b/astrid/plugin-src/com/todoroo/astrid/locale/LocaleReceiver.java index 95be919df..99c4b710b 100644 --- a/astrid/plugin-src/com/todoroo/astrid/locale/LocaleReceiver.java +++ b/astrid/plugin-src/com/todoroo/astrid/locale/LocaleReceiver.java @@ -53,8 +53,9 @@ public class LocaleReceiver extends BroadcastReceiver { try { if (com.twofortyfouram.Intent.ACTION_FIRE_SETTING.equals(intent.getAction())) { - if (!PluginServices.getAddOnService().hasLocalePlugin()) + if (!PluginServices.getAddOnService().hasLocalePlugin()) { return; + } final Bundle forwardedBundle = intent.getBundleExtra(com.twofortyfouram.Intent.EXTRA_BUNDLE); @@ -64,8 +65,9 @@ public class LocaleReceiver extends BroadcastReceiver { final int interval = forwardedBundle.getInt(LocaleEditAlerts.KEY_INTERVAL, 24 * 3600); if (TextUtils.isEmpty(title) || TextUtils.isEmpty(sql) || - sql.contains("--") || sql.contains(";") || interval == 0) + sql.contains("--") || sql.contains(";") || interval == 0) { return; + } // check if we've already made a notification recently String preferenceKey = makePreferenceKey(title, interval); @@ -82,11 +84,13 @@ public class LocaleReceiver extends BroadcastReceiver { TodorooCursor cursor = PluginServices.getTaskService().fetchFiltered( sql, null, Task.ID); try { - if (cursor.getCount() == 0) + if (cursor.getCount() == 0) { return; + } - if (values != null) + if (values != null) { filter.valuesForNewTasks = AndroidUtilities.contentValuesFromSerializedString(values); + } Resources r = context.getResources(); String reminder = r.getString(R.string.locale_notification). diff --git a/astrid/plugin-src/com/todoroo/astrid/notes/EditNoteActivity.java b/astrid/plugin-src/com/todoroo/astrid/notes/EditNoteActivity.java index dcbcb2507..5014f9eff 100644 --- a/astrid/plugin-src/com/todoroo/astrid/notes/EditNoteActivity.java +++ b/astrid/plugin-src/com/todoroo/astrid/notes/EditNoteActivity.java @@ -136,11 +136,13 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene activity.runOnUiThread(new Runnable() { @Override public void run() { - if (task == null) + if (task == null) { return; + } fetchTask(task.getId()); - if (task == null) + if (task == null) { return; + } setUpListAdapter(); loadingText.setText(R.string.ENA_no_comments); loadingText.setVisibility(items.size() == 0 ? View.VISIBLE : View.GONE); @@ -219,8 +221,9 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene refreshData(); } else { loadingText.setText(R.string.ENA_no_comments); - if (items.size() == 0) + if (items.size() == 0) { loadingText.setVisibility(View.VISIBLE); + } } } } @@ -257,9 +260,10 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene public void afterTextChanged(Editable s) { commentButton.setVisibility((s.length() > 0 || pendingCommentPicture != null) ? View.VISIBLE : View.GONE); - if (showTimerShortcut) + if (showTimerShortcut) { timerView.setVisibility((s.length() > 0 || pendingCommentPicture != null) ? View.GONE : View.VISIBLE); + } } @Override @@ -301,10 +305,11 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene pictureButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - if (pendingCommentPicture != null) + if (pendingCommentPicture != null) { ActFmCameraModule.showPictureLauncher(fragment, clearImage); - else + } else { ActFmCameraModule.showPictureLauncher(fragment, null); + } respondToPicture = true; } }); @@ -374,8 +379,9 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene noa = NoteOrUpdate.fromUpdateOrHistory(activity, null, history, user, linkColor); historyCount++; } - if (noa != null) + if (noa != null) { items.add(noa); + } } } finally { updates.close(); @@ -384,12 +390,13 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene Collections.sort(items, new Comparator() { @Override public int compare(NoteOrUpdate a, NoteOrUpdate b) { - if (a.createdAt < b.createdAt) + if (a.createdAt < b.createdAt) { return 1; - else if (a.createdAt == b.createdAt) + } else if (a.createdAt == b.createdAt) { return 0; - else + } else { return -1; + } } }); @@ -408,9 +415,10 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene // Perform action on click commentItems += 10; setUpListAdapter(); - if (task.getValue(Task.HISTORY_HAS_MORE) > 0) + if (task.getValue(Task.HISTORY_HAS_MORE) > 0) { new FetchHistory(taskDao, Task.HISTORY_FETCH_DATE, Task.HISTORY_HAS_MORE, NameMaps.TABLE_ID_TASKS, task.getUuid(), task.getValue(Task.TITLE), 0, historyCount, callback).execute(); + } } }); this.addView(loadMore); @@ -456,10 +464,11 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene final TextView nameView = (TextView) view.findViewById(R.id.title); { nameView.setText(item.title); - if (NameMaps.TABLE_ID_HISTORY.equals(item.type)) + if (NameMaps.TABLE_ID_HISTORY.equals(item.type)) { nameView.setTextColor(grayColor); - else + } else { nameView.setTextColor(color); + } Linkify.addLinks(nameView, Linkify.ALL); } @@ -528,21 +537,25 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene userActivity.setValue(UserActivity.CREATED_AT, DateUtilities.now()); if (usePicture && pendingCommentPicture != null) { JSONObject pictureJson = RemoteModel.PictureHelper.savePictureJson(activity, pendingCommentPicture); - if (pictureJson != null) + if (pictureJson != null) { userActivity.setValue(UserActivity.PICTURE, pictureJson.toString()); + } } userActivityDao.createNew(userActivity); - if (commentField != null) + if (commentField != null) { commentField.setText(""); //$NON-NLS-1$ + } pendingCommentPicture = usePicture ? null : pendingCommentPicture; if (usePicture) { - if (activity != null) + if (activity != null) { activity.getIntent().removeExtra(TaskEditFragment.TOKEN_PICTURE_IN_PROGRESS); + } } - if (pictureButton != null) + if (pictureButton != null) { pictureButton.setImageResource(cameraButton); + } StatisticsService.reportEvent(StatisticsConstants.ACTFM_TASK_COMMENT); setUpListAdapter(); @@ -576,10 +589,12 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene } public static NoteOrUpdate fromMetadata(Metadata m) { - if (!m.containsNonNullValue(NoteMetadata.THUMBNAIL)) + if (!m.containsNonNullValue(NoteMetadata.THUMBNAIL)) { m.setValue(NoteMetadata.THUMBNAIL, ""); //$NON-NLS-1$ - if (!m.containsNonNullValue(NoteMetadata.COMMENT_PICTURE)) + } + if (!m.containsNonNullValue(NoteMetadata.COMMENT_PICTURE)) { m.setValue(NoteMetadata.COMMENT_PICTURE, ""); //$NON-NLS-1$ + } Spanned title = Html.fromHtml(String.format("%s\n%s", m.getValue(NoteMetadata.TITLE), m.getValue(NoteMetadata.BODY))); //$NON-NLS-1$ return new NoteOrUpdate(m.getValue(NoteMetadata.THUMBNAIL), title, @@ -601,17 +616,20 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene if (u != null) { pictureThumb = u.getPictureUrl(UserActivity.PICTURE, RemoteModel.PICTURE_MEDIUM); pictureFull = u.getPictureUrl(UserActivity.PICTURE, RemoteModel.PICTURE_LARGE); - if (TextUtils.isEmpty(pictureThumb)) + if (TextUtils.isEmpty(pictureThumb)) { commentBitmap = u.getPictureBitmap(UserActivity.PICTURE); + } title = UpdateAdapter.getUpdateComment(context, u, user, linkColor, UpdateAdapter.FROM_TASK_VIEW); userImage = ""; //$NON-NLS-1$ - if (user.containsNonNullValue(UpdateAdapter.USER_PICTURE)) + if (user.containsNonNullValue(UpdateAdapter.USER_PICTURE)) { userImage = user.getPictureUrl(UpdateAdapter.USER_PICTURE, RemoteModel.PICTURE_THUMB); + } createdAt = u.getValue(UserActivity.CREATED_AT); type = NameMaps.TABLE_ID_USER_ACTIVITY; } else { - if (user.containsNonNullValue(UpdateAdapter.USER_PICTURE)) + if (user.containsNonNullValue(UpdateAdapter.USER_PICTURE)) { userImage = user.getPictureUrl(UpdateAdapter.USER_PICTURE, RemoteModel.PICTURE_THUMB); + } title = new SpannableString(UpdateAdapter.getHistoryComment(context, history, user, linkColor, UpdateAdapter.FROM_TASK_VIEW)); createdAt = history.getValue(History.CREATED_AT); type = NameMaps.TABLE_ID_HISTORY; @@ -633,8 +651,9 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene } public void removeListener(UpdatesChangedListener listener) { - if (listeners.contains(listener)) + if (listeners.contains(listener)) { listeners.remove(listener); + } } @Override diff --git a/astrid/plugin-src/com/todoroo/astrid/notes/NotesDecorationExposer.java b/astrid/plugin-src/com/todoroo/astrid/notes/NotesDecorationExposer.java index c7ff000b1..d72d06105 100644 --- a/astrid/plugin-src/com/todoroo/astrid/notes/NotesDecorationExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/notes/NotesDecorationExposer.java @@ -25,10 +25,12 @@ public class NotesDecorationExposer implements TaskDecorationExposer { @Override public TaskDecoration expose(Task task) { - if (Preferences.getBoolean(R.string.p_showNotes, false)) + if (Preferences.getBoolean(R.string.p_showNotes, false)) { return null; - if (task == null || !NotesPlugin.hasNotes(task)) + } + if (task == null || !NotesPlugin.hasNotes(task)) { return null; + } Intent intent = new Intent(ContextManager.getContext(), EditNoteActivity.class); intent.setAction(EditNoteActivity.class.getName()); diff --git a/astrid/plugin-src/com/todoroo/astrid/notes/NotesDetailExposer.java b/astrid/plugin-src/com/todoroo/astrid/notes/NotesDetailExposer.java index 38eecae57..1f0841f23 100644 --- a/astrid/plugin-src/com/todoroo/astrid/notes/NotesDetailExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/notes/NotesDetailExposer.java @@ -35,12 +35,14 @@ public class NotesDetailExposer extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { // get tags associated with this task long taskId = intent.getLongExtra(AstridApiConstants.EXTRAS_TASK_ID, -1); - if (taskId == -1) + if (taskId == -1) { return; + } String taskDetail = getTaskDetails(taskId); - if (taskDetail == null) + if (taskDetail == null) { return; + } // transmit Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_SEND_DETAILS); @@ -52,12 +54,14 @@ public class NotesDetailExposer extends BroadcastReceiver { @SuppressWarnings("nls") public String getTaskDetails(long id) { - if (!Preferences.getBoolean(R.string.p_showNotes, false)) + if (!Preferences.getBoolean(R.string.p_showNotes, false)) { return null; + } Task task = PluginServices.getTaskService().fetchById(id, Task.ID, Task.NOTES); - if (task == null) + if (task == null) { return null; + } StringBuilder notesBuilder = new StringBuilder(); @@ -79,8 +83,9 @@ public class NotesDetailExposer extends BroadcastReceiver { for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { metadata.readFromCursor(cursor); - if (notesBuilder.length() > 0) + if (notesBuilder.length() > 0) { notesBuilder.append("\n"); + } notesBuilder.append("").append(metadata.getValue(NoteMetadata.TITLE)).append("\n"); notesBuilder.append(metadata.getValue(NoteMetadata.BODY)); } @@ -88,8 +93,9 @@ public class NotesDetailExposer extends BroadcastReceiver { cursor.close(); } - if (notesBuilder.length() == 0) + if (notesBuilder.length() == 0) { return null; + } return " " + notesBuilder; //$NON-NLS-1$ } diff --git a/astrid/plugin-src/com/todoroo/astrid/notes/NotesPlugin.java b/astrid/plugin-src/com/todoroo/astrid/notes/NotesPlugin.java index 52d668d1d..b76ef8f5e 100644 --- a/astrid/plugin-src/com/todoroo/astrid/notes/NotesPlugin.java +++ b/astrid/plugin-src/com/todoroo/astrid/notes/NotesPlugin.java @@ -37,11 +37,13 @@ public class NotesPlugin extends BroadcastReceiver { * @return */ public static boolean hasNotes(Task task) { - if (task.containsNonNullValue(Task.NOTES) && !TextUtils.isEmpty(task.getValue(Task.NOTES))) + if (task.containsNonNullValue(Task.NOTES) && !TextUtils.isEmpty(task.getValue(Task.NOTES))) { return true; + } - if (PluginServices.getMetadataService().hasMetadata(task.getId(), NoteMetadata.METADATA_KEY)) + if (PluginServices.getMetadataService().hasMetadata(task.getId(), NoteMetadata.METADATA_KEY)) { return true; + } return false; } diff --git a/astrid/plugin-src/com/todoroo/astrid/opencrx/OpencrxControlSet.java b/astrid/plugin-src/com/todoroo/astrid/opencrx/OpencrxControlSet.java index 48a80a3f9..91a270662 100644 --- a/astrid/plugin-src/com/todoroo/astrid/opencrx/OpencrxControlSet.java +++ b/astrid/plugin-src/com/todoroo/astrid/opencrx/OpencrxControlSet.java @@ -187,16 +187,20 @@ public class OpencrxControlSet extends PopupControlSet { displayString += firstname; hasFirstname = true; } - if (lastname != null && lastname.length() > 0) + if (lastname != null && lastname.length() > 0) { hasLastname = true; - if (hasFirstname && hasLastname) + } + if (hasFirstname && hasLastname) { displayString += " "; //$NON-NLS-1$ - if (hasLastname) + } + if (hasLastname) { displayString += lastname; + } if (!hasFirstname && !hasLastname && email != null - && email.length() > 0) + && email.length() > 0) { displayString += email; + } return displayString; } } @@ -244,13 +248,15 @@ public class OpencrxControlSet extends PopupControlSet { Metadata metadata = getTaskMetadata(model.getId()); - if (metadata == null) + if (metadata == null) { metadata = OpencrxCoreUtils.INSTANCE.newMetadata(model.getId()); + } // Fill the dashboard-spinner and set the current dashboard long dashboardId = OpencrxCoreUtils.INSTANCE.getDefaultCreator(); - if (metadata.containsNonNullValue(OpencrxCoreUtils.ACTIVITY_CREATOR_ID)) + if (metadata.containsNonNullValue(OpencrxCoreUtils.ACTIVITY_CREATOR_ID)) { dashboardId = metadata.getValue(OpencrxCoreUtils.ACTIVITY_CREATOR_ID); + } StoreObject[] dashboardsData = readStoreObjects(OpencrxActivityCreator.TYPE); dashboards = new ArrayList(dashboardsData.length); @@ -283,7 +289,9 @@ public class OpencrxControlSet extends PopupControlSet { long id) { OpencrxActivityCreator creatorInput = (OpencrxActivityCreator) adapter.getItemAtPosition(position); - if (creatorInput == null) return; + if (creatorInput == null) { + return; + } int selectedIndex = creatorSelector.getSelectedItemPosition(); @@ -338,7 +346,9 @@ public class OpencrxControlSet extends PopupControlSet { OpencrxContact userInput = (OpencrxContact) adapter.getItemAtPosition(position); - if (userInput == null) return; + if (userInput == null) { + return; + } int selectedIndex = assignedToSelector.getSelectedItemPosition(); @@ -369,10 +379,11 @@ public class OpencrxControlSet extends PopupControlSet { OpencrxContact responsibleUser = (OpencrxContact) assignedToSelector.getSelectedItem(); - if (responsibleUser == null) + if (responsibleUser == null) { metadata.setValue(OpencrxCoreUtils.ACTIVITY_ASSIGNED_TO_ID, 0L); - else + } else { metadata.setValue(OpencrxCoreUtils.ACTIVITY_ASSIGNED_TO_ID, responsibleUser.getId()); + } if (metadata.getSetValues().size() > 0) { metadataService.save(metadata); @@ -394,8 +405,9 @@ public class OpencrxControlSet extends PopupControlSet { MetadataCriteria.byTaskAndwithKey(taskId, OpencrxCoreUtils.OPENCRX_ACTIVITY_METADATA_KEY)) ); try { - if (cursor.getCount() == 0) + if (cursor.getCount() == 0) { return null; + } cursor.moveToFirst(); return new Metadata(cursor); } finally { diff --git a/astrid/plugin-src/com/todoroo/astrid/opencrx/OpencrxCoreUtils.java b/astrid/plugin-src/com/todoroo/astrid/opencrx/OpencrxCoreUtils.java index caa13d3db..cf16bbd30 100644 --- a/astrid/plugin-src/com/todoroo/astrid/opencrx/OpencrxCoreUtils.java +++ b/astrid/plugin-src/com/todoroo/astrid/opencrx/OpencrxCoreUtils.java @@ -112,10 +112,11 @@ public class OpencrxCoreUtils extends SyncProviderUtilities { public boolean isLoggedIn() { SharedPreferences sharedPreferences = OpencrxCoreUtils.getPrefs(); - if (sharedPreferences != null) + if (sharedPreferences != null) { return sharedPreferences.getString(getIdentifier() + PREF_TOKEN, null) != null; - else + } else { return false; + } } @Override diff --git a/astrid/plugin-src/com/todoroo/astrid/people/PeopleFilterExposer.java b/astrid/plugin-src/com/todoroo/astrid/people/PeopleFilterExposer.java index 1050183be..729c86128 100644 --- a/astrid/plugin-src/com/todoroo/astrid/people/PeopleFilterExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/people/PeopleFilterExposer.java @@ -65,11 +65,13 @@ public class PeopleFilterExposer extends BroadcastReceiver { User user = new User(); for (users.moveToFirst(); !users.isAfterLast(); users.moveToNext()) { user.readFromCursor(users); - if (ActFmPreferenceService.userId().equals(user.getValue(User.UUID))) + if (ActFmPreferenceService.userId().equals(user.getValue(User.UUID))) { continue; + } Filter currFilter = filterFromUserData(user); - if (currFilter != null) + if (currFilter != null) { items.add(currFilter); + } } return items.toArray(new FilterListItem[items.size()]); } finally { @@ -80,16 +82,18 @@ public class PeopleFilterExposer extends BroadcastReceiver { @SuppressWarnings({"nls", "deprecation"}) private static FilterWithCustomIntent filterFromUserData(User user) { String title = user.getDisplayName(); - if (TextUtils.isEmpty(title) || "null".equals(title)) + if (TextUtils.isEmpty(title) || "null".equals(title)) { return null; + } String email = user.getValue(User.EMAIL); Criterion criterion; - if (TextUtils.isEmpty(email) || "null".equals(email)) + if (TextUtils.isEmpty(email) || "null".equals(email)) { criterion = Task.USER_ID.eq(user.getValue(User.UUID)); - else + } else { criterion = Criterion.or(Task.USER_ID.eq(user.getValue(User.UUID)), Task.USER.like("%" + email + "%")); // Deprecated field OK for backwards compatibility + } criterion = Criterion.and(TaskCriteria.activeAndVisible(), criterion); diff --git a/astrid/plugin-src/com/todoroo/astrid/people/PeopleListFragment.java b/astrid/plugin-src/com/todoroo/astrid/people/PeopleListFragment.java index 25ad25207..a66223301 100644 --- a/astrid/plugin-src/com/todoroo/astrid/people/PeopleListFragment.java +++ b/astrid/plugin-src/com/todoroo/astrid/people/PeopleListFragment.java @@ -21,9 +21,10 @@ public class PeopleListFragment extends FilterListFragment { @Override protected int getLayout(Activity activity) { - if (AstridPreferences.useTabletLayout(activity)) + if (AstridPreferences.useTabletLayout(activity)) { return R.layout.filter_list_fragment_alternative_3pane; - else + } else { return R.layout.filter_list_fragment_alternative; + } } } diff --git a/astrid/plugin-src/com/todoroo/astrid/people/PersonViewFragment.java b/astrid/plugin-src/com/todoroo/astrid/people/PersonViewFragment.java index 23b61b240..948c50d3d 100644 --- a/astrid/plugin-src/com/todoroo/astrid/people/PersonViewFragment.java +++ b/astrid/plugin-src/com/todoroo/astrid/people/PersonViewFragment.java @@ -93,11 +93,13 @@ public class PersonViewFragment extends TaskListFragment { protected void setupQuickAddBar() { super.setupQuickAddBar(); quickAddBar.setUsePeopleControl(false); - if (user != null) + if (user != null) { quickAddBar.getQuickAddBox().setHint(getString(R.string.TLA_quick_add_hint_assign, user.getDisplayName())); + } - if (extras.containsKey(EXTRA_HIDE_QUICK_ADD)) + if (extras.containsKey(EXTRA_HIDE_QUICK_ADD)) { quickAddBar.setVisibility(View.GONE); + } // set listener for astrid icon emptyView.setOnClickListener(null); @@ -107,17 +109,19 @@ public class PersonViewFragment extends TaskListFragment { private String getUserSubtitleText() { String status = user.getValue(User.STATUS); String userName = user.getDisplayName(); - if (User.STATUS_PENDING.equals(status) || User.STATUS_REQUEST.equals(status)) + if (User.STATUS_PENDING.equals(status) || User.STATUS_REQUEST.equals(status)) { return getString(R.string.actfm_friendship_pending, userName); - else if (User.STATUS_BLOCKED.equals(status) || User.STATUS_RENOUNCE.equals(status)) + } else if (User.STATUS_BLOCKED.equals(status) || User.STATUS_RENOUNCE.equals(status)) { return getString(R.string.actfm_friendship_blocked, userName); - else if (User.STATUS_FRIENDS.equals(status) || User.STATUS_CONFIRM.equals(status)) + } else if (User.STATUS_FRIENDS.equals(status) || User.STATUS_CONFIRM.equals(status)) { return getString(R.string.actfm_friendship_friends, userName); - else if (User.STATUS_OTHER_PENDING.equals(status)) + } else if (User.STATUS_OTHER_PENDING.equals(status)) { return getString(R.string.actfm_friendship_other_pending, userName); - else if (User.STATUS_IGNORED.equals(status) || User.STATUS_IGNORE.equals(status)) + } else if (User.STATUS_IGNORED.equals(status) || User.STATUS_IGNORE.equals(status)) { return getString(R.string.actfm_friendship_ignored, userName); - else return getString(R.string.actfm_friendship_no_status, userName); + } else { + return getString(R.string.actfm_friendship_no_status, userName); + } } @@ -125,13 +129,16 @@ public class PersonViewFragment extends TaskListFragment { String status = user.getValue(User.STATUS); userStatusButton.setVisibility(View.VISIBLE); if (User.STATUS_CONFIRM.equals(status) || User.STATUS_IGNORE.equals(status) || User.STATUS_RENOUNCE.equals(status) || User.STATUS_REQUEST.equals(user)) // All the pending status options + { userStatusButton.setVisibility(View.GONE); - else if (TextUtils.isEmpty(status) || "null".equals(status)) //$NON-NLS-1$ + } else if (TextUtils.isEmpty(status) || "null".equals(status)) //$NON-NLS-1$ + { userStatusButton.setText(getString(R.string.actfm_friendship_connect)); - else if (User.STATUS_OTHER_PENDING.equals(status)) + } else if (User.STATUS_OTHER_PENDING.equals(status)) { userStatusButton.setText(getString(R.string.actfm_friendship_accept)); - else + } else { userStatusButton.setVisibility(View.GONE); + } } @Override @@ -191,8 +198,9 @@ public class PersonViewFragment extends TaskListFragment { @Override protected void initiateAutomaticSyncImpl() { - if (!isCurrentTaskListFragment()) + if (!isCurrentTaskListFragment()) { return; + } if (user != null) { long lastAutosync = user.getValue(User.LAST_AUTOSYNC); diff --git a/astrid/plugin-src/com/todoroo/astrid/reminders/Notifications.java b/astrid/plugin-src/com/todoroo/astrid/reminders/Notifications.java index 40cac4b50..6ada7d9b2 100644 --- a/astrid/plugin-src/com/todoroo/astrid/reminders/Notifications.java +++ b/astrid/plugin-src/com/todoroo/astrid/reminders/Notifications.java @@ -112,21 +112,24 @@ public class Notifications extends BroadcastReceiver { Resources r = context.getResources(); String reminder; - if (type == ReminderService.TYPE_ALARM) + if (type == ReminderService.TYPE_ALARM) { reminder = getRandomReminder(r.getStringArray(R.array.reminders_alarm)); - else if (Preferences.getBoolean(R.string.p_rmd_nagging, true)) { - if (type == ReminderService.TYPE_DUE || type == ReminderService.TYPE_OVERDUE) + } else if (Preferences.getBoolean(R.string.p_rmd_nagging, true)) { + if (type == ReminderService.TYPE_DUE || type == ReminderService.TYPE_OVERDUE) { reminder = getRandomReminder(r.getStringArray(R.array.reminders_due)); - else if (type == ReminderService.TYPE_SNOOZE) + } else if (type == ReminderService.TYPE_SNOOZE) { reminder = getRandomReminder(r.getStringArray(R.array.reminders_snooze)); - else + } else { reminder = getRandomReminder(r.getStringArray(R.array.reminders)); - } else + } + } else { reminder = ""; //$NON-NLS-1$ + } synchronized (Notifications.class) { - if (notificationManager == null) + if (notificationManager == null) { notificationManager = new AndroidNotificationManager(context); + } } if (!showTaskNotification(id, type, reminder)) { @@ -160,34 +163,40 @@ public class Notifications extends BroadcastReceiver { try { task = taskDao.fetch(id, Task.ID, Task.TITLE, Task.HIDE_UNTIL, Task.COMPLETION_DATE, Task.DUE_DATE, Task.DELETION_DATE, Task.REMINDER_FLAGS, Task.USER_ID); - if (task == null) + if (task == null) { throw new IllegalArgumentException("cound not find item with id"); //$NON-NLS-1$ + } } catch (Exception e) { exceptionService.reportError("show-notif", e); //$NON-NLS-1$ return false; } - if (!Preferences.getBoolean(R.string.p_rmd_enabled, true)) + if (!Preferences.getBoolean(R.string.p_rmd_enabled, true)) { return false; + } // you're done, or not yours - don't sound, do delete - if (task.isCompleted() || task.isDeleted() || !Task.USER_ID_SELF.equals(task.getValue(Task.USER_ID))) + if (task.isCompleted() || task.isDeleted() || !Task.USER_ID_SELF.equals(task.getValue(Task.USER_ID))) { return false; + } // new task edit in progress - if (TextUtils.isEmpty(task.getValue(Task.TITLE))) + if (TextUtils.isEmpty(task.getValue(Task.TITLE))) { return false; + } // it's hidden - don't sound, don't delete - if (task.isHidden() && type == ReminderService.TYPE_RANDOM) + if (task.isHidden() && type == ReminderService.TYPE_RANDOM) { return true; + } // task due date was changed, but alarm wasn't rescheduled boolean dueInFuture = task.hasDueTime() && task.getValue(Task.DUE_DATE) > DateUtilities.now() || !task.hasDueTime() && task.getValue(Task.DUE_DATE) - DateUtilities.now() > DateUtilities.ONE_DAY; if ((type == ReminderService.TYPE_DUE || type == ReminderService.TYPE_OVERDUE) && - (!task.hasDueDate() || dueInFuture)) + (!task.hasDueDate() || dueInFuture)) { return true; + } // read properties String taskTitle = task.getValue(Task.TITLE); @@ -237,10 +246,11 @@ public class Notifications extends BroadcastReceiver { inAppNotify.putExtra(EXTRAS_TEXT, text); inAppNotify.putExtra(EXTRAS_RING_TIMES, ringTimes); - if (forceNotificationManager) + if (forceNotificationManager) { new ShowNotificationReceiver().onReceive(ContextManager.getContext(), inAppNotify); - else + } else { context.sendOrderedBroadcast(inAppNotify, AstridApiConstants.PERMISSION_READ); + } } /** @@ -286,12 +296,14 @@ public class Notifications extends BroadcastReceiver { String text, int ringTimes) { Context context = ContextManager.getContext(); - if (notificationManager == null) + if (notificationManager == null) { notificationManager = new AndroidNotificationManager(context); + } // don't ring multiple times if random reminder - if (type == ReminderService.TYPE_RANDOM) + if (type == ReminderService.TYPE_RANDOM) { ringTimes = 1; + } // quiet hours? unless alarm clock boolean quietHours = (type == ReminderService.TYPE_ALARM || type == ReminderService.TYPE_DUE) ? false : isQuietHours(); @@ -327,8 +339,9 @@ public class Notifications extends BroadcastReceiver { notification.ledOffMS = 5000; notification.ledOnMS = 700; notification.ledARGB = Color.YELLOW; - } else + } else { notification.defaults = Notification.DEFAULT_LIGHTS; + } AudioManager audioManager = (AudioManager) context.getSystemService( Context.AUDIO_SERVICE); @@ -399,17 +412,19 @@ public class Notifications extends BroadcastReceiver { } } - if (Constants.DEBUG) + if (Constants.DEBUG) { Log.w("Astrid", "Logging notification: " + text); //$NON-NLS-1$ //$NON-NLS-2$ + } singleThreadVoicePool.submit(new NotificationRunnable(ringTimes, notificationId, notification, voiceReminder, maxOutVolumeForMultipleRingReminders, audioManager, previousAlarmVolume, text)); - if (forceNotificationManager) + if (forceNotificationManager) { try { singleThreadVoicePool.awaitTermination(1000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { // } + } } private static class NotificationRunnable implements Runnable { @@ -445,15 +460,18 @@ public class Notifications extends BroadcastReceiver { AndroidUtilities.sleepDeep(2000); for (int i = 0; i < 50; i++) { AndroidUtilities.sleepDeep(500); - if (audioManager.getMode() != AudioManager.MODE_RINGTONE) + if (audioManager.getMode() != AudioManager.MODE_RINGTONE) { break; + } } try { // first reset the Alarm-volume to the value before it was eventually maxed out - if (maxOutVolumeForMultipleRingReminders) + if (maxOutVolumeForMultipleRingReminders) { audioManager.setStreamVolume(AudioManager.STREAM_ALARM, previousAlarmVolume, 0); - if (voiceReminder) + } + if (voiceReminder) { VoiceOutputService.getVoiceOutputInstance().queueSpeak(text); + } } catch (VerifyError e) { // unavailable } @@ -472,11 +490,13 @@ public class Notifications extends BroadcastReceiver { if (quietHoursStart != -1 && quietHoursEnd != -1) { int hour = new Date().getHours(); if (quietHoursStart <= quietHoursEnd) { - if (hour >= quietHoursStart && hour < quietHoursEnd) + if (hour >= quietHoursStart && hour < quietHoursEnd) { return true; + } } else { // wrap across 24/hour boundary - if (hour >= quietHoursStart || hour < quietHoursEnd) + if (hour >= quietHoursStart || hour < quietHoursEnd) { return true; + } } } return false; @@ -488,12 +508,14 @@ public class Notifications extends BroadcastReceiver { * @param shouldPerformPropertyCheck whether to check if task has requisite properties */ public static void cancelNotifications(long taskId) { - if (notificationManager == null) + if (notificationManager == null) { synchronized (Notifications.class) { - if (notificationManager == null) + if (notificationManager == null) { notificationManager = new AndroidNotificationManager( ContextManager.getContext()); + } } + } notificationManager.cancel((int) taskId); } diff --git a/astrid/plugin-src/com/todoroo/astrid/reminders/ReengagementReceiver.java b/astrid/plugin-src/com/todoroo/astrid/reminders/ReengagementReceiver.java index 6b8af477f..750b588d0 100644 --- a/astrid/plugin-src/com/todoroo/astrid/reminders/ReengagementReceiver.java +++ b/astrid/plugin-src/com/todoroo/astrid/reminders/ReengagementReceiver.java @@ -49,8 +49,9 @@ public class ReengagementReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { - if (!Preferences.getBoolean(R.string.p_rmd_enabled, true)) + if (!Preferences.getBoolean(R.string.p_rmd_enabled, true)) { return; + } DependencyInjectionService.getInstance().inject(this); @@ -76,10 +77,12 @@ public class ReengagementReceiver extends BroadcastReceiver { if (actFmPreferenceService.isLoggedIn()) { JSONObject thisUser = ActFmPreferenceService.thisUser(); name = thisUser.optString("first_name"); //$NON-NLS-1$ - if (TextUtils.isEmpty(name)) + if (TextUtils.isEmpty(name)) { name = thisUser.optString("name"); //$NON-NLS-1$ - if (TextUtils.isEmpty(name)) + } + if (TextUtils.isEmpty(name)) { name = context.getString(R.string.rmd_reengage_name_default); + } } title = String.format(title, name); } diff --git a/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderDebugContextActions.java b/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderDebugContextActions.java index 3fc4dc933..0dd5ecd5a 100644 --- a/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderDebugContextActions.java +++ b/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderDebugContextActions.java @@ -22,8 +22,9 @@ public class ReminderDebugContextActions { @Override public Object getLabel(Task task) { - if (Constants.DEBUG) + if (Constants.DEBUG) { return "when alarm?"; + } return null; } @@ -32,8 +33,9 @@ public class ReminderDebugContextActions { ReminderService.getInstance().setScheduler(new AlarmScheduler() { @Override public void createAlarm(Task theTask, long time, int type) { - if (time == 0 || time == Long.MAX_VALUE) + if (time == 0 || time == Long.MAX_VALUE) { return; + } Toast.makeText(ContextManager.getContext(), "Scheduled Alarm: " + new Date(time), Toast.LENGTH_LONG).show(); @@ -41,8 +43,9 @@ public class ReminderDebugContextActions { } }); ReminderService.getInstance().scheduleAlarm(task); - if (ReminderService.getInstance().getScheduler() != null) + if (ReminderService.getInstance().getScheduler() != null) { Toast.makeText(ContextManager.getContext(), "No alarms", Toast.LENGTH_LONG).show(); + } ReminderService.getInstance().setScheduler(original); } } @@ -50,8 +53,9 @@ public class ReminderDebugContextActions { public static class MakeNotification implements TaskContextActionExposer { public Object getLabel(Task task) { - if (Constants.DEBUG) + if (Constants.DEBUG) { return "when alarm?"; //$NON-NLS-1$ + } return null; } diff --git a/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderDialog.java b/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderDialog.java index 38b51bbf0..12c3c5888 100644 --- a/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderDialog.java +++ b/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderDialog.java @@ -94,8 +94,9 @@ public class ReminderDialog extends Dialog { Date alarmTime = new Date(); alarmTime.setHours(hours); alarmTime.setMinutes(minutes); - if (alarmTime.getTime() < DateUtilities.now()) + if (alarmTime.getTime() < DateUtilities.now()) { alarmTime.setDate(alarmTime.getDate() + 1); + } dialogSnooze.snoozeForTime(alarmTime.getTime()); } }; @@ -129,8 +130,9 @@ public class ReminderDialog extends Dialog { @Override public void onClick(View arg0) { Task task = taskService.fetchById(taskId, Task.ID, Task.REMINDER_LAST, Task.SOCIAL_REMINDER); - if (task != null) + if (task != null) { taskService.setComplete(task, true); + } activity.sendBroadcast(new Intent(AstridApiConstants.BROADCAST_EVENT_REFRESH)); Toast.makeText(activity, R.string.rmd_NoA_completed_toast, @@ -170,8 +172,9 @@ public class ReminderDialog extends Dialog { } private void addFacesToReminder(Activity activity, Task task) { - if (task == null) + if (task == null) { return; + } Resources resources = activity.getResources(); LinkedHashSet pictureUrls = new LinkedHashSet(); List names = new ArrayList(); @@ -200,8 +203,9 @@ public class ReminderDialog extends Dialog { lp.setMargins(padding, padding, 0, padding); image.setLayoutParams(lp); layout.addView(image); - if (++count >= MAX_FACES) + if (++count >= MAX_FACES) { break; + } } LinearLayout container = (LinearLayout) findViewById(R.id.speech_bubble_content); @@ -209,21 +213,23 @@ public class ReminderDialog extends Dialog { container.addView(layout, 0); String text; - if (names.size() == 0) + if (names.size() == 0) { text = activity.getString(R.string.reminders_social); - else if (names.size() == 1) + } else if (names.size() == 1) { text = activity.getString(R.string.reminders_social_one, names.get(0)); - else + } else { text = activity.getString(R.string.reminders_social_multiple, names.get(0), names.get(1)); + } ((TextView) findViewById(R.id.reminder_message)).setText(text); task.setValue(Task.SOCIAL_REMINDER, Task.REMINDER_SOCIAL_FACES); } else { - if (isSharedTask.get()) + if (isSharedTask.get()) { task.setValue(Task.SOCIAL_REMINDER, Task.REMINDER_SOCIAL_NO_FACES); - else + } else { task.setValue(Task.SOCIAL_REMINDER, Task.REMINDER_SOCIAL_PRIVATE); + } } } @@ -232,7 +238,9 @@ public class ReminderDialog extends Dialog { JSONObject person = array.getJSONObject(i); if (person.has("picture")) { //$NON-NLS-1$ if (ActFmPreferenceService.userId().equals(Long.toString(person.optLong("id")))) //$NON-NLS-1$ + { continue; + } isSharedTask.set(true); String pictureUrl = person.getString("picture"); //$NON-NLS-1$ if (!TextUtils.isEmpty(pictureUrl)) { @@ -240,12 +248,13 @@ public class ReminderDialog extends Dialog { } String name = person.optString("first_name"); //$NON-NLS-1$ - if (!TextUtils.isEmpty(name)) + if (!TextUtils.isEmpty(name)) { names.add(name); - else { + } else { name = person.optString("name"); //$NON-NLS-1$ - if (!TextUtils.isEmpty(name)) + if (!TextUtils.isEmpty(name)) { names.add(name); + } } diff --git a/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderPreferences.java b/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderPreferences.java index d58dd5835..7f320256a 100644 --- a/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderPreferences.java +++ b/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderPreferences.java @@ -46,9 +46,9 @@ public class ReminderPreferences extends TodorooPreferenceActivity { } else if (r.getString(R.string.p_rmd_quietEnd).equals(preference.getKey())) { int index = AndroidUtilities.indexOf(r.getStringArray(R.array.EPr_quiet_hours_end_values), (String) value); int quietHoursStart = Preferences.getIntegerFromString(R.string.p_rmd_quietStart, -1); - if (index == -1 || quietHoursStart == -1) + if (index == -1 || quietHoursStart == -1) { preference.setSummary(r.getString(R.string.rmd_EPr_quiet_hours_desc_none)); - else { + } else { String setting = r.getStringArray(R.array.EPr_quiet_hours_end)[index]; preference.setSummary(r.getString(R.string.rmd_EPr_quiet_hours_end_desc, setting)); } @@ -62,46 +62,56 @@ public class ReminderPreferences extends TodorooPreferenceActivity { } } else if (r.getString(R.string.p_rmd_ringtone).equals(preference.getKey())) { if (value == null || "content://settings/system/notification_sound".equals(value)) //$NON-NLS-1$ + { preference.setSummary(r.getString(R.string.rmd_EPr_ringtone_desc_default)); - else if ("".equals(value)) //$NON-NLS-1$ + } else if ("".equals(value)) //$NON-NLS-1$ + { preference.setSummary(r.getString(R.string.rmd_EPr_ringtone_desc_silent)); - else + } else { preference.setSummary(r.getString(R.string.rmd_EPr_ringtone_desc_custom)); + } } else if (r.getString(R.string.p_rmd_persistent).equals(preference.getKey())) { - if ((Boolean) value) + if ((Boolean) value) { preference.setSummary(r.getString(R.string.rmd_EPr_persistent_desc_true)); - else + } else { preference.setSummary(r.getString(R.string.rmd_EPr_persistent_desc_false)); + } } else if (r.getString(R.string.p_rmd_maxvolume).equals(preference.getKey())) { - if ((Boolean) value) + if ((Boolean) value) { preference.setSummary(r.getString(R.string.rmd_EPr_multiple_maxvolume_desc_true)); - else + } else { preference.setSummary(r.getString(R.string.rmd_EPr_multiple_maxvolume_desc_false)); + } } else if (r.getString(R.string.p_rmd_vibrate).equals(preference.getKey())) { - if ((Boolean) value) + if ((Boolean) value) { preference.setSummary(r.getString(R.string.rmd_EPr_vibrate_desc_true)); - else + } else { preference.setSummary(r.getString(R.string.rmd_EPr_vibrate_desc_false)); + } } else if (r.getString(R.string.p_rmd_nagging).equals(preference.getKey())) { - if ((Boolean) value) + if ((Boolean) value) { preference.setSummary(r.getString(R.string.rmd_EPr_nagging_desc_true)); - else + } else { preference.setSummary(r.getString(R.string.rmd_EPr_nagging_desc_false)); + } } else if (r.getString(R.string.p_rmd_snooze_dialog).equals(preference.getKey())) { - if (value == null || ((Boolean) value) == true) + if (value == null || ((Boolean) value) == true) { preference.setSummary(r.getString(R.string.rmd_EPr_snooze_dialog_desc_true)); - else + } else { preference.setSummary(r.getString(R.string.rmd_EPr_snooze_dialog_desc_false)); + } } else if (r.getString(R.string.p_rmd_enabled).equals(preference.getKey())) { - if ((Boolean) value) + if ((Boolean) value) { preference.setSummary(R.string.rmd_EPr_enabled_desc_true); - else + } else { preference.setSummary(R.string.rmd_EPr_enabled_desc_false); + } } else if (r.getString(R.string.p_rmd_social).equals(preference.getKey())) { - if ((Boolean) value) + if ((Boolean) value) { preference.setSummary(R.string.rmd_EPr_social_summary_enabled); - else + } else { preference.setSummary(R.string.rmd_EPr_social_summary_disabled); + } } } diff --git a/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderService.java b/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderService.java index 561cc384f..d233ce28f 100644 --- a/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderService.java +++ b/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderService.java @@ -97,8 +97,9 @@ public final class ReminderService { private static ReminderService instance = null; public static synchronized ReminderService getInstance() { - if (instance == null) + if (instance == null) { instance = new ReminderService(); + } return instance; } @@ -110,8 +111,9 @@ public final class ReminderService { * Set preference defaults, if unset. called at startup */ public void setPreferenceDefaults() { - if (preferencesInitialized) + if (preferencesInitialized) { return; + } Context context = ContextManager.getContext(); SharedPreferences prefs = Preferences.getPrefs(context); @@ -184,16 +186,18 @@ public final class ReminderService { * @param shouldPerformPropertyCheck whether to check if task has requisite properties */ private void scheduleAlarm(Task task, boolean shouldPerformPropertyCheck) { - if (task == null || !task.isSaved()) + if (task == null || !task.isSaved()) { return; + } // read data if necessary if (shouldPerformPropertyCheck) { for (Property property : NOTIFICATION_PROPERTIES) { if (!task.containsValue(property)) { task = taskDao.fetch(task.getId(), NOTIFICATION_PROPERTIES); - if (task == null) + if (task == null) { return; + } break; } } @@ -227,8 +231,9 @@ public final class ReminderService { } // if random reminders are too close to due date, favor due date - if (whenRandom != NO_ALARM && whenDueDate - whenRandom < DateUtilities.ONE_DAY) + if (whenRandom != NO_ALARM && whenDueDate - whenRandom < DateUtilities.ONE_DAY) { whenRandom = NO_ALARM; + } // snooze trumps all if (whenSnooze != NO_ALARM) { @@ -254,8 +259,9 @@ public final class ReminderService { * @return */ private long calculateNextSnoozeReminder(Task task) { - if (task.getValue(Task.REMINDER_SNOOZE) > DateUtilities.now()) + if (task.getValue(Task.REMINDER_SNOOZE) > DateUtilities.now()) { return task.getValue(Task.REMINDER_SNOOZE); + } return NO_ALARM; } @@ -281,16 +287,19 @@ public final class ReminderService { long dueDateForOverdue = due.getTime(); long lastReminder = task.getValue(Task.REMINDER_LAST); - if (dueDateForOverdue > getNowValue()) + if (dueDateForOverdue > getNowValue()) { return dueDateForOverdue + (long) ((0.5f + 2f * random.nextFloat()) * DateUtilities.ONE_HOUR); + } - if (lastReminder < dueDateForOverdue) + if (lastReminder < dueDateForOverdue) { return getNowValue(); + } - if (getNowValue() - lastReminder < 6 * DateUtilities.ONE_HOUR) + if (getNowValue() - lastReminder < 6 * DateUtilities.ONE_HOUR) { return getNowValue() + (long) ((2.0f + task.getValue(Task.IMPORTANCE) + 6f * random.nextFloat()) * DateUtilities.ONE_HOUR); + } return getNowValue(); } @@ -320,8 +329,9 @@ public final class ReminderService { if (task.hasDueTime()) // return due date straight up + { dueDateAlarm = dueDate; - else if (DateUtilities.now() > lastReminder + DateUtilities.ONE_DAY) { + } else if (DateUtilities.now() > lastReminder + DateUtilities.ONE_DAY) { // return notification time on this day Date date = new Date(dueDate); date.setHours(Preferences.getIntegerFromString(R.string.p_rmd_time, 18)); @@ -365,10 +375,11 @@ public final class ReminderService { long millisAfterQuiet = dueDate - quietHoursEndDate.getTime(); // if there is more time after quiethours today, select quiethours-end for reminder - if (millisAfterQuiet > (millisToQuiet / ((float) (1 - (1 / periodDivFactor))))) + if (millisAfterQuiet > (millisToQuiet / ((float) (1 - (1 / periodDivFactor))))) { dueDateAlarm = quietHoursEndDate.getTime(); - else + } else { dueDateAlarm = getNowValue() + (long) (millisToQuiet / periodDivFactor); + } } else { // after quietHours, reuse dueDate for end of day dueDateAlarm = getNowValue() + (long) (millisToEndOfDay / periodDivFactor); @@ -391,13 +402,15 @@ public final class ReminderService { dueDateAlarm = getNowValue() + (long) (millisToEndOfDay / periodDivFactor); } - if (dueDate > getNowValue() && dueDateAlarm < getNowValue()) + if (dueDate > getNowValue() && dueDateAlarm < getNowValue()) { dueDateAlarm = dueDate; + } } } - if (lastReminder > dueDateAlarm) + if (lastReminder > dueDateAlarm) { return NO_ALARM; + } return dueDateAlarm; } @@ -419,8 +432,9 @@ public final class ReminderService { if ((reminderPeriod) > 0) { long when = task.getValue(Task.REMINDER_LAST); - if (when == 0) + if (when == 0) { when = task.getValue(Task.CREATION_DATE); + } when += (long) (reminderPeriod * (0.85f + 0.3f * random.nextFloat())); @@ -462,8 +476,9 @@ public final class ReminderService { */ @SuppressWarnings("nls") public void createAlarm(Task task, long time, int type) { - if (task.getId() == Task.NO_ID) + if (task.getId() == Task.NO_ID) { return; + } Context context = ContextManager.getContext(); Intent intent = new Intent(context, Notifications.class); intent.setType(Long.toString(task.getId())); @@ -484,14 +499,16 @@ public final class ReminderService { PendingIntent pendingIntent = PendingIntent.getBroadcast(context, requestCode, intent, 0); - if (time == 0 || time == NO_ALARM) + if (time == 0 || time == NO_ALARM) { am.cancel(pendingIntent); - else { - if (time < DateUtilities.now()) + } else { + if (time < DateUtilities.now()) { time = DateUtilities.now() + 5000L; + } - if (Constants.DEBUG) + if (Constants.DEBUG) { Log.e("Astrid", "Reminder set for " + new Date(time) + " for (\"" + task.getValue(Task.TITLE) + "\" (" + task.getId() + "), " + type + ")"); + } am.set(AlarmManager.RTC_WAKEUP, time, pendingIntent); } } diff --git a/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatControlSet.java b/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatControlSet.java index b7ff551dc..fbcf09cde 100644 --- a/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatControlSet.java +++ b/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatControlSet.java @@ -113,16 +113,18 @@ public class RepeatControlSet extends PopupControlSet { private void setRepeatUntilValue(long newValue) { repeatUntilValue = newValue; - if (newValue == 0) + if (newValue == 0) { repeatUntil.setText(activity.getString(R.string.repeat_forever)); - else + } else { repeatUntil.setText(activity.getString(R.string.repeat_until, DateAndTimePicker.getDisplayString(activity, newValue))); + } } protected void repeatValueClick() { int dialogValue = repeatValue; - if (dialogValue == 0) + if (dialogValue == 0) { dialogValue = 1; + } new NumberPickerDialog(activity, new OnNumberPickedListener() { @Override @@ -157,8 +159,9 @@ public class RepeatControlSet extends PopupControlSet { } public void removeListener(RepeatChangedListener listener) { - if (listeners.contains(listener)) + if (listeners.contains(listener)) { listeners.remove(listener); + } } @SuppressWarnings("nls") @@ -166,8 +169,9 @@ public class RepeatControlSet extends PopupControlSet { public void readFromTask(Task task) { super.readFromTask(task); recurrence = model.sanitizedRecurrence(); - if (recurrence == null) + if (recurrence == null) { recurrence = ""; + } repeatUntilValue = model.getValue(Task.REPEAT_UNTIL); @@ -218,8 +222,9 @@ public class RepeatControlSet extends PopupControlSet { date = new Date(model.getValue(Task.DUE_DATE)); int dayOfWeek = date.getDay(); - for (int i = 0; i < 7; i++) + for (int i = 0; i < 7; i++) { daysOfWeek[i].setChecked(i == dayOfWeek); + } } // read recurrence rule @@ -232,13 +237,16 @@ public class RepeatControlSet extends PopupControlSet { interval.setSelection(intervalValue); // clear all day of week checks, then update them - for (int i = 0; i < 7; i++) + for (int i = 0; i < 7; i++) { daysOfWeek[i].setChecked(false); + } for (WeekdayNum day : rrule.getByDay()) { - for (int i = 0; i < 7; i++) - if (daysOfWeek[i].getTag().equals(day.wday)) + for (int i = 0; i < 7; i++) { + if (daysOfWeek[i].getTag().equals(day.wday)) { daysOfWeek[i].setChecked(true); + } + } } // suppress first call to interval.onItemSelected @@ -252,10 +260,11 @@ public class RepeatControlSet extends PopupControlSet { doRepeat = recurrence.length() > 0; // read flag - if (model.repeatAfterCompletion()) + if (model.repeatAfterCompletion()) { type.setSelection(TYPE_COMPLETION_DATE); - else + } else { type.setSelection(TYPE_DUE_DATE); + } refreshDisplayView(); } @@ -328,9 +337,9 @@ public class RepeatControlSet extends PopupControlSet { @Override protected String writeToModelAfterInitialized(Task task) { String result; - if (!doRepeat) + if (!doRepeat) { result = ""; //$NON-NLS-1$ - else { + } else { if (TextUtils.isEmpty(task.getValue(Task.RECURRENCE))) { StatisticsService.reportEvent(StatisticsConstants.REPEAT_TASK_CREATE); } @@ -345,9 +354,11 @@ public class RepeatControlSet extends PopupControlSet { rrule.setFreq(Frequency.WEEKLY); ArrayList days = new ArrayList(); - for (int i = 0; i < daysOfWeek.length; i++) - if (daysOfWeek[i].isChecked()) + for (int i = 0; i < daysOfWeek.length; i++) { + if (daysOfWeek[i].isChecked()) { days.add(new WeekdayNum(0, (Weekday) daysOfWeek[i].getTag())); + } + } rrule.setByDay(days); break; } @@ -373,12 +384,15 @@ public class RepeatControlSet extends PopupControlSet { } if (!result.equals(task.getValue(Task.RECURRENCE).replaceAll("BYDAY=;", ""))) //$NON-NLS-1$//$NON-NLS-2$ + { task.putTransitory(TaskService.TRANS_REPEAT_CHANGED, true); + } task.setValue(Task.RECURRENCE, result); task.setValue(Task.REPEAT_UNTIL, repeatUntilValue); - if (task.repeatAfterCompletion()) + if (task.repeatAfterCompletion()) { type.setSelection(1); + } return null; } @@ -416,18 +430,20 @@ public class RepeatControlSet extends PopupControlSet { private String getRepeatString(boolean useAbbrev) { int arrayResource; - if (useAbbrev) + if (useAbbrev) { arrayResource = R.array.repeat_interval_short; - else + } else { arrayResource = R.array.repeat_interval; + } String[] dates = activity.getResources().getStringArray( arrayResource); String date = String.format("%s %s", repeatValue, dates[intervalValue]); //$NON-NLS-1$ - if (repeatUntilValue > 0) + if (repeatUntilValue > 0) { return activity.getString(R.string.repeat_detail_duedate_until, date, DateAndTimePicker.getDisplayString(activity, repeatUntilValue, false, useAbbrev, useAbbrev)); - else + } else { return activity.getString(R.string.repeat_detail_duedate, date); // Every freq int + } } @Override diff --git a/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatDetailExposer.java b/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatDetailExposer.java index 21bf31b53..210999092 100644 --- a/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatDetailExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatDetailExposer.java @@ -33,12 +33,14 @@ public class RepeatDetailExposer extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { // get tags associated with this task long taskId = intent.getLongExtra(AstridApiConstants.EXTRAS_TASK_ID, -1); - if (taskId == -1) + if (taskId == -1) { return; + } String taskDetail = getTaskDetails(context, taskId); - if (taskDetail == null) + if (taskDetail == null) { return; + } // transmit Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_SEND_DETAILS); @@ -50,8 +52,9 @@ public class RepeatDetailExposer extends BroadcastReceiver { public String getTaskDetails(Context context, long id) { Task task = PluginServices.getTaskService().fetchById(id, Task.RECURRENCE); - if (task == null) + if (task == null) { return null; + } Resources r = context.getResources(); @@ -76,8 +79,9 @@ public class RepeatDetailExposer extends BroadcastReceiver { String[] weekdays = dfs.getShortWeekdays(); for (int i = 0; i < byDay.size(); i++) { byDayString.append(weekdays[byDay.get(i).wday.javaDayNum]); - if (i < byDay.size() - 1) + if (i < byDay.size() - 1) { byDayString.append(", "); //$NON-NLS-1$ + } } interval = r.getString(R.string.repeat_detail_byday).replace("$I", //$NON-NLS-1$ interval).replace("$D", byDayString); //$NON-NLS-1$ @@ -85,10 +89,11 @@ public class RepeatDetailExposer extends BroadcastReceiver { } String detail; - if (task.repeatAfterCompletion()) + if (task.repeatAfterCompletion()) { detail = context.getString(R.string.repeat_detail_completion, interval); - else + } else { detail = context.getString(R.string.repeat_detail_duedate, interval); + } return " " + detail; //$NON-NLS-1$ } diff --git a/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatTaskCompleteListener.java b/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatTaskCompleteListener.java index a7b6b91dd..2f9031f90 100644 --- a/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatTaskCompleteListener.java +++ b/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatTaskCompleteListener.java @@ -50,12 +50,14 @@ public class RepeatTaskCompleteListener extends BroadcastReceiver { ContextManager.setContext(context); DependencyInjectionService.getInstance().inject(this); long taskId = intent.getLongExtra(AstridApiConstants.EXTRAS_TASK_ID, -1); - if (taskId == -1) + if (taskId == -1) { return; + } Task task = PluginServices.getTaskService().fetchById(taskId, Task.PROPERTIES); - if (task == null || !task.isCompleted()) + if (task == null || !task.isCompleted()) { return; + } String recurrence = task.sanitizedRecurrence(); boolean repeatAfterCompletion = task.repeatAfterCompletion(); @@ -64,8 +66,9 @@ public class RepeatTaskCompleteListener extends BroadcastReceiver { long newDueDate; try { newDueDate = computeNextDueDate(task, recurrence, repeatAfterCompletion); - if (newDueDate == -1) + if (newDueDate == -1) { return; + } } catch (ParseException e) { PluginServices.getExceptionService().reportError("repeat-parse", e); //$NON-NLS-1$ return; @@ -126,14 +129,15 @@ public class RepeatTaskCompleteListener extends BroadcastReceiver { Date original = setUpStartDate(task, repeatAfterCompletion, rrule.getFreq()); DateValue startDateAsDV = setUpStartDateAsDV(task, original); - if (rrule.getFreq() == Frequency.HOURLY || rrule.getFreq() == Frequency.MINUTELY) + if (rrule.getFreq() == Frequency.HOURLY || rrule.getFreq() == Frequency.MINUTELY) { return handleSubdayRepeat(original, rrule); - else if (rrule.getFreq() == Frequency.WEEKLY && rrule.getByDay().size() > 0 && repeatAfterCompletion) + } else if (rrule.getFreq() == Frequency.WEEKLY && rrule.getByDay().size() > 0 && repeatAfterCompletion) { return handleWeeklyRepeatAfterComplete(rrule, original, task.hasDueTime()); - else if (rrule.getFreq() == Frequency.MONTHLY) + } else if (rrule.getFreq() == Frequency.MONTHLY) { return handleMonthlyRepeat(original, startDateAsDV, task.hasDueTime(), rrule); - else + } else { return invokeRecurrence(rrule, original, startDateAsDV); + } } private static long handleWeeklyRepeatAfterComplete(RRule rrule, Date original, @@ -152,10 +156,11 @@ public class RepeatTaskCompleteListener extends BroadcastReceiver { } while (date.get(Calendar.DAY_OF_WEEK) != next.wday.javaDayNum); long time = date.getTimeInMillis(); - if (hasDueTime) + if (hasDueTime) { return Task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, time); - else + } else { return Task.createDueDate(Task.URGENCY_SPECIFIC_DAY, time); + } } private static long handleMonthlyRepeat(Date original, DateValue startDateAsDV, boolean hasDueTime, RRule rrule) { @@ -168,10 +173,11 @@ public class RepeatTaskCompleteListener extends BroadcastReceiver { cal.add(Calendar.MONTH, interval); cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE)); long time = cal.getTimeInMillis(); - if (hasDueTime) + if (hasDueTime) { return Task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, time); - else + } else { return Task.createDueDate(Task.URGENCY_SPECIFIC_DAY, time); + } } else { return invokeRecurrence(rrule, original, startDateAsDV); } @@ -205,18 +211,21 @@ public class RepeatTaskCompleteListener extends BroadcastReceiver { DateValue nextDate = startDateAsDV; for (int i = 0; i < 10; i++) { // ten tries then we give up - if (!iterator.hasNext()) + if (!iterator.hasNext()) { return -1; + } nextDate = iterator.next(); - if (nextDate.compareTo(startDateAsDV) == 0) + if (nextDate.compareTo(startDateAsDV) == 0) { continue; + } newDueDate = buildNewDueDate(original, nextDate); // detect if we finished - if (newDueDate > original.getTime()) + if (newDueDate > original.getTime()) { break; + } } return newDueDate; } @@ -252,8 +261,9 @@ public class RepeatTaskCompleteListener extends BroadcastReceiver { // handle the iCalendar "byDay" field differently depending on if // we are weekly or otherwise - if (rrule.getFreq() != Frequency.WEEKLY) + if (rrule.getFreq() != Frequency.WEEKLY) { rrule.setByDay(Collections.EMPTY_LIST); + } return rrule; } @@ -267,10 +277,11 @@ public class RepeatTaskCompleteListener extends BroadcastReceiver { Date startDate = new Date(); if (task.hasDueDate()) { Date dueDate = new Date(task.getValue(Task.DUE_DATE)); - if (repeatAfterCompletion) + if (repeatAfterCompletion) { startDate = new Date(task.getValue(Task.COMPLETION_DATE)); - else + } else { startDate = dueDate; + } if (task.hasDueTime() && frequency != Frequency.HOURLY && frequency != Frequency.MINUTELY) { startDate.setHours(dueDate.getHours()); @@ -282,13 +293,14 @@ public class RepeatTaskCompleteListener extends BroadcastReceiver { } private static DateValue setUpStartDateAsDV(Task task, Date startDate) { - if (task.hasDueTime()) + if (task.hasDueTime()) { return new DateTimeValueImpl(startDate.getYear() + 1900, startDate.getMonth() + 1, startDate.getDate(), startDate.getHours(), startDate.getMinutes(), startDate.getSeconds()); - else + } else { return new DateValueImpl(startDate.getYear() + 1900, startDate.getMonth() + 1, startDate.getDate()); + } } private static long handleSubdayRepeat(Date startDate, RRule rrule) { diff --git a/astrid/plugin-src/com/todoroo/astrid/subtasks/AstridOrderedListFragmentHelper.java b/astrid/plugin-src/com/todoroo/astrid/subtasks/AstridOrderedListFragmentHelper.java index caf9948d2..bc3791d42 100644 --- a/astrid/plugin-src/com/todoroo/astrid/subtasks/AstridOrderedListFragmentHelper.java +++ b/astrid/plugin-src/com/todoroo/astrid/subtasks/AstridOrderedListFragmentHelper.java @@ -91,8 +91,9 @@ public class AstridOrderedListFragmentHelper implements OrderedListFragmen getTouchListView().setSwipeListener(swipeListener); getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics); - if (Preferences.getInt(AstridPreferences.P_SUBTASKS_HELP, 0) == 0) + if (Preferences.getInt(AstridPreferences.P_SUBTASKS_HELP, 0) == 0) { showSubtasksHelp(); + } } @SuppressWarnings("nls") @@ -121,15 +122,17 @@ public class AstridOrderedListFragmentHelper implements OrderedListFragmen @Override public void drop(int from, int to) { String targetTaskId = taskAdapter.getItemUuid(from); - if (!RemoteModel.isValidUuid(targetTaskId)) + if (!RemoteModel.isValidUuid(targetTaskId)) { return; // This can happen with gestures on empty parts of the list (e.g. extra space below tasks) + } String destinationTaskId = taskAdapter.getItemUuid(to); try { - if (to >= getListView().getCount()) + if (to >= getListView().getCount()) { updater.moveTo(list, getFilter(), targetTaskId, "-1"); //$NON-NLS-1$ - else + } else { updater.moveTo(list, getFilter(), targetTaskId, destinationTaskId); + } } catch (Exception e) { Log.e("drag", "Drag Error", e); //$NON-NLS-1$ //$NON-NLS-2$ } @@ -152,8 +155,9 @@ public class AstridOrderedListFragmentHelper implements OrderedListFragmen protected void indent(int which, int delta) { String targetTaskId = taskAdapter.getItemUuid(which); - if (!RemoteModel.isValidUuid(targetTaskId)) + if (!RemoteModel.isValidUuid(targetTaskId)) { return; // This can happen with gestures on empty parts of the list (e.g. extra space below tasks) + } try { updater.indent(list, getFilter(), targetTaskId, delta); } catch (Exception e) { @@ -168,8 +172,9 @@ public class AstridOrderedListFragmentHelper implements OrderedListFragmen private final GrabberClickListener rowClickListener = new GrabberClickListener() { @Override public void onLongClick(final View v) { - if (v == null) + if (v == null) { return; + } fragment.registerForContextMenu(getListView()); getListView().showContextMenuForChild(v); @@ -178,8 +183,9 @@ public class AstridOrderedListFragmentHelper implements OrderedListFragmen @Override public void onClick(View v) { - if (v == null) + if (v == null) { return; + } ((DraggableTaskAdapter) taskAdapter).getListener().onClick(v); } }; diff --git a/astrid/plugin-src/com/todoroo/astrid/subtasks/AstridOrderedListUpdater.java b/astrid/plugin-src/com/todoroo/astrid/subtasks/AstridOrderedListUpdater.java index 582911f37..4f7378c00 100644 --- a/astrid/plugin-src/com/todoroo/astrid/subtasks/AstridOrderedListUpdater.java +++ b/astrid/plugin-src/com/todoroo/astrid/subtasks/AstridOrderedListUpdater.java @@ -58,8 +58,9 @@ public abstract class AstridOrderedListUpdater { public int getIndentForTask(String targetTaskId) { Node n = idToNode.get(targetTaskId); - if (n == null) + if (n == null) { return 0; + } return n.indent; } @@ -93,8 +94,9 @@ public abstract class AstridOrderedListUpdater { for (tasks.moveToFirst(); !tasks.isAfterLast(); tasks.moveToNext()) { String id = tasks.getString(0); idsInQuery.add(id); - if (idToNode.containsKey(id)) + if (idToNode.containsKey(id)) { continue; + } changedThings = true; Node newNode = new Node(id, treeRoot, 0); @@ -110,15 +112,17 @@ public abstract class AstridOrderedListUpdater { } finally { tasks.close(); } - if (changedThings) + if (changedThings) { writeSerialization(list, serializeTree(), false); + } } private void removeNodes(Set idsToRemove) { for (String id : idsToRemove) { Node node = idToNode.get(id); - if (node == null) + if (node == null) { continue; + } // Remove node from tree, put all children under parent Node parent = node.parent; @@ -148,19 +152,22 @@ public abstract class AstridOrderedListUpdater { public static String buildOrderString(String[] ids) { StringBuilder builder = new StringBuilder(); - if (ids.length == 0) + if (ids.length == 0) { 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) + if (i > 0) { builder.append(", "); //$NON-NLS-1$ + } } return builder.toString(); } private void orderedIdHelper(Node node, List ids) { - if (node != treeRoot) + if (node != treeRoot) { ids.add(node.uuid); + } for (Node child : node.children) { orderedIdHelper(child, ids); @@ -169,8 +176,9 @@ public abstract class AstridOrderedListUpdater { public void applyToDescendants(String taskId, OrderedListNodeVisitor visitor) { Node n = idToNode.get(taskId); - if (n == null) + if (n == null) { return; + } applyToDescendantsHelper(n, visitor); } @@ -192,19 +200,24 @@ public abstract class AstridOrderedListUpdater { } private void indentHelper(LIST list, Filter filter, Node node, int delta) { - if (node == null) + if (node == null) { return; - if (delta == 0) + } + if (delta == 0) { return; + } Node parent = node.parent; - if (parent == null) + if (parent == null) { return; + } if (delta > 0) { ArrayList siblings = parent.children; int index = siblings.indexOf(node); if (index <= 0) // Can't indent first child + { return; + } Node newParent = siblings.get(index - 1); siblings.remove(index); node.parent = newParent; @@ -212,12 +225,15 @@ public abstract class AstridOrderedListUpdater { setNodeIndent(node, newParent.indent + 1); } else if (delta < 0) { if (parent == treeRoot) // Can't deindent a top level item + { return; + } ArrayList siblings = parent.children; int index = siblings.indexOf(node); - if (index < 0) + if (index < 0) { return; + } Node newParent = parent.parent; ArrayList newSiblings = newParent.children; @@ -246,8 +262,9 @@ public abstract class AstridOrderedListUpdater { public void moveTo(LIST list, Filter filter, String targetTaskId, String beforeTaskId) { Node target = idToNode.get(targetTaskId); - if (target == null) + if (target == null) { return; + } if ("-1".equals(beforeTaskId)) { //$NON-NLS-1$ moveToEndOfList(list, filter, target); @@ -256,23 +273,27 @@ public abstract class AstridOrderedListUpdater { Node before = idToNode.get(beforeTaskId); - if (before == null) + if (before == null) { return; + } - if (isDescendantOf(before, target)) + if (isDescendantOf(before, target)) { return; + } moveHelper(list, filter, target, before); } public void moveToParentOf(String moveThis, String toParentOfThis) { Node target = idToNode.get(toParentOfThis); - if (target == null) + if (target == null) { return; + } Node toMove = idToNode.get(moveThis); - if (toMove == null) + if (toMove == null) { return; + } Node newParent = target.parent; Node oldParent = toMove.parent; @@ -291,12 +312,14 @@ public abstract class AstridOrderedListUpdater { ArrayList newSiblings = newParent.children; int beforeIndex = newSiblings.indexOf(beforeThis); - if (beforeIndex < 0) + if (beforeIndex < 0) { return; + } int nodeIndex = oldSiblings.indexOf(moveThis); - if (nodeIndex < 0) + if (nodeIndex < 0) { return; + } moveThis.parent = newParent; setNodeIndent(moveThis, newParent.indent + 1); @@ -314,8 +337,9 @@ public abstract class AstridOrderedListUpdater { private boolean isDescendantOf(Node desc, Node parent) { Node curr = desc; while (curr != treeRoot) { - if (curr == parent) + if (curr == parent) { return true; + } curr = curr.parent; } return false; @@ -332,8 +356,9 @@ public abstract class AstridOrderedListUpdater { } public void onCreateTask(LIST list, Filter filter, String uuid) { - if (idToNode.containsKey(uuid) || !RemoteModel.isValidUuid(uuid)) + if (idToNode.containsKey(uuid) || !RemoteModel.isValidUuid(uuid)) { return; + } Node newNode = new Node(uuid, treeRoot, 0); treeRoot.children.add(0, newNode); @@ -344,15 +369,17 @@ public abstract class AstridOrderedListUpdater { public void onDeleteTask(LIST list, Filter filter, String taskId) { Node task = idToNode.get(taskId); - if (task == null) + if (task == null) { return; + } Node parent = task.parent; ArrayList siblings = parent.children; int index = siblings.indexOf(task); - if (index >= 0) + if (index >= 0) { siblings.remove(index); + } for (Node child : task.children) { child.parent = parent; siblings.add(index, child); @@ -384,17 +411,20 @@ public abstract class AstridOrderedListUpdater { for (int i = 1; i < children.length(); i++) { JSONArray subarray = children.optJSONArray(i); String uuid = RemoteModel.NO_UUID; - if (subarray == null) + if (subarray == null) { uuid = children.getString(i); - else + } else { uuid = subarray.getString(0); + } Node child = new Node(uuid, node, node.indent + 1); - if (subarray != null) + if (subarray != null) { recursivelyBuildChildren(child, subarray, callback); + } node.children.add(child); - if (callback != null) + if (callback != null) { callback.afterAddNode(child); + } } } diff --git a/astrid/plugin-src/com/todoroo/astrid/subtasks/OrderedMetadataListFragmentHelper.java b/astrid/plugin-src/com/todoroo/astrid/subtasks/OrderedMetadataListFragmentHelper.java index 763f2d2be..5aa651344 100644 --- a/astrid/plugin-src/com/todoroo/astrid/subtasks/OrderedMetadataListFragmentHelper.java +++ b/astrid/plugin-src/com/todoroo/astrid/subtasks/OrderedMetadataListFragmentHelper.java @@ -95,8 +95,9 @@ public class OrderedMetadataListFragmentHelper implements OrderedListFragm getTouchListView().setSwipeListener(swipeListener); getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics); - if (Preferences.getInt(AstridPreferences.P_SUBTASKS_HELP, 0) == 0) + if (Preferences.getInt(AstridPreferences.P_SUBTASKS_HELP, 0) == 0) { showSubtasksHelp(); + } } @SuppressWarnings("nls") @@ -123,8 +124,9 @@ public class OrderedMetadataListFragmentHelper implements OrderedListFragm public Property[] taskProperties() { Property[] baseProperties = TaskAdapter.PROPERTIES; - if (Preferences.getIntegerFromString(R.string.p_taskRowStyle_v2, 0) == 2) + if (Preferences.getIntegerFromString(R.string.p_taskRowStyle_v2, 0) == 2) { baseProperties = TaskAdapter.BASIC_PROPERTIES; + } ArrayList> properties = new ArrayList>(Arrays.asList(baseProperties)); properties.add(updater.indentProperty()); @@ -137,15 +139,17 @@ public class OrderedMetadataListFragmentHelper implements OrderedListFragm @Override public void drop(int from, int to) { long targetTaskId = taskAdapter.getItemId(from); - if (targetTaskId <= 0) + if (targetTaskId <= 0) { return; // This can happen with gestures on empty parts of the list (e.g. extra space below tasks) + } long destinationTaskId = taskAdapter.getItemId(to); try { - if (to >= getListView().getCount()) + if (to >= getListView().getCount()) { updater.moveTo(getFilter(), list, targetTaskId, -1); - else + } else { updater.moveTo(getFilter(), list, targetTaskId, destinationTaskId); + } } catch (Exception e) { Log.e("drag", "Drag Error", e); //$NON-NLS-1$ //$NON-NLS-2$ } @@ -167,8 +171,9 @@ public class OrderedMetadataListFragmentHelper implements OrderedListFragm protected void indent(int which, int delta) { long targetTaskId = taskAdapter.getItemId(which); - if (targetTaskId <= 0) + if (targetTaskId <= 0) { return; // This can happen with gestures on empty parts of the list (e.g. extra space below tasks) + } try { updater.indent(getFilter(), list, targetTaskId, delta); } catch (Exception e) { @@ -181,8 +186,9 @@ public class OrderedMetadataListFragmentHelper implements OrderedListFragm private final GrabberClickListener rowClickListener = new GrabberClickListener() { @Override public void onLongClick(final View v) { - if (v == null) + if (v == null) { return; + } fragment.registerForContextMenu(getListView()); getListView().showContextMenuForChild(v); @@ -191,8 +197,9 @@ public class OrderedMetadataListFragmentHelper implements OrderedListFragm @Override public void onClick(View v) { - if (v == null) + if (v == null) { return; + } ((DraggableTaskAdapter) taskAdapter).getListener().onClick(v); } }; diff --git a/astrid/plugin-src/com/todoroo/astrid/subtasks/OrderedMetadataListUpdater.java b/astrid/plugin-src/com/todoroo/astrid/subtasks/OrderedMetadataListUpdater.java index 7e64e152a..8c10a76b8 100644 --- a/astrid/plugin-src/com/todoroo/astrid/subtasks/OrderedMetadataListUpdater.java +++ b/astrid/plugin-src/com/todoroo/astrid/subtasks/OrderedMetadataListUpdater.java @@ -82,8 +82,9 @@ abstract public class OrderedMetadataListUpdater { * Indent a task and all its children */ public void indent(final Filter filter, final LIST list, final long targetTaskId, final int delta) { - if (list == null) + if (list == null) { return; + } beforeIndent(list); @@ -95,8 +96,9 @@ abstract public class OrderedMetadataListUpdater { iterateThroughList(filter, list, new OrderedListIterator() { @Override public void processTask(long taskId, Metadata metadata) { - if (!metadata.isSaved()) + if (!metadata.isSaved()) { metadata = createEmptyMetadata(list, taskId); + } int indent = metadata.containsNonNullValue(indentProperty()) ? metadata.getValue(indentProperty()) : 0; @@ -112,18 +114,19 @@ abstract public class OrderedMetadataListUpdater { if (parentProperty() != null) { long newParent = computeNewParent(filter, list, taskId, indent + delta - 1); - if (newParent == taskId) + if (newParent == taskId) { metadata.setValue(parentProperty(), Task.NO_ID); - else + } else { metadata.setValue(parentProperty(), newParent); + } } saveAndUpdateModifiedDate(metadata); } } else if (targetTaskIndent.get() > -1) { // found first task that is not beneath target - if (indent <= targetTaskIndent.get()) + if (indent <= targetTaskIndent.get()) { targetTaskIndent.set(-1); - else { + } else { metadata.setValue(indentProperty(), indent + delta); saveAndUpdateModifiedDate(metadata); } @@ -132,8 +135,9 @@ abstract public class OrderedMetadataListUpdater { previousTask.set(taskId); } - if (!metadata.isSaved()) + if (!metadata.isSaved()) { saveAndUpdateModifiedDate(metadata); + } } }); @@ -169,7 +173,9 @@ abstract public class OrderedMetadataListUpdater { } }); - if (lastPotentialParent.get() == Task.NO_ID) return Task.NO_ID; + if (lastPotentialParent.get() == Task.NO_ID) { + return Task.NO_ID; + } return lastPotentialParent.get(); } @@ -183,8 +189,9 @@ abstract public class OrderedMetadataListUpdater { */ public void moveTo(Filter filter, LIST list, final long targetTaskId, final long moveBeforeTaskId) { - if (list == null) + if (list == null) { return; + } Node root = buildTreeModel(filter, list); Node target = findNode(root, targetTaskId); @@ -200,8 +207,9 @@ abstract public class OrderedMetadataListUpdater { int index = sibling.parent.children.indexOf(sibling); if (target.parent == sibling.parent && - target.parent.children.indexOf(target) < index) + target.parent.children.indexOf(target) < index) { index--; + } target.parent.children.remove(target); sibling.parent.children.add(index, target); @@ -215,10 +223,12 @@ abstract public class OrderedMetadataListUpdater { } private boolean ancestorOf(Node ancestor, Node descendant) { - if (descendant.parent == ancestor) + if (descendant.parent == ancestor) { return true; - if (descendant.parent == null) + } + if (descendant.parent == null) { return false; + } return ancestorOf(ancestor, descendant.parent); } @@ -236,8 +246,9 @@ abstract public class OrderedMetadataListUpdater { protected void traverseTreeAndWriteValues(LIST list, Node node, AtomicLong order, int indent) { if (node.taskId != Task.NO_ID) { Metadata metadata = getTaskMetadata(list, node.taskId); - if (metadata == null) + if (metadata == null) { metadata = createEmptyMetadata(list, node.taskId); + } metadata.setValue(orderProperty(), order.getAndIncrement()); metadata.setValue(indentProperty(), indent); boolean parentChanged = false; @@ -247,8 +258,9 @@ abstract public class OrderedMetadataListUpdater { metadata.setValue(parentProperty(), node.parent.taskId); } saveAndUpdateModifiedDate(metadata); - if (parentChanged) + if (parentChanged) { onMovedOrIndented(metadata); + } } for (Node child : node.children) { @@ -257,12 +269,14 @@ abstract public class OrderedMetadataListUpdater { } protected Node findNode(Node node, long taskId) { - if (node.taskId == taskId) + if (node.taskId == taskId) { return node; + } for (Node child : node.children) { Node found = findNode(child, taskId); - if (found != null) + if (found != null) { return found; + } } return null; } @@ -306,8 +320,9 @@ abstract public class OrderedMetadataListUpdater { } protected void saveAndUpdateModifiedDate(Metadata metadata) { - if (metadata.getSetValues().size() == 0) + if (metadata.getSetValues().size() == 0) { return; + } PluginServices.getMetadataService().save(metadata); } @@ -326,15 +341,18 @@ abstract public class OrderedMetadataListUpdater { Node root = buildTreeModel(filter, list); Node target = findNode(root, targetTaskId); - if (target != null) - for (Node child : target.children) + if (target != null) { + for (Node child : target.children) { applyVisitor(child, visitor); + } + } } private void applyVisitor(Node node, OrderedListNodeVisitor visitor) { visitor.visitNode(node); - for (Node child : node.children) + for (Node child : node.children) { applyVisitor(child, visitor); + } } /** @@ -345,8 +363,9 @@ abstract public class OrderedMetadataListUpdater { * @param targetTaskId */ public void onDeleteTask(Filter filter, LIST list, final long targetTaskId) { - if (list == null) + if (list == null) { return; + } Node root = buildTreeModel(filter, list); Node target = findNode(root, targetTaskId); @@ -379,12 +398,15 @@ abstract public class OrderedMetadataListUpdater { @SuppressWarnings("nls") public void debugPrint(Node root, int depth) { - for (int i = 0; i < depth; i++) System.err.print(" + "); + for (int i = 0; i < depth; i++) { + System.err.print(" + "); + } System.err.format("%03d", root.taskId); System.err.print("\n"); - for (int i = 0; i < root.children.size(); i++) + for (int i = 0; i < root.children.size(); i++) { debugPrint(root.children.get(i), depth + 1); + } } } diff --git a/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksFilterUpdater.java b/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksFilterUpdater.java index fc9167742..398588b92 100644 --- a/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksFilterUpdater.java +++ b/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksFilterUpdater.java @@ -18,11 +18,14 @@ public class SubtasksFilterUpdater extends SubtasksUpdater { @Override protected String getSerializedTree(TaskListMetadata list, Filter filter) { - if (list == null) + if (list == null) { return "[]"; //$NON-NLS-1$ + } String order = list.getValue(TaskListMetadata.TASK_IDS); if (TextUtils.isEmpty(order) || "null".equals(order)) //$NON-NLS-1$ + { order = "[]"; //$NON-NLS-1$ + } return order; } @@ -31,15 +34,17 @@ public class SubtasksFilterUpdater extends SubtasksUpdater { protected void writeSerialization(TaskListMetadata list, String serialized, boolean shouldQueueSync) { if (list != null && syncMigrationOccurred()) { list.setValue(TaskListMetadata.TASK_IDS, serialized); - if (!shouldQueueSync) + if (!shouldQueueSync) { list.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true); + } taskListMetadataDao.saveExisting(list); } } private boolean syncMigrationOccurred() { - if (migrationOccurred) + if (migrationOccurred) { return true; + } migrationOccurred = Preferences.getBoolean(AstridNewSyncMigrator.PREF_SYNC_MIGRATION, false); return migrationOccurred; } diff --git a/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksHelper.java b/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksHelper.java index 750754fd8..5931cc69b 100644 --- a/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksHelper.java +++ b/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksHelper.java @@ -33,15 +33,17 @@ public class SubtasksHelper { if (filter == null || CoreFilterExposer.isInbox(filter) || CoreFilterExposer.isTodayFilter(filter) || SubtasksHelper.isTagFilter(filter)) { SharedPreferences publicPrefs = AstridPreferences.getPublicPrefs(ContextManager.getContext()); int sortFlags = publicPrefs.getInt(SortHelper.PREF_SORT_FLAGS, 0); - if (SortHelper.isManualSort(sortFlags)) + if (SortHelper.isManualSort(sortFlags)) { return true; + } } return false; } public static Class subtasksClassForFilter(Filter filter) { - if (SubtasksHelper.isTagFilter(filter)) + if (SubtasksHelper.isTagFilter(filter)) { return SubtasksTagListFragment.class; + } return SubtasksListFragment.class; } @@ -50,7 +52,9 @@ public class SubtasksHelper { String className = ((FilterWithCustomIntent) filter).customTaskList.getClassName(); if (TagViewFragment.class.getName().equals(className) || SubtasksTagListFragment.class.getName().equals(className)) // Need to check this subclass because some shortcuts/widgets may have been saved with it + { return true; + } } return false; } @@ -74,8 +78,9 @@ public class SubtasksHelper { query = query + String.format(" ORDER BY %s, %s, %s, %s", Task.DELETION_DATE, Task.COMPLETION_DATE, getOrderString(tagData, tlm), Task.CREATION_DATE); - if (limit > 0) + if (limit > 0) { query = query + " LIMIT " + limit; + } query = query.replace(TaskCriteria.isVisible().toString(), Criterion.all.toString()); @@ -86,12 +91,13 @@ public class SubtasksHelper { private static String getOrderString(TagData tagData, TaskListMetadata tlm) { String serialized; - if (tlm != null) + if (tlm != null) { serialized = tlm.getValue(TaskListMetadata.TASK_IDS); - else if (tagData != null) + } else if (tagData != null) { serialized = convertTreeToRemoteIds(tagData.getValue(TagData.TAG_ORDERING)); - else + } else { serialized = "[]"; //$NON-NLS-1$ + } return AstridOrderedListUpdater.buildOrderString(getStringIdArray(serialized)); } @@ -103,8 +109,9 @@ public class SubtasksHelper { String[] digitsOnly = serializedTree.split("[\\[\\],\\s]"); // Split on [ ] , or whitespace chars for (String idString : digitsOnly) { try { - if (!TextUtils.isEmpty(idString)) + if (!TextUtils.isEmpty(idString)) { ids.add(Long.parseLong(idString)); + } } catch (NumberFormatException e) { Log.e("widget-subtasks", "error parsing id " + idString, e); } @@ -117,8 +124,9 @@ public class SubtasksHelper { ArrayList ids = new ArrayList(); String[] values = serializedTree.split("[\\[\\],\"\\s]"); // Split on [ ] , or whitespace chars for (String idString : values) { - if (!TextUtils.isEmpty(idString)) + if (!TextUtils.isEmpty(idString)) { ids.add(idString); + } } return ids.toArray(new String[ids.size()]); } diff --git a/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksMetadataMigration.java b/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksMetadataMigration.java index 203521e0b..65d4c2d04 100644 --- a/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksMetadataMigration.java +++ b/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksMetadataMigration.java @@ -72,8 +72,9 @@ public class SubtasksMetadataMigration { if (td == null && !SubtasksMetadata.LIST_ACTIVE_TASKS.equals(tag)) { for (; !subtasksMetadata.isAfterLast(); subtasksMetadata.moveToNext()) { item.readFromCursor(subtasksMetadata); - if (!item.getValue(SubtasksMetadata.TAG).equals(tag)) + if (!item.getValue(SubtasksMetadata.TAG).equals(tag)) { break; + } } } else { String newTree = buildTreeModelFromMetadata(tag, subtasksMetadata); @@ -94,14 +95,16 @@ public class SubtasksMetadataMigration { for (; !cursor.isAfterLast(); cursor.moveToNext()) { item.clear(); item.readFromCursor(cursor); - if (!item.getValue(SubtasksMetadata.TAG).equals(tag)) + if (!item.getValue(SubtasksMetadata.TAG).equals(tag)) { break; + } int indent = 0; if (item.containsNonNullValue(SubtasksMetadata.INDENT)) { Integer i = item.getValue(SubtasksMetadata.INDENT); - if (i != null) + if (i != null) { indent = i.intValue(); + } } Node parent = findNextParentForIndent(root, indent); Node newNode = new Node(item.getValue(Metadata.TASK).toString(), parent, parent.indent + 1); @@ -111,12 +114,14 @@ public class SubtasksMetadataMigration { } private Node findNextParentForIndent(Node root, int indent) { - if (indent <= 0) + if (indent <= 0) { return root; + } ArrayList children = root.children; - if (children.size() == 0) + if (children.size() == 0) { return root; + } return findNextParentForIndent(children.get(children.size() - 1), indent - 1); } diff --git a/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksTagUpdater.java b/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksTagUpdater.java index de825accc..765caeb22 100644 --- a/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksTagUpdater.java +++ b/astrid/plugin-src/com/todoroo/astrid/subtasks/SubtasksTagUpdater.java @@ -15,8 +15,9 @@ public class SubtasksTagUpdater extends SubtasksFilterUpdater { @Override protected String getSerializedTree(TaskListMetadata list, Filter filter) { - if (isBeingFiltered.get()) + if (isBeingFiltered.get()) { return "[]"; //$NON-NLS-1$ + } return super.getSerializedTree(list, filter); } @@ -29,8 +30,9 @@ public class SubtasksTagUpdater extends SubtasksFilterUpdater { @Override public int getIndentForTask(String targetTaskId) { - if (isBeingFiltered.get()) + if (isBeingFiltered.get()) { return 0; + } return super.getIndentForTask(targetTaskId); } diff --git a/astrid/plugin-src/com/todoroo/astrid/tags/TagCaseMigrator.java b/astrid/plugin-src/com/todoroo/astrid/tags/TagCaseMigrator.java index fe28ef8ba..8d445e907 100644 --- a/astrid/plugin-src/com/todoroo/astrid/tags/TagCaseMigrator.java +++ b/astrid/plugin-src/com/todoroo/astrid/tags/TagCaseMigrator.java @@ -80,7 +80,9 @@ public class TagCaseMigrator { } private void markForRenaming(String tag, long remoteId) { - if (renameMap.containsKey(tag)) return; + if (renameMap.containsKey(tag)) { + return; + } String targetName = targetNameForTag(tag); @@ -162,10 +164,11 @@ public class TagCaseMigrator { Metadata metadata = new Metadata(); metadata.setValue(TaskToTagMetadata.TAG_NAME, newTag); int ret; - if (caseSensitive) + if (caseSensitive) { ret = metadataService.update(tagEq(oldTag, Criterion.all), metadata); - else + } else { ret = metadataService.update(TagService.tagEqIgnoreCase(oldTag, Criterion.all), metadata); + } invalidateTaskCache(newTag); return ret; } diff --git a/astrid/plugin-src/com/todoroo/astrid/tags/TagCustomFilterCriteriaExposer.java b/astrid/plugin-src/com/todoroo/astrid/tags/TagCustomFilterCriteriaExposer.java index a62a5c45b..7e89254bd 100644 --- a/astrid/plugin-src/com/todoroo/astrid/tags/TagCustomFilterCriteriaExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/tags/TagCustomFilterCriteriaExposer.java @@ -43,8 +43,9 @@ public class TagCustomFilterCriteriaExposer extends BroadcastReceiver { TagService.Tag[] tags = TagService.getInstance().getGroupedTags(TagService.GROUPED_TAGS_BY_SIZE, TaskDao.TaskCriteria.activeAndVisible()); String[] tagNames = new String[tags.length]; - for (int i = 0; i < tags.length; i++) + for (int i = 0; i < tags.length; i++) { tagNames[i] = tags[i].tag; + } ContentValues values = new ContentValues(); values.put(Metadata.KEY.name, TaskToTagMetadata.KEY); values.put(TaskToTagMetadata.TAG_NAME.name, "?"); diff --git a/astrid/plugin-src/com/todoroo/astrid/tags/TagDetailExposer.java b/astrid/plugin-src/com/todoroo/astrid/tags/TagDetailExposer.java index c00ca113b..426296632 100644 --- a/astrid/plugin-src/com/todoroo/astrid/tags/TagDetailExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/tags/TagDetailExposer.java @@ -22,12 +22,14 @@ public class TagDetailExposer extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { // get tags associated with this task long taskId = intent.getLongExtra(AstridApiConstants.EXTRAS_TASK_ID, -1); - if (taskId == -1) + if (taskId == -1) { return; + } String taskDetail = getTaskDetails(taskId); - if (taskDetail == null) + if (taskDetail == null) { return; + } // transmit Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_SEND_DETAILS); @@ -39,8 +41,9 @@ public class TagDetailExposer extends BroadcastReceiver { public String getTaskDetails(long id) { String tagList = TagService.getInstance().getTagsAsString(id); - if (tagList.length() == 0) + if (tagList.length() == 0) { return null; + } return /*" " +*/ tagList; } diff --git a/astrid/plugin-src/com/todoroo/astrid/tags/TagFilterExposer.java b/astrid/plugin-src/com/todoroo/astrid/tags/TagFilterExposer.java index 48798776c..baf61ccaa 100644 --- a/astrid/plugin-src/com/todoroo/astrid/tags/TagFilterExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/tags/TagFilterExposer.java @@ -73,8 +73,9 @@ public class TagFilterExposer extends BroadcastReceiver implements AstridFilterE @SuppressWarnings("nls") public static FilterWithCustomIntent filterFromTag(Context context, Tag tag, Criterion criterion) { String title = tag.tag; - if (TextUtils.isEmpty(title)) + if (TextUtils.isEmpty(title)) { return null; + } QueryTemplate tagTemplate = tag.queryTemplate(criterion); ContentValues contentValues = new ContentValues(); contentValues.put(Metadata.KEY.name, TaskToTagMetadata.KEY); @@ -89,10 +90,11 @@ public class TagFilterExposer extends BroadcastReceiver implements AstridFilterE } int deleteIntentLabel; - if (tag.memberCount > 0 && !Task.USER_ID_SELF.equals(tag.userId)) + if (tag.memberCount > 0 && !Task.USER_ID_SELF.equals(tag.userId)) { deleteIntentLabel = R.string.tag_cm_leave; - else + } else { deleteIntentLabel = R.string.tag_cm_delete; + } filter.contextMenuLabels = new String[]{ context.getString(R.string.tag_cm_rename), @@ -104,8 +106,9 @@ public class TagFilterExposer extends BroadcastReceiver implements AstridFilterE }; filter.customTaskList = new ComponentName(ContextManager.getContext(), TagViewFragment.class); - if (tag.image != null) + if (tag.image != null) { filter.imageUrl = tag.image; + } Bundle extras = new Bundle(); extras.putString(TagViewFragment.EXTRA_TAG_NAME, tag.tag); extras.putString(TagViewFragment.EXTRA_TAG_UUID, tag.uuid.toString()); @@ -186,8 +189,9 @@ public class TagFilterExposer extends BroadcastReceiver implements AstridFilterE for (int i = 0; i < tags.length; i++) { Filter f = constructFilter(context, tags[i]); - if (f != null) + if (f != null) { filters.add(f); + } } FilterCategory filter = new FilterCategory(context.getString(name), filters.toArray(new Filter[filters.size()])); return filter; @@ -283,12 +287,14 @@ public class TagFilterExposer extends BroadcastReceiver implements AstridFilterE protected void showDialog(TagData tagData) { int string; if (tagData != null && (tagMetadataDao.tagHasMembers(uuid) || tagData.getValue(TagData.MEMBER_COUNT) > 0)) { - if (Task.USER_ID_SELF.equals(tagData.getValue(TagData.USER_ID))) + if (Task.USER_ID_SELF.equals(tagData.getValue(TagData.USER_ID))) { string = R.string.actfm_tag_operation_owner_delete; - else + } else { string = R.string.DLG_leave_this_shared_tag_question; - } else + } + } else { string = R.string.DLG_delete_this_tag_question; + } DialogUtilities.okCancelDialog(this, getString(string, tag), getOkListener(), getCancelListener()); } @@ -311,8 +317,9 @@ public class TagFilterExposer extends BroadcastReceiver implements AstridFilterE @Override protected Intent ok() { - if (editor == null) + if (editor == null) { return null; + } String text = editor.getText().toString(); if (text == null || text.length() == 0) { @@ -335,8 +342,9 @@ public class TagFilterExposer extends BroadcastReceiver implements AstridFilterE @Override public FilterListItem[] getFilters() { - if (ContextManager.getContext() == null) + if (ContextManager.getContext() == null) { return null; + } return prepareFilters(ContextManager.getContext()); } diff --git a/astrid/plugin-src/com/todoroo/astrid/tags/TagService.java b/astrid/plugin-src/com/todoroo/astrid/tags/TagService.java index d23f267d9..382ee19b9 100644 --- a/astrid/plugin-src/com/todoroo/astrid/tags/TagService.java +++ b/astrid/plugin-src/com/todoroo/astrid/tags/TagService.java @@ -70,8 +70,9 @@ public final class TagService { }; public static synchronized TagService getInstance() { - if (instance == null) + if (instance == null) { instance = new TagService(); + } return instance; } @@ -203,8 +204,9 @@ public final class TagService { for (int i = 0; i < cursor.getCount(); i++) { cursor.moveToNext(); Tag tag = Tag.tagFromUUID(cursor.get(TaskToTagMetadata.TAG_UUID)); - if (tag != null) + if (tag != null) { array.add(tag); + } } return array.toArray(new Tag[array.size()]); } finally { @@ -258,12 +260,14 @@ public final class TagService { } Metadata link = TaskToTagMetadata.newTagMetadata(taskId, taskUuid, name, tagUuid); - if (suppressOutstanding) + if (suppressOutstanding) { link.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true); + } if (metadataDao.update(Criterion.and(MetadataCriteria.byTaskAndwithKey(taskId, TaskToTagMetadata.KEY), TaskToTagMetadata.TASK_UUID.eq(taskUuid), TaskToTagMetadata.TAG_UUID.eq(tagUuid)), link) <= 0) { - if (suppressOutstanding) + if (suppressOutstanding) { link.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true); + } metadataDao.createNew(link); } @@ -280,8 +284,9 @@ public final class TagService { */ public void deleteLink(long taskId, String taskUuid, String tagUuid, boolean suppressOutstanding) { Metadata deleteTemplate = new Metadata(); - if (suppressOutstanding) + if (suppressOutstanding) { deleteTemplate.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true); + } deleteTemplate.setValue(Metadata.TASK, taskId); // Need this for recording changes in outstanding table deleteTemplate.setValue(TaskToTagMetadata.TAG_UUID, tagUuid); // Need this for recording changes in outstanding table deleteTemplate.setValue(Metadata.DELETION_DATE, DateUtilities.now()); @@ -304,8 +309,9 @@ public final class TagService { // TODO: Right now this is in a loop because each deleteTemplate needs the individual tagUuid in order to record // the outstanding entry correctly. If possible, this should be improved to a single query deleteTemplate.setValue(TaskToTagMetadata.TAG_UUID, uuid); // Need this for recording changes in outstanding table - if (suppressOutstanding) + if (suppressOutstanding) { deleteTemplate.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true); + } metadataDao.update(Criterion.and(MetadataCriteria.withKey(TaskToTagMetadata.KEY), Metadata.DELETION_DATE.eq(0), TaskToTagMetadata.TASK_UUID.eq(taskUuid), TaskToTagMetadata.TAG_UUID.eq(uuid)), deleteTemplate); } @@ -369,8 +375,9 @@ public final class TagService { tags.moveToNext(); metadata.readFromCursor(tags); tagBuilder.append(metadata.getValue(TaskToTagMetadata.TAG_NAME)); - if (i < length - 1) + if (i < length - 1) { tagBuilder.append(separator); + } } } finally { tags.close(); @@ -413,8 +420,9 @@ public final class TagService { continue; } Tag tag = new Tag(tagData); - if (TextUtils.isEmpty(tag.tag)) + if (TextUtils.isEmpty(tag.tag)) { continue; + } tagList.add(tag); } } finally { @@ -432,12 +440,14 @@ public final class TagService { TagData tagData = new TagData(); for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { tagData.readFromCursor(cursor); - if (tagData.getValue(TagData.DELETION_DATE) > 0) + if (tagData.getValue(TagData.DELETION_DATE) > 0) { continue; + } String tagName = tagData.getValue(TagData.NAME).trim(); Tag tag = new Tag(tagData); - if (TextUtils.isEmpty(tag.tag)) + if (TextUtils.isEmpty(tag.tag)) { continue; + } tags.put(tagName, tag); } } finally { @@ -554,8 +564,9 @@ public final class TagService { public int rename(String uuid, String newName, boolean suppressSync) { TagData template = new TagData(); template.setValue(TagData.NAME, newName); - if (suppressSync) + if (suppressSync) { template.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true); + } int result = tagDataDao.update(TagData.UUID.eq(uuid), template); boolean tagRenamed = result > 0; diff --git a/astrid/plugin-src/com/todoroo/astrid/tags/TagsControlSet.java b/astrid/plugin-src/com/todoroo/astrid/tags/TagsControlSet.java index 540fd3631..d418c9005 100644 --- a/astrid/plugin-src/com/todoroo/astrid/tags/TagsControlSet.java +++ b/astrid/plugin-src/com/todoroo/astrid/tags/TagsControlSet.java @@ -95,8 +95,9 @@ public final class TagsControlSet extends PopupControlSet { LinkedHashSet tags = getTagSet(); for (String tag : tags) { - if (builder.length() != 0) + if (builder.length() != 0) { builder.append(", "); //$NON-NLS-1$ + } builder.append(tag); } @@ -119,14 +120,16 @@ public final class TagsControlSet extends PopupControlSet { LinkedHashSet tags = new LinkedHashSet(); if (initialized) { for (int i = 0; i < selectedTags.getAdapter().getCount(); i++) { - if (selectedTags.isItemChecked(i)) + if (selectedTags.isItemChecked(i)) { tags.add(allTagNames.get(i)); + } } for (int i = 0; i < newTags.getChildCount(); i++) { TextView tagName = (TextView) newTags.getChildAt(i).findViewById(R.id.text1); - if (tagName.getText().length() == 0) + if (tagName.getText().length() == 0) { continue; + } tags.add(tagName.getText().toString()); } @@ -149,8 +152,9 @@ public final class TagsControlSet extends PopupControlSet { for (int i = 0; i < newTags.getChildCount(); i++) { View view = newTags.getChildAt(i); lastText = (TextView) view.findViewById(R.id.text1); - if (lastText.getText().equals(tagName)) + if (lastText.getText().equals(tagName)) { return false; + } } final View tagItem; @@ -160,8 +164,9 @@ public final class TagsControlSet extends PopupControlSet { tagItem = inflater.inflate(R.layout.tag_edit_row, null); newTags.addView(tagItem); } - if (tagName == null) + if (tagName == null) { tagName = ""; //$NON-NLS-1$ + } final AutoCompleteTextView textView = (AutoCompleteTextView) tagItem. findViewById(R.id.text1); @@ -183,16 +188,18 @@ public final class TagsControlSet extends PopupControlSet { public void onTextChanged(CharSequence s, int start, int before, int count) { if (count > 0 && newTags.getChildAt(newTags.getChildCount() - 1) == - tagItem) + tagItem) { addTag("", false); //$NON-NLS-1$ + } } }); textView.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView arg0, int actionId, KeyEvent arg2) { - if (actionId != EditorInfo.IME_NULL) + if (actionId != EditorInfo.IME_NULL) { return false; + } if (getLastTextView().getText().length() != 0) { addTag("", false); //$NON-NLS-1$ } @@ -205,13 +212,15 @@ public final class TagsControlSet extends PopupControlSet { reminderRemoveButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { TextView lastView = getLastTextView(); - if (lastView == textView && textView.getText().length() == 0) + if (lastView == textView && textView.getText().length() == 0) { return; + } - if (newTags.getChildCount() > 1) + if (newTags.getChildCount() > 1) { newTags.removeView(tagItem); - else + } else { textView.setText(""); //$NON-NLS-1$ + } } }); @@ -224,8 +233,9 @@ public final class TagsControlSet extends PopupControlSet { * @return */ private TextView getLastTextView() { - if (newTags.getChildCount() == 0) + if (newTags.getChildCount() == 0) { return null; + } View lastItem = newTags.getChildAt(newTags.getChildCount() - 1); TextView lastText = (TextView) lastItem.findViewById(R.id.text1); return lastText; @@ -297,8 +307,9 @@ public final class TagsControlSet extends PopupControlSet { @Override protected String writeToModelAfterInitialized(Task task) { // this is a case where we're asked to save but the UI was not yet populated - if (!populated) + if (!populated) { return null; + } LinkedHashSet tags = getTagSet(); diff --git a/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedListFilterExposer.java b/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedListFilterExposer.java index 21b198a8d..8e1be0916 100644 --- a/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedListFilterExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedListFilterExposer.java @@ -58,8 +58,9 @@ public class FeaturedListFilterExposer extends TagFilterExposer { Class fragmentClass = FeaturedTaskListFragment.class; filter.customTaskList = new ComponentName(ContextManager.getContext(), fragmentClass); - if (tag.image != null) + if (tag.image != null) { filter.imageUrl = tag.image; + } Bundle extras = new Bundle(); extras.putString(TagViewFragment.EXTRA_TAG_NAME, tag.tag); diff --git a/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedListFilterMode.java b/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedListFilterMode.java index b3e794364..d356a5c58 100644 --- a/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedListFilterMode.java +++ b/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedListFilterMode.java @@ -31,10 +31,11 @@ public class FeaturedListFilterMode implements FilterModeSpec { @Override public Filter getDefaultFilter(Context context) { Filter defaultFilter = FeaturedListFilterExposer.getDefaultFilter(); - if (defaultFilter == null) + if (defaultFilter == null) { return CoreFilterExposer.buildInboxFilter(context.getResources()); - else + } else { return defaultFilter; + } } @Override diff --git a/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedListFragment.java b/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedListFragment.java index f7aa17663..895be9ccf 100644 --- a/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedListFragment.java +++ b/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedListFragment.java @@ -16,10 +16,11 @@ public class FeaturedListFragment extends FilterListFragment { @Override protected int getLayout(Activity activity) { - if (AstridPreferences.useTabletLayout(activity)) + if (AstridPreferences.useTabletLayout(activity)) { return R.layout.filter_list_fragment_alternative_3pane; - else + } else { return R.layout.filter_list_fragment_alternative; + } } } diff --git a/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedTaskListFragment.java b/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedTaskListFragment.java index d167b6806..7069a2b92 100644 --- a/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedTaskListFragment.java +++ b/astrid/plugin-src/com/todoroo/astrid/tags/reusable/FeaturedTaskListFragment.java @@ -95,15 +95,17 @@ public class FeaturedTaskListFragment extends TagViewFragment { AsyncImageView imageView = (AsyncImageView) getView().findViewById(R.id.url_image); String imageUrl = tagData.getPictureUrl(TagData.PICTURE, RemoteModel.PICTURE_MEDIUM); Bitmap bitmap = null; - if (TextUtils.isEmpty(imageUrl)) + if (TextUtils.isEmpty(imageUrl)) { bitmap = tagData.getPictureBitmap(TagData.PICTURE); + } if (!TextUtils.isEmpty(imageUrl) || bitmap != null) { imageView.setVisibility(View.VISIBLE); imageView.setDefaultImageDrawable(ResourceDrawableCache.getImageDrawableFromId(resources, R.drawable.default_list_0)); - if (bitmap != null) + if (bitmap != null) { imageView.setImageBitmap(bitmap); - else + } else { imageView.setUrl(imageUrl); + } } else { imageView.setVisibility(View.GONE); } diff --git a/astrid/plugin-src/com/todoroo/astrid/tags/reusable/ReusableTaskAdapter.java b/astrid/plugin-src/com/todoroo/astrid/tags/reusable/ReusableTaskAdapter.java index 2ebb79d45..22db4018c 100644 --- a/astrid/plugin-src/com/todoroo/astrid/tags/reusable/ReusableTaskAdapter.java +++ b/astrid/plugin-src/com/todoroo/astrid/tags/reusable/ReusableTaskAdapter.java @@ -43,8 +43,9 @@ public class ReusableTaskAdapter extends TaskAdapter { } view.setTag(viewHolder); - for (int i = 0; i < view.getChildCount(); i++) + for (int i = 0; i < view.getChildCount(); i++) { view.getChildAt(i).setTag(viewHolder); + } viewHolder.clone.setOnClickListener(new OnClickListener() { @Override diff --git a/astrid/plugin-src/com/todoroo/astrid/timers/TimerActionControlSet.java b/astrid/plugin-src/com/todoroo/astrid/timers/TimerActionControlSet.java index e9a08cc5d..f24bb743d 100644 --- a/astrid/plugin-src/com/todoroo/astrid/timers/TimerActionControlSet.java +++ b/astrid/plugin-src/com/todoroo/astrid/timers/TimerActionControlSet.java @@ -41,10 +41,11 @@ public class TimerActionControlSet extends TaskEditControlSet { @Override protected void readFromTaskOnInitialize() { - if (model.getValue(Task.TIMER_START) == 0) + if (model.getValue(Task.TIMER_START) == 0) { timerActive = false; - else + } else { timerActive = true; + } updateDisplay(); } @@ -66,13 +67,15 @@ public class TimerActionControlSet extends TaskEditControlSet { if (timerActive) { TimerPlugin.updateTimer(activity, model, false); - for (TimerActionListener listener : listeners) + for (TimerActionListener listener : listeners) { listener.timerStopped(model); + } chronometer.stop(); } else { TimerPlugin.updateTimer(activity, model, true); - for (TimerActionListener listener : listeners) + for (TimerActionListener listener : listeners) { listener.timerStarted(model); + } chronometer.start(); } timerActive = !timerActive; @@ -122,7 +125,8 @@ public class TimerActionControlSet extends TaskEditControlSet { } public void removeListener(TimerActionListener listener) { - if (listeners.contains(listener)) + if (listeners.contains(listener)) { listeners.remove(listener); + } } } diff --git a/astrid/plugin-src/com/todoroo/astrid/timers/TimerControlSet.java b/astrid/plugin-src/com/todoroo/astrid/timers/TimerControlSet.java index 17bb8290d..003e66268 100644 --- a/astrid/plugin-src/com/todoroo/astrid/timers/TimerControlSet.java +++ b/astrid/plugin-src/com/todoroo/astrid/timers/TimerControlSet.java @@ -107,8 +107,9 @@ public class TimerControlSet extends PopupControlSet implements TimerActionListe public String getDisplayString() { int seconds = controlSet.getTimeDurationInSeconds(); - if (seconds > 0) + if (seconds > 0) { return DateUtils.formatElapsedTime(controlSet.getTimeDurationInSeconds()); + } return null; } } @@ -116,22 +117,25 @@ public class TimerControlSet extends PopupControlSet implements TimerActionListe @Override protected void refreshDisplayView() { String est = estimated.getDisplayString(); - if (!TextUtils.isEmpty(est)) + if (!TextUtils.isEmpty(est)) { est = activity.getString(R.string.TEA_timer_est, est); + } String elap = elapsed.getDisplayString(); - if (!TextUtils.isEmpty(elap)) + if (!TextUtils.isEmpty(elap)) { elap = activity.getString(R.string.TEA_timer_elap, elap); + } String toDisplay; - if (!TextUtils.isEmpty(est) && !TextUtils.isEmpty(elap)) + if (!TextUtils.isEmpty(est) && !TextUtils.isEmpty(elap)) { toDisplay = est + ", " + elap; //$NON-NLS-1$ - else if (!TextUtils.isEmpty(est)) + } else if (!TextUtils.isEmpty(est)) { toDisplay = est; - else if (!TextUtils.isEmpty(elap)) + } else if (!TextUtils.isEmpty(elap)) { toDisplay = elap; - else + } else { toDisplay = null; + } if (!TextUtils.isEmpty(toDisplay)) { displayEdit.setText(toDisplay); diff --git a/astrid/plugin-src/com/todoroo/astrid/timers/TimerDecorationExposer.java b/astrid/plugin-src/com/todoroo/astrid/timers/TimerDecorationExposer.java index 50a6676fb..e7c8d9ffa 100644 --- a/astrid/plugin-src/com/todoroo/astrid/timers/TimerDecorationExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/timers/TimerDecorationExposer.java @@ -33,8 +33,9 @@ public class TimerDecorationExposer implements TaskDecorationExposer { @Override public TaskDecoration expose(Task task) { if (task == null || (task.getValue(Task.ELAPSED_SECONDS) == 0 && - task.getValue(Task.TIMER_START) == 0)) + task.getValue(Task.TIMER_START) == 0)) { return null; + } TaskDecoration decoration; RemoteViews remoteViews = new RemoteViews(ContextManager.getContext().getPackageName(), @@ -65,8 +66,9 @@ public class TimerDecorationExposer implements TaskDecorationExposer { public void updateDecoration(Context context, Task task) { TaskDecoration decoration = expose(task); - if (decoration == null) + if (decoration == null) { return; + } Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_SEND_DECORATIONS); broadcastIntent.putExtra(AstridApiConstants.EXTRAS_ADDON, TimerPlugin.IDENTIFIER); diff --git a/astrid/plugin-src/com/todoroo/astrid/timers/TimerFilterExposer.java b/astrid/plugin-src/com/todoroo/astrid/timers/TimerFilterExposer.java index 423a770b6..210049c4a 100644 --- a/astrid/plugin-src/com/todoroo/astrid/timers/TimerFilterExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/timers/TimerFilterExposer.java @@ -43,8 +43,9 @@ public final class TimerFilterExposer extends BroadcastReceiver implements Astri private FilterListItem[] prepareFilters(Context context) { if (PluginServices.getTaskService().count(Query.select(Task.ID). - where(Task.TIMER_START.gt(0))) == 0) + where(Task.TIMER_START.gt(0))) == 0) { return null; + } Filter workingOn = createFilter(context); @@ -68,8 +69,9 @@ public final class TimerFilterExposer extends BroadcastReceiver implements Astri @Override public FilterListItem[] getFilters() { - if (ContextManager.getContext() == null) + if (ContextManager.getContext() == null) { return null; + } return prepareFilters(ContextManager.getContext()); } diff --git a/astrid/plugin-src/com/todoroo/astrid/timers/TimerPlugin.java b/astrid/plugin-src/com/todoroo/astrid/timers/TimerPlugin.java index 9af185622..6627055ae 100644 --- a/astrid/plugin-src/com/todoroo/astrid/timers/TimerPlugin.java +++ b/astrid/plugin-src/com/todoroo/astrid/timers/TimerPlugin.java @@ -53,10 +53,12 @@ public class TimerPlugin extends BroadcastReceiver { public static void updateTimer(Context context, Task task, boolean start) { // if this call comes from tasklist, then we need to fill in the gaps to handle this correctly // this is needed just for stopping a task - if (!task.containsNonNullValue(Task.TIMER_START)) + if (!task.containsNonNullValue(Task.TIMER_START)) { task = PluginServices.getTaskService().fetchById(task.getId(), Task.ID, Task.TIMER_START, Task.ELAPSED_SECONDS); - if (task == null) + } + if (task == null) { return; + } if (start) { if (task.getValue(Task.TIMER_START) == 0) { diff --git a/astrid/plugin-src/com/todoroo/astrid/timers/TimerTaskCompleteListener.java b/astrid/plugin-src/com/todoroo/astrid/timers/TimerTaskCompleteListener.java index 4ff249755..b3ca230cf 100644 --- a/astrid/plugin-src/com/todoroo/astrid/timers/TimerTaskCompleteListener.java +++ b/astrid/plugin-src/com/todoroo/astrid/timers/TimerTaskCompleteListener.java @@ -20,13 +20,15 @@ public class TimerTaskCompleteListener extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { ContextManager.setContext(context); long taskId = intent.getLongExtra(AstridApiConstants.EXTRAS_TASK_ID, -1); - if (taskId == -1) + if (taskId == -1) { return; + } Task task = PluginServices.getTaskService().fetchById(taskId, Task.ID, Task.ELAPSED_SECONDS, Task.TIMER_START); - if (task == null || task.getValue(Task.TIMER_START) == 0) + if (task == null || task.getValue(Task.TIMER_START) == 0) { return; + } TimerPlugin.updateTimer(context, task, false); } diff --git a/astrid/src-legacy/com/timsu/astrid/data/Identifier.java b/astrid/src-legacy/com/timsu/astrid/data/Identifier.java index 2d91e8434..83daa5ec7 100644 --- a/astrid/src-legacy/com/timsu/astrid/data/Identifier.java +++ b/astrid/src-legacy/com/timsu/astrid/data/Identifier.java @@ -30,8 +30,9 @@ public abstract class Identifier { @Override public boolean equals(Object o) { - if (o == null || o.getClass() != getClass()) + if (o == null || o.getClass() != getClass()) { return false; + } return ((Identifier) o).getId() == getId(); } diff --git a/astrid/src-legacy/com/timsu/astrid/data/LegacyAbstractModel.java b/astrid/src-legacy/com/timsu/astrid/data/LegacyAbstractModel.java index 7673235a4..936375b0d 100644 --- a/astrid/src-legacy/com/timsu/astrid/data/LegacyAbstractModel.java +++ b/astrid/src-legacy/com/timsu/astrid/data/LegacyAbstractModel.java @@ -96,10 +96,12 @@ public abstract class LegacyAbstractModel { if (!setValues.containsKey(field) && values.containsKey(field)) { String value = values.getAsString(field); if (value == null) { - if (newValue == null) + if (newValue == null) { return; - } else if (value.equals(newValue)) + } + } else if (value.equals(newValue)) { return; + } } setValues.put(field, newValue); } @@ -108,10 +110,12 @@ public abstract class LegacyAbstractModel { if (!setValues.containsKey(field) && values.containsKey(field)) { Long value = values.getAsLong(field); if (value == null) { - if (newValue == null) + if (newValue == null) { return; - } else if (value.equals(newValue)) + } + } else if (value.equals(newValue)) { return; + } } setValues.put(field, newValue); } @@ -120,10 +124,12 @@ public abstract class LegacyAbstractModel { if (!setValues.containsKey(field) && values.containsKey(field)) { Integer value = values.getAsInteger(field); if (value == null) { - if (newValue == null) + if (newValue == null) { return; - } else if (value.equals(newValue)) + } + } else if (value.equals(newValue)) { return; + } } setValues.put(field, newValue); } @@ -132,10 +138,12 @@ public abstract class LegacyAbstractModel { if (!setValues.containsKey(field) && values.containsKey(field)) { Double value = values.getAsDouble(field); if (value == null) { - if (newValue == null) + if (newValue == null) { return; - } else if (value.equals(newValue)) + } + } else if (value.equals(newValue)) { return; + } } setValues.put(field, newValue); } @@ -163,11 +171,13 @@ public abstract class LegacyAbstractModel { // --- data retrieval for the different object types protected String retrieveString(String field) { - if (setValues.containsKey(field)) + if (setValues.containsKey(field)) { return setValues.getAsString(field); + } - if (values.containsKey(field)) + if (values.containsKey(field)) { return values.getAsString(field); + } // if we have a database to hit, do that now if (cursor != null) { @@ -178,18 +188,21 @@ public abstract class LegacyAbstractModel { // do we have defaults? ContentValues defaults = getDefaultValues(); - if (defaults != null && defaults.containsKey(field)) + if (defaults != null && defaults.containsKey(field)) { return defaults.getAsString(field); + } throw new UnsupportedOperationException("Could not read field " + field); } protected Integer retrieveInteger(String field) { - if (setValues.containsKey(field)) + if (setValues.containsKey(field)) { return setValues.getAsInteger(field); + } - if (values.containsKey(field)) + if (values.containsKey(field)) { return values.getAsInteger(field); + } // if we have a database to hit, do that now if (cursor != null) { @@ -204,18 +217,21 @@ public abstract class LegacyAbstractModel { // do we have defaults? ContentValues defaults = getDefaultValues(); - if (defaults != null && defaults.containsKey(field)) + if (defaults != null && defaults.containsKey(field)) { return defaults.getAsInteger(field); + } throw new UnsupportedOperationException("Could not read field " + field); } protected Long retrieveLong(String field) { - if (setValues.containsKey(field)) + if (setValues.containsKey(field)) { return setValues.getAsLong(field); + } - if (values.containsKey(field)) + if (values.containsKey(field)) { return values.getAsLong(field); + } // if we have a database to hit, do that now if (cursor != null) { @@ -226,18 +242,21 @@ public abstract class LegacyAbstractModel { // do we have defaults? ContentValues defaults = getDefaultValues(); - if (defaults != null && defaults.containsKey(field)) + if (defaults != null && defaults.containsKey(field)) { return defaults.getAsLong(field); + } throw new UnsupportedOperationException("Could not read field " + field); } protected Double retrieveDouble(String field) { - if (setValues.containsKey(field)) + if (setValues.containsKey(field)) { return setValues.getAsDouble(field); + } - if (values.containsKey(field)) + if (values.containsKey(field)) { return values.getAsDouble(field); + } // if we have a database to hit, do that now if (cursor != null) { @@ -248,8 +267,9 @@ public abstract class LegacyAbstractModel { // do we have defaults? ContentValues defaults = getDefaultValues(); - if (defaults != null && defaults.containsKey(field)) + if (defaults != null && defaults.containsKey(field)) { return defaults.getAsDouble(field); + } throw new UnsupportedOperationException("Could not read field " + field); } @@ -260,8 +280,9 @@ public abstract class LegacyAbstractModel { Long time; try { time = retrieveLong(field); - if (time == null || time == 0) + if (time == null || time == 0) { return null; + } } catch (NullPointerException e) { return null; } diff --git a/astrid/src-legacy/com/timsu/astrid/data/alerts/AlertController.java b/astrid/src-legacy/com/timsu/astrid/data/alerts/AlertController.java index 62fe96134..daf35ffcc 100644 --- a/astrid/src-legacy/com/timsu/astrid/data/alerts/AlertController.java +++ b/astrid/src-legacy/com/timsu/astrid/data/alerts/AlertController.java @@ -50,8 +50,9 @@ public class AlertController extends LegacyAbstractController { new String[]{taskId.idAsString()}, null, null, null); try { - if (cursor.getCount() == 0) + if (cursor.getCount() == 0) { return list; + } do { cursor.moveToNext(); list.add(new Alert(cursor).getDate()); @@ -74,8 +75,9 @@ public class AlertController extends LegacyAbstractController { new String[]{Long.toString(System.currentTimeMillis())}, null, null, null); try { - if (cursor.getCount() == 0) + if (cursor.getCount() == 0) { return list; + } do { cursor.moveToNext(); list.add(new Alert(cursor).getTask()); diff --git a/astrid/src-legacy/com/timsu/astrid/data/enums/RepeatInterval.java b/astrid/src-legacy/com/timsu/astrid/data/enums/RepeatInterval.java index 0d54e8368..c71d7c510 100644 --- a/astrid/src-legacy/com/timsu/astrid/data/enums/RepeatInterval.java +++ b/astrid/src-legacy/com/timsu/astrid/data/enums/RepeatInterval.java @@ -52,8 +52,9 @@ public enum RepeatInterval { int intervalCount = RepeatInterval.values().length; String[] result = new String[intervalCount]; - for (int i = 0; i < intervalCount; i++) + for (int i = 0; i < intervalCount; i++) { result[i] = r.getString(RepeatInterval.values()[i].getLabelResource()); + } return result; } } diff --git a/astrid/src-legacy/com/timsu/astrid/data/sync/SyncDataController.java b/astrid/src-legacy/com/timsu/astrid/data/sync/SyncDataController.java index 0883ec49d..81b470fea 100644 --- a/astrid/src-legacy/com/timsu/astrid/data/sync/SyncDataController.java +++ b/astrid/src-legacy/com/timsu/astrid/data/sync/SyncDataController.java @@ -73,8 +73,9 @@ public class SyncDataController extends LegacyAbstractController { null, null, null, null); try { - if (cursor.getCount() == 0) + if (cursor.getCount() == 0) { return list; + } do { cursor.moveToNext(); list.add(new SyncMapping(cursor)); @@ -99,8 +100,9 @@ public class SyncDataController extends LegacyAbstractController { null, null, null); try { - if (cursor.getCount() == 0) + if (cursor.getCount() == 0) { return list; + } do { cursor.moveToNext(); list.add(new SyncMapping(cursor)); @@ -125,8 +127,9 @@ public class SyncDataController extends LegacyAbstractController { null, null, null); try { - if (cursor.getCount() == 0) + if (cursor.getCount() == 0) { return null; + } cursor.moveToNext(); return new SyncMapping(cursor); } finally { @@ -151,8 +154,9 @@ public class SyncDataController extends LegacyAbstractController { */ public boolean deleteSyncMapping(SyncMapping mapping) { // was never saved - if (mapping.getId() == 0) + if (mapping.getId() == 0) { return false; + } return syncDatabase.delete(syncTable, KEY_ROWID + "=" + mapping.getId(), null) > 0; @@ -197,7 +201,8 @@ public class SyncDataController extends LegacyAbstractController { */ @Override public void close() { - if (syncDatabase != null) + if (syncDatabase != null) { syncDatabase.close(); + } } } diff --git a/astrid/src-legacy/com/timsu/astrid/data/tag/AbstractTagModel.java b/astrid/src-legacy/com/timsu/astrid/data/tag/AbstractTagModel.java index c15216251..864ec1852 100644 --- a/astrid/src-legacy/com/timsu/astrid/data/tag/AbstractTagModel.java +++ b/astrid/src-legacy/com/timsu/astrid/data/tag/AbstractTagModel.java @@ -184,9 +184,10 @@ public abstract class AbstractTagModel extends LegacyAbstractModel { // --- utility methods static void putDate(ContentValues cv, String fieldName, Date date) { - if (date == null) + if (date == null) { cv.put(fieldName, (Long) null); - else + } else { cv.put(fieldName, date.getTime()); + } } } diff --git a/astrid/src-legacy/com/timsu/astrid/data/tag/TagController.java b/astrid/src-legacy/com/timsu/astrid/data/tag/TagController.java index cf8b45e72..3bf97841d 100644 --- a/astrid/src-legacy/com/timsu/astrid/data/tag/TagController.java +++ b/astrid/src-legacy/com/timsu/astrid/data/tag/TagController.java @@ -43,8 +43,9 @@ public class TagController extends LegacyAbstractController { TagModelForView.FIELD_LIST, null, null, null, null, null, null); try { - if (cursor.getCount() == 0) + if (cursor.getCount() == 0) { return list; + } do { cursor.moveToNext(); list.add(new TagModelForView(cursor)); @@ -63,8 +64,9 @@ public class TagController extends LegacyAbstractController { */ public HashMap getAllTagsAsMap() throws SQLException { HashMap map = new HashMap(); - for (TagModelForView tag : getAllTags()) + for (TagModelForView tag : getAllTags()) { map.put(tag.getTagIdentifier(), tag); + } return map; } @@ -79,8 +81,9 @@ public class TagController extends LegacyAbstractController { new String[]{taskId.idAsString()}, null, null, null); try { - if (cursor.getCount() == 0) + if (cursor.getCount() == 0) { return list; + } do { cursor.moveToNext(); list.add(new TagToTaskMapping(cursor).getTag()); @@ -105,8 +108,9 @@ public class TagController extends LegacyAbstractController { new String[]{tagId.idAsString()}, null, null, null); try { - if (cursor.getCount() == 0) + if (cursor.getCount() == 0) { return list; + } do { cursor.moveToNext(); list.add(new TagToTaskMapping(cursor).getTask()); @@ -143,8 +147,9 @@ public class TagController extends LegacyAbstractController { LinkedList list = new LinkedList(); try { - if (taskCursor.getCount() == 0) + if (taskCursor.getCount() == 0) { return list; + } do { taskCursor.moveToNext(); @@ -163,8 +168,9 @@ public class TagController extends LegacyAbstractController { taskDatabase.close(); } - for (Long id : ids) + for (Long id : ids) { list.add(new TaskIdentifier(id)); + } return list; } @@ -172,8 +178,9 @@ public class TagController extends LegacyAbstractController { // --- single tag operations public TagIdentifier createTag(String name) throws SQLException { - if (name == null) + if (name == null) { throw new NullPointerException("Name can't be null"); + } TagModelForView newTag = new TagModelForView(name); long row = tagDatabase.insertOrThrow(tagsTable, AbstractTagModel.NAME, @@ -218,8 +225,9 @@ public class TagController extends LegacyAbstractController { } return null; } finally { - if (cursor != null) + if (cursor != null) { cursor.close(); + } } } @@ -241,8 +249,9 @@ public class TagController extends LegacyAbstractController { throw new SQLException("Returned empty set!"); } finally { - if (cursor != null) + if (cursor != null) { cursor.close(); + } } } @@ -252,8 +261,9 @@ public class TagController extends LegacyAbstractController { public boolean deleteTag(TagIdentifier tagId) throws SQLException { if (tagToTaskMapDatabase.delete(tagTaskTable, - TagToTaskMapping.TAG + " = " + tagId.idAsString(), null) < 0) + TagToTaskMapping.TAG + " = " + tagId.idAsString(), null) < 0) { return false; + } int res = tagDatabase.delete(tagsTable, KEY_ROWID + " = " + tagId.idAsString(), null); @@ -333,9 +343,11 @@ public class TagController extends LegacyAbstractController { */ @Override public void close() { - if (tagDatabase != null) + if (tagDatabase != null) { tagDatabase.close(); - if (tagToTaskMapDatabase != null) + } + if (tagToTaskMapDatabase != null) { tagToTaskMapDatabase.close(); + } } } diff --git a/astrid/src-legacy/com/timsu/astrid/data/tag/TagModelForView.java b/astrid/src-legacy/com/timsu/astrid/data/tag/TagModelForView.java index 325aab505..32bc76891 100644 --- a/astrid/src-legacy/com/timsu/astrid/data/tag/TagModelForView.java +++ b/astrid/src-legacy/com/timsu/astrid/data/tag/TagModelForView.java @@ -88,9 +88,10 @@ public class TagModelForView extends AbstractTagModel { } public void toggleHideFromMainList() { - if (shouldHideFromMainList()) + if (shouldHideFromMainList()) { setName(getName().substring(HIDDEN_FROM_MAIN_LIST_PREFIX.length())); - else + } else { setName(HIDDEN_FROM_MAIN_LIST_PREFIX + getName()); + } } } diff --git a/astrid/src-legacy/com/timsu/astrid/data/task/AbstractTaskModel.java b/astrid/src-legacy/com/timsu/astrid/data/task/AbstractTaskModel.java index 029f71cd7..6c047e0c7 100644 --- a/astrid/src-legacy/com/timsu/astrid/data/task/AbstractTaskModel.java +++ b/astrid/src-legacy/com/timsu/astrid/data/task/AbstractTaskModel.java @@ -283,8 +283,9 @@ public abstract class AbstractTaskModel extends LegacyAbstractModel { * elapsedSeconds */ protected void stopTimerAndUpdateElapsedTime() { - if (getTimerStart() == null) + if (getTimerStart() == null) { return; + } long start = getTimerStart().getTime(); setTimerStart(null); @@ -294,44 +295,45 @@ public abstract class AbstractTaskModel extends LegacyAbstractModel { protected void prefetchData(String[] fields) { for (String field : fields) { - if (field.equals(NAME)) + if (field.equals(NAME)) { getName(); - else if (field.equals(NOTES)) + } else if (field.equals(NOTES)) { getNotes(); - else if (field.equals(PROGRESS_PERCENTAGE)) + } else if (field.equals(PROGRESS_PERCENTAGE)) { getProgressPercentage(); - else if (field.equals(IMPORTANCE)) + } else if (field.equals(IMPORTANCE)) { getImportance(); - else if (field.equals(ESTIMATED_SECONDS)) + } else if (field.equals(ESTIMATED_SECONDS)) { getEstimatedSeconds(); - else if (field.equals(ELAPSED_SECONDS)) + } else if (field.equals(ELAPSED_SECONDS)) { getElapsedSeconds(); - else if (field.equals(TIMER_START)) + } else if (field.equals(TIMER_START)) { getTimerStart(); - else if (field.equals(DEFINITE_DUE_DATE)) + } else if (field.equals(DEFINITE_DUE_DATE)) { getDefiniteDueDate(); - else if (field.equals(PREFERRED_DUE_DATE)) + } else if (field.equals(PREFERRED_DUE_DATE)) { getPreferredDueDate(); - else if (field.equals(HIDDEN_UNTIL)) + } else if (field.equals(HIDDEN_UNTIL)) { getHiddenUntil(); - else if (field.equals(BLOCKING_ON)) + } else if (field.equals(BLOCKING_ON)) { getBlockingOn(); - else if (field.equals(POSTPONE_COUNT)) + } else if (field.equals(POSTPONE_COUNT)) { getPostponeCount(); - else if (field.equals(NOTIFICATIONS)) + } else if (field.equals(NOTIFICATIONS)) { getNotificationIntervalSeconds(); - else if (field.equals(CREATION_DATE)) + } else if (field.equals(CREATION_DATE)) { getCreationDate(); - else if (field.equals(COMPLETION_DATE)) + } else if (field.equals(COMPLETION_DATE)) { getCompletionDate(); - else if (field.equals(NOTIFICATION_FLAGS)) + } else if (field.equals(NOTIFICATION_FLAGS)) { getNotificationFlags(); - else if (field.equals(LAST_NOTIFIED)) + } else if (field.equals(LAST_NOTIFIED)) { getLastNotificationDate(); - else if (field.equals(REPEAT)) + } else if (field.equals(REPEAT)) { getRepeat(); - else if (field.equals(FLAGS)) + } else if (field.equals(FLAGS)) { getFlags(); + } } } @@ -362,17 +364,19 @@ public abstract class AbstractTaskModel extends LegacyAbstractModel { public static int toSingleField(RepeatInfo repeatInfo) { int repeat; - if (repeatInfo == null) + if (repeatInfo == null) { repeat = 0; - else + } else { repeat = (repeatInfo.value << REPEAT_VALUE_OFFSET) + repeatInfo.interval.ordinal(); + } return repeat; } public static RepeatInfo fromSingleField(int repeat) { - if (repeat == 0) + if (repeat == 0) { return null; + } int value = repeat >> REPEAT_VALUE_OFFSET; RepeatInterval interval = RepeatInterval.values() [repeat - (value << REPEAT_VALUE_OFFSET)]; @@ -440,8 +444,9 @@ public abstract class AbstractTaskModel extends LegacyAbstractModel { protected Importance getImportance() { Integer value = retrieveInteger(IMPORTANCE); - if (value == null) + if (value == null) { return null; + } return Importance.values()[value]; } @@ -470,8 +475,9 @@ public abstract class AbstractTaskModel extends LegacyAbstractModel { } protected boolean isHidden() { - if (getHiddenUntil() == null) + if (getHiddenUntil() == null) { return false; + } return getHiddenUntil().getTime() > System.currentTimeMillis(); } @@ -485,8 +491,9 @@ public abstract class AbstractTaskModel extends LegacyAbstractModel { protected TaskIdentifier getBlockingOn() { Long value = retrieveLong(BLOCKING_ON); - if (value == null) + if (value == null) { return null; + } return new TaskIdentifier(value); } @@ -508,8 +515,9 @@ public abstract class AbstractTaskModel extends LegacyAbstractModel { protected RepeatInfo getRepeat() { int repeat = retrieveInteger(REPEAT); - if (repeat == 0) + if (repeat == 0) { return null; + } int value = repeat >> REPEAT_VALUE_OFFSET; RepeatInterval interval = RepeatInterval.values() [repeat - (value << REPEAT_VALUE_OFFSET)]; @@ -519,10 +527,11 @@ public abstract class AbstractTaskModel extends LegacyAbstractModel { protected String getCalendarUri() { String uri = retrieveString(CALENDAR_URI); - if (uri != null && uri.length() == 0) + if (uri != null && uri.length() == 0) { return null; - else + } else { return uri; + } } protected int getFlags() { @@ -543,8 +552,9 @@ public abstract class AbstractTaskModel extends LegacyAbstractModel { putIfChangedFromDatabase(PROGRESS_PERCENTAGE, progressPercentage); if (getProgressPercentage() != progressPercentage && - progressPercentage == COMPLETE_PERCENTAGE) + progressPercentage == COMPLETE_PERCENTAGE) { setCompletionDate(new Date()); + } } protected void setImportance(Importance importance) { @@ -576,10 +586,11 @@ public abstract class AbstractTaskModel extends LegacyAbstractModel { } protected void setBlockingOn(TaskIdentifier blockingOn) { - if (blockingOn == null || blockingOn.equals(getTaskIdentifier())) + if (blockingOn == null || blockingOn.equals(getTaskIdentifier())) { putIfChangedFromDatabase(BLOCKING_ON, (Integer) null); - else + } else { putIfChangedFromDatabase(BLOCKING_ON, blockingOn.getId()); + } } protected void setPostponeCount(int postponeCount) { @@ -608,11 +619,12 @@ public abstract class AbstractTaskModel extends LegacyAbstractModel { protected void setRepeat(RepeatInfo repeatInfo) { int repeat; - if (repeatInfo == null) + if (repeatInfo == null) { repeat = 0; - else + } else { repeat = (repeatInfo.value << REPEAT_VALUE_OFFSET) + repeatInfo.interval.ordinal(); + } putIfChangedFromDatabase(REPEAT, repeat); } @@ -627,9 +639,10 @@ public abstract class AbstractTaskModel extends LegacyAbstractModel { // --- utility methods protected void putDate(String fieldName, Date date) { - if (date == null) + if (date == null) { putIfChangedFromDatabase(fieldName, 0); - else + } else { putIfChangedFromDatabase(fieldName, date.getTime()); + } } } diff --git a/astrid/src-legacy/com/timsu/astrid/data/task/TaskController.java b/astrid/src-legacy/com/timsu/astrid/data/task/TaskController.java index 8e42d3088..5b9480642 100644 --- a/astrid/src-legacy/com/timsu/astrid/data/task/TaskController.java +++ b/astrid/src-legacy/com/timsu/astrid/data/task/TaskController.java @@ -56,8 +56,9 @@ public class TaskController extends LegacyAbstractController { AbstractTaskModel.NOTIFICATION_FLAGS), null, null, null, null, null); try { - if (cursor.getCount() == 0) + if (cursor.getCount() == 0) { return list; + } do { cursor.moveToNext(); list.add(new TaskModelForNotify(cursor)); @@ -82,8 +83,9 @@ public class TaskController extends LegacyAbstractController { AbstractTaskModel.PREFERRED_DUE_DATE), null, null, null, null, null); try { - if (cursor.getCount() == 0) + if (cursor.getCount() == 0) { return list; + } do { cursor.moveToNext(); @@ -148,8 +150,9 @@ public class TaskController extends LegacyAbstractController { public ArrayList createTaskListFromCursor(Cursor cursor) { ArrayList list = new ArrayList(); - if (cursor.getCount() == 0) + if (cursor.getCount() == 0) { return list; + } do { cursor.moveToNext(); @@ -166,8 +169,9 @@ public class TaskController extends LegacyAbstractController { private HashSet createTaskIdentifierSet(Cursor cursor) { HashSet list = new HashSet(); try { - if (cursor.getCount() == 0) + if (cursor.getCount() == 0) { return list; + } do { cursor.moveToNext(); @@ -223,13 +227,15 @@ public class TaskController extends LegacyAbstractController { where.append(KEY_ROWID); where.append("="); where.append(idList.get(i).idAsString()); - if (i < idList.size() - 1) + if (i < idList.size() - 1) { where.append(" OR "); + } } // hack for empty arrays - if (idList.size() == 0) + if (idList.size() == 0) { where.append("0"); + } return database.query(true, tasksTable, TaskModelForList.FIELD_LIST, where.toString(), null, null, @@ -242,8 +248,9 @@ public class TaskController extends LegacyAbstractController { * Delete the given task */ public boolean deleteTask(TaskIdentifier taskId) { - if (taskId == null) + if (taskId == null) { throw new UnsupportedOperationException("Cannot delete uncreated task!"); + } long id = taskId.getId(); cleanupTask(taskId, false); @@ -272,7 +279,9 @@ public class TaskController extends LegacyAbstractController { ContentValues values = task.getSetValues(); if (values.size() == 0) // nothing changed + { return true; + } onTaskSave(task, values, duringSync); @@ -456,8 +465,9 @@ public class TaskController extends LegacyAbstractController { public TaskModelForEdit fetchTaskForEdit(Activity activity, TaskIdentifier taskId) throws SQLException { Cursor cursor = fetchTaskCursor(taskId, TaskModelForEdit.FIELD_LIST); - if (cursor == null) + if (cursor == null) { return null; + } activity.startManagingCursor(cursor); TaskModelForEdit model = new TaskModelForEdit(taskId, cursor); return model; @@ -468,8 +478,9 @@ public class TaskController extends LegacyAbstractController { */ public TaskModelForList fetchTaskForList(TaskIdentifier taskId) throws SQLException { Cursor cursor = fetchTaskCursor(taskId, TaskModelForList.FIELD_LIST); - if (cursor == null) + if (cursor == null) { return null; + } TaskModelForList model = new TaskModelForList(cursor); cursor.close(); return model; @@ -480,8 +491,9 @@ public class TaskController extends LegacyAbstractController { */ public TaskModelForXml fetchTaskForXml(TaskIdentifier taskId) throws SQLException { Cursor cursor = fetchTaskCursor(taskId, TaskModelForXml.FIELD_LIST); - if (cursor == null) + if (cursor == null) { return null; + } TaskModelForXml model = new TaskModelForXml(cursor); cursor.close(); return model; @@ -534,14 +546,16 @@ public class TaskController extends LegacyAbstractController { AbstractTaskModel.COMPLETE_PERCENTAGE, new String[]{name}, null, null, null, null); try { - if (cursor == null || cursor.getCount() == 0) + if (cursor == null || cursor.getCount() == 0) { return null; + } cursor.moveToFirst(); TaskModelForSync model = new TaskModelForSync(cursor); return model; } finally { - if (cursor != null) + if (cursor != null) { cursor.close(); + } } } @@ -563,8 +577,9 @@ public class TaskController extends LegacyAbstractController { long id = taskId.getId(); Cursor cursor = database.query(true, tasksTable, fieldList, KEY_ROWID + "=" + id, null, null, null, null, null); - if (cursor == null) + if (cursor == null) { throw new SQLException("Returned empty set!"); + } cursor.moveToFirst(); return cursor; @@ -582,8 +597,9 @@ public class TaskController extends LegacyAbstractController { String approximateCreationDate = (creationDate / 1000) + "%"; Cursor cursor = database.query(true, tasksTable, fieldList, where, new String[]{name, approximateCreationDate}, null, null, null, null); - if (cursor == null) + if (cursor == null) { throw new SQLException("Returned empty set!"); + } if (cursor.moveToFirst()) { return cursor; @@ -599,15 +615,17 @@ public class TaskController extends LegacyAbstractController { public int fetchTaskPostponeCount(TaskIdentifier taskId) throws SQLException { Cursor cursor = fetchTaskCursor(taskId, new String[]{AbstractTaskModel.POSTPONE_COUNT}); try { - if (cursor == null || cursor.getCount() == 0) + if (cursor == null || cursor.getCount() == 0) { return 0; + } cursor.moveToFirst(); return cursor.getInt(0); } catch (Exception e) { return 0; } finally { - if (cursor != null) + if (cursor != null) { cursor.close(); + } } } @@ -638,8 +656,9 @@ public class TaskController extends LegacyAbstractController { try { ArrayList list = new ArrayList(); - for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) + for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { list.add(new TaskModelForWidget(cursor)); + } return list; } finally { cursor.close(); @@ -660,8 +679,9 @@ public class TaskController extends LegacyAbstractController { try { ArrayList list = new ArrayList(); - for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) + for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { list.add(new TaskModelForProvider(cursor)); + } return list; } finally { cursor.close(); diff --git a/astrid/src-legacy/com/timsu/astrid/data/task/TaskModelForHandlers.java b/astrid/src-legacy/com/timsu/astrid/data/task/TaskModelForHandlers.java index 57929fd1a..9a7e42733 100644 --- a/astrid/src-legacy/com/timsu/astrid/data/task/TaskModelForHandlers.java +++ b/astrid/src-legacy/com/timsu/astrid/data/task/TaskModelForHandlers.java @@ -49,20 +49,24 @@ public class TaskModelForHandlers extends AbstractTaskModel { RepeatInfo repeatInfo) { // move dates back - if (getDefiniteDueDate() != null) + if (getDefiniteDueDate() != null) { setDefiniteDueDate(repeatInfo.shiftDate(getDefiniteDueDate())); - if (getHiddenUntil() != null) + } + if (getHiddenUntil() != null) { setHiddenUntil(repeatInfo.shiftDate(getHiddenUntil())); - if (getPreferredDueDate() != null) + } + if (getPreferredDueDate() != null) { setPreferredDueDate(repeatInfo.shiftDate(getPreferredDueDate())); + } setProgressPercentage(0); // set elapsed time to 0... yes, we're losing data setElapsedSeconds(0); // if no deadlines set, create one (so users don't get confused) - if (getDefiniteDueDate() == null && getPreferredDueDate() == null) + if (getDefiniteDueDate() == null && getPreferredDueDate() == null) { setPreferredDueDate(repeatInfo.shiftDate(new Date())); + } // shift fixed alerts AlertController alertController = new AlertController(context); diff --git a/astrid/src-legacy/com/timsu/astrid/data/task/TaskModelForList.java b/astrid/src-legacy/com/timsu/astrid/data/task/TaskModelForList.java index e7611fae2..42b9769d0 100644 --- a/astrid/src-legacy/com/timsu/astrid/data/task/TaskModelForList.java +++ b/astrid/src-legacy/com/timsu/astrid/data/task/TaskModelForList.java @@ -43,8 +43,9 @@ public class TaskModelForList extends AbstractTaskModel { static { HashMap indexCache = new HashMap(); columnIndexCache.put(TaskModelForList.class, indexCache); - for (int i = 0; i < FIELD_LIST.length; i++) + for (int i = 0; i < FIELD_LIST.length; i++) { indexCache.put(FIELD_LIST[i], i); + } } /** @@ -54,8 +55,9 @@ public class TaskModelForList extends AbstractTaskModel { int weight = 0; // bubble tasks with timers to the top - if (getTimerStart() != null) + if (getTimerStart() != null) { weight -= 10000; + } // importance weight += getImportance().ordinal() * 80; @@ -64,8 +66,9 @@ public class TaskModelForList extends AbstractTaskModel { if (getDefiniteDueDate() != null) { int hoursLeft = (int) ((getDefiniteDueDate().getTime() - System.currentTimeMillis()) / 1000 / 3600); - if (hoursLeft < 5 * 24) + if (hoursLeft < 5 * 24) { weight += (hoursLeft - 5 * 24); + } weight -= 20; } @@ -73,18 +76,20 @@ public class TaskModelForList extends AbstractTaskModel { if (getPreferredDueDate() != null) { int hoursLeft = (int) ((getPreferredDueDate().getTime() - System.currentTimeMillis()) / 1000 / 3600); - if (hoursLeft < 5 * 24) + if (hoursLeft < 5 * 24) { weight += (hoursLeft - 5 * 24) / 2; + } weight -= 10; } // bubble completed tasks to the bottom if (isTaskCompleted()) { - if (getCompletionDate() == null) + if (getCompletionDate() == null) { weight += 1e6; - else + } else { weight = (int) Math.max(10000 + (System.currentTimeMillis() - getCompletionDate().getTime()) / 1000, 10000); + } return weight; } diff --git a/astrid/src-legacy/com/timsu/astrid/utilities/LegacyTasksXmlExporter.java b/astrid/src-legacy/com/timsu/astrid/utilities/LegacyTasksXmlExporter.java index c7d8b69a6..a13c23ecb 100644 --- a/astrid/src-legacy/com/timsu/astrid/utilities/LegacyTasksXmlExporter.java +++ b/astrid/src-legacy/com/timsu/astrid/utilities/LegacyTasksXmlExporter.java @@ -84,8 +84,9 @@ public class LegacyTasksXmlExporter { throws IOException { LinkedList tags = tagController.getTaskTags(task); for (TagIdentifier tag : tags) { - if (!tagMap.containsKey(tag) || tagMap.get(tag) == null) + if (!tagMap.containsKey(tag) || tagMap.get(tag) == null) { continue; + } xml.startTag(null, TAG_TAG); xml.attribute(null, TAG_ATTR_NAME, tagMap.get(tag).toString()); xml.endTag(null, TAG_TAG); diff --git a/astrid/src/com/todoroo/astrid/activity/AddOnActivity.java b/astrid/src/com/todoroo/astrid/activity/AddOnActivity.java index d00f14381..20ef64fca 100644 --- a/astrid/src/com/todoroo/astrid/activity/AddOnActivity.java +++ b/astrid/src/com/todoroo/astrid/activity/AddOnActivity.java @@ -121,36 +121,41 @@ public class AddOnActivity extends SherlockFragmentActivity { private void populate() { AddOn[] list = addOnService.getAddOns(); - if (list == null) + if (list == null) { return; + } ArrayList installed = new ArrayList(); ArrayList available = new ArrayList(); for (AddOn addOn : list) { if (AddOnService.POWER_PACK_PACKAGE.equals(addOn.getPackageName())) { - if (addOnService.hasPowerPack()) + if (addOnService.hasPowerPack()) { installed.add(addOn); - else if (Constants.MARKET_STRATEGY.generateMarketLink(addOn.getPackageName()) != null) + } else if (Constants.MARKET_STRATEGY.generateMarketLink(addOn.getPackageName()) != null) { available.add(addOn); + } } else { - if (addOnService.isInstalled(addOn)) + if (addOnService.isInstalled(addOn)) { installed.add(addOn); - else if (Constants.MARKET_STRATEGY.generateMarketLink(addOn.getPackageName()) != null) + } else if (Constants.MARKET_STRATEGY.generateMarketLink(addOn.getPackageName()) != null) { available.add(addOn); + } } } ListView installedList = (ListView) installedView.findViewById(R.id.list); installedList.setAdapter(new AddOnAdapter(this, true, installed)); - if (installed.size() > 0) + if (installed.size() > 0) { installedView.findViewById(R.id.empty).setVisibility(View.GONE); + } ListView availableList = (ListView) availableView.findViewById(R.id.list); availableList.setAdapter(new AddOnAdapter(this, false, available)); - if (available.size() > 0) + if (available.size() > 0) { availableView.findViewById(R.id.empty).setVisibility(View.GONE); + } } /** @@ -169,8 +174,9 @@ public class AddOnActivity extends SherlockFragmentActivity { AddOnActivity.class); intent.putExtra(AddOnActivity.TOKEN_START_WITH_AVAILABLE, true); activity.startActivity(intent); - if (finish) + if (finish) { activity.finish(); + } } }; } diff --git a/astrid/src/com/todoroo/astrid/activity/AstridActivity.java b/astrid/src/com/todoroo/astrid/activity/AstridActivity.java index ee8631b47..83584a8c8 100644 --- a/astrid/src/com/todoroo/astrid/activity/AstridActivity.java +++ b/astrid/src/com/todoroo/astrid/activity/AstridActivity.java @@ -192,17 +192,20 @@ public class AstridActivity extends SherlockFragmentActivity setIntent(intent); Bundle extras = intent.getExtras(); - if (extras != null) + if (extras != null) { extras = (Bundle) extras.clone(); + } return extras; } public void setupActivityFragment(TagData tagData) { - if (fragmentLayout == LAYOUT_SINGLE) + if (fragmentLayout == LAYOUT_SINGLE) { return; + } - if (fragmentLayout == LAYOUT_TRIPLE) + if (fragmentLayout == LAYOUT_TRIPLE) { findViewById(R.id.taskedit_fragment_container).setVisibility(View.VISIBLE); + } FragmentManager manager = getSupportFragmentManager(); FragmentTransaction transaction = manager.beginTransaction(); @@ -214,8 +217,9 @@ public class AstridActivity extends SherlockFragmentActivity public void setupTasklistFragmentWithFilter(Filter filter, Bundle extras) { Class customTaskList = null; - if (SubtasksHelper.shouldUseSubtasksFragmentForFilter(filter)) + if (SubtasksHelper.shouldUseSubtasksFragmentForFilter(filter)) { customTaskList = SubtasksHelper.subtasksClassForFilter(filter); + } setupTasklistFragmentWithFilterAndCustomTaskList(filter, extras, customTaskList); } @@ -244,14 +248,16 @@ public class AstridActivity extends SherlockFragmentActivity @Override public void onTaskListItemClicked(long taskId) { Task task = taskDao.fetch(taskId, Task.IS_READONLY, Task.IS_PUBLIC, Task.USER_ID); - if (task != null) + if (task != null) { onTaskListItemClicked(taskId, task.isEditable()); + } } public void onTaskListItemClicked(String uuid) { Task task = taskDao.fetch(uuid, Task.ID, Task.IS_READONLY, Task.IS_PUBLIC, Task.USER_ID); - if (task != null) + if (task != null) { onTaskListItemClicked(task.getId(), task.isEditable()); + } } @Override @@ -267,8 +273,9 @@ public class AstridActivity extends SherlockFragmentActivity Intent intent = new Intent(this, TaskEditActivity.class); intent.putExtra(TaskEditFragment.TOKEN_ID, taskId); getIntent().putExtra(TaskEditFragment.TOKEN_ID, taskId); // Needs to be in activity intent so that TEA onResume doesn't create a blank activity - if (getIntent().hasExtra(TaskListFragment.TOKEN_FILTER)) + if (getIntent().hasExtra(TaskListFragment.TOKEN_FILTER)) { intent.putExtra(TaskListFragment.TOKEN_FILTER, getIntent().getParcelableExtra(TaskListFragment.TOKEN_FILTER)); + } if (fragmentLayout != LAYOUT_SINGLE) { TaskEditFragment editActivity = getTaskEditFragment(); @@ -293,8 +300,9 @@ public class AstridActivity extends SherlockFragmentActivity } TaskListFragment tlf = getTaskListFragment(); - if (tlf != null) + if (tlf != null) { tlf.loadTaskListContent(true); + } } else { startActivityForResult(intent, TaskListFragment.ACTIVITY_EDIT_TASK); @@ -311,8 +319,9 @@ public class AstridActivity extends SherlockFragmentActivity @Override public void onBackPressed() { - if (isFinishing()) + if (isFinishing()) { return; + } super.onBackPressed(); } @@ -343,19 +352,22 @@ public class AstridActivity extends SherlockFragmentActivity FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); if (container == 0) { - if (oldFragment != null && replace) + if (oldFragment != null && replace) { ft.remove(oldFragment); + } ft.add(fragment, tag); - } else + } else { ft.replace(container, fragment, tag); + } ft.commit(); - if (createImmediate) + if (createImmediate) { runOnUiThread(new Runnable() { @Override public void run() { fm.executePendingTransactions(); } }); + } } return fragment; } @@ -366,8 +378,9 @@ public class AstridActivity extends SherlockFragmentActivity TaskListFragment tlf = getTaskListFragment(); if (tlf != null) { EditText box = tlf.quickAddBar.getQuickAddBox(); - if (box != null) + if (box != null) { box.setText(result); + } } } @@ -379,8 +392,9 @@ public class AstridActivity extends SherlockFragmentActivity QuickAddBar quickAdd = tlf.quickAddBar; if (quickAdd != null) { VoiceRecognizer vr = quickAdd.getVoiceRecognizer(); - if (vr != null) + if (vr != null) { vr.cancel(); + } } } @@ -398,8 +412,9 @@ public class AstridActivity extends SherlockFragmentActivity break; } - if (errorStr > 0) + if (errorStr > 0) { DialogUtilities.okDialog(this, getString(errorStr), null); + } } public void switchToActiveTasks() { diff --git a/astrid/src/com/todoroo/astrid/activity/BeastModePreferences.java b/astrid/src/com/todoroo/astrid/activity/BeastModePreferences.java index 484947caf..45358fa5a 100644 --- a/astrid/src/com/todoroo/astrid/activity/BeastModePreferences.java +++ b/astrid/src/com/todoroo/astrid/activity/BeastModePreferences.java @@ -48,11 +48,13 @@ public class BeastModePreferences extends ListActivity { * @param c */ public static void assertHideUntilSectionExists(Context c, long latestSetVersion) { - if (latestSetVersion == 0) + if (latestSetVersion == 0) { Preferences.setBoolean(BEAST_MODE_ASSERTED_HIDE_ALWAYS, true); + } - if (Preferences.getBoolean(BEAST_MODE_ASSERTED_HIDE_ALWAYS, false)) + if (Preferences.getBoolean(BEAST_MODE_ASSERTED_HIDE_ALWAYS, false)) { return; + } String order = Preferences.getStringValue(BEAST_MODE_ORDER_PREF); String hideSectionPref = c.getString(R.string.TEA_ctrl_hide_section_pref); @@ -61,8 +63,9 @@ public class BeastModePreferences extends ListActivity { String[] items = c.getResources().getStringArray(R.array.TEA_control_sets_prefs); StringBuilder builder = new StringBuilder(); for (String item : items) { - if (item.equals(hideSectionPref)) + if (item.equals(hideSectionPref)) { continue; + } builder.append(item); builder.append(BEAST_MODE_PREF_ITEM_SEPARATOR); } @@ -79,11 +82,13 @@ public class BeastModePreferences extends ListActivity { } public static void setDefaultLiteModeOrder(Context context, boolean force) { - if (Preferences.getStringValue(BEAST_MODE_ORDER_PREF) != null && !force) + if (Preferences.getStringValue(BEAST_MODE_ORDER_PREF) != null && !force) { return; + } - if (force) + if (force) { Preferences.clear(BEAST_MODE_ORDER_PREF); + } ArrayList list = constructOrderedControlList(context); String moreSeparator = context.getResources().getString(R.string.TEA_ctrl_more_pref); String hideSeparator = context.getResources().getString(R.string.TEA_ctrl_hide_section_pref); @@ -100,10 +105,11 @@ public class BeastModePreferences extends ListActivity { list.remove(hideSeparator); moreIndex = list.indexOf(moreSeparator); - if (moreIndex >= 0) + if (moreIndex >= 0) { list.add(moreIndex, hideSeparator); - else + } else { list.add(hideSeparator); + } StringBuilder newSetting = new StringBuilder(30); for (String item : list) { @@ -114,11 +120,13 @@ public class BeastModePreferences extends ListActivity { } public static void setDefaultOrder(Context context, boolean force) { - if (Preferences.getStringValue(BEAST_MODE_ORDER_PREF) != null && !force) + if (Preferences.getStringValue(BEAST_MODE_ORDER_PREF) != null && !force) { return; + } - if (force) + if (force) { Preferences.clear(BEAST_MODE_ORDER_PREF); + } ArrayList list = constructOrderedControlList(context); StringBuilder newSetting = new StringBuilder(30); for (String item : list) { @@ -185,10 +193,12 @@ public class BeastModePreferences extends ListActivity { private void resetToDefault() { String[] prefsArray = getResources().getStringArray(R.array.TEA_control_sets_prefs); - while (items.size() > 0) + while (items.size() > 0) { items.remove(0); - for (String s : prefsArray) + } + for (String s : prefsArray) { items.add(s); + } adapter.notifyDataSetChanged(); } @@ -219,13 +229,15 @@ public class BeastModePreferences extends ListActivity { } } - if (order == null) + if (order == null) { return list; + } itemsArray = context.getResources().getStringArray(R.array.TEA_control_sets_prefs); for (int i = 0; i < itemsArray.length; i++) { - if (!list.contains(itemsArray[i])) + if (!list.contains(itemsArray[i])) { list.add(i, itemsArray[i]); + } } return list; } diff --git a/astrid/src/com/todoroo/astrid/activity/EditPreferences.java b/astrid/src/com/todoroo/astrid/activity/EditPreferences.java index 7509bad04..1ac88acb8 100644 --- a/astrid/src/com/todoroo/astrid/activity/EditPreferences.java +++ b/astrid/src/com/todoroo/astrid/activity/EditPreferences.java @@ -259,8 +259,9 @@ public class EditPreferences extends TodorooPreferenceActivity { public static void removeForbiddenPreferences(PreferenceScreen screen, Resources r) { int[] forbiddenPrefs = Constants.MARKET_STRATEGY.excludedSettings(); - if (forbiddenPrefs == null) + if (forbiddenPrefs == null) { return; + } for (int i : forbiddenPrefs) { searchForAndRemovePreference(screen, r.getString(i)); } @@ -357,21 +358,24 @@ public class EditPreferences extends TodorooPreferenceActivity { resolveInfo.activityInfo.name); if (GtasksPreferences.class.getName().equals(resolveInfo.activityInfo.name) - && AmazonMarketStrategy.isKindleFire()) + && AmazonMarketStrategy.isKindleFire()) { continue; + } Preference preference = new Preference(this); preference.setTitle(resolveInfo.activityInfo.loadLabel(pm)); Bundle metadata = resolveInfo.activityInfo.metaData; if (metadata != null) { int resource = metadata.getInt("summary", 0); //$NON-NLS-1$ - if (resource > 0) + if (resource > 0) { preference.setSummary(resource); + } } try { Class intentComponent = Class.forName(intent.getComponent().getClassName()); - if (intentComponent.getSuperclass().equals(SyncProviderPreferences.class)) + if (intentComponent.getSuperclass().equals(SyncProviderPreferences.class)) { intentComponent = SyncProviderPreferences.class; + } if (PREFERENCE_REQUEST_CODES.containsKey(intentComponent)) { final int code = PREFERENCE_REQUEST_CODES.get(intentComponent); preference.setOnPreferenceClickListener(new OnPreferenceClickListener() { @@ -390,26 +394,30 @@ public class EditPreferences extends TodorooPreferenceActivity { String category = MetadataHelper.resolveActivityCategoryName(resolveInfo, pm); - if (!categoryPreferences.containsKey(category)) + if (!categoryPreferences.containsKey(category)) { categoryPreferences.put(category, new ArrayList()); + } ArrayList arrayList = categoryPreferences.get(category); arrayList.add(preference); } for (Entry> entry : categoryPreferences.entrySet()) { if (entry.getKey().equals(getString(R.string.app_name))) { - for (Preference preference : entry.getValue()) + for (Preference preference : entry.getValue()) { screen.addPreference(preference); + } } else { PreferenceManager manager = getPreferenceManager(); PreferenceScreen header = manager.createPreferenceScreen(this); header.setTitle(entry.getKey()); - if (entry.getKey().equals(getString(R.string.SyP_label))) + if (entry.getKey().equals(getString(R.string.SyP_label))) { header.setSummary(R.string.SyP_summary); + } screen.addPreference(header); - for (Preference preference : entry.getValue()) + for (Preference preference : entry.getValue()) { header.addPreference(preference); + } } @@ -418,8 +426,9 @@ public class EditPreferences extends TodorooPreferenceActivity { @SuppressWarnings("nls") private void addDebugPreferences() { - if (!Constants.DEBUG) + if (!Constants.DEBUG) { return; + } PreferenceCategory group = new PreferenceCategory(this); group.setTitle("DEBUG"); @@ -528,29 +537,33 @@ public class EditPreferences extends TodorooPreferenceActivity { }); } else if (r.getString(R.string.p_showNotes).equals(preference.getKey())) { - if (value != null && !(Boolean) value) + if (value != null && !(Boolean) value) { preference.setSummary(R.string.EPr_showNotes_desc_disabled); - else + } 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) + if (value != null && (Boolean) value) { preference.setSummary(R.string.EPr_fullTask_desc_enabled); - else + } 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)) + if (value instanceof String && !TextUtils.isEmpty((String) value)) { index = AndroidUtilities.indexOf(r.getStringArray(R.array.EPr_theme_settings), (String) value); - if (index < 0) + } + if (index < 0) { index = 0; + } preference.setSummary(getString(R.string.EPr_theme_desc, r.getStringArray(R.array.EPr_themes)[index])); } @@ -560,10 +573,12 @@ public class EditPreferences extends TodorooPreferenceActivity { preference.setSummary(R.string.EPr_theme_desc_unsupported); } else { int index = 0; - if (value instanceof String && !TextUtils.isEmpty((String) value)) + if (value instanceof String && !TextUtils.isEmpty((String) value)) { index = AndroidUtilities.indexOf(r.getStringArray(R.array.EPr_theme_widget_settings), (String) value); - if (index < 0) + } + if (index < 0) { index = 0; + } preference.setSummary(getString(R.string.EPr_theme_desc, r.getStringArray(R.array.EPr_themes_widget)[index])); } @@ -578,19 +593,21 @@ public class EditPreferences extends TodorooPreferenceActivity { } preference.setSummary(r.getString(R.string.p_files_dir_desc, dir)); } 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_field_missed_calls, - R.string.MCA_missed_calls_pref_desc_disabled, R.string.MCA_missed_calls_pref_desc_enabled)) + R.string.EPr_statistics_desc_disabled, R.string.EPr_statistics_desc_enabled)) { + ; + } else if (booleanPreference(preference, value, R.string.p_field_missed_calls, + R.string.MCA_missed_calls_pref_desc_disabled, R.string.MCA_missed_calls_pref_desc_enabled)) { + ; + } else if (booleanPreference(preference, value, R.string.p_calendar_reminders, + R.string.CRA_calendar_reminders_pref_desc_disabled, R.string.CRA_calendar_reminders_pref_desc_enabled)) { ; - else if (booleanPreference(preference, value, R.string.p_calendar_reminders, - R.string.CRA_calendar_reminders_pref_desc_disabled, R.string.CRA_calendar_reminders_pref_desc_enabled)) + } else if (booleanPreference(preference, value, R.string.p_use_contact_picker, + R.string.EPr_use_contact_picker_desc_disabled, R.string.EPr_use_contact_picker_desc_enabled)) { ; - else if (booleanPreference(preference, value, R.string.p_use_contact_picker, - R.string.EPr_use_contact_picker_desc_disabled, R.string.EPr_use_contact_picker_desc_enabled)) + } else if (booleanPreference(preference, value, R.string.p_end_at_deadline, + R.string.EPr_cal_end_at_due_time, R.string.EPr_cal_start_at_due_time)) { ; - else if (booleanPreference(preference, value, R.string.p_end_at_deadline, - R.string.EPr_cal_end_at_due_time, R.string.EPr_cal_start_at_due_time)) ; - else if (r.getString(R.string.p_swipe_lists_enabled).equals(preference.getKey())) { + } else if (r.getString(R.string.p_swipe_lists_enabled).equals(preference.getKey())) { preference.setOnPreferenceChangeListener(new SetResultOnPreferenceChangeListener(RESULT_CODE_PERFORMANCE_PREF_CHANGED) { @Override public boolean onPreferenceChange(Preference p, Object newValue) { @@ -609,16 +626,18 @@ public class EditPreferences extends TodorooPreferenceActivity { } }); } else if (r.getString(R.string.p_voiceInputEnabled).equals(preference.getKey())) { - if (value != null && !(Boolean) value) + if (value != null && !(Boolean) value) { preference.setSummary(R.string.EPr_voiceInputEnabled_desc_disabled); - else + } 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) + if (value != null && !(Boolean) value) { preference.setSummary(R.string.EPr_voiceRemindersEnabled_desc_disabled); - else + } else { preference.setSummary(R.string.EPr_voiceRemindersEnabled_desc_enabled); + } onVoiceReminderStatusChanged(preference, (Boolean) value); } } @@ -626,10 +645,11 @@ public class EditPreferences extends TodorooPreferenceActivity { protected boolean booleanPreference(Preference preference, Object value, int key, int disabledString, int enabledString) { if (getString(key).equals(preference.getKey())) { - if (value != null && !(Boolean) value) + if (value != null && !(Boolean) value) { preference.setSummary(disabledString); - else + } else { preference.setSummary(enabledString); + } return true; } return false; @@ -691,8 +711,9 @@ public class EditPreferences extends TodorooPreferenceActivity { findPreference(getString(R.string.p_calendar_reminders)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { - if (newValue != null && ((Boolean) newValue)) + if (newValue != null && ((Boolean) newValue)) { CalendarStartupReceiver.scheduleCalendarAlarms(EditPreferences.this, true); + } return true; } }); @@ -737,8 +758,9 @@ public class EditPreferences extends TodorooPreferenceActivity { private void onVoiceReminderStatusChanged(final Preference preference, boolean newValue) { try { VoiceOutputService.getVoiceOutputInstance(); - if (newValue) + if (newValue) { VoiceOutputService.getVoiceOutputInstance().checkIsTTSInstalled(); + } } catch (VerifyError e) { // doesn't work :( preference.setEnabled(false); @@ -747,11 +769,13 @@ public class EditPreferences extends TodorooPreferenceActivity { } private void onVoiceInputStatusChanged(final Preference preference, boolean newValue) { - if (!newValue) + if (!newValue) { return; + } int[] excludedSettings = Constants.MARKET_STRATEGY.excludedSettings(); - if (excludedSettings != null && AndroidUtilities.indexOf(excludedSettings, R.string.p_voiceInputEnabled) >= 0) + if (excludedSettings != null && AndroidUtilities.indexOf(excludedSettings, R.string.p_voiceInputEnabled) >= 0) { return; + } final Resources r = getResources(); if (!VoiceRecognizer.voiceInputAvailable(this)) { diff --git a/astrid/src/com/todoroo/astrid/activity/Eula.java b/astrid/src/com/todoroo/astrid/activity/Eula.java index a66c683f0..df0c57ba2 100644 --- a/astrid/src/com/todoroo/astrid/activity/Eula.java +++ b/astrid/src/com/todoroo/astrid/activity/Eula.java @@ -50,8 +50,9 @@ public final class Eula { * @param activity The Activity to finish if the user rejects the EULA */ public static void showEula(final Activity activity) { - if (!new Eula().shouldShowEula(activity)) + if (!new Eula().shouldShowEula(activity)) { return; + } final AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.DLG_eula_title); @@ -89,15 +90,18 @@ public final class Eula { } private boolean shouldShowEula(Activity activity) { - if (Preferences.getBoolean(PREFERENCE_EULA_ACCEPTED, false)) + 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)) + if (p.getBoolean(PREFERENCE_EULA_ACCEPTED, false)) { return false; + } - if (taskService.countTasks() > 0) + if (taskService.countTasks() > 0) { return false; + } return true; } diff --git a/astrid/src/com/todoroo/astrid/activity/FilterListFragment.java b/astrid/src/com/todoroo/astrid/activity/FilterListFragment.java index 4460cd200..2f83d9bc1 100644 --- a/astrid/src/com/todoroo/astrid/activity/FilterListFragment.java +++ b/astrid/src/com/todoroo/astrid/activity/FilterListFragment.java @@ -146,8 +146,9 @@ public class FilterListFragment extends SherlockListFragment { if (AstridPreferences.useTabletLayout(activity)) { adapter.filterStyle = R.style.TextAppearance_FLA_Filter_Tablet; return R.layout.filter_list_activity_3pane; - } else + } else { return R.layout.filter_list_activity; + } } @Override @@ -160,16 +161,18 @@ public class FilterListFragment extends SherlockListFragment { //ImageView backButton = (ImageView) getView().findViewById(R.id.back); newListButton = getView().findViewById(R.id.new_list_button); - if (newListButton != null) + if (newListButton != null) { newListButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = TagsPlugin.newTagDialog(getActivity()); getActivity().startActivityForResult(intent, REQUEST_NEW_LIST); - if (!AstridPreferences.useTabletLayout(getActivity())) + if (!AstridPreferences.useTabletLayout(getActivity())) { AndroidUtilities.callOverridePendingTransition(getActivity(), R.anim.slide_left_in, R.anim.slide_left_out); + } } }); + } setUpList(); } @@ -192,8 +195,9 @@ public class FilterListFragment extends SherlockListFragment { public void onResume() { super.onResume(); StatisticsService.sessionStart(getActivity()); - if (adapter != null) + if (adapter != null) { adapter.registerRecevier(); + } // also load sync actions Activity activity = getActivity(); @@ -214,8 +218,9 @@ public class FilterListFragment extends SherlockListFragment { public void onPause() { StatisticsService.sessionPause(); super.onPause(); - if (adapter != null) + if (adapter != null) { adapter.unregisterRecevier(); + } try { getActivity().unregisterReceiver(refreshReceiver); } catch (IllegalArgumentException e) { @@ -302,14 +307,16 @@ public class FilterListFragment extends SherlockListFragment { } for (int i = 0; i < item.contextMenuLabels.length; i++) { - if (item.contextMenuIntents.length <= i) + if (item.contextMenuIntents.length <= i) { break; + } menuItem = menu.add(0, CONTEXT_MENU_INTENT, 0, item.contextMenuLabels[i]); menuItem.setIntent(item.contextMenuIntents[i]); } - if (menu.size() > 0) + if (menu.size() > 0) { menu.setHeaderTitle(item.listingTitle); + } } /** @@ -319,15 +326,17 @@ public class FilterListFragment extends SherlockListFragment { * @param label */ private static void createShortcut(Activity activity, Filter filter, Intent shortcutIntent, String label) { - if (label.length() == 0) + if (label.length() == 0) { return; + } String defaultImageId = filter.listingTitle; if (filter instanceof FilterWithUpdate) { FilterWithUpdate fwu = (FilterWithUpdate) filter; Bundle customExtras = fwu.customExtras; - if (customExtras != null && customExtras.containsKey(TagViewFragment.EXTRA_TAG_UUID)) + if (customExtras != null && customExtras.containsKey(TagViewFragment.EXTRA_TAG_UUID)) { defaultImageId = customExtras.getString(TagViewFragment.EXTRA_TAG_UUID); + } } Bitmap bitmap = superImposeListIcon(activity, filter.listingIcon, defaultImageId); @@ -345,9 +354,10 @@ public class FilterListFragment extends SherlockListFragment { public static Bitmap superImposeListIcon(Activity activity, Bitmap listingIcon, String uuid) { Bitmap emblem = listingIcon; - if (emblem == null) + if (emblem == null) { emblem = ((BitmapDrawable) activity.getResources().getDrawable( TagService.getDefaultImageIDForTag(uuid))).getBitmap(); + } // create icon by superimposing astrid w/ icon DisplayMetrics metrics = new DisplayMetrics(); @@ -377,8 +387,9 @@ public class FilterListFragment extends SherlockListFragment { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); final Intent shortcutIntent = item.getIntent(); FilterListItem filter = ((FilterAdapter.ViewHolder) info.targetView.getTag()).item; - if (filter instanceof Filter) + if (filter instanceof Filter) { showCreateShortcutDialog(getActivity(), shortcutIntent, (Filter) filter); + } return true; } @@ -389,8 +400,9 @@ public class FilterListFragment extends SherlockListFragment { } default: { TaskListFragment tasklist = (TaskListFragment) getActivity().getSupportFragmentManager().findFragmentByTag(TaskListFragment.TAG_TASKLIST_FRAGMENT); - if (tasklist != null && tasklist.isInLayout()) + if (tasklist != null && tasklist.isInLayout()) { return tasklist.onOptionsItemSelected(item); + } } } return false; @@ -401,8 +413,9 @@ public class FilterListFragment extends SherlockListFragment { FrameLayout frameLayout = new FrameLayout(activity); frameLayout.setPadding(10, 0, 10, 0); final EditText editText = new EditText(activity); - if (filter.listingTitle == null) + if (filter.listingTitle == null) { filter.listingTitle = ""; //$NON-NLS-1$ + } editText.setText(filter.listingTitle. replaceAll("\\(\\d+\\)$", "").trim()); //$NON-NLS-1$ //$NON-NLS-2$ frameLayout.addView(editText, new FrameLayout.LayoutParams( @@ -463,8 +476,9 @@ public class FilterListFragment extends SherlockListFragment { protected class RefreshReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { - if (intent == null || !AstridApiConstants.BROADCAST_EVENT_REFRESH.equals(intent.getAction())) + if (intent == null || !AstridApiConstants.BROADCAST_EVENT_REFRESH.equals(intent.getAction())) { return; + } Activity activity = getActivity(); if (activity != null) { diff --git a/astrid/src/com/todoroo/astrid/activity/ShareLinkActivity.java b/astrid/src/com/todoroo/astrid/activity/ShareLinkActivity.java index 641e30736..ac5dcbe1a 100644 --- a/astrid/src/com/todoroo/astrid/activity/ShareLinkActivity.java +++ b/astrid/src/com/todoroo/astrid/activity/ShareLinkActivity.java @@ -38,8 +38,9 @@ public final class ShareLinkActivity extends TaskListActivity { Intent callerIntent = getIntent(); subject = callerIntent.getStringExtra(Intent.EXTRA_SUBJECT); - if (subject == null) + if (subject == null) { subject = ""; //$NON-NLS-1$ + } } @Override diff --git a/astrid/src/com/todoroo/astrid/activity/ShortcutActivity.java b/astrid/src/com/todoroo/astrid/activity/ShortcutActivity.java index 76add5f91..8d824aeea 100644 --- a/astrid/src/com/todoroo/astrid/activity/ShortcutActivity.java +++ b/astrid/src/com/todoroo/astrid/activity/ShortcutActivity.java @@ -104,8 +104,9 @@ public class ShortcutActivity extends Activity { Intent taskListIntent = new Intent(this, TaskListActivity.class); - if (extras != null && extras.containsKey(TaskListActivity.TOKEN_SOURCE)) + if (extras != null && extras.containsKey(TaskListActivity.TOKEN_SOURCE)) { taskListIntent.putExtra(TaskListActivity.TOKEN_SOURCE, extras.getInt(TaskListActivity.TOKEN_SOURCE)); + } if (extras != null && extras.containsKey(TOKEN_CUSTOM_CLASS)) { taskListIntent.putExtras(intent.getExtras()); @@ -116,28 +117,30 @@ public class ShortcutActivity extends Activity { String title = extras.getString(TOKEN_FILTER_TITLE); String sql = extras.getString(TOKEN_FILTER_SQL); ContentValues values = null; - if (extras.containsKey(TOKEN_FILTER_VALUES)) + if (extras.containsKey(TOKEN_FILTER_VALUES)) { values = AndroidUtilities.contentValuesFromString(extras.getString(TOKEN_FILTER_VALUES)); - else { + } else { values = new ContentValues(); for (String key : extras.keySet()) { - if (!key.startsWith(TOKEN_FILTER_VALUES_ITEM)) + if (!key.startsWith(TOKEN_FILTER_VALUES_ITEM)) { continue; + } Object value = extras.get(key); key = key.substring(TOKEN_FILTER_VALUES_ITEM.length()); // assume one of the big 4... - if (value instanceof String) + if (value instanceof String) { values.put(key, (String) value); - else if (value instanceof Integer) + } else if (value instanceof Integer) { values.put(key, (Integer) value); - else if (value instanceof Double) + } else if (value instanceof Double) { values.put(key, (Double) value); - else if (value instanceof Long) + } else if (value instanceof Long) { values.put(key, (Long) value); - else + } else { throw new IllegalStateException("Unsupported bundle type " + value.getClass()); //$NON-NLS-1$ + } } } @@ -146,14 +149,16 @@ public class ShortcutActivity extends Activity { if (extras.containsKey(TOKEN_IMAGE_URL)) { filter = new FilterWithUpdate(title, title, sql, values); ((FilterWithUpdate) filter).imageUrl = extras.getString(TOKEN_IMAGE_URL); - } else + } else { filter = new FilterWithCustomIntent(title, title, sql, values); + } Bundle customExtras = new Bundle(); Set keys = extras.keySet(); for (String key : keys) { - if (AndroidUtilities.indexOf(CUSTOM_EXTRAS, key) < 0) + if (AndroidUtilities.indexOf(CUSTOM_EXTRAS, key) < 0) { AndroidUtilities.putInto(customExtras, key, extras.get(key), false); + } } ((FilterWithCustomIntent) filter).customExtras = customExtras; // Something @@ -182,13 +187,15 @@ public class ShortcutActivity extends Activity { if (filter instanceof FilterWithCustomIntent) { FilterWithCustomIntent customFilter = ((FilterWithCustomIntent) filter); - if (customFilter.customExtras != null) + if (customFilter.customExtras != null) { shortcutIntent.putExtras(customFilter.customExtras); + } shortcutIntent.putExtra(TOKEN_CUSTOM_CLASS, customFilter.customTaskList.flattenToString()); if (filter instanceof FilterWithUpdate) { FilterWithUpdate filterWithUpdate = (FilterWithUpdate) filter; - if (filterWithUpdate.imageUrl != null) + if (filterWithUpdate.imageUrl != null) { shortcutIntent.putExtra(TOKEN_IMAGE_URL, filterWithUpdate.imageUrl); + } } } @@ -209,16 +216,17 @@ public class ShortcutActivity extends Activity { private static void putExtra(Intent intent, String key, Object value) { // assume one of the big 4... - if (value instanceof String) + if (value instanceof String) { intent.putExtra(key, (String) value); - else if (value instanceof Integer) + } else if (value instanceof Integer) { intent.putExtra(key, (Integer) value); - else if (value instanceof Double) + } else if (value instanceof Double) { intent.putExtra(key, (Double) value); - else if (value instanceof Long) + } else if (value instanceof Long) { intent.putExtra(key, (Long) value); - else + } else { throw new IllegalStateException( "Unsupported bundle type " + value.getClass()); //$NON-NLS-1$ + } } } diff --git a/astrid/src/com/todoroo/astrid/activity/SortSelectionActivity.java b/astrid/src/com/todoroo/astrid/activity/SortSelectionActivity.java index 952f8dcc4..eaf158650 100644 --- a/astrid/src/com/todoroo/astrid/activity/SortSelectionActivity.java +++ b/astrid/src/com/todoroo/astrid/activity/SortSelectionActivity.java @@ -37,21 +37,26 @@ public class SortSelectionActivity { OnSortSelectedListener listener, int flags, int sort) { View body = activity.getLayoutInflater().inflate(R.layout.sort_selection_dialog, null); - if ((flags & SortHelper.FLAG_REVERSE_SORT) > 0) + if ((flags & SortHelper.FLAG_REVERSE_SORT) > 0) { ((CheckBox) body.findViewById(R.id.reverse)).setChecked(true); - if ((flags & SortHelper.FLAG_SHOW_COMPLETED) > 0) + } + if ((flags & SortHelper.FLAG_SHOW_COMPLETED) > 0) { ((CheckBox) body.findViewById(R.id.completed)).setChecked(true); - if ((flags & SortHelper.FLAG_SHOW_HIDDEN) > 0) + } + if ((flags & SortHelper.FLAG_SHOW_HIDDEN) > 0) { ((CheckBox) body.findViewById(R.id.hidden)).setChecked(true); - if ((flags & SortHelper.FLAG_SHOW_DELETED) > 0) + } + if ((flags & SortHelper.FLAG_SHOW_DELETED) > 0) { ((CheckBox) body.findViewById(R.id.deleted)).setChecked(true); + } - if (!showDragDrop) + if (!showDragDrop) { body.findViewById(R.id.sort_drag).setVisibility(View.GONE); + } - if (showDragDrop && (flags & SortHelper.FLAG_DRAG_DROP) > 0) + if (showDragDrop && (flags & SortHelper.FLAG_DRAG_DROP) > 0) { ((RadioButton) body.findViewById(R.id.sort_drag)).setChecked(true); - else { + } else { switch (sort) { case SortHelper.SORT_ALPHA: ((RadioButton) body.findViewById(R.id.sort_alpha)).setChecked(true); @@ -111,27 +116,33 @@ public class SortSelectionActivity { int flags = 0; int sort = 0; - if (((CheckBox) body.findViewById(R.id.reverse)).isChecked()) + if (((CheckBox) body.findViewById(R.id.reverse)).isChecked()) { flags |= SortHelper.FLAG_REVERSE_SORT; - if (((CheckBox) body.findViewById(R.id.completed)).isChecked()) + } + if (((CheckBox) body.findViewById(R.id.completed)).isChecked()) { flags |= SortHelper.FLAG_SHOW_COMPLETED; - if (((CheckBox) body.findViewById(R.id.hidden)).isChecked()) + } + if (((CheckBox) body.findViewById(R.id.hidden)).isChecked()) { flags |= SortHelper.FLAG_SHOW_HIDDEN; - if (((CheckBox) body.findViewById(R.id.deleted)).isChecked()) + } + if (((CheckBox) body.findViewById(R.id.deleted)).isChecked()) { flags |= SortHelper.FLAG_SHOW_DELETED; - if (((RadioButton) body.findViewById(R.id.sort_drag)).isChecked()) + } + if (((RadioButton) body.findViewById(R.id.sort_drag)).isChecked()) { flags |= SortHelper.FLAG_DRAG_DROP; + } - if (((RadioButton) body.findViewById(R.id.sort_alpha)).isChecked()) + if (((RadioButton) body.findViewById(R.id.sort_alpha)).isChecked()) { sort = SortHelper.SORT_ALPHA; - else if (((RadioButton) body.findViewById(R.id.sort_due)).isChecked()) + } else if (((RadioButton) body.findViewById(R.id.sort_due)).isChecked()) { sort = SortHelper.SORT_DUE; - else if (((RadioButton) body.findViewById(R.id.sort_importance)).isChecked()) + } else if (((RadioButton) body.findViewById(R.id.sort_importance)).isChecked()) { sort = SortHelper.SORT_IMPORTANCE; - else if (((RadioButton) body.findViewById(R.id.sort_modified)).isChecked()) + } else if (((RadioButton) body.findViewById(R.id.sort_modified)).isChecked()) { sort = SortHelper.SORT_MODIFIED; - else + } else { sort = SortHelper.SORT_AUTO; + } listener.onSortSelected(always, flags, sort); } diff --git a/astrid/src/com/todoroo/astrid/activity/TaskEditActivity.java b/astrid/src/com/todoroo/astrid/activity/TaskEditActivity.java index 26d9fbe22..35cf43eec 100644 --- a/astrid/src/com/todoroo/astrid/activity/TaskEditActivity.java +++ b/astrid/src/com/todoroo/astrid/activity/TaskEditActivity.java @@ -26,10 +26,11 @@ public class TaskEditActivity extends AstridActivity { ThemeService.applyTheme(this); ActionBar actionBar = getSupportActionBar(); if (Preferences.getBoolean(R.string.p_save_and_cancel, false)) { - if (ThemeService.getTheme() == R.style.Theme_White_Alt) + if (ThemeService.getTheme() == R.style.Theme_White_Alt) { actionBar.setLogo(R.drawable.ic_menu_save_blue_alt); - else + } else { actionBar.setLogo(R.drawable.ic_menu_save); + } } else { actionBar.setLogo(null); } @@ -50,10 +51,11 @@ public class TaskEditActivity extends AstridActivity { ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { TextView title = ((TextView) actionBar.getCustomView().findViewById(R.id.title)); - if (ActFmPreferenceService.isPremiumUser()) + if (ActFmPreferenceService.isPremiumUser()) { title.setText(""); //$NON-NLS-1$ - else + } else { title.setText(isNewTask ? R.string.TEA_new_task : R.string.TAd_contextEditTask); + } } } @@ -77,8 +79,9 @@ public class TaskEditActivity extends AstridActivity { public boolean onKeyDown(int keyCode, KeyEvent event) { TaskEditFragment frag = (TaskEditFragment) getSupportFragmentManager() .findFragmentByTag(TaskEditFragment.TAG_TASKEDIT_FRAGMENT); - if (frag != null && frag.isInLayout()) + if (frag != null && frag.isInLayout()) { return frag.onKeyDown(keyCode); + } return super.onKeyDown(keyCode, event); } diff --git a/astrid/src/com/todoroo/astrid/activity/TaskEditFragment.java b/astrid/src/com/todoroo/astrid/activity/TaskEditFragment.java index 1fbba8efa..c48e449e2 100755 --- a/astrid/src/com/todoroo/astrid/activity/TaskEditFragment.java +++ b/astrid/src/com/todoroo/astrid/activity/TaskEditFragment.java @@ -360,13 +360,15 @@ public final class TaskEditFragment extends SherlockFragment implements overrideFinishAnim = false; if (activity != null) { - if (activity.getIntent() != null) + if (activity.getIntent() != null) { overrideFinishAnim = activity.getIntent().getBooleanExtra( OVERRIDE_FINISH_ANIM, true); + } } - if (activity instanceof TaskListActivity) + if (activity instanceof TaskListActivity) { ((TaskListActivity) activity).setCommentsButtonVisibility(false); + } } private void instantiateEditNotes() { @@ -389,11 +391,13 @@ public final class TaskEditFragment extends SherlockFragment implements tabStyle = TaskEditViewPager.TAB_SHOW_ACTIVITY; - if (!showEditComments) + if (!showEditComments) { tabStyle &= ~TaskEditViewPager.TAB_SHOW_ACTIVITY; + } - if (moreSectionHasControls) + if (moreSectionHasControls) { tabStyle |= TaskEditViewPager.TAB_SHOW_MORE; + } if (editNotes == null) { instantiateEditNotes(); @@ -406,8 +410,9 @@ public final class TaskEditFragment extends SherlockFragment implements timerAction.addListener(editNotes); } - if (editNotes != null) + if (editNotes != null) { editNotes.addListener(this); + } if (tabStyle == 0) { return; @@ -428,8 +433,9 @@ public final class TaskEditFragment extends SherlockFragment implements ((ViewGroup) moreControls.getParent()).removeView(moreControls); } - if (showEditComments) + if (showEditComments) { commentsBar.setVisibility(View.VISIBLE); + } moreTab.setVisibility(View.VISIBLE); setCurrentTab(TAB_VIEW_UPDATES); setPagerHeightForPosition(TAB_VIEW_UPDATES); @@ -443,8 +449,9 @@ public final class TaskEditFragment extends SherlockFragment implements } private void setCurrentTab(int position) { - if (mIndicator == null) + if (mIndicator == null) { return; + } mIndicator.setCurrentItem(position); mPager.setCurrentItem(position); @@ -647,16 +654,18 @@ public final class TaskEditFragment extends SherlockFragment implements View controlSet = null; TaskEditControlSet curr = controlSetMap.get(item); - if (curr != null) + if (curr != null) { controlSet = (LinearLayout) curr.getDisplayView(); + } if (controlSet != null) { if ((i + 1 >= itemOrder.length || itemOrder[i + 1].equals(moreSectionTrigger))) { removeTeaSeparator(controlSet); } section.addView(controlSet); - if (section == moreControls) + if (section == moreControls) { moreSectionHasControls = true; + } } if (curr != null && curr.getClass().equals(openControl) && curr instanceof PopupControlSet) { @@ -726,8 +735,9 @@ public final class TaskEditFragment extends SherlockFragment implements AndroidUtilities.sleepDeep(500L); Activity activity = getActivity(); - if (activity == null) + if (activity == null) { return; + } activity.runOnUiThread(new Runnable() { public void run() { @@ -762,8 +772,9 @@ public final class TaskEditFragment extends SherlockFragment implements if (idParam > -1L) { model = taskService.fetchById(idParam, Task.PROPERTIES); - if (model != null && model.containsNonNullValue(Task.UUID)) + if (model != null && model.containsNonNullValue(Task.UUID)) { uuid = model.getValue(Task.UUID); + } } // not found by id or was never passed an id @@ -771,8 +782,9 @@ public final class TaskEditFragment extends SherlockFragment implements String valuesAsString = intent.getStringExtra(TOKEN_VALUES); ContentValues values = null; try { - if (valuesAsString != null) + if (valuesAsString != null) { values = AndroidUtilities.contentValuesFromSerializedString(valuesAsString); + } } catch (Exception e) { // oops, can't serialize } @@ -858,32 +870,36 @@ public final class TaskEditFragment extends SherlockFragment implements private String getWomText(WaitingOnMe wom) { int resource; String type = wom.getValue(WaitingOnMe.WAIT_TYPE); - if (WaitingOnMe.WAIT_TYPE_ASSIGNED.equals(type)) + if (WaitingOnMe.WAIT_TYPE_ASSIGNED.equals(type)) { resource = R.string.wom_assigned; - else if (WaitingOnMe.WAIT_TYPE_CHANGED_DUE.equals(type)) + } else if (WaitingOnMe.WAIT_TYPE_CHANGED_DUE.equals(type)) { resource = R.string.wom_changed_due; - else if (WaitingOnMe.WAIT_TYPE_COMMENTED.equals(type)) + } else if (WaitingOnMe.WAIT_TYPE_COMMENTED.equals(type)) { resource = R.string.wom_commented; - else if (WaitingOnMe.WAIT_TYPE_MENTIONED.equals(type)) + } else if (WaitingOnMe.WAIT_TYPE_MENTIONED.equals(type)) { resource = R.string.wom_mentioned; - else if (WaitingOnMe.WAIT_TYPE_RAISED_PRI.equals(type)) + } else if (WaitingOnMe.WAIT_TYPE_RAISED_PRI.equals(type)) { resource = R.string.wom_raised_pri; - else + } else { resource = R.string.wom_default; + } String userString = null; User user = userDao.fetch(wom.getValue(WaitingOnMe.WAITING_USER_ID), User.PROPERTIES); - if (user != null) + if (user != null) { userString = user.getDisplayName(); - if (TextUtils.isEmpty(userString)) + } + if (TextUtils.isEmpty(userString)) { userString = getString(R.string.ENA_no_user); + } return getString(resource, userString); } public long getTaskIdInProgress() { - if (model != null && model.getId() > 0) + if (model != null && model.getId() > 0) { return model.getId(); + } return getActivity().getIntent().getLongExtra(TOKEN_ID, -1); } @@ -915,8 +931,9 @@ public final class TaskEditFragment extends SherlockFragment implements if (!taskAttachmentDao.taskHasAttachments(model.getUuid())) { filesControlSet.getDisplayView().setVisibility(View.GONE); } - for (TaskEditControlSet controlSet : controls) + for (TaskEditControlSet controlSet : controls) { controlSet.readFromTask(model); + } } } @@ -938,14 +955,17 @@ public final class TaskEditFragment extends SherlockFragment implements * Save task model from values in UI components */ public void save(boolean onPause) { - if (title == null) + if (title == null) { return; + } - if (title.getText().length() > 0) + if (title.getText().length() > 0) { model.setValue(Task.DELETION_DATE, 0L); + } - if (title.getText().length() == 0) + if (title.getText().length() == 0) { return; + } if (isNewTask) { taskOutstandingDao.deleteWhere(Criterion.and(TaskOutstanding.TASK_ID.eq(model.getId()), @@ -964,8 +984,9 @@ public final class TaskEditFragment extends SherlockFragment implements } } String toastText = controlSet.writeToModel(model); - if (toastText != null) + if (toastText != null) { toast.append('\n').append(toastText); + } } } @@ -994,9 +1015,12 @@ public final class TaskEditFragment extends SherlockFragment implements if (!isAssignedToMe) { data.putExtra(TOKEN_TASK_WAS_ASSIGNED, true); data.putExtra(TOKEN_ASSIGNED_TO_DISPLAY, assignedTo); - if (!TextUtils.isEmpty(assignedEmail)) + if (!TextUtils.isEmpty(assignedEmail)) { data.putExtra(TOKEN_ASSIGNED_TO_EMAIL, assignedEmail); - if (Task.isRealUserId(assignedId)) ; + } + if (Task.isRealUserId(assignedId)) { + ; + } data.putExtra(TOKEN_ASSIGNED_TO_ID, assignedId); } if (showRepeatAlert) { @@ -1009,13 +1033,15 @@ public final class TaskEditFragment extends SherlockFragment implements // Notify task list fragment in multi-column case // since the activity isn't actually finishing TaskListActivity tla = (TaskListActivity) getActivity(); - if (!isAssignedToMe) + if (!isAssignedToMe) { tla.taskAssignedTo(assignedTo, assignedEmail, assignedId); - else if (showRepeatAlert) + } else if (showRepeatAlert) { DateChangedAlerts.showRepeatChangedDialog(tla, model); + } - if (tagsChanged) + if (tagsChanged) { tla.tagsChanged(); + } tla.refreshTaskList(); } @@ -1028,10 +1054,11 @@ public final class TaskEditFragment extends SherlockFragment implements public boolean onKeyDown(int keyCode) { if (keyCode == KeyEvent.KEYCODE_BACK) { - if (title.getText().length() == 0 || !peopleControlSet.hasLoadedUI()) + if (title.getText().length() == 0 || !peopleControlSet.hasLoadedUI()) { discardButtonClick(); - else + } else { saveButtonClick(); + } return true; } return false; @@ -1142,8 +1169,9 @@ public final class TaskEditFragment extends SherlockFragment implements } else if (a instanceof TaskListActivity) { discardButtonClick(); TaskListFragment tlf = ((TaskListActivity) a).getTaskListFragment(); - if (tlf != null) + if (tlf != null) { tlf.refresh(); + } } } }).setNegativeButton(android.R.string.cancel, null).show(); @@ -1204,8 +1232,9 @@ public final class TaskEditFragment extends SherlockFragment implements if (!TextUtils.isEmpty(extension)) { MimeTypeMap map = MimeTypeMap.getSingleton(); String guessedType = map.getMimeTypeFromExtension(extension); - if (!TextUtils.isEmpty(guessedType)) + if (!TextUtils.isEmpty(guessedType)) { type = guessedType; + } } createNewFileAttachment(path, name, type); @@ -1230,8 +1259,9 @@ public final class TaskEditFragment extends SherlockFragment implements } private void createNewFileAttachment(String path, String fileName, String fileType) { - if (!ActFmPreferenceService.isPremiumUser()) + if (!ActFmPreferenceService.isPremiumUser()) { return; + } TaskAttachment attachment = TaskAttachment.createNewAttachment(model.getUuid(), path, fileName, fileType); taskAttachmentDao.createNew(attachment); @@ -1255,8 +1285,9 @@ public final class TaskEditFragment extends SherlockFragment implements startRecordingAudio(); return true; case MENU_COMMENTS_REFRESH_ID: { - if (editNotes != null) + if (editNotes != null) { editNotes.refreshData(); + } return true; } case MENU_SHOW_COMMENTS_ID: { @@ -1267,10 +1298,11 @@ public final class TaskEditFragment extends SherlockFragment implements return true; } case android.R.id.home: - if (title.getText().length() == 0) + if (title.getText().length() == 0) { discardButtonClick(); - else + } else { saveButtonClick(); + } return true; } @@ -1325,8 +1357,9 @@ public final class TaskEditFragment extends SherlockFragment implements super.onPause(); StatisticsService.sessionPause(); - if (shouldSaveState) + if (shouldSaveState) { save(true); + } } @Override @@ -1338,8 +1371,9 @@ public final class TaskEditFragment extends SherlockFragment implements @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { - if (editNotes == null) + if (editNotes == null) { instantiateEditNotes(); + } if (editNotes != null && editNotes.activityResult(requestCode, resultCode, data)) { return; @@ -1400,8 +1434,9 @@ public final class TaskEditFragment extends SherlockFragment implements private void adjustInfoPopovers() { Preferences.setBoolean(R.string.p_showed_tap_task_help, true); - if (!Preferences.isSet(getString(R.string.p_showed_lists_help))) + if (!Preferences.isSet(getString(R.string.p_showed_lists_help))) { Preferences.setBoolean(R.string.p_showed_lists_help, false); + } } /* @@ -1452,7 +1487,9 @@ public final class TaskEditFragment extends SherlockFragment implements break; } - if (view == null || mPager == null) return; + if (view == null || mPager == null) { + return; + } int desiredWidth = MeasureSpec.makeMeasureSpec(view.getWidth(), MeasureSpec.AT_MOST); @@ -1478,8 +1515,9 @@ public final class TaskEditFragment extends SherlockFragment implements } ViewGroup.LayoutParams params = view.getLayoutParams(); - if (params == null) + if (params == null) { return; + } params.height = totalHeight; view.setLayoutParams(params); @@ -1508,8 +1546,9 @@ public final class TaskEditFragment extends SherlockFragment implements // EditNoteActivity Listener when there are new updates/comments @Override public void updatesChanged() { - if (mPager != null && mPager.getCurrentItem() == TAB_VIEW_UPDATES) + if (mPager != null && mPager.getCurrentItem() == TAB_VIEW_UPDATES) { setPagerHeightForPosition(TAB_VIEW_UPDATES); + } } // EditNoteActivity Lisener when there are new updates/comments diff --git a/astrid/src/com/todoroo/astrid/activity/TaskEditViewPager.java b/astrid/src/com/todoroo/astrid/activity/TaskEditViewPager.java index 21e3a0f35..9f2d9409c 100644 --- a/astrid/src/com/todoroo/astrid/activity/TaskEditViewPager.java +++ b/astrid/src/com/todoroo/astrid/activity/TaskEditViewPager.java @@ -26,10 +26,12 @@ public class TaskEditViewPager extends PagerAdapter implements TitleProvider { public TaskEditViewPager(Context context, int tabStyleMask) { ArrayList titleList = new ArrayList(); - if ((tabStyleMask & TAB_SHOW_ACTIVITY) > 0) + if ((tabStyleMask & TAB_SHOW_ACTIVITY) > 0) { titleList.add(context.getString(R.string.TEA_tab_activity)); - if ((tabStyleMask & TAB_SHOW_MORE) > 0) + } + if ((tabStyleMask & TAB_SHOW_MORE) > 0) { titleList.add(context.getString(R.string.TEA_tab_more)); + } titles = titleList.toArray(new String[titleList.size()]); } @@ -37,10 +39,12 @@ public class TaskEditViewPager extends PagerAdapter implements TitleProvider { public static int getPageForPosition(int position, int tabStyle) { int numOnesEncountered = 0; for (int i = 0; i <= 2; i++) { - if ((tabStyle & (1 << i)) > 0) + if ((tabStyle & (1 << i)) > 0) { numOnesEncountered++; - if (numOnesEncountered == position + 1) + } + if (numOnesEncountered == position + 1) { return 1 << i; + } } return -1; } diff --git a/astrid/src/com/todoroo/astrid/activity/TaskListActivity.java b/astrid/src/com/todoroo/astrid/activity/TaskListActivity.java index ae3f7de42..f44a516b3 100644 --- a/astrid/src/com/todoroo/astrid/activity/TaskListActivity.java +++ b/astrid/src/com/todoroo/astrid/activity/TaskListActivity.java @@ -151,15 +151,17 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener public void onClick(View v) { if (fragmentLayout == LAYOUT_DOUBLE) { View container = findViewById(R.id.taskedit_fragment_container); - if (getTaskEditFragment() != null) + if (getTaskEditFragment() != null) { return; + } container.setVisibility(container.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE); commentsVisible = container.getVisibility() == View.VISIBLE; } else { // In this case we should be in LAYOUT_SINGLE--delegate to the task list fragment TaskListFragment tlf = getTaskListFragment(); - if (tlf != null) + if (tlf != null) { tlf.handleCommentsButtonClicked(); + } } } }; @@ -168,8 +170,9 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener @Override public void onClick(View v) { TaskListFragment tlf = getTaskListFragment(); - if (tlf == null || !(tlf instanceof PersonViewFragment)) + if (tlf == null || !(tlf instanceof PersonViewFragment)) { return; + } ((PersonViewFragment) tlf).handleStatusButtonClicked(); } }; @@ -184,8 +187,9 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener DependencyInjectionService.getInstance().inject(this); int contentView = getContentView(); - if (contentView == R.layout.task_list_wrapper_activity) + if (contentView == R.layout.task_list_wrapper_activity) { swipeEnabled = true; + } setContentView(contentView); ActionBar actionBar = getSupportActionBar(); @@ -199,8 +203,9 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener mainMenu = (ImageView) actionBar.getCustomView().findViewById(R.id.main_menu); personStatus = (TextView) actionBar.getCustomView().findViewById(R.id.person_image); commentsButton = (Button) actionBar.getCustomView().findViewById(R.id.comments); - if (ThemeService.getTheme() == R.style.Theme_White_Alt) + if (ThemeService.getTheme() == R.style.Theme_White_Alt) { commentsButton.setTextColor(getResources().getColor(R.color.blue_theme_color)); + } initializeFragments(actionBar); createMainMenuPopover(); @@ -209,11 +214,13 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener personStatus.setOnClickListener(friendStatusClickListener); Bundle extras = getIntent().getExtras(); - if (extras != null) + if (extras != null) { extras = (Bundle) extras.clone(); + } - if (extras == null) + if (extras == null) { extras = new Bundle(); + } Filter savedFilter = getIntent().getParcelableExtra(TaskListFragment.TOKEN_FILTER); if (Intent.ACTION_SEARCH.equals(getIntent().getAction())) { @@ -239,8 +246,9 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener setupTasklistFragmentWithFilter(savedFilter, extras); - if (savedFilter != null) + if (savedFilter != null) { setListsTitle(savedFilter.title); + } if (getIntent().hasExtra(TOKEN_SOURCE)) { trackActivitySource(); @@ -253,8 +261,9 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener private void setupPagerAdapter() { FilterListFragment flf = getFilterListFragment(); - if (flf == null) + if (flf == null) { throw new RuntimeException("Filterlist fragment was null, needs to exist to construct the fragment pager"); //$NON-NLS-1$ + } FilterAdapter adapter = flf.adapter; tlfPager = (TaskListFragmentPager) findViewById(R.id.pager); tlfPagerAdapter = new TaskListFragmentPagerAdapter(getSupportFragmentManager(), adapter); @@ -267,12 +276,13 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener } protected int getContentView() { - if (AstridPreferences.useTabletLayout(this)) + if (AstridPreferences.useTabletLayout(this)) { return R.layout.task_list_wrapper_activity_3pane; - else if (!Preferences.getBoolean(R.string.p_swipe_lists_enabled, false)) + } else if (!Preferences.getBoolean(R.string.p_swipe_lists_enabled, false)) { return R.layout.task_list_wrapper_activity_no_swipe; - else + } else { return R.layout.task_list_wrapper_activity; + } } protected Filter getDefaultFilter() { @@ -369,12 +379,13 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener private void createMainMenuPopover() { int layout; boolean isTabletLayout = AstridPreferences.useTabletLayout(this); - if (isTabletLayout) + if (isTabletLayout) { layout = R.layout.main_menu_popover_tablet; - else if (AndroidUtilities.isTabletSized(this)) + } else if (AndroidUtilities.isTabletSized(this)) { layout = R.layout.main_menu_popover_tablet_phone_layout; - else + } else { layout = R.layout.main_menu_popover; + } mainMenuPopover = new MainMenuPopover(this, layout, (fragmentLayout != LAYOUT_SINGLE), this); mainMenuPopover.setOnDismissListener(new OnDismissListener() { @@ -384,8 +395,9 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener } }); - if (isTabletLayout) + if (isTabletLayout) { mainMenuPopover.refreshFixedItems(); + } } private void setupPopoverWithFragment(FragmentPopover popover, Fragment frag, LayoutParams params) { @@ -393,12 +405,14 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener View view = frag.getView(); if (view != null) { FrameLayout parent = (FrameLayout) view.getParent(); - if (parent != null) + if (parent != null) { parent.removeView(view); - if (params == null) + } + if (params == null) { popover.setContent(view); - else + } else { popover.setContent(view, params); + } } } } @@ -409,8 +423,9 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener @Override public boolean onFilterItemClicked(FilterListItem item) { - if (listsPopover != null) + if (listsPopover != null) { listsPopover.dismiss(); + } setCommentsCount(0); if (swipeIsEnabled()) { @@ -421,8 +436,9 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener TaskEditFragment.removeExtrasFromIntent(getIntent()); TaskEditFragment tef = getTaskEditFragment(); - if (tef != null) + if (tef != null) { onBackPressed(); + } boolean result = super.onFilterItemClicked(item); filterModeSpec.onFilterItemClickedCallback(item); @@ -439,8 +455,9 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener commentsButton.setVisibility(visibility); } else { View container = findViewById(R.id.taskedit_fragment_container); - if (container != null) + if (container != null) { container.setVisibility(visibility); + } } } @@ -466,8 +483,9 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener if (!Flags.checkAndClear(Flags.TLA_DISMISSED_FROM_TASK_EDIT)) { TaskEditFragment tea = getTaskEditFragment(); - if (tea != null) + if (tea != null) { onBackPressed(); + } } if (getIntent().hasExtra(TOKEN_SWITCH_TO_FILTER)) { @@ -484,12 +502,14 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener TaskListFragment tlf = getTaskListFragment(); if (tlf != null) { Task result = tlf.quickAddBar.quickAddTask("", true); //$NON-NLS-1$ - if (result != null) + if (result != null) { onTaskListItemClicked(result.getId(), true); + } } } - if (fragmentLayout == LAYOUT_SINGLE) + if (fragmentLayout == LAYOUT_SINGLE) { getIntent().removeExtra(OPEN_TASK); + } } if (getIntent().getBooleanExtra(TOKEN_CREATE_NEW_LIST, false)) { @@ -509,11 +529,13 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener @Override public void onTaskListItemClicked(long taskId, boolean editable) { - if (fragmentLayout != LAYOUT_SINGLE && editable) + if (fragmentLayout != LAYOUT_SINGLE && editable) { getIntent().putExtra(OPEN_TASK, taskId); + } CommentsFragment tuf = getTagUpdatesFragment(); - if (tuf != null) + if (tuf != null) { tuf.getView().setVisibility(View.INVISIBLE); + } super.onTaskListItemClicked(taskId, editable); } @@ -526,8 +548,9 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener protected void onResume() { super.onResume(); - if (Preferences.getBoolean(WelcomeWalkthrough.KEY_SHOWED_WELCOME_LOGIN, false)) + if (Preferences.getBoolean(WelcomeWalkthrough.KEY_SHOWED_WELCOME_LOGIN, false)) { SyncUpgradePrompt.showSyncUpgradePrompt(this); + } } @Override @@ -561,8 +584,9 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener fragment.initiateAutomaticSync(); fragment.requestCommentCountUpdate(); } - if (position != 0) + if (position != 0) { Preferences.setBoolean(TaskListFragmentPager.PREF_SHOWED_SWIPE_HELPER, true); + } } } @@ -596,15 +620,17 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener View taskeditFragmentContainer = findViewById(R.id.taskedit_fragment_container); if (taskeditFragmentContainer != null && taskeditFragmentContainer.getVisibility() == View.VISIBLE) { if (fragmentLayout == LAYOUT_DOUBLE) { - if (!commentsVisible) + if (!commentsVisible) { findViewById(R.id.taskedit_fragment_container).setVisibility(View.GONE); + } } Flags.set(Flags.TLA_DISMISSED_FROM_TASK_EDIT); onPostResume(); CommentsFragment tuf = getTagUpdatesFragment(); - if (tuf != null) + if (tuf != null) { tuf.getView().setVisibility(View.VISIBLE); + } } super.onBackPressed(); } @@ -620,15 +646,17 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener if ((requestCode == FilterListFragment.REQUEST_NEW_LIST || requestCode == TaskListFragment.ACTIVITY_REQUEST_NEW_FILTER) && resultCode == Activity.RESULT_OK) { - if (data == null) + if (data == null) { return; + } Filter newList = data.getParcelableExtra(TagSettingsActivity.TOKEN_NEW_FILTER); if (newList != null) { getIntent().putExtra(TOKEN_SWITCH_TO_FILTER, newList); // Handle in onPostResume() FilterListFragment fla = getFilterListFragment(); - if (fla != null && !swipeIsEnabled()) + if (fla != null && !swipeIsEnabled()) { fla.clear(); + } } } else if (requestCode == TaskListFragment.ACTIVITY_EDIT_TASK && resultCode != Activity.RESULT_CANCELED) { // Handle switch to assigned filter when it comes from TaskEditActivity finishing @@ -645,8 +673,9 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener Task repeating = data.getParcelableExtra(TaskEditFragment.TOKEN_NEW_REPEATING_TASK); DateChangedAlerts.showRepeatChangedDialog(this, repeating); } - if (data.getBooleanExtra(TaskEditFragment.TOKEN_TAGS_CHANGED, false)) + if (data.getBooleanExtra(TaskEditFragment.TOKEN_TAGS_CHANGED, false)) { tagsChanged(true); + } } tlf.refresh(); } @@ -661,8 +690,9 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener if (tlf != null) { TagData tagData = tlf.getActiveTagData(); String activeUuid = RemoteModel.NO_UUID; - if (tagData != null) + if (tagData != null) { activeUuid = tagData.getUuid(); + } if (activeUuid.equals(uuid)) { getIntent().putExtra(TOKEN_SWITCH_TO_FILTER, CoreFilterExposer.buildInboxFilter(getResources())); // Handle in onPostResume() @@ -672,8 +702,9 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener } } - if (fl != null) + if (fl != null) { fl.refresh(); + } } else if (AstridApiConstants.BROADCAST_EVENT_TAG_RENAMED.equals(action)) { TaskListFragment tlf = getTaskListFragment(); if (tlf != null) { @@ -690,8 +721,9 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener } FilterListFragment flf = getFilterListFragment(); - if (flf != null) + if (flf != null) { flf.refresh(); + } } } @@ -705,17 +737,19 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener private void tagsChanged(boolean onActivityResult) { FilterListFragment flf = getFilterListFragment(); if (flf != null) { - if (onActivityResult) + if (onActivityResult) { flf.clear(); - else + } else { flf.refresh(); + } } } protected void refreshTaskList() { TaskListFragment tlf = getTaskListFragment(); - if (tlf != null) + if (tlf != null) { tlf.refresh(); + } } public void taskAssignedTo(final String assignedDisplay, String assignedEmail, final String assignedId) { @@ -744,16 +778,18 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener String members = td.getValue(TagData.MEMBERS); boolean memberFound = false; - if (TextUtils.isEmpty(members)) + if (TextUtils.isEmpty(members)) { memberFound = td.getValue(TagData.USER_ID).equals(assignedId) || tagMetadataDao.memberOfTagData(assignedEmail, td.getUuid(), assignedId); - else { + } else { JSONObject user = new JSONObject(); JSONArray membersArray = null; try { - if (!TextUtils.isEmpty(assignedEmail)) + if (!TextUtils.isEmpty(assignedEmail)) { user.put("email", assignedEmail); //$NON-NLS-1$ - if (Task.isRealUserId(assignedId)) + } + if (Task.isRealUserId(assignedId)) { user.put("id", assignedId); //$NON-NLS-1$ + } membersArray = new JSONArray(members); for (int i = 0; i < membersArray.length(); i++) { @@ -770,8 +806,9 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener if (!TextUtils.isEmpty(ownerString)) { JSONObject owner = new JSONObject(ownerString); String ownerId = Long.toString(owner.optLong("id", -3)); //$NON-NLS-1$ - if (Task.isRealUserId(ownerId) && assignedId.equals(ownerId)) + if (Task.isRealUserId(ownerId) && assignedId.equals(ownerId)) { memberFound = true; + } } } } catch (JSONException e) { @@ -779,8 +816,9 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener } } - if (memberFound) + if (memberFound) { return; + } DialogInterface.OnClickListener okListener = new DialogInterface.OnClickListener() { @Override @@ -857,10 +895,11 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener TaskListFragment tlf = getTaskListFragment(); switch (item) { case MainMenuPopover.MAIN_MENU_ITEM_LISTS: - if (filterMode == FILTER_MODE_NORMAL) + if (filterMode == FILTER_MODE_NORMAL) { listsNav.performClick(); - else + } else { setFilterMode(FILTER_MODE_NORMAL); + } return; case MainMenuPopover.MAIN_MENU_ITEM_SEARCH: onSearchRequested(); @@ -875,8 +914,9 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener // Doesn't exist yet return; case MainMenuPopover.MAIN_MENU_ITEM_SETTINGS: - if (tlf != null) + if (tlf != null) { tlf.showSettings(); + } return; } tlf.handleOptionsMenuItemSelected(item, customIntent); @@ -910,10 +950,12 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener } onFilterItemClicked(getDefaultFilter()); - if (swipeIsEnabled()) + if (swipeIsEnabled()) { setListsTitle(tlfPagerAdapter.getPageTitle(0).toString()); - if (fragmentLayout == LAYOUT_SINGLE) + } + if (fragmentLayout == LAYOUT_SINGLE) { listsNav.performClick(); + } } public void refreshMainMenu() { @@ -943,13 +985,15 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener private void hideKeyboard() { TaskListFragment tlf = getTaskListFragment(); - if (tlf == null) + if (tlf == null) { return; + } InputMethodManager imm = (InputMethodManager) getSystemService( Context.INPUT_METHOD_SERVICE); QuickAddBar qab = tlf.quickAddBar; - if (qab != null) + if (qab != null) { imm.hideSoftInputFromWindow(qab.getQuickAddBox().getWindowToken(), 0); + } } @Override @@ -960,8 +1004,9 @@ public class TaskListActivity extends AstridActivity implements MainMenuListener return true; } else if (keyCode == KeyEvent.KEYCODE_BACK) { TaskEditFragment tef = getTaskEditFragment(); - if (tef != null && tef.onKeyDown(keyCode)) + if (tef != null && tef.onKeyDown(keyCode)) { return true; + } } return super.onKeyDown(keyCode, event); } diff --git a/astrid/src/com/todoroo/astrid/activity/TaskListFragment.java b/astrid/src/com/todoroo/astrid/activity/TaskListFragment.java index f88603db6..df634fd1e 100644 --- a/astrid/src/com/todoroo/astrid/activity/TaskListFragment.java +++ b/astrid/src/com/todoroo/astrid/activity/TaskListFragment.java @@ -259,8 +259,9 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele // Invalid } } - if (component == null) + if (component == null) { component = TaskListFragment.class; + } TaskListFragment newFragment; try { @@ -331,8 +332,9 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele DependencyInjectionService.getInstance().inject(this); super.onCreate(savedInstanceState); extras = getArguments() != null ? getArguments().getBundle(TOKEN_EXTRAS) : null; - if (extras == null) + if (extras == null) { extras = new Bundle(); // Just need an empty one to prevent potential null pointers + } } /* @@ -374,9 +376,10 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele getListView().setItemsCanFocus(false); } - if (Preferences.getInt(AstridPreferences.P_UPGRADE_FROM, -1) > -1) + if (Preferences.getInt(AstridPreferences.P_UPGRADE_FROM, -1) > -1) { upgradeService.showChangeLog(getActivity(), Preferences.getInt(AstridPreferences.P_UPGRADE_FROM, -1)); + } getListView().setOnItemClickListener(new OnItemClickListener() { @Override @@ -385,8 +388,9 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele if (taskAdapter != null) { TodorooCursor cursor = (TodorooCursor) taskAdapter.getItem(position); Task task = new Task(cursor); - if (task.isDeleted()) + if (task.isDeleted()) { return; + } onTaskListItemClicked(id, task.isEditable()); } @@ -415,8 +419,9 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele filter.setFilterQueryOverride(null); isInbox = CoreFilterExposer.isInbox(filter); isTodayFilter = false; - if (!isInbox) + if (!isInbox) { isTodayFilter = CoreFilterExposer.isTodayFilter(filter); + } initializeTaskListMetadata(); @@ -443,8 +448,9 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele taskListMetadata = taskListMetadataDao.fetchByTagId(filterId, TaskListMetadata.PROPERTIES); if (taskListMetadata == null) { String defaultOrder = Preferences.getStringValue(prefId); - if (TextUtils.isEmpty(defaultOrder)) + if (TextUtils.isEmpty(defaultOrder)) { defaultOrder = "[]"; //$NON-NLS-1$ + } defaultOrder = SubtasksHelper.convertTreeToRemoteIds(defaultOrder); taskListMetadata = new TaskListMetadata(); taskListMetadata.setValue(TaskListMetadata.FILTER, filterId); @@ -478,8 +484,9 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele if ((activity.getFragmentLayout() != AstridActivity.LAYOUT_SINGLE && showAsAction) || !(activity instanceof TaskListActivity)) { MenuItem item = menu.add(Menu.NONE, id, Menu.NONE, title); item.setIcon(imageRes); - if (activity instanceof TaskListActivity) + if (activity instanceof TaskListActivity) { item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); + } } else { ((TaskListActivity) activity).getMainMenuPopover().addMenuItem(title, imageRes, id); } @@ -504,10 +511,12 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele @Override public void onCreateOptionsMenu(Menu menu, com.actionbarsherlock.view.MenuInflater inflater) { Activity activity = getActivity(); - if (activity == null) + if (activity == null) { return; - if (!isCurrentTaskListFragment()) + } + if (!isCurrentTaskListFragment()) { return; + } addMenuItems(menu, activity); } @@ -520,8 +529,9 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele tla.getMainMenuPopover().clear(); } // --- sync - if (tla == null || tla.getTaskEditFragment() == null && Preferences.getBoolean(R.string.p_show_menu_sync, true)) + if (tla == null || tla.getTaskEditFragment() == null && Preferences.getBoolean(R.string.p_show_menu_sync, true)) { addSyncRefreshMenuItem(menu, isTablet ? ThemeService.FLAG_INVERT : 0); + } // --- sort if (allowResorting() && Preferences.getBoolean(R.string.p_show_menu_sort, true)) { @@ -530,9 +540,10 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele } // --- new filter - if (Preferences.getBoolean(R.string.p_use_filters, true)) + if (Preferences.getBoolean(R.string.p_use_filters, true)) { addMenuItem(menu, R.string.FLA_new_filter, ThemeService.getDrawable(R.drawable.icn_menu_filters, isTablet ? ThemeService.FLAG_FORCE_DARK : 0), MENU_NEW_FILTER_ID, false); + } // ask about plug-ins Intent queryIntent = new Intent( @@ -560,8 +571,9 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele getListView().setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View view, int keyCode, KeyEvent event) { - if (event.getAction() != KeyEvent.ACTION_UP || view == null) + if (event.getAction() != KeyEvent.ACTION_UP || view == null) { return false; + } boolean filterOn = getListView().isTextFilterEnabled(); View selected = getListView().getSelectedView(); @@ -767,8 +779,9 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele public final void initiateAutomaticSync() { final AstridActivity activity = (AstridActivity) getActivity(); - if (activity == null) + if (activity == null) { return; + } if (activity.fragmentLayout != AstridActivity.LAYOUT_SINGLE) { initiateAutomaticSyncImpl(); } else { @@ -794,15 +807,17 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele * the above method takes care of calling it in the correct way */ protected void initiateAutomaticSyncImpl() { - if (isCurrentTaskListFragment() && isInbox) + if (isCurrentTaskListFragment() && isInbox) { syncActionHelper.initiateAutomaticSync(); + } } // Subclasses should override this public void requestCommentCountUpdate() { TaskListActivity activity = (TaskListActivity) getActivity(); - if (activity != null) + if (activity != null) { activity.setCommentsCount(0); + } } @Override @@ -825,8 +840,9 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele @Override public void onReceive(Context context, Intent intent) { if (intent == null - || !AstridApiConstants.BROADCAST_EVENT_REFRESH.equals(intent.getAction())) + || !AstridApiConstants.BROADCAST_EVENT_REFRESH.equals(intent.getAction())) { return; + } final Activity activity = getActivity(); if (activity != null) { @@ -834,8 +850,9 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele @Override public void run() { refresh(); - if (activity instanceof TaskListActivity) + if (activity instanceof TaskListActivity) { ((TaskListActivity) activity).refreshMainMenu(); + } } }); } @@ -847,8 +864,9 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele * broadcast. Subclasses should override this. */ protected void refresh() { - if (taskAdapter != null) + if (taskAdapter != null) { taskAdapter.flushCaches(); + } taskService.cleanup(); loadTaskListContent(true); } @@ -884,8 +902,9 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { - if (quickAddBar.onActivityResult(requestCode, resultCode, data)) + if (quickAddBar.onActivityResult(requestCode, resultCode, data)) { return; + } if (requestCode == ACTIVITY_SETTINGS) { if (resultCode == EditPreferences.RESULT_CODE_THEME_CHANGED || resultCode == EditPreferences.RESULT_CODE_PERFORMANCE_PREF_CHANGED) { @@ -901,8 +920,9 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele super.onActivityResult(requestCode, resultCode, data); if (!Preferences.getBoolean(R.string.p_showed_add_task_help, false)) { - if (!AstridPreferences.canShowPopover()) + if (!AstridPreferences.canShowPopover()) { return; + } quickAddBar.getQuickAddBox().postDelayed(new Runnable() { @Override public void run() { @@ -950,8 +970,9 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele if (getView() != null) { // This was happening sometimes int oldListItemSelected = getListView().getSelectedItemPosition(); if (oldListItemSelected != ListView.INVALID_POSITION - && oldListItemSelected < taskCursor.getCount()) + && oldListItemSelected < taskCursor.getCount()) { getListView().setSelection(oldListItemSelected); + } } // also load sync actions @@ -978,8 +999,9 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele new OnCompletedTaskListener() { @Override public void onCompletedTask(Task item, boolean newState) { - if (newState == true) + if (newState == true) { onTaskCompleted(item); + } } }); } @@ -997,12 +1019,14 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele * @param withCustomId force task with given custom id to be part of list */ public void setUpTaskList() { - if (filter == null) + if (filter == null) { return; + } TodorooCursor currentCursor = constructCursor(); - if (currentCursor == null) + if (currentCursor == null) { return; + } // set up list adapters taskAdapter = createTaskAdapter(currentCursor); @@ -1014,8 +1038,9 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele } public Property[] taskProperties() { - if (Preferences.getIntegerFromString(R.string.p_taskRowStyle_v2, 0) == 2) + if (Preferences.getIntegerFromString(R.string.p_taskRowStyle_v2, 0) == 2) { return TaskAdapter.BASIC_PROPERTIES; + } return TaskAdapter.PROPERTIES; } @@ -1026,15 +1051,17 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele @SuppressWarnings("nls") private TodorooCursor constructCursor() { String tagName = null; - if (getActiveTagData() != null) + if (getActiveTagData() != null) { tagName = getActiveTagData().getValue(TagData.NAME); + } 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) + 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. @@ -1050,12 +1077,14 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele joinedQuery, sortFlags, sortSort)); String groupedQuery; - if (sqlQueryTemplate.get().contains("GROUP BY")) + if (sqlQueryTemplate.get().contains("GROUP BY")) { groupedQuery = sqlQueryTemplate.get(); - else if (sqlQueryTemplate.get().contains("ORDER BY")) //$NON-NLS-1$ + } 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 + } else { groupedQuery = sqlQueryTemplate.get() + " GROUP BY " + Task.ID; + } sqlQueryTemplate.set(groupedQuery); // Peform query @@ -1073,8 +1102,9 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele public void reconstructCursor() { TodorooCursor cursor = constructCursor(); - if (cursor == null || taskAdapter == null) + if (cursor == null || taskAdapter == null) { return; + } taskAdapter.changeCursor(cursor); } @@ -1097,8 +1127,9 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele } private void showTaskCreateHelpPopover() { - if (!AstridPreferences.canShowPopover()) + if (!AstridPreferences.canShowPopover()) { return; + } if (!Preferences.getBoolean(R.string.p_showed_add_task_help, false)) { Preferences.setBoolean(R.string.p_showed_add_task_help, true); HelpInfoPopover.showPopover(getActivity(), quickAddBar.getQuickAddBox(), @@ -1107,8 +1138,9 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele } public void showTaskEditHelpPopover() { - if (!AstridPreferences.canShowPopover()) + if (!AstridPreferences.canShowPopover()) { return; + } if (!Preferences.getBoolean(R.string.p_showed_tap_task_help, false)) { quickAddBar.hideKeyboard(); getListView().postDelayed(new Runnable() { @@ -1136,16 +1168,18 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele } private void showListsHelp() { - if (!AstridPreferences.canShowPopover()) + if (!AstridPreferences.canShowPopover()) { return; + } if (!Preferences.getBoolean( R.string.p_showed_lists_help, false)) { AstridActivity activity = (AstridActivity) getActivity(); if (activity != null) { if (AstridPreferences.useTabletLayout(activity)) { FilterListFragment flf = activity.getFilterListFragment(); - if (flf != null) + if (flf != null) { flf.showAddListPopover(); + } } else { ActionBar ab = activity.getSupportActionBar(); View anchor = ab.getCustomView().findViewById(R.id.lists_nav); @@ -1171,10 +1205,11 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele * @param item task that was completed */ protected void onTaskCompleted(Task item) { - if (isInbox) + if (isInbox) { StatisticsService.reportEvent(StatisticsConstants.TASK_COMPLETED_INBOX); - else + } else { StatisticsService.reportEvent(StatisticsConstants.TASK_COMPLETED_FILTER); + } } /** @@ -1186,8 +1221,9 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele Intent intent = new Intent(activity, CommentsActivity.class); long id = 0; TagData td = getActiveTagData(); - if (td != null) + if (td != null) { id = td.getId(); + } intent.putExtra(TagViewFragment.EXTRA_TAG_DATA, id); startActivity(intent); AndroidUtilities.callOverridePendingTransition(activity, R.anim.slide_left_in, R.anim.slide_left_out); @@ -1199,8 +1235,9 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele ContextMenuInfo menuInfo) { AdapterContextMenuInfo adapterInfo = (AdapterContextMenuInfo) menuInfo; Task task = ((ViewHolder) adapterInfo.targetView.getTag()).task; - if (task.getValue(Task.IS_READONLY) > 0) + if (task.getValue(Task.IS_READONLY) > 0) { return; + } int id = (int) task.getId(); menu.setHeaderTitle(task.getValue(Task.TITLE)); @@ -1220,12 +1257,13 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele for (int i = 0; i < contextItemExposers.length; i++) { Object label = contextItemExposers[i].getLabel(task); if (label != null) { - if (label instanceof Integer) + if (label instanceof Integer) { menu.add(id, CONTEXT_MENU_PLUGIN_ID_FIRST + i, Menu.NONE, (Integer) label); - else + } else { menu.add(id, CONTEXT_MENU_PLUGIN_ID_FIRST + i, Menu.NONE, (String) label); + } } } @@ -1276,8 +1314,9 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele AstridActivity activity = (AstridActivity) a; TaskEditFragment tef = activity.getTaskEditFragment(); if (tef != null) { - if (task.getId() == tef.model.getId()) + if (task.getId() == tef.model.getId()) { tef.discardButtonClick(); + } } } TimerPlugin.updateTimer(ContextManager.getContext(), task, false); @@ -1304,8 +1343,9 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele @Override public void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); - if (mDualFragments) + if (mDualFragments) { setSelection(position); + } } @Override @@ -1329,9 +1369,10 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele syncActionHelper.performSyncAction(); return true; case MENU_ADDON_INTENT_ID: - if (activity != null) + if (activity != null) { AndroidUtilities.startExternalIntent(activity, intent, ACTIVITY_MENU_EXTERNAL); + } return true; case MENU_NEW_FILTER_ID: if (activity != null) { @@ -1348,12 +1389,14 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele Intent intent; long itemId; - if (!isCurrentTaskListFragment()) + if (!isCurrentTaskListFragment()) { return false; + } // handle my own menus - if (handleOptionsMenuItemSelected(item.getItemId(), item.getIntent())) + if (handleOptionsMenuItemSelected(item.getItemId(), item.getIntent())) { return true; + } switch (item.getItemId()) { // --- context menu items @@ -1376,8 +1419,9 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele case CONTEXT_MENU_DELETE_TASK_ID: { itemId = item.getGroupId(); Task task = taskService.fetchById(itemId, Task.ID, Task.UUID); - if (task != null) + if (task != null) { deleteTask(task); + } return true; } case CONTEXT_MENU_UNDELETE_TASK_ID: { @@ -1399,10 +1443,12 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele return true; } default: { - if (item.getItemId() < CONTEXT_MENU_PLUGIN_ID_FIRST) + if (item.getItemId() < CONTEXT_MENU_PLUGIN_ID_FIRST) { return false; - if (item.getItemId() - CONTEXT_MENU_PLUGIN_ID_FIRST >= contextItemExposers.length) + } + if (item.getItemId() - CONTEXT_MENU_PLUGIN_ID_FIRST >= contextItemExposers.length) { return false; + } AdapterContextMenuInfo adapterInfo = (AdapterContextMenuInfo) item.getMenuInfo(); Task task = ((ViewHolder) adapterInfo.targetView.getTag()).task; @@ -1425,8 +1471,9 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele public void showSettings() { Activity activity = getActivity(); - if (activity == null) + if (activity == null) { return; + } StatisticsService.reportEvent(StatisticsConstants.TLA_MENU_SETTINGS); Intent intent = new Intent(activity, EditPreferences.class); @@ -1439,10 +1486,10 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele protected void toggleDragDrop(boolean newState) { extras.putParcelable(TOKEN_FILTER, filter); - if (newState) + if (newState) { ((AstridActivity) getActivity()).setupTasklistFragmentWithFilterAndCustomTaskList(filter, extras, SubtasksListFragment.class); - else { + } else { filter.setFilterQueryOverride(null); ((AstridActivity) getActivity()).setupTasklistFragmentWithFilterAndCustomTaskList(filter, extras, TaskListFragment.class); @@ -1479,10 +1526,11 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele } try { - if (manualSettingChanged) + if (manualSettingChanged) { toggleDragDrop(SortHelper.isManualSort(sortFlags)); - else + } else { setUpTaskList(); + } } catch (IllegalStateException e) { // TODO: Fragment got detached somehow (rare) } diff --git a/astrid/src/com/todoroo/astrid/adapter/AddOnAdapter.java b/astrid/src/com/todoroo/astrid/adapter/AddOnAdapter.java index 2704a2e55..1fa31ec53 100644 --- a/astrid/src/com/todoroo/astrid/adapter/AddOnAdapter.java +++ b/astrid/src/com/todoroo/astrid/adapter/AddOnAdapter.java @@ -133,11 +133,12 @@ public class AddOnAdapter extends ArrayAdapter { viewHolder.market.setTag(new ButtonTag("market-" + item.getPackageName(), //$NON-NLS-1$ marketIntent)); Drawable icon = getIntentIcon(marketIntent); - if (icon == null) + if (icon == null) { viewHolder.market.setImageResource( android.R.drawable.stat_sys_download); - else + } else { viewHolder.market.setImageDrawable(icon); + } } } } diff --git a/astrid/src/com/todoroo/astrid/adapter/FilterAdapter.java b/astrid/src/com/todoroo/astrid/adapter/FilterAdapter.java index 530689143..2672aa332 100644 --- a/astrid/src/com/todoroo/astrid/adapter/FilterAdapter.java +++ b/astrid/src/com/todoroo/astrid/adapter/FilterAdapter.java @@ -165,8 +165,9 @@ public class FilterAdapter extends ArrayAdapter { this.nook = (Constants.MARKET_STRATEGY instanceof NookMarketStrategy); - if (activity instanceof AstridActivity && ((AstridActivity) activity).getFragmentLayout() != AstridActivity.LAYOUT_SINGLE) + if (activity instanceof AstridActivity && ((AstridActivity) activity).getFragmentLayout() != AstridActivity.LAYOUT_SINGLE) { filterStyle = R.style.TextAppearance_FLA_Filter_Tablet; + } inflater = (LayoutInflater) activity.getSystemService( Context.LAYOUT_INFLATER_SERVICE); @@ -175,8 +176,9 @@ public class FilterAdapter extends ArrayAdapter { } private void offerFilter(final Filter filter) { - if (selectable && selection == null) + if (selectable && selection == null) { setSelection(filter); + } filterExecutor.submit(new Runnable() { @Override public void run() { @@ -239,10 +241,11 @@ public class FilterAdapter extends ArrayAdapter { // Helper function: if a filter was created from serialized extras, it may not // have the same image data we can get from the in-app broadcast private void transferImageReferences(Filter from, Filter to) { - if (from instanceof FilterWithUpdate && to instanceof FilterWithUpdate) + if (from instanceof FilterWithUpdate && to instanceof FilterWithUpdate) { ((FilterWithUpdate) to).imageUrl = ((FilterWithUpdate) from).imageUrl; - else + } else { to.listingIcon = from.listingIcon; + } } public int adjustFilterCount(Filter filter, int delta) { @@ -436,15 +439,17 @@ public class FilterAdapter extends ArrayAdapter { } protected void populateFiltersToAdapter(final Parcelable[] filters) { - if (filters == null) + if (filters == null) { return; + } for (Parcelable item : filters) { FilterListItem filter = (FilterListItem) item; if (skipIntentFilters && !(filter instanceof Filter || filter instanceof FilterListHeader || - filter instanceof FilterCategory)) + filter instanceof FilterCategory)) { continue; + } onReceiveFilter((FilterListItem) item); if (filter instanceof FilterCategory) { @@ -464,8 +469,9 @@ public class FilterAdapter extends ArrayAdapter { @Override public void notifyDataSetChanged() { super.notifyDataSetChanged(); - if (listener != null) + if (listener != null) { listener.filterDataSourceChanged(); + } } /** @@ -509,8 +515,9 @@ public class FilterAdapter extends ArrayAdapter { public void populateView(ViewHolder viewHolder) { FilterListItem filter = viewHolder.item; - if (filter == null) + if (filter == null) { return; + } viewHolder.view.setBackgroundResource(0); @@ -571,18 +578,20 @@ public class FilterAdapter extends ArrayAdapter { countInt = -1; } - if (countInt == 0 && filter instanceof FilterWithCustomIntent) + if (countInt == 0 && filter instanceof FilterWithCustomIntent) { viewHolder.name.setTextColor(Color.GRAY); + } viewHolder.name.getLayoutParams().height = (int) (58 * metrics.density); if (!nook && filter instanceof FilterWithUpdate) { String defaultImageId = RemoteModel.NO_UUID; FilterWithUpdate fwu = (FilterWithUpdate) filter; Bundle customExtras = fwu.customExtras; - if (customExtras != null && customExtras.containsKey(TagViewFragment.EXTRA_TAG_UUID)) + if (customExtras != null && customExtras.containsKey(TagViewFragment.EXTRA_TAG_UUID)) { defaultImageId = customExtras.getString(TagViewFragment.EXTRA_TAG_UUID); - else + } else { defaultImageId = viewHolder.name.getText().toString(); + } viewHolder.urlImage.setVisibility(View.VISIBLE); viewHolder.urlImage.setDefaultImageDrawable(ResourceDrawableCache.getImageDrawableFromId(resources, TagService.getDefaultImageIDForTag(defaultImageId))); @@ -594,18 +603,21 @@ public class FilterAdapter extends ArrayAdapter { params.setMargins((int) (8 * metrics.density), 0, 0, 0); } - if (filter.color != 0) + if (filter.color != 0) { viewHolder.name.setTextColor(filter.color); + } // selection if (selection == viewHolder.item) { viewHolder.selected.setVisibility(View.VISIBLE); viewHolder.view.setBackgroundColor(Color.rgb(128, 230, 0)); - } else + } else { viewHolder.selected.setVisibility(View.GONE); + } - if (filter instanceof FilterCategoryWithNewButton) + if (filter instanceof FilterCategoryWithNewButton) { setupCustomHeader(viewHolder, (FilterCategoryWithNewButton) filter); + } } private void setupCustomHeader(ViewHolder viewHolder, final FilterCategoryWithNewButton filter) { diff --git a/astrid/src/com/todoroo/astrid/adapter/TaskAdapter.java b/astrid/src/com/todoroo/astrid/adapter/TaskAdapter.java index a8f7f874e..24d979449 100644 --- a/astrid/src/com/todoroo/astrid/adapter/TaskAdapter.java +++ b/astrid/src/com/todoroo/astrid/adapter/TaskAdapter.java @@ -391,10 +391,12 @@ public class TaskAdapter extends CursorAdapter implements Filterable { view.setTag(viewHolder); - for (int i = 0; i < view.getChildCount(); i++) + for (int i = 0; i < view.getChildCount(); i++) { view.getChildAt(i).setTag(viewHolder); - if (viewHolder.details1 != null) + } + if (viewHolder.details1 != null) { viewHolder.details1.setTag(viewHolder); + } // add UI component listeners addListeners(view); @@ -479,10 +481,11 @@ public class TaskAdapter extends CursorAdapter implements Filterable { viewHolder.completeBox.setMinimumHeight(minRowHeight); } - if (task.isEditable()) + if (task.isEditable()) { viewHolder.view.setBackgroundColor(resources.getColor(android.R.color.transparent)); - else + } else { viewHolder.view.setBackgroundColor(readonlyBackground); + } // name final TextView nameView = viewHolder.nameView; @@ -490,10 +493,12 @@ public class TaskAdapter extends CursorAdapter implements Filterable { String nameValue = task.getValue(Task.TITLE); long hiddenUntil = task.getValue(Task.HIDE_UNTIL); - if (task.getValue(Task.DELETION_DATE) > 0) + if (task.getValue(Task.DELETION_DATE) > 0) { nameValue = resources.getString(R.string.TAd_deletedFormat, nameValue); - if (hiddenUntil > DateUtilities.now()) + } + if (hiddenUntil > DateUtilities.now()) { nameValue = resources.getString(R.string.TAd_hiddenFormat, nameValue); + } nameView.setText(nameValue); } @@ -505,10 +510,11 @@ public class TaskAdapter extends CursorAdapter implements Filterable { String details; if (viewHolder.details1 != null) { - if (taskDetailLoader.containsKey(task.getId())) + if (taskDetailLoader.containsKey(task.getId())) { details = taskDetailLoader.get(task.getId()).toString(); - else + } else { details = task.getValue(Task.DETAILS); + } if (TextUtils.isEmpty(details) || DETAIL_SEPARATOR.equals(details) || task.isCompleted()) { viewHolder.details1.setVisibility(View.GONE); viewHolder.details2.setVisibility(View.GONE); @@ -517,8 +523,9 @@ public class TaskAdapter extends CursorAdapter implements Filterable { if (details.startsWith(DETAIL_SEPARATOR)) { StringBuffer buffer = new StringBuffer(details); int length = DETAIL_SEPARATOR.length(); - while (buffer.lastIndexOf(DETAIL_SEPARATOR, length) == 0) + while (buffer.lastIndexOf(DETAIL_SEPARATOR, length) == 0) { buffer.delete(0, length); + } details = buffer.toString(); //details.substring(DETAIL_SEPARATOR.length()); } drawDetails(viewHolder, details, dueDateTextWidth); @@ -539,14 +546,16 @@ public class TaskAdapter extends CursorAdapter implements Filterable { } } - if (Math.abs(DateUtilities.now() - task.getValue(Task.MODIFICATION_DATE)) < 2000L) + if (Math.abs(DateUtilities.now() - task.getValue(Task.MODIFICATION_DATE)) < 2000L) { mostRecentlyMade = task.getId(); + } } private TaskAction getTaskAction(Task task, boolean hasFiles, boolean hasNotes) { - if (titleOnlyLayout || task.isCompleted() || !task.isEditable()) + if (titleOnlyLayout || task.isCompleted() || !task.isEditable()) { return null; + } if (taskActionLoader.containsKey(task.getId())) { return taskActionLoader.get(task.getId()); } else { @@ -576,8 +585,9 @@ public class TaskAdapter extends CursorAdapter implements Filterable { viewHolder.details1.setText(prospective); viewHolder.details1.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); - if (rightWidth > 0 && viewHolder.details1.getMeasuredWidth() > availableWidth) + if (rightWidth > 0 && viewHolder.details1.getMeasuredWidth() > availableWidth) { break; + } actual.insert(actual.length(), spanned); } @@ -591,8 +601,9 @@ public class TaskAdapter extends CursorAdapter implements Filterable { viewHolder.details2.setVisibility(View.VISIBLE); } - for (; i < splitDetails.length; i++) + for (; i < splitDetails.length; i++) { actual.insert(actual.length(), convertToHtml(splitDetails[i] + " ", detailImageGetter, null)); + } viewHolder.details2.setText(actual); } @@ -652,10 +663,12 @@ public class TaskAdapter extends CursorAdapter implements Filterable { private void showEditNotesDialog(final Task task) { String notes = null; Task t = taskService.fetchById(task.getId(), Task.NOTES); - if (t != null) + if (t != null) { notes = t.getValue(Task.NOTES); - if (TextUtils.isEmpty(notes)) + } + if (TextUtils.isEmpty(notes)) { return; + } int theme = ThemeService.getEditDialogTheme(); final Dialog dialog = new Dialog(fragment.getActivity(), theme); @@ -718,14 +731,16 @@ public class TaskAdapter extends CursorAdapter implements Filterable { @SuppressWarnings("nls") private String formatDate(long date) { - if (dateCache.containsKey(date)) + if (dateCache.containsKey(date)) { return dateCache.get(date); + } String formatString = "%s" + (simpleLayout ? " " : "\n") + "%s"; String string = DateUtilities.getRelativeDay(fragment.getActivity(), date); - if (Task.hasDueTime(date)) + if (Task.hasDueTime(date)) { string = String.format(formatString, string, //$NON-NLS-1$ DateUtilities.getTimeString(fragment.getActivity(), new Date(date))); + } dateCache.put(date, string); return string; @@ -752,8 +767,9 @@ public class TaskAdapter extends CursorAdapter implements Filterable { for (fetchCursor.moveToFirst(); !fetchCursor.isAfterLast(); fetchCursor.moveToNext()) { task.clear(); task.readFromCursor(fetchCursor); - if (task.isCompleted()) + if (task.isCompleted()) { continue; + } if (detailsAreRecentAndUpToDate(task)) { // even if we are up to date, randomly load a fraction @@ -761,8 +777,9 @@ public class TaskAdapter extends CursorAdapter implements Filterable { taskDetailLoader.put(task.getId(), new StringBuilder(task.getValue(Task.DETAILS))); requestNewDetails(task); - if (Constants.DEBUG) + if (Constants.DEBUG) { System.err.println("Refreshing details: " + task.getId()); //$NON-NLS-1$ + } } continue; } else if (Constants.DEBUG) { @@ -810,8 +827,9 @@ public class TaskAdapter extends CursorAdapter implements Filterable { Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_REQUEST_DETAILS); broadcastIntent.putExtra(AstridApiConstants.EXTRAS_TASK_ID, task.getId()); Activity activity = fragment.getActivity(); - if (activity != null) + if (activity != null) { activity.sendOrderedBroadcast(broadcastIntent, AstridApiConstants.PERMISSION_READ); + } } } @@ -823,13 +841,16 @@ public class TaskAdapter extends CursorAdapter implements Filterable { */ public void addDetails(long id, String detail) { final StringBuilder details = taskDetailLoader.get(id); - if (details == null) + if (details == null) { return; + } synchronized (details) { - if (details.toString().contains(detail)) + if (details.toString().contains(detail)) { return; - if (details.length() > 0) + } + if (details.length() > 0) { details.append(DETAIL_SEPARATOR); + } details.append(detail); Task task = new Task(); task.setId(id); @@ -856,26 +877,30 @@ public class TaskAdapter extends CursorAdapter implements Filterable { @SuppressWarnings("nls") public Drawable getDrawable(String source) { int drawable = 0; - if (source.equals("silk_clock")) + if (source.equals("silk_clock")) { drawable = R.drawable.details_alarm; - else if (source.equals("silk_tag_pink")) + } else if (source.equals("silk_tag_pink")) { drawable = R.drawable.details_tag; - else if (source.equals("silk_date")) + } else if (source.equals("silk_date")) { drawable = R.drawable.details_repeat; - else if (source.equals("silk_note")) + } else if (source.equals("silk_note")) { drawable = R.drawable.details_note; + } - if (drawable == 0) + if (drawable == 0) { drawable = resources.getIdentifier("drawable/" + source, null, Constants.PACKAGE); - if (drawable == 0) + } + if (drawable == 0) { return null; + } Drawable d; if (!cache.containsKey(drawable)) { d = resources.getDrawable(drawable); d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); cache.put(drawable, d); - } else + } else { d = cache.get(drawable); + } return d; } }; @@ -944,18 +969,21 @@ public class TaskAdapter extends CursorAdapter implements Filterable { @Override protected void draw(ViewHolder viewHolder, long taskId, Collection decorations) { - if (decorations == null || viewHolder.task.getId() != taskId) + if (decorations == null || viewHolder.task.getId() != taskId) { return; + } reset(viewHolder, taskId); - if (decorations.size() == 0) + if (decorations.size() == 0) { return; + } int i = 0; boolean colorSet = false; - if (viewHolder.decorations == null || viewHolder.decorations.length != decorations.size()) + if (viewHolder.decorations == null || viewHolder.decorations.length != decorations.size()) { viewHolder.decorations = new View[decorations.size()]; + } for (TaskDecoration decoration : decorations) { if (decoration.color != 0 && !colorSet) { colorSet = true; @@ -990,10 +1018,11 @@ public class TaskAdapter extends CursorAdapter implements Filterable { } viewHolder.decorations = null; } - if (viewHolder.task.getId() == mostRecentlyMade) + if (viewHolder.task.getId() == mostRecentlyMade) { viewHolder.view.setBackgroundColor(Color.argb(30, 150, 150, 150)); - else + } else { viewHolder.view.setBackgroundResource(android.R.drawable.list_selector_background); + } } @Override @@ -1030,8 +1059,9 @@ public class TaskAdapter extends CursorAdapter implements Filterable { // set check box to actual action item state setTaskAppearance(viewHolder, task); - if (viewHolder.completeBox.getVisibility() == View.VISIBLE) + if (viewHolder.completeBox.getVisibility() == View.VISIBLE) { viewHolder.completeBox.startAnimation(scaleAnimation); + } } }; @@ -1044,8 +1074,9 @@ public class TaskAdapter extends CursorAdapter implements Filterable { public void onClick(View v) { // expand view (unless deleted) final ViewHolder viewHolder = (ViewHolder) v.getTag(); - if (viewHolder.task.isDeleted()) + if (viewHolder.task.isDeleted()) { return; + } long taskId = viewHolder.task.getId(); fragment.onTaskListItemClicked(taskId, viewHolder.task.isEditable()); @@ -1056,8 +1087,9 @@ public class TaskAdapter extends CursorAdapter implements Filterable { * Call me when the parent presses trackpad */ public void onTrackpadPressed(View container) { - if (container == null) + if (container == null) { return; + } final CheckBox completeBox = ((CheckBox) container.findViewById(R.id.completeBox)); completeBox.performClick(); @@ -1073,12 +1105,14 @@ public class TaskAdapter extends CursorAdapter implements Filterable { */ protected void setTaskAppearance(ViewHolder viewHolder, Task task) { Activity activity = fragment.getActivity(); - if (activity == null) + if (activity == null) { return; + } // show item as completed if it was recently checked Boolean value = completedItems.get(task.getUuid()); - if (value == null) + if (value == null) { value = completedItems.get(task.getId()); + } if (value != null) { task.setValue(Task.COMPLETION_DATE, value ? DateUtilities.now() : 0); @@ -1099,19 +1133,23 @@ public class TaskAdapter extends CursorAdapter implements Filterable { setupDueDateAndTags(viewHolder, task); float detailTextSize = Math.max(10, fontSize * 14 / 20); - if (viewHolder.details1 != null) + if (viewHolder.details1 != null) { viewHolder.details1.setTextSize(detailTextSize); - if (viewHolder.details2 != null) + } + if (viewHolder.details2 != null) { viewHolder.details2.setTextSize(detailTextSize); + } if (viewHolder.dueDate != null) { viewHolder.dueDate.setTextSize(detailTextSize); - if (simpleLayout) + if (simpleLayout) { viewHolder.dueDate.setTypeface(null, 0); + } } if (viewHolder.tagsView != null) { viewHolder.tagsView.setTextSize(detailTextSize); - if (simpleLayout) + if (simpleLayout) { viewHolder.tagsView.setTypeface(null, 0); + } } paint.setTextSize(detailTextSize); @@ -1121,16 +1159,18 @@ public class TaskAdapter extends CursorAdapter implements Filterable { if (pictureView != null) { if (Task.USER_ID_SELF.equals(task.getValue(Task.USER_ID))) { pictureView.setVisibility(View.GONE); - if (viewHolder.pictureBorder != null) + if (viewHolder.pictureBorder != null) { viewHolder.pictureBorder.setVisibility(View.GONE); + } } else { pictureView.setVisibility(View.VISIBLE); - if (viewHolder.pictureBorder != null) + if (viewHolder.pictureBorder != null) { viewHolder.pictureBorder.setVisibility(View.VISIBLE); + } pictureView.setUrl(null); - if (Task.USER_ID_UNASSIGNED.equals(task.getValue(Task.USER_ID))) + if (Task.USER_ID_UNASSIGNED.equals(task.getValue(Task.USER_ID))) { pictureView.setDefaultImageDrawable(ResourceDrawableCache.getImageDrawableFromId(resources, R.drawable.icn_anyone_transparent)); - else { + } else { pictureView.setDefaultImageDrawable(ResourceDrawableCache.getImageDrawableFromId(resources, R.drawable.icn_default_person_image)); if (!TextUtils.isEmpty(viewHolder.imageUrl)) { pictureView.setUrl(viewHolder.imageUrl); @@ -1164,8 +1204,9 @@ public class TaskAdapter extends CursorAdapter implements Filterable { checkBoxView.setEnabled(viewHolder.task.isEditable()); int value = task.getValue(Task.IMPORTANCE); - if (value >= IMPORTANCE_RESOURCES.length) + if (value >= IMPORTANCE_RESOURCES.length) { value = IMPORTANCE_RESOURCES.length - 1; + } Drawable[] boxes = IMPORTANCE_DRAWABLES; if (!TextUtils.isEmpty(task.getValue(Task.RECURRENCE))) { boxes = completed ? IMPORTANCE_REPEAT_DRAWABLES_CHECKED : IMPORTANCE_REPEAT_DRAWABLES; @@ -1173,20 +1214,24 @@ public class TaskAdapter extends CursorAdapter implements Filterable { boxes = completed ? IMPORTANCE_DRAWABLES_CHECKED : IMPORTANCE_DRAWABLES; } checkBoxView.setImageDrawable(boxes[value]); - if (titleOnlyLayout) + if (titleOnlyLayout) { return; + } if (checkBoxView.isChecked()) { - if (pictureView != null) + if (pictureView != null) { pictureView.setVisibility(View.GONE); - if (viewHolder.pictureBorder != null) + } + if (viewHolder.pictureBorder != null) { viewHolder.pictureBorder.setVisibility(View.GONE); + } } if (pictureView != null && pictureView.getVisibility() == View.VISIBLE) { checkBoxView.setVisibility(View.INVISIBLE); - if (viewHolder.pictureBorder != null) + if (viewHolder.pictureBorder != null) { viewHolder.pictureBorder.setBackgroundDrawable(IMPORTANCE_DRAWABLES_LARGE[value]); + } } else { checkBoxView.setVisibility(View.VISIBLE); } @@ -1203,10 +1248,11 @@ public class TaskAdapter extends CursorAdapter implements Filterable { if (activity != null) { if (!task.isCompleted() && task.hasDueDate()) { long dueDate = task.getValue(Task.DUE_DATE); - if (task.isOverdue()) + if (task.isOverdue()) { dueDateView.setTextAppearance(activity, R.style.TextAppearance_TAd_ItemDueDate_Overdue); - else + } else { dueDateView.setTextAppearance(activity, R.style.TextAppearance_TAd_ItemDueDate); + } String dateValue = formatDate(dueDate); dueDateView.setText(dateValue); dueDateTextWidth = paint.measureText(dateValue); @@ -1223,8 +1269,9 @@ public class TaskAdapter extends CursorAdapter implements Filterable { if (viewHolder.tagsView != null) { String tags = viewHolder.tagsString; - if (tags != null && task.hasDueDate()) + if (tags != null && task.hasDueDate()) { tags = " | " + tags; //$NON-NLS-1$ + } if (!task.isCompleted()) { viewHolder.tagsView.setText(tags); viewHolder.tagsView.setVisibility(TextUtils.isEmpty(tags) ? View.GONE : View.VISIBLE); @@ -1247,12 +1294,14 @@ public class TaskAdapter extends CursorAdapter implements Filterable { * @param completeBox the box that was clicked. can be null */ protected void completeTask(final Task task, final boolean newState) { - if (task == null) + if (task == null) { return; + } if (newState != task.isCompleted()) { - if (onCompletedTaskListener != null) + if (onCompletedTaskListener != null) { onCompletedTaskListener.onCompletedTask(task, newState); + } completedItems.put(task.getUuid(), newState); taskService.setComplete(task, newState); @@ -1265,9 +1314,9 @@ public class TaskAdapter extends CursorAdapter implements Filterable { * @param newListener */ public void addOnCompletedTaskListener(final OnCompletedTaskListener newListener) { - if (this.onCompletedTaskListener == null) + if (this.onCompletedTaskListener == null) { this.onCompletedTaskListener = newListener; - else { + } else { final OnCompletedTaskListener old = this.onCompletedTaskListener; this.onCompletedTaskListener = new OnCompletedTaskListener() { @Override diff --git a/astrid/src/com/todoroo/astrid/adapter/TaskListFragmentPagerAdapter.java b/astrid/src/com/todoroo/astrid/adapter/TaskListFragmentPagerAdapter.java index f615423ab..f894f1742 100644 --- a/astrid/src/com/todoroo/astrid/adapter/TaskListFragmentPagerAdapter.java +++ b/astrid/src/com/todoroo/astrid/adapter/TaskListFragmentPagerAdapter.java @@ -101,22 +101,26 @@ public class TaskListFragmentPagerAdapter extends FragmentStatePagerAdapter impl private Fragment getFragmentForFilter(Filter filter) { Bundle extras = getExtrasForFilter(filter); Class customList = null; - if (SubtasksHelper.shouldUseSubtasksFragmentForFilter(filter)) + if (SubtasksHelper.shouldUseSubtasksFragmentForFilter(filter)) { customList = SubtasksHelper.subtasksClassForFilter(filter); + } return TaskListFragment.instantiateWithFilterAndExtras(filter, extras, customList); } // Constructs extras corresponding to the specified filter that can be used as arguments to the fragment private Bundle getExtrasForFilter(Filter filter) { Bundle extras = null; - if (filter instanceof FilterWithCustomIntent) + if (filter instanceof FilterWithCustomIntent) { extras = ((FilterWithCustomIntent) filter).customExtras; + } - if (extras == null) + if (extras == null) { extras = new Bundle(); + } - if (filter != null) + if (filter != null) { extras.putParcelable(TaskListFragment.TOKEN_FILTER, filter); + } return extras; } diff --git a/astrid/src/com/todoroo/astrid/adapter/UpdateAdapter.java b/astrid/src/com/todoroo/astrid/adapter/UpdateAdapter.java index f05b0d369..81b5ed2b1 100644 --- a/astrid/src/com/todoroo/astrid/adapter/UpdateAdapter.java +++ b/astrid/src/com/todoroo/astrid/adapter/UpdateAdapter.java @@ -183,8 +183,9 @@ public class UpdateAdapter extends CursorAdapter { private static void readPreferenceToUser(User u, StringProperty prop, String prefKey) { String val = Preferences.getStringValue(prefKey); - if (val == null) + if (val == null) { val = ""; //$NON-NLS-1$ + } u.setValue(prop, val); } @@ -313,8 +314,9 @@ public class UpdateAdapter extends CursorAdapter { String pictureThumb = activity.getPictureUrl(UserActivity.PICTURE, RemoteModel.PICTURE_MEDIUM); String pictureFull = activity.getPictureUrl(UserActivity.PICTURE, RemoteModel.PICTURE_LARGE); Bitmap updateBitmap = null; - if (TextUtils.isEmpty(pictureThumb)) + if (TextUtils.isEmpty(pictureThumb)) { updateBitmap = activity.getPictureBitmap(UserActivity.PICTURE); + } setupImagePopupForCommentView(view, commentPictureView, pictureThumb, pictureFull, updateBitmap, activity.getValue(UserActivity.MESSAGE), fragment, imageCache); } @@ -377,10 +379,11 @@ public class UpdateAdapter extends CursorAdapter { final String message, final Fragment fragment, ImageCache imageCache) { if ((!TextUtils.isEmpty(pictureThumb) && !"null".equals(pictureThumb)) || updateBitmap != null) { //$NON-NLS-1$ commentPictureView.setVisibility(View.VISIBLE); - if (updateBitmap != null) + if (updateBitmap != null) { commentPictureView.setImageBitmap(updateBitmap); - else + } else { commentPictureView.setUrl(pictureThumb); + } if (pictureThumb != null && imageCache.contains(pictureThumb) && updateBitmap == null) { try { @@ -399,10 +402,11 @@ public class UpdateAdapter extends CursorAdapter { AsyncImageView imageView = new AsyncImageView(fragment.getActivity()); imageView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); imageView.setDefaultImageResource(android.R.drawable.ic_menu_gallery); - if (updateBitmap != null) + if (updateBitmap != null) { imageView.setImageBitmap(updateBitmap); - else + } else { imageView.setUrl(pictureFull); + } image.setView(imageView); image.setMessage(message); @@ -433,33 +437,38 @@ public class UpdateAdapter extends CursorAdapter { } else { userDisplay = user.getDisplayName(USER_NAME, USER_FIRST_NAME, USER_LAST_NAME); } - if (TextUtils.isEmpty(userDisplay)) + if (TextUtils.isEmpty(userDisplay)) { userDisplay = context.getString(R.string.ENA_no_user); + } String targetName = activity.getValue(UserActivity.TARGET_NAME); String action = activity.getValue(UserActivity.ACTION); String message = activity.getValue(UserActivity.MESSAGE); int commentResource = 0; if (UserActivity.ACTION_TASK_COMMENT.equals(action)) { - if (fromView.equals(FROM_TASK_VIEW) || TextUtils.isEmpty(targetName)) + if (fromView.equals(FROM_TASK_VIEW) || TextUtils.isEmpty(targetName)) { commentResource = R.string.update_string_default_comment; - else + } else { commentResource = R.string.update_string_task_comment; + } } else if (UserActivity.ACTION_TAG_COMMENT.equals(action)) { - if (fromView.equals(FROM_TAG_VIEW) || TextUtils.isEmpty(targetName)) + if (fromView.equals(FROM_TAG_VIEW) || TextUtils.isEmpty(targetName)) { commentResource = R.string.update_string_default_comment; - else + } else { commentResource = R.string.update_string_tag_comment; + } } - if (commentResource == 0) + if (commentResource == 0) { return Html.fromHtml(String.format("%s %s", userDisplay, message)); //$NON-NLS-1$ + } String original = context.getString(commentResource, userDisplay, targetName, message); int taskLinkIndex = original.indexOf(TARGET_LINK_PREFIX); - if (taskLinkIndex < 0) + if (taskLinkIndex < 0) { return Html.fromHtml(original); + } String[] components = original.split(" "); //$NON-NLS-1$ SpannableStringBuilder builder = new SpannableStringBuilder(); @@ -486,8 +495,9 @@ public class UpdateAdapter extends CursorAdapter { } } - if (htmlStringBuilder.length() > 0) + if (htmlStringBuilder.length() > 0) { builder.append(Html.fromHtml(htmlStringBuilder.toString())); + } return builder; } @@ -525,18 +535,20 @@ public class UpdateAdapter extends CursorAdapter { if (History.COL_TAG_ADDED.equals(column) || History.COL_TAG_REMOVED.equals(column)) { JSONArray tagObj = new JSONArray(newValue); String tagName = tagObj.getString(1); - if (History.COL_TAG_ADDED.equals(column)) + if (History.COL_TAG_ADDED.equals(column)) { result = context.getString(R.string.history_tag_added, item, tagName); - else + } else { result = context.getString(R.string.history_tag_removed, item, tagName); + } } else if (History.COL_ATTACHMENT_ADDED.equals(column) || History.COL_ATTACHMENT_REMOVED.equals(column)) { JSONArray attachmentArray = new JSONArray(newValue); String attachmentName = attachmentArray.getString(0); - if (History.COL_ATTACHMENT_ADDED.equals(column)) + if (History.COL_ATTACHMENT_ADDED.equals(column)) { result = context.getString(R.string.history_attach_added, attachmentName, item); - else + } else { result = context.getString(R.string.history_attach_removed, attachmentName, item); + } } else if (History.COL_ACKNOWLEDGED.equals(column)) { result = context.getString(R.string.history_acknowledged, item); } else if (History.COL_SHARED_WITH.equals(column) || History.COL_UNSHARED_WITH.equals(column)) { @@ -546,24 +558,27 @@ public class UpdateAdapter extends CursorAdapter { for (int i = 0; i < members.length(); i++) { JSONObject m = members.getJSONObject(i); memberList.append(userDisplay(context, userId, m)); - if (i != members.length() - 1) + if (i != members.length() - 1) { memberList.append(", "); + } } - if (History.COL_SHARED_WITH.equals(column)) + if (History.COL_SHARED_WITH.equals(column)) { result = context.getString(R.string.history_shared_with, item, memberList); - else + } else { result = context.getString(R.string.history_unshared_with, item, memberList); + } } else if (History.COL_MEMBER_ADDED.equals(column) || History.COL_MEMBER_REMOVED.equals(column)) { JSONObject userValue = new JSONObject(newValue); - if (history.getValue(History.USER_UUID).equals(userValue.optString("id")) && History.COL_MEMBER_REMOVED.equals(column)) + if (history.getValue(History.USER_UUID).equals(userValue.optString("id")) && History.COL_MEMBER_REMOVED.equals(column)) { result = context.getString(R.string.history_left_list, item); - else { + } else { String userDisplay = userDisplay(context, history.getValue(History.USER_UUID), userValue); - if (History.COL_MEMBER_ADDED.equals(column)) + if (History.COL_MEMBER_ADDED.equals(column)) { result = context.getString(R.string.history_added_user, userDisplay, item); - else + } else { result = context.getString(R.string.history_removed_user, userDisplay, item); + } } } else if (History.COL_COMPLETED_AT.equals(column)) { if (!TextUtils.isEmpty(newValue) && !"null".equals(newValue)) { @@ -586,83 +601,94 @@ public class UpdateAdapter extends CursorAdapter { int oldLength = AndroidUtilities.tryParseInt(oldValue, 0); int newLength = AndroidUtilities.tryParseInt(newValue, 0); - if (oldLength > 0 && newLength > oldLength) + if (oldLength > 0 && newLength > oldLength) { result = context.getString(R.string.history_added_description_characters, (newLength - oldLength), itemPosessive); - else if (newLength == 0) + } else if (newLength == 0) { result = context.getString(R.string.history_removed_description, itemPosessive); - else if (oldLength > 0 && newLength < oldLength) + } else if (oldLength > 0 && newLength < oldLength) { result = context.getString(R.string.history_removed_description_characters, (oldLength - newLength), itemPosessive); - else if (oldLength > 0 && oldLength == newLength) + } else if (oldLength > 0 && oldLength == newLength) { result = context.getString(R.string.history_updated_description, itemPosessive); + } } else if (History.COL_PUBLIC.equals(column)) { int value = AndroidUtilities.tryParseInt(newValue, 0); - if (value > 0) + if (value > 0) { result = context.getString(R.string.history_made_public, item); - else + } else { result = context.getString(R.string.history_made_private, item); + } } else if (History.COL_DUE.equals(column)) { if (!TextUtils.isEmpty(oldValue) && !TextUtils.isEmpty(newValue) - && !"null".equals(oldValue) && !"null".equals(newValue)) + && !"null".equals(oldValue) && !"null".equals(newValue)) { result = context.getString(R.string.history_changed_due_date, itemPosessive, dateString(context, oldValue, newValue), dateString(context, newValue, oldValue)); - else if (!TextUtils.isEmpty(newValue) && !"null".equals(newValue)) + } else if (!TextUtils.isEmpty(newValue) && !"null".equals(newValue)) { result = context.getString(R.string.history_set_due_date, itemPosessive, dateString(context, newValue, DateUtilities.timeToIso8601(DateUtilities.now(), true))); - else + } else { result = context.getString(R.string.history_removed_due_date, itemPosessive); + } } else if (History.COL_REPEAT.equals(column)) { String repeatString = getRepeatString(context, newValue); - if (!TextUtils.isEmpty(repeatString)) + if (!TextUtils.isEmpty(repeatString)) { result = context.getString(R.string.history_changed_repeat, itemPosessive, repeatString); - else + } else { result = context.getString(R.string.history_removed_repeat, itemPosessive); + } } else if (History.COL_TASK_REPEATED.equals(column)) { result = context.getString(R.string.history_completed_repeating_task, item, dateString(context, newValue, oldValue)); } else if (History.COL_TITLE.equals(column)) { - if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue)) + if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue)) { result = context.getString(R.string.history_title_changed, itemPosessive, oldValue, newValue); - else + } else { result = context.getString(R.string.history_title_set, itemPosessive, newValue); + } } else if (History.COL_NAME.equals(column)) { - if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue)) + if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue)) { result = context.getString(R.string.history_name_changed, oldValue, newValue); - else + } else { result = context.getString(R.string.history_name_set, newValue); + } } else if (History.COL_DESCRIPTION.equals(column)) { - if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue)) + if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue)) { result = context.getString(R.string.history_description_changed, oldValue, newValue); - else + } else { result = context.getString(R.string.history_description_set, newValue); + } } else if (History.COL_PICTURE_ID.equals(column) || History.COL_DEFAULT_LIST_IMAGE_ID.equals(column)) { result = context.getString(R.string.history_changed_list_picture); } else if (History.COL_IS_SILENT.equals(column)) { int value = AndroidUtilities.tryParseInt(newValue, 0); - if (value > 0) + if (value > 0) { result = context.getString(R.string.history_silenced, item); - else + } else { result = context.getString(R.string.history_unsilenced, item); + } } else if (History.COL_IS_FAVORITE.equals(column)) { int value = AndroidUtilities.tryParseInt(newValue, 0); - if (value > 0) + if (value > 0) { result = context.getString(R.string.history_favorited, item); - else + } else { result = context.getString(R.string.history_unfavorited, item); + } } else if (History.COL_USER_ID.equals(column)) { String userId = history.getValue(History.USER_UUID); JSONObject userValue = new JSONObject(newValue); if (FROM_TAG_VIEW.equals(fromView) && !hasTask) { - if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue)) + if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue)) { result = context.getString(R.string.history_changed_list_owner, userDisplay(context, userId, userValue)); - else + } else { result = context.getString(R.string.history_created_this_list); - } else if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue) && Task.USER_ID_UNASSIGNED.equals(userValue)) + } + } else if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue) && Task.USER_ID_UNASSIGNED.equals(userValue)) { result = context.getString(R.string.history_unassigned, item); - else if (Task.USER_ID_UNASSIGNED.equals(oldValue) && userValue.optString("id").equals(ActFmPreferenceService.userId())) + } else if (Task.USER_ID_UNASSIGNED.equals(oldValue) && userValue.optString("id").equals(ActFmPreferenceService.userId())) { result = context.getString(R.string.history_claimed, item); - else if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue)) + } else if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue)) { result = context.getString(R.string.history_assigned_to, item, userDisplay(context, userId, userValue)); - else if (!userValue.optString("id").equals(ActFmPreferenceService.userId()) && !Task.USER_ID_UNASSIGNED.equals(userValue.optString("id"))) + } else if (!userValue.optString("id").equals(ActFmPreferenceService.userId()) && !Task.USER_ID_UNASSIGNED.equals(userValue.optString("id"))) { result = context.getString(R.string.history_created_for, item, userDisplay(context, userId, userValue)); - else + } else { result = context.getString(R.string.history_created, item); + } } else { result = context.getString(R.string.history_default, column, newValue); } @@ -671,8 +697,9 @@ public class UpdateAdapter extends CursorAdapter { result = context.getString(R.string.history_default, column, newValue); } - if (TextUtils.isEmpty(result)) + if (TextUtils.isEmpty(result)) { result = context.getString(R.string.history_default, column, newValue); + } String userDisplay; if (history.getValue(History.USER_UUID).equals(Task.USER_ID_SELF) || history.getValue(History.USER_UUID).equals(ActFmPreferenceService.userId())) { @@ -695,8 +722,9 @@ public class UpdateAdapter extends CursorAdapter { time = DateUtilities.parseIso8601(value); Date date = new Date(time); String result = DateUtilities.getDateString(context, date, includeYear); - if (hasTime) + if (hasTime) { result += ", " + DateUtilities.getTimeString(context, date, false); //$NON-NLS-1$ + } return result; } catch (ParseException e) { return value; @@ -721,8 +749,9 @@ public class UpdateAdapter extends CursorAdapter { @SuppressWarnings("nls") private static String getRepeatString(Context context, String value) { - if (TextUtils.isEmpty(value) || "null".equals(value)) + if (TextUtils.isEmpty(value) || "null".equals(value)) { return null; + } try { JSONObject repeat = new JSONObject(value); @@ -771,12 +800,13 @@ public class UpdateAdapter extends CursorAdapter { public int compare(String lhs, String rhs) { int lhIndex = AndroidUtilities.indexOf(SORTED_WEEKDAYS, lhs); int rhIndex = AndroidUtilities.indexOf(SORTED_WEEKDAYS, rhs); - if (lhIndex < rhIndex) + if (lhIndex < rhIndex) { return -1; - else if (lhIndex > rhIndex) + } else if (lhIndex > rhIndex) { return 1; - else + } else { return 0; + } } }); @@ -789,8 +819,9 @@ public class UpdateAdapter extends CursorAdapter { result += (" " + context.getString(R.string.history_repeat_on, byDayDisplay.toString())); } - if ("COMPLETION".equals(repeat.optString("from"))) + if ("COMPLETION".equals(repeat.optString("from"))) { result += (" " + context.getString(R.string.history_repeat_from_completion)); + } return result; } else { @@ -807,13 +838,15 @@ public class UpdateAdapter extends CursorAdapter { String id = userJson.getString("id"); String name = userJson.getString("name"); - if (historyUserId.equals(id) && ActFmPreferenceService.userId().equals(id)) + if (historyUserId.equals(id) && ActFmPreferenceService.userId().equals(id)) { return context.getString(R.string.history_yourself); - else if (ActFmPreferenceService.userId().equals(id)) + } else if (ActFmPreferenceService.userId().equals(id)) { return context.getString(R.string.history_you); - else if (RemoteModel.isValidUuid(id)) + } else if (RemoteModel.isValidUuid(id)) { return name; - else return context.getString(R.string.history_a_deleted_user); + } else { + return context.getString(R.string.history_a_deleted_user); + } } catch (JSONException e) { return context.getString(R.string.ENA_no_user).toLowerCase(); } @@ -835,7 +868,9 @@ public class UpdateAdapter extends CursorAdapter { @Override public void onClick(View widget) { if (activity != null) // TODO: This shouldn't happen, but sometimes does + { activity.onTaskListItemClicked(taskId); + } } @Override diff --git a/astrid/src/com/todoroo/astrid/billing/AstridPurchaseObserver.java b/astrid/src/com/todoroo/astrid/billing/AstridPurchaseObserver.java index 5e3adcdf1..e7154d109 100644 --- a/astrid/src/com/todoroo/astrid/billing/AstridPurchaseObserver.java +++ b/astrid/src/com/todoroo/astrid/billing/AstridPurchaseObserver.java @@ -140,8 +140,9 @@ public abstract class AstridPurchaseObserver extends PurchaseObserver { @Override public void run() { Preferences.setBoolean(ActFmPreferenceService.PREF_LOCAL_PREMIUM, false); - if (actFmPreferenceService.isLoggedIn()) + if (actFmPreferenceService.isLoggedIn()) { actFmSyncService.updateUserSubscriptionStatus(null, null, null); + } } }.start(); } @@ -183,8 +184,9 @@ public abstract class AstridPurchaseObserver extends PurchaseObserver { Log.d(TAG, "RestoreTransactions error: " + responseCode); } } - if (restoreTransactionsListener != null) + if (restoreTransactionsListener != null) { restoreTransactionsListener.restoreTransactionsResponse(responseCode); + } } } diff --git a/astrid/src/com/todoroo/astrid/billing/BillingActivity.java b/astrid/src/com/todoroo/astrid/billing/BillingActivity.java index 2439f04a8..64b8d63b8 100644 --- a/astrid/src/com/todoroo/astrid/billing/BillingActivity.java +++ b/astrid/src/com/todoroo/astrid/billing/BillingActivity.java @@ -153,8 +153,9 @@ public class BillingActivity extends SherlockFragmentActivity implements AstridP buyYear.setEnabled(false); restorePurchases.setEnabled(false); - if (!Preferences.getBoolean(BillingConstants.PREF_TRANSACTIONS_INITIALIZED, false)) + if (!Preferences.getBoolean(BillingConstants.PREF_TRANSACTIONS_INITIALIZED, false)) { restorePurchases.setVisibility(View.GONE); + } buyMonth.setOnClickListener(new OnClickListener() { @Override @@ -194,8 +195,9 @@ public class BillingActivity extends SherlockFragmentActivity implements AstridP for (int i = 0; i < bullets.length; i++) { String curr = getString(bullets[i]); - if (curr.contains("\n")) + if (curr.contains("\n")) { curr = curr.replace("\n", "
"); + } builder.append("
  • ").append(curr); builder.append("
  • \n"); diff --git a/astrid/src/com/todoroo/astrid/billing/BillingService.java b/astrid/src/com/todoroo/astrid/billing/BillingService.java index 6348b5076..f207614e8 100644 --- a/astrid/src/com/todoroo/astrid/billing/BillingService.java +++ b/astrid/src/com/todoroo/astrid/billing/BillingService.java @@ -378,8 +378,9 @@ public class BillingService extends Service implements ServiceConnection { * @param startId an identifier for the invocation instance of this service */ public void handleCommand(Intent intent, int startId) { - if (intent == null) + if (intent == null) { return; + } String action = intent.getAction(); if (BillingConstants.DEBUG) { Log.i(TAG, "handleCommand() action: " + action); diff --git a/astrid/src/com/todoroo/astrid/dao/ABTestEventDao.java b/astrid/src/com/todoroo/astrid/dao/ABTestEventDao.java index 185f18ecf..1241cf4e1 100644 --- a/astrid/src/com/todoroo/astrid/dao/ABTestEventDao.java +++ b/astrid/src/com/todoroo/astrid/dao/ABTestEventDao.java @@ -62,8 +62,9 @@ public class ABTestEventDao extends DatabaseDao { .where(ABTestEvent.TEST_NAME.eq(testName)).orderBy(Order.asc(ABTestEvent.TIME_INTERVAL))); try { - if (existing.getCount() == 0) + if (existing.getCount() == 0) { return; + } existing.moveToLast(); ABTestEvent item = new ABTestEvent(existing); @@ -73,8 +74,9 @@ public class ABTestEventDao extends DatabaseDao { int currentTimeIntervalIndex = AndroidUtilities.indexOf( ABTestEvent.TIME_INTERVALS, timeInterval); - if (lastRecordedTimeIntervalIndex < 0 || currentTimeIntervalIndex < 0) + if (lastRecordedTimeIntervalIndex < 0 || currentTimeIntervalIndex < 0) { return; + } long now = DateUtilities.now(); for (int i = lastRecordedTimeIntervalIndex + 1; i <= currentTimeIntervalIndex; i++) { @@ -110,12 +112,15 @@ public class ABTestEventDao extends DatabaseDao { String testName = event.getValue(ABTestEvent.TEST_NAME); int timeInterval = -1; long days = timeSinceBase / DateUtilities.ONE_DAY; - for (int i = 0; i < ABTestEvent.TIME_INTERVALS.length; i++) - if (days >= ABTestEvent.TIME_INTERVALS[i]) + for (int i = 0; i < ABTestEvent.TIME_INTERVALS.length; i++) { + if (days >= ABTestEvent.TIME_INTERVALS[i]) { timeInterval = ABTestEvent.TIME_INTERVALS[i]; + } + } - if (timeInterval > 0) + if (timeInterval > 0) { createTestEventWithTimeInterval(testName, timeInterval); + } } } finally { allEvents.close(); diff --git a/astrid/src/com/todoroo/astrid/dao/Database.java b/astrid/src/com/todoroo/astrid/dao/Database.java index f0c2b04d3..19687ce0e 100644 --- a/astrid/src/com/todoroo/astrid/dao/Database.java +++ b/astrid/src/com/todoroo/astrid/dao/Database.java @@ -172,9 +172,10 @@ public class Database extends AbstractDatabase { } case 2: { for (Property property : new Property[]{Metadata.VALUE2, - Metadata.VALUE3, Metadata.VALUE4, Metadata.VALUE5}) + Metadata.VALUE3, Metadata.VALUE4, Metadata.VALUE5}) { database.execSQL("ALTER TABLE " + Metadata.TABLE.name + " ADD " + property.accept(visitor, null)); + } } case 3: { database.execSQL(createTableSql(visitor, StoreObject.TABLE.name, StoreObject.PROPERTIES)); @@ -285,9 +286,10 @@ public class Database extends AbstractDatabase { } case 19: try { - for (Property property : new Property[]{Update.TASK_LOCAL, Update.TAGS_LOCAL}) + for (Property property : new Property[]{Update.TASK_LOCAL, Update.TAGS_LOCAL}) { database.execSQL("ALTER TABLE " + Update.TABLE.name + " ADD " + property.accept(visitor, null)); + } database.execSQL("CREATE INDEX IF NOT EXISTS up_tid ON " + Update.TABLE + "(" + Update.TASK_LOCAL.name + ")"); database.execSQL("CREATE INDEX IF NOT EXISTS up_tid ON " + @@ -318,9 +320,10 @@ public class Database extends AbstractDatabase { } case 21: try { - for (Property property : new Property[]{Update.OTHER_USER_ID, Update.OTHER_USER}) + for (Property property : new Property[]{Update.OTHER_USER_ID, Update.OTHER_USER}) { database.execSQL("ALTER TABLE " + Update.TABLE.name + " ADD " + property.accept(visitor, null)); + } } catch (SQLiteException e) { Log.e("astrid", "db-upgrade-" + oldVersion + "-" + newVersion, e); @@ -451,8 +454,9 @@ public class Database extends AbstractDatabase { SqlConstructorVisitor visitor = new SqlConstructorVisitor(); String sql = "ALTER TABLE " + table.name + " ADD " + //$NON-NLS-1$//$NON-NLS-2$ column.accept(visitor, null); - if (!TextUtils.isEmpty(defaultValue)) + if (!TextUtils.isEmpty(defaultValue)) { sql += " DEFAULT " + defaultValue; + } database.execSQL(sql); } catch (SQLiteException e) { // ignored, column already exists @@ -473,8 +477,9 @@ public class Database extends AbstractDatabase { sql.append("CREATE TABLE IF NOT EXISTS ").append(tableName).append('('). append(AbstractModel.ID_PROPERTY).append(" INTEGER PRIMARY KEY AUTOINCREMENT"); for (Property property : properties) { - if (AbstractModel.ID_PROPERTY.name.equals(property.name)) + if (AbstractModel.ID_PROPERTY.name.equals(property.name)) { continue; + } sql.append(',').append(property.accept(visitor, null)); } sql.append(')'); diff --git a/astrid/src/com/todoroo/astrid/dao/HistoryDao.java b/astrid/src/com/todoroo/astrid/dao/HistoryDao.java index e21e4aa42..e9d973156 100644 --- a/astrid/src/com/todoroo/astrid/dao/HistoryDao.java +++ b/astrid/src/com/todoroo/astrid/dao/HistoryDao.java @@ -21,16 +21,18 @@ public class HistoryDao extends DatabaseDao { @Override public boolean createNew(History item) { - if (!item.containsValue(History.CREATED_AT)) + if (!item.containsValue(History.CREATED_AT)) { item.setValue(History.CREATED_AT, DateUtilities.now()); + } return super.createNew(item); } @Override public boolean saveExisting(History item) { ContentValues values = item.getSetValues(); - if (values == null || values.size() == 0) + if (values == null || values.size() == 0) { return false; + } return super.saveExisting(item); } } diff --git a/astrid/src/com/todoroo/astrid/dao/MetadataDao.java b/astrid/src/com/todoroo/astrid/dao/MetadataDao.java index 48f1de679..a1f1d2273 100644 --- a/astrid/src/com/todoroo/astrid/dao/MetadataDao.java +++ b/astrid/src/com/todoroo/astrid/dao/MetadataDao.java @@ -100,16 +100,18 @@ public class MetadataDao extends DatabaseDao { Long taskId = modelSetValues.getAsLong(Metadata.TASK.name); String tagUuid = modelSetValues.getAsString(TaskToTagMetadata.TAG_UUID.name); Long deletionDate = modelSetValues.getAsLong(Metadata.DELETION_DATE.name); - if (taskId == null || taskId == AbstractModel.NO_ID || RemoteModel.isUuidEmpty(tagUuid)) + if (taskId == null || taskId == AbstractModel.NO_ID || RemoteModel.isUuidEmpty(tagUuid)) { return -1; + } TaskOutstanding to = new TaskOutstanding(); to.setValue(OutstandingEntry.ENTITY_ID_PROPERTY, taskId); to.setValue(OutstandingEntry.CREATED_AT_PROPERTY, DateUtilities.now()); String addedOrRemoved = NameMaps.TAG_ADDED_COLUMN; - if (deletionDate != null && deletionDate > 0) + if (deletionDate != null && deletionDate > 0) { addedOrRemoved = NameMaps.TAG_REMOVED_COLUMN; + } to.setValue(OutstandingEntry.COLUMN_STRING_PROPERTY, addedOrRemoved); to.setValue(OutstandingEntry.VALUE_STRING_PROPERTY, tagUuid); @@ -171,8 +173,9 @@ public class MetadataDao extends DatabaseDao { @Override public boolean persist(Metadata item) { - if (!item.containsValue(Metadata.CREATION_DATE)) + if (!item.containsValue(Metadata.CREATION_DATE)) { item.setValue(Metadata.CREATION_DATE, DateUtilities.now()); + } boolean state = super.persist(item); if (Preferences.getBoolean(AstridPreferences.P_FIRST_LIST, true)) { diff --git a/astrid/src/com/todoroo/astrid/dao/RemoteModelDao.java b/astrid/src/com/todoroo/astrid/dao/RemoteModelDao.java index a70eda0bc..57addb8e3 100644 --- a/astrid/src/com/todoroo/astrid/dao/RemoteModelDao.java +++ b/astrid/src/com/todoroo/astrid/dao/RemoteModelDao.java @@ -48,10 +48,11 @@ public class RemoteModelDao extends DatabaseDao extends DatabaseDao cursor = query(Query.select(AbstractModel.ID_PROPERTY).where(RemoteModel.UUID_PROPERTY.eq(uuid))); try { - if (cursor.getCount() == 0) + if (cursor.getCount() == 0) { return AbstractModel.NO_ID; + } cursor.moveToFirst(); return cursor.get(AbstractModel.ID_PROPERTY); } finally { @@ -113,8 +115,9 @@ public class RemoteModelDao extends DatabaseDao cursor = query(Query.select(RemoteModel.UUID_PROPERTY).where(AbstractModel.ID_PROPERTY.eq(localId))); try { - if (cursor.getCount() == 0) + if (cursor.getCount() == 0) { return RemoteModel.NO_UUID; + } cursor.moveToFirst(); return cursor.get(RemoteModel.UUID_PROPERTY); } finally { diff --git a/astrid/src/com/todoroo/astrid/dao/TagMetadataDao.java b/astrid/src/com/todoroo/astrid/dao/TagMetadataDao.java index 7df603b72..512435073 100644 --- a/astrid/src/com/todoroo/astrid/dao/TagMetadataDao.java +++ b/astrid/src/com/todoroo/astrid/dao/TagMetadataDao.java @@ -93,16 +93,18 @@ public class TagMetadataDao extends DatabaseDao { Long tagDataId = modelSetValues.getAsLong(TagMetadata.TAG_ID.name); String memberId = modelSetValues.getAsString(TagMemberMetadata.USER_UUID.name); Long deletionDate = modelSetValues.getAsLong(TagMetadata.DELETION_DATE.name); - if (tagDataId == null || tagDataId == AbstractModel.NO_ID || RemoteModel.isUuidEmpty(memberId)) + if (tagDataId == null || tagDataId == AbstractModel.NO_ID || RemoteModel.isUuidEmpty(memberId)) { return -1; + } TagOutstanding to = new TagOutstanding(); to.setValue(OutstandingEntry.ENTITY_ID_PROPERTY, tagDataId); to.setValue(OutstandingEntry.CREATED_AT_PROPERTY, DateUtilities.now()); String addedOrRemoved = NameMaps.MEMBER_ADDED_COLUMN; - if (deletionDate != null && deletionDate > 0) + if (deletionDate != null && deletionDate > 0) { addedOrRemoved = NameMaps.MEMBER_REMOVED_COLUMN; + } to.setValue(OutstandingEntry.COLUMN_STRING_PROPERTY, addedOrRemoved); to.setValue(OutstandingEntry.VALUE_STRING_PROPERTY, memberId); @@ -118,14 +120,17 @@ public class TagMetadataDao extends DatabaseDao { public void createMemberLink(long tagId, String tagUuid, String memberId, boolean removedMember, boolean suppressOutstanding) { TagMetadata newMetadata = TagMemberMetadata.newMemberMetadata(tagId, tagUuid, memberId); - if (removedMember) + if (removedMember) { newMetadata.setValue(TagMetadata.DELETION_DATE, DateUtilities.now()); - if (suppressOutstanding) + } + if (suppressOutstanding) { newMetadata.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true); + } if (update(Criterion.and(TagMetadataCriteria.byTagAndWithKey(tagUuid, TagMemberMetadata.KEY), TagMemberMetadata.USER_UUID.eq(memberId)), newMetadata) <= 0) { - if (suppressOutstanding) + if (suppressOutstanding) { newMetadata.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true); + } createNew(newMetadata); } } @@ -136,8 +141,9 @@ public class TagMetadataDao extends DatabaseDao { deleteTemplate.setValue(TagMetadata.DELETION_DATE, DateUtilities.now()); deleteTemplate.setValue(TagMemberMetadata.USER_UUID, memberId); // Need this for recording changes in outstanding table - if (suppressOutstanding) + if (suppressOutstanding) { deleteTemplate.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true); + } update(Criterion.and(TagMetadataCriteria.withKey(TagMemberMetadata.KEY), TagMetadata.DELETION_DATE.eq(0), TagMetadata.TAG_UUID.eq(tagUuid), TagMemberMetadata.USER_UUID.eq(memberId)), deleteTemplate); } @@ -151,8 +157,9 @@ public class TagMetadataDao extends DatabaseDao { // TODO: Right now this is in a loop because each deleteTemplate needs the individual tagUuid in order to record // the outstanding entry correctly. If possible, this should be improved to a single query deleteTemplate.setValue(TagMemberMetadata.USER_UUID, uuid); // Need this for recording changes in outstanding table - if (suppressOutstanding) + if (suppressOutstanding) { deleteTemplate.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true); + } update(Criterion.and(TagMetadataCriteria.withKey(TagMemberMetadata.KEY), TagMetadata.DELETION_DATE.eq(0), TagMetadata.TAG_UUID.eq(tagUuid), TagMemberMetadata.USER_UUID.eq(uuid)), deleteTemplate); } @@ -170,12 +177,14 @@ public class TagMetadataDao extends DatabaseDao { JSONObject person = members.optJSONObject(i); if (person != null) { String id = person.optString("id"); //$NON-NLS-1$ - if (!TextUtils.isEmpty(id)) + if (!TextUtils.isEmpty(id)) { ids.add(id); + } String email = person.optString("email"); //$NON-NLS-1$ - if (!TextUtils.isEmpty(email)) + if (!TextUtils.isEmpty(email)) { emails.add(email); + } if (!TextUtils.isEmpty(id) && !TextUtils.isEmpty(email)) { idToEmail.put(id, email); @@ -249,14 +258,15 @@ public class TagMetadataDao extends DatabaseDao { public boolean memberOfTagData(String email, String tagId, String memberId) { Criterion criterion; - if (!RemoteModel.isUuidEmpty(memberId) && !TextUtils.isEmpty(email)) + if (!RemoteModel.isUuidEmpty(memberId) && !TextUtils.isEmpty(email)) { criterion = Criterion.or(TagMemberMetadata.USER_UUID.eq(email), TagMemberMetadata.USER_UUID.eq(memberId)); - else if (!RemoteModel.isUuidEmpty(memberId)) + } else if (!RemoteModel.isUuidEmpty(memberId)) { criterion = TagMemberMetadata.USER_UUID.eq(memberId); - else if (!TextUtils.isEmpty(email)) + } else if (!TextUtils.isEmpty(email)) { criterion = TagMemberMetadata.USER_UUID.eq(email); - else + } else { return false; + } TodorooCursor count = query(Query.select(TagMetadata.ID).where( Criterion.and(TagMetadataCriteria.withKey(TagMemberMetadata.KEY), TagMetadata.TAG_UUID.eq(tagId), criterion))); diff --git a/astrid/src/com/todoroo/astrid/dao/TaskAttachmentDao.java b/astrid/src/com/todoroo/astrid/dao/TaskAttachmentDao.java index 931ebecb0..d7349168f 100644 --- a/astrid/src/com/todoroo/astrid/dao/TaskAttachmentDao.java +++ b/astrid/src/com/todoroo/astrid/dao/TaskAttachmentDao.java @@ -51,8 +51,9 @@ public class TaskAttachmentDao extends RemoteModelDao { if (modelSetValues.containsKey(TaskAttachment.CONTENT_TYPE.name)) { TaskAttachmentOutstanding m = new TaskAttachmentOutstanding(); String path = modelSetValues.getAsString(TaskAttachment.FILE_PATH.name); - if (TextUtils.isEmpty(path)) + if (TextUtils.isEmpty(path)) { return -1; + } try { JSONObject newFileHash = new JSONObject(); newFileHash.put("name", modelSetValues.getAsString(TaskAttachment.NAME.name)); //$NON-NLS-1$ @@ -70,7 +71,9 @@ public class TaskAttachmentDao extends RemoteModelDao { } int result = super.createOutstandingEntries(modelId, modelSetValues); if (result < 0) // Error + { return result; + } return 1 + result; } diff --git a/astrid/src/com/todoroo/astrid/dao/TaskDao.java b/astrid/src/com/todoroo/astrid/dao/TaskDao.java index 136d19470..fbe9ed75e 100644 --- a/astrid/src/com/todoroo/astrid/dao/TaskDao.java +++ b/astrid/src/com/todoroo/astrid/dao/TaskDao.java @@ -194,8 +194,9 @@ public class TaskDao extends RemoteModelDao { @Override public boolean delete(long id) { boolean result = super.delete(id); - if (!result) + if (!result) { return false; + } // delete all metadata metadataDao.deleteWhere(MetadataCriteria.byTask(id)); @@ -242,14 +243,16 @@ public class TaskDao extends RemoteModelDao { @Override public boolean createNew(Task item) { - if (!item.containsValue(Task.CREATION_DATE)) + if (!item.containsValue(Task.CREATION_DATE)) { item.setValue(Task.CREATION_DATE, DateUtilities.now()); + } item.setValue(Task.MODIFICATION_DATE, DateUtilities.now()); // set up task defaults - if (!item.containsValue(Task.IMPORTANCE)) + if (!item.containsValue(Task.IMPORTANCE)) { item.setValue(Task.IMPORTANCE, Preferences.getIntegerFromString( R.string.p_default_importance_key, Task.IMPORTANCE_SHOULD_DO)); + } if (!item.containsValue(Task.DUE_DATE)) { int setting = Preferences.getIntegerFromString(R.string.p_default_urgency_key, Task.URGENCY_NONE); @@ -298,16 +301,19 @@ public class TaskDao extends RemoteModelDao { @Override public boolean saveExisting(Task item) { ContentValues values = item.getSetValues(); - if (values == null || values.size() == 0) + if (values == null || values.size() == 0) { return false; + } if (!TaskApiDao.insignificantChange(values)) { item.setValue(Task.DETAILS, null); - if (!values.containsKey(Task.MODIFICATION_DATE.name)) + if (!values.containsKey(Task.MODIFICATION_DATE.name)) { item.setValue(Task.MODIFICATION_DATE, DateUtilities.now()); + } } boolean result = super.saveExisting(item); - if (result) + if (result) { afterSave(item, values); + } return result; } @@ -343,8 +349,9 @@ public class TaskDao extends RemoteModelDao { for (tasksWithUUID.moveToFirst(); !tasksWithUUID.isAfterLast(); tasksWithUUID.moveToNext()) { curr.readFromCursor(tasksWithUUID); - if (curr.getId() == item.getId()) + if (curr.getId() == item.getId()) { continue; + } compareAndMergeAfterConflict(curr, fetch(item.getId(), tasksWithUUID.getProperties())); @@ -365,17 +372,20 @@ public class TaskDao extends RemoteModelDao { private void compareAndMergeAfterConflict(Task existing, Task newConflict) { boolean match = true; for (Property p : SQL_CONSTRAINT_MERGE_PROPERTIES) { - if (p.equals(Task.ID)) + if (p.equals(Task.ID)) { continue; - if (existing.containsNonNullValue(p) != newConflict.containsNonNullValue(p)) + } + if (existing.containsNonNullValue(p) != newConflict.containsNonNullValue(p)) { match = false; - else if (existing.containsNonNullValue(p) && - !existing.getValue(p).equals(newConflict.getValue(p))) + } else if (existing.containsNonNullValue(p) && + !existing.getValue(p).equals(newConflict.getValue(p))) { match = false; + } } if (!match) { - if (existing.getValue(Task.CREATION_DATE).equals(newConflict.getValue(Task.CREATION_DATE))) + if (existing.getValue(Task.CREATION_DATE).equals(newConflict.getValue(Task.CREATION_DATE))) { newConflict.setValue(Task.CREATION_DATE, newConflict.getValue(Task.CREATION_DATE) + 1000L); + } newConflict.clearValue(Task.UUID); saveExisting(newConflict); } else { @@ -389,19 +399,21 @@ public class TaskDao extends RemoteModelDao { * Astrid. Order matters here! */ public static void afterSave(Task task, ContentValues values) { - if (values == null) + if (values == null) { return; + } task.markSaved(); - if (values.containsKey(Task.COMPLETION_DATE.name) && task.isCompleted()) + if (values.containsKey(Task.COMPLETION_DATE.name) && task.isCompleted()) { afterComplete(task, values); - else { + } else { if (values.containsKey(Task.DUE_DATE.name) || values.containsKey(Task.REMINDER_FLAGS.name) || values.containsKey(Task.REMINDER_PERIOD.name) || values.containsKey(Task.REMINDER_LAST.name) || - values.containsKey(Task.REMINDER_SNOOZE.name)) + values.containsKey(Task.REMINDER_SNOOZE.name)) { ReminderService.getInstance().scheduleAlarm(task); + } } // run api save hooks @@ -415,8 +427,9 @@ public class TaskDao extends RemoteModelDao { * @param values values that were updated */ public static void broadcastTaskSave(Task task, ContentValues values) { - if (TaskApiDao.insignificantChange(values)) + if (TaskApiDao.insignificantChange(values)) { return; + } if (values.containsKey(Task.COMPLETION_DATE.name) && task.isCompleted()) { Context context = ContextManager.getContext(); diff --git a/astrid/src/com/todoroo/astrid/dao/TaskListMetadataDao.java b/astrid/src/com/todoroo/astrid/dao/TaskListMetadataDao.java index b4b5565fb..6f86ae1ec 100644 --- a/astrid/src/com/todoroo/astrid/dao/TaskListMetadataDao.java +++ b/astrid/src/com/todoroo/astrid/dao/TaskListMetadataDao.java @@ -35,11 +35,13 @@ public class TaskListMetadataDao extends RemoteModelDao { @Override protected boolean shouldRecordOutstandingEntry(String columnName, Object value) { - if (TaskListMetadata.FILTER.name.equals(columnName) || TaskListMetadata.TAG_UUID.name.equals(columnName)) + if (TaskListMetadata.FILTER.name.equals(columnName) || TaskListMetadata.TAG_UUID.name.equals(columnName)) { return !RemoteModel.isUuidEmpty(value.toString()); + } - if (TaskListMetadata.TASK_IDS.name.equals(columnName)) + if (TaskListMetadata.TASK_IDS.name.equals(columnName)) { return !TaskListMetadata.taskIdsIsEmpty(value.toString()); + } return NameMaps.shouldRecordOutstandingColumnForTable(NameMaps.TABLE_ID_TASK_LIST_METADATA, columnName); } diff --git a/astrid/src/com/todoroo/astrid/dao/UserActivityDao.java b/astrid/src/com/todoroo/astrid/dao/UserActivityDao.java index b2ff0afee..c3ad9d022 100644 --- a/astrid/src/com/todoroo/astrid/dao/UserActivityDao.java +++ b/astrid/src/com/todoroo/astrid/dao/UserActivityDao.java @@ -21,16 +21,18 @@ public class UserActivityDao extends RemoteModelDao { @Override public boolean createNew(UserActivity item) { - if (!item.containsValue(UserActivity.CREATED_AT)) + if (!item.containsValue(UserActivity.CREATED_AT)) { item.setValue(UserActivity.CREATED_AT, DateUtilities.now()); + } return super.createNew(item); } @Override public boolean saveExisting(UserActivity item) { ContentValues values = item.getSetValues(); - if (values == null || values.size() == 0) + if (values == null || values.size() == 0) { return false; + } return super.saveExisting(item); } diff --git a/astrid/src/com/todoroo/astrid/helper/AsyncImageView.java b/astrid/src/com/todoroo/astrid/helper/AsyncImageView.java index 2f690e351..ff42318a3 100644 --- a/astrid/src/com/todoroo/astrid/helper/AsyncImageView.java +++ b/astrid/src/com/todoroo/astrid/helper/AsyncImageView.java @@ -75,8 +75,9 @@ public class AsyncImageView extends greendroid.widget.AsyncImageView { buildDrawingCache(true); Bitmap drawingCache = getDrawingCache(); - if (drawingCache == null) + if (drawingCache == null) { return null; + } Bitmap b = Bitmap.createBitmap(getDrawingCache()); setDrawingCacheEnabled(false); // clear drawing cache return b; @@ -89,8 +90,9 @@ public class AsyncImageView extends greendroid.widget.AsyncImageView { synchronized (AsyncImageView.class) { if (imageCacheInstance == null) { try { - if (Looper.myLooper() == null) + if (Looper.myLooper() == null) { Looper.prepare(); + } } catch (Exception e) { // Ignore } diff --git a/astrid/src/com/todoroo/astrid/helper/ProgressBarSyncResultCallback.java b/astrid/src/com/todoroo/astrid/helper/ProgressBarSyncResultCallback.java index a60ed4065..cb61510de 100644 --- a/astrid/src/com/todoroo/astrid/helper/ProgressBarSyncResultCallback.java +++ b/astrid/src/com/todoroo/astrid/helper/ProgressBarSyncResultCallback.java @@ -30,8 +30,9 @@ public class ProgressBarSyncResultCallback extends SyncResultCallbackAdapter { this.activity = activity; this.onFinished = onFinished; - if (progressBar == null) + if (progressBar == null) { progressBar = new ProgressBar(activity); + } progressBar.setProgress(0); progressBar.setMax(0); diff --git a/astrid/src/com/todoroo/astrid/helper/SyncActionHelper.java b/astrid/src/com/todoroo/astrid/helper/SyncActionHelper.java index c4ccba2ea..471cde309 100644 --- a/astrid/src/com/todoroo/astrid/helper/SyncActionHelper.java +++ b/astrid/src/com/todoroo/astrid/helper/SyncActionHelper.java @@ -103,8 +103,9 @@ public class SyncActionHelper { @Override public void onReceive(Context context, Intent intent) { if (intent == null - || !AstridApiConstants.BROADCAST_SEND_SYNC_ACTIONS.equals(intent.getAction())) + || !AstridApiConstants.BROADCAST_SEND_SYNC_ACTIONS.equals(intent.getAction())) { return; + } try { Bundle extras = intent.getExtras(); @@ -140,8 +141,9 @@ public class SyncActionHelper { protected void performSyncServiceV2Sync(boolean manual) { boolean syncOccurred = syncService.synchronizeActiveTasks(manual, syncResultCallback); - if (syncOccurred) + if (syncOccurred) { Preferences.setLong(PREF_LAST_AUTO_SYNC, DateUtilities.now()); + } } /** @@ -191,13 +193,16 @@ public class SyncActionHelper { resolveInfo, pm); if (GtasksPreferences.class.getName().equals( - resolveInfo.activityInfo.name)) + resolveInfo.activityInfo.name)) { continue; + } if (resolveInfo.activityInfo.metaData != null) { Bundle metadata = resolveInfo.activityInfo.metaData; if (!metadata.getBoolean("syncAction")) //$NON-NLS-1$ + { continue; + } } if (category.equals(desiredCategory)) { diff --git a/astrid/src/com/todoroo/astrid/helper/TaskAdapterAddOnManager.java b/astrid/src/com/todoroo/astrid/helper/TaskAdapterAddOnManager.java index c8436bf5d..45503c265 100644 --- a/astrid/src/com/todoroo/astrid/helper/TaskAdapterAddOnManager.java +++ b/astrid/src/com/todoroo/astrid/helper/TaskAdapterAddOnManager.java @@ -50,8 +50,9 @@ abstract public class TaskAdapterAddOnManager { // request details draw(viewHolder, taskId, get(taskId)); Intent broadcastIntent = createBroadcastIntent(viewHolder.task); - if (broadcastIntent != null) + if (broadcastIntent != null) { fragment.getActivity().sendOrderedBroadcast(broadcastIntent, AstridApiConstants.PERMISSION_READ); + } return true; } @@ -74,21 +75,23 @@ abstract public class TaskAdapterAddOnManager { * on receive an intent */ public void addNew(long taskId, String addOn, TYPE item, ViewHolder thisViewHolder) { - if (item == null) + if (item == null) { return; + } Collection cacheList = addIfNotExists(taskId, addOn, item); if (cacheList != null) { - if (thisViewHolder != null) + if (thisViewHolder != null) { draw(thisViewHolder, taskId, cacheList); - else { + } else { ListView listView = fragment.getListView(); // update view if it is visible int length = listView.getChildCount(); for (int i = 0; i < length; i++) { ViewHolder viewHolder = (ViewHolder) listView.getChildAt(i).getTag(); - if (viewHolder == null || viewHolder.task.getId() != taskId) + if (viewHolder == null || viewHolder.task.getId() != taskId) { continue; + } draw(viewHolder, taskId, cacheList); break; } @@ -120,8 +123,9 @@ abstract public class TaskAdapterAddOnManager { * @return list if there was already one */ protected synchronized Collection initialize(long taskId) { - if (cache.containsKey(taskId) && cache.get(taskId) != null) + if (cache.containsKey(taskId) && cache.get(taskId) != null) { return get(taskId); + } cache.put(taskId, new LinkedHashMap(0)); return null; } @@ -136,10 +140,12 @@ abstract public class TaskAdapterAddOnManager { protected synchronized Collection addIfNotExists(long taskId, String addOn, TYPE item) { LinkedHashMap list = cache.get(taskId); - if (list == null) + if (list == null) { return null; - if (list.containsValue(item)) + } + if (list.containsValue(item)) { return null; + } list.put(addOn, item); return get(taskId); } @@ -151,8 +157,9 @@ abstract public class TaskAdapterAddOnManager { * @return */ protected Collection get(long taskId) { - if (cache.get(taskId) == null) + if (cache.get(taskId) == null) { return null; + } return cache.get(taskId).values(); } diff --git a/astrid/src/com/todoroo/astrid/helper/TaskEditControlSet.java b/astrid/src/com/todoroo/astrid/helper/TaskEditControlSet.java index 434b78194..ec93975a0 100644 --- a/astrid/src/com/todoroo/astrid/helper/TaskEditControlSet.java +++ b/astrid/src/com/todoroo/astrid/helper/TaskEditControlSet.java @@ -36,8 +36,9 @@ public abstract class TaskEditControlSet { public TaskEditControlSet(Activity activity, int viewLayout) { this.activity = activity; this.viewLayout = viewLayout; - if (viewLayout == -1) + if (viewLayout == -1) { initialized = true; + } themeColor = activity.getResources().getColor(ThemeService.getTaskEditThemeColor()); unsetColor = activity.getResources().getColor(R.color.task_edit_deadline_gray); @@ -50,8 +51,9 @@ public abstract class TaskEditControlSet { afterInflate(); setupOkButton(view); } - if (model != null) + if (model != null) { readFromTaskOnInitialize(); + } this.initialized = true; } return view; @@ -66,8 +68,9 @@ public abstract class TaskEditControlSet { */ public void readFromTask(Task task) { this.model = task; - if (initialized) + if (initialized) { readFromTaskOnInitialize(); + } } diff --git a/astrid/src/com/todoroo/astrid/legacy/LegacyRepeatInfo.java b/astrid/src/com/todoroo/astrid/legacy/LegacyRepeatInfo.java index 80e03e833..801deb02c 100644 --- a/astrid/src/com/todoroo/astrid/legacy/LegacyRepeatInfo.java +++ b/astrid/src/com/todoroo/astrid/legacy/LegacyRepeatInfo.java @@ -41,8 +41,9 @@ public class LegacyRepeatInfo { } public static LegacyRepeatInfo fromSingleField(int repeat) { - if (repeat == 0) + if (repeat == 0) { return null; + } int value = repeat >> REPEAT_VALUE_OFFSET; LegacyRepeatInterval interval = LegacyRepeatInterval.values() [repeat - (value << REPEAT_VALUE_OFFSET)]; diff --git a/astrid/src/com/todoroo/astrid/provider/Astrid2TaskProvider.java b/astrid/src/com/todoroo/astrid/provider/Astrid2TaskProvider.java index 981d3ac46..7724743ed 100644 --- a/astrid/src/com/todoroo/astrid/provider/Astrid2TaskProvider.java +++ b/astrid/src/com/todoroo/astrid/provider/Astrid2TaskProvider.java @@ -109,8 +109,9 @@ public class Astrid2TaskProvider extends ContentProvider { @Override public int delete(Uri uri, String selection, String[] selectionArgs) { - if (LOGD) + if (LOGD) { Log.d(TAG, "delete"); + } return 0; } @@ -220,8 +221,9 @@ public class Astrid2TaskProvider extends ContentProvider { @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { - if (LOGD) + if (LOGD) { Log.d(TAG, "query"); + } Cursor cursor; switch (URI_MATCHER.match(uri)) { @@ -244,8 +246,9 @@ public class Astrid2TaskProvider extends ContentProvider { @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { - if (LOGD) + if (LOGD) { Log.d(TAG, "update"); + } switch (URI_MATCHER.match(uri)) { @@ -253,19 +256,24 @@ public class Astrid2TaskProvider extends ContentProvider { Task task = new Task(); // map values - if (values.containsKey(NAME)) + if (values.containsKey(NAME)) { task.setValue(Task.TITLE, values.getAsString(NAME)); - if (values.containsKey(PREFERRED_DUE_DATE)) + } + if (values.containsKey(PREFERRED_DUE_DATE)) { task.setValue(Task.DUE_DATE, values.getAsLong(PREFERRED_DUE_DATE)); - if (values.containsKey(DEFINITE_DUE_DATE)) + } + if (values.containsKey(DEFINITE_DUE_DATE)) { task.setValue(Task.DUE_DATE, values.getAsLong(DEFINITE_DUE_DATE)); - if (values.containsKey(IMPORTANCE)) + } + 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); - if (task.isCompleted()) + if (task.isCompleted()) { StatisticsService.reportEvent(StatisticsConstants.TASK_COMPLETED_API2); + } } // map selection criteria @@ -288,11 +296,13 @@ public class Astrid2TaskProvider extends ContentProvider { public static void notifyDatabaseModification() { - if (LOGD) + if (LOGD) { Log.d(TAG, "notifyDatabaseModification"); + } - if (ctx == null) + if (ctx == null) { ctx = ContextManager.getContext(); + } try { ctx.getContentResolver().notifyChange(CONTENT_URI, null); } catch (Exception e) { diff --git a/astrid/src/com/todoroo/astrid/provider/Astrid3ContentProvider.java b/astrid/src/com/todoroo/astrid/provider/Astrid3ContentProvider.java index c17fae12b..f9d1548d1 100644 --- a/astrid/src/com/todoroo/astrid/provider/Astrid3ContentProvider.java +++ b/astrid/src/com/todoroo/astrid/provider/Astrid3ContentProvider.java @@ -227,8 +227,9 @@ public class Astrid3ContentProvider extends ContentProvider { } private AbstractDatabase getDatabase() { - if (databaseOverride != null) + if (databaseOverride != null) { return databaseOverride; + } return database; } @@ -257,10 +258,11 @@ public class Astrid3ContentProvider extends ContentProvider { case URI_ITEM: { String itemSelector = String.format("%s = '%s'", AbstractModel.ID_PROPERTY, uri.getPathSegments().get(1)); - if (TextUtils.isEmpty(selection)) + if (TextUtils.isEmpty(selection)) { selection = itemSelector; - else + } else { selection = itemSelector + " AND " + selection; + } } @@ -298,8 +300,9 @@ public class Astrid3ContentProvider extends ContentProvider { case URI_DIR: { helper.model.mergeWith(values); readTransitoriesFromModelContentValues(helper.model); - if (!helper.create()) + if (!helper.create()) { throw new SQLException("Could not insert row into database (constraint failed?)"); + } Uri newUri = ContentUris.withAppendedId(uri, helper.model.getId()); getContext().getContentResolver().notifyChange(newUri, null); @@ -333,10 +336,11 @@ public class Astrid3ContentProvider extends ContentProvider { case URI_ITEM: { String itemSelector = String.format("%s = '%s'", AbstractModel.ID_PROPERTY, uri.getPathSegments().get(1)); - if (TextUtils.isEmpty(selection)) + if (TextUtils.isEmpty(selection)) { selection = itemSelector; - else + } else { selection = itemSelector + " AND " + selection; + } } diff --git a/astrid/src/com/todoroo/astrid/service/AddOnService.java b/astrid/src/com/todoroo/astrid/service/AddOnService.java index 967539f0c..e8a0ece38 100644 --- a/astrid/src/com/todoroo/astrid/service/AddOnService.java +++ b/astrid/src/com/todoroo/astrid/service/AddOnService.java @@ -50,10 +50,11 @@ public class AddOnService { * Checks whether power pack should be enabled */ public boolean hasPowerPack() { - if (Preferences.getBoolean(PREF_OEM, false)) + if (Preferences.getBoolean(PREF_OEM, false)) { return true; - else if (isInstalled(POWER_PACK_PACKAGE, true)) + } else if (isInstalled(POWER_PACK_PACKAGE, true)) { return true; + } return false; } @@ -61,10 +62,11 @@ public class AddOnService { * Checks whether locale plugin should be enabled */ public boolean hasLocalePlugin() { - if (Preferences.getBoolean(PREF_OEM, false)) + if (Preferences.getBoolean(PREF_OEM, false)) { return true; - else if (isInstalled(LOCALE_PACKAGE, true)) + } else if (isInstalled(LOCALE_PACKAGE, true)) { return true; + } return false; } @@ -83,8 +85,9 @@ public class AddOnService { */ public boolean isInstalled(AddOn addOn) { // it isnt installed if it is null... - if (addOn == null) + if (addOn == null) { return false; + } return isInstalled(addOn.getPackageName(), addOn.isInternal()); } @@ -106,16 +109,19 @@ public class AddOnService { * @return */ private boolean isInstalled(String packageName, boolean internal) { - if (Constants.PACKAGE.equals(packageName)) + if (Constants.PACKAGE.equals(packageName)) { return true; + } Context context = ContextManager.getContext(); String packageSignature = AndroidUtilities.getSignature(context, packageName); - if (packageSignature == null) + if (packageSignature == null) { return false; - if (!internal) + } + if (!internal) { return true; + } String astridSignature = AndroidUtilities.getSignature(context, Constants.PACKAGE); return packageSignature.equals(astridSignature); @@ -129,8 +135,9 @@ public class AddOnService { * @return the addon-descriptor, if it is available (registered here in getAddOns), otherwise null */ public AddOn getAddOn(String packageName, String title) { - if (title == null || packageName == null) + if (title == null || packageName == null) { return null; + } AddOn addon = null; AddOn[] addons = getAddOns(); @@ -152,17 +159,19 @@ public class AddOnService { // temporary temporary ArrayList list = new ArrayList(3); - if (Constants.MARKET_STRATEGY.includesPowerPack()) + if (Constants.MARKET_STRATEGY.includesPowerPack()) { list.add(new AddOn(false, true, r.getString(R.string.AOA_ppack_title), null, r.getString(R.string.AOA_ppack_description), POWER_PACK_PACKAGE, ((BitmapDrawable) r.getDrawable(R.drawable.icon_pp)).getBitmap())); + } - if (Constants.MARKET_STRATEGY.includesLocalePlugin()) + if (Constants.MARKET_STRATEGY.includesLocalePlugin()) { list.add(new AddOn(false, true, r.getString(R.string.AOA_locale_title), null, r.getString(R.string.AOA_locale_description), LOCALE_PACKAGE, ((BitmapDrawable) r.getDrawable(R.drawable.icon_locale)).getBitmap())); + } return list.toArray(new AddOn[list.size()]); } diff --git a/astrid/src/com/todoroo/astrid/service/Astrid2To3UpgradeHelper.java b/astrid/src/com/todoroo/astrid/service/Astrid2To3UpgradeHelper.java index 3870991e6..39e386a22 100644 --- a/astrid/src/com/todoroo/astrid/service/Astrid2To3UpgradeHelper.java +++ b/astrid/src/com/todoroo/astrid/service/Astrid2To3UpgradeHelper.java @@ -118,8 +118,9 @@ public class Astrid2To3UpgradeHelper { * @param from */ public void upgrade3To3_1(final Context context, final int from) { - if (!checkIfDatabaseExists(context, alertsTable)) + if (!checkIfDatabaseExists(context, alertsTable)) { return; + } database.openForWriting(); migrateAlarmsToMetadata(); @@ -136,16 +137,19 @@ public class Astrid2To3UpgradeHelper { public void upgrade2To3(final Context context, final int from) { // if from < 1 (we don't know what version, and database exists, leave it alone) - if (from < 1 && checkIfDatabaseExists(context, database.getName())) + if (from < 1 && checkIfDatabaseExists(context, database.getName())) { return; + } // if you don't have a legacy task table, skip this step - if (!checkIfDatabaseExists(context, tasksTable)) + if (!checkIfDatabaseExists(context, tasksTable)) { return; + } // else, if there's already a database table, clear it out (!!!) - if (checkIfDatabaseExists(context, database.getName())) + if (checkIfDatabaseExists(context, database.getName())) { context.deleteDatabase(database.getName()); + } database.openForWriting(); // initiate a backup @@ -266,13 +270,14 @@ public class Astrid2To3UpgradeHelper { // special handling for due date if (property == Task.DUE_DATE) { long preferredDueDate = data.cursor.getLong(data.cursor.getColumnIndex(LegacyTaskModel.PREFERRED_DUE_DATE)); - if (value == 0) + if (value == 0) { value = preferredDueDate; - else if (preferredDueDate != 0) { + } else if (preferredDueDate != 0) { // had both absolute and preferred due dates. write // preferred due date into notes field - if (data.upgradeNotes == null) + if (data.upgradeNotes == null) { data.upgradeNotes = new StringBuilder(); + } data.upgradeNotes.append("Goal Deadline: " + DateUtilities.getDateString(ContextManager.getContext(), new Date(preferredDueDate))); @@ -283,8 +288,9 @@ public class Astrid2To3UpgradeHelper { } else if (property == Task.COMPLETION_DATE) { // check if the task was actually completed int progress = data.cursor.getInt(data.cursor.getColumnIndex(LegacyTaskModel.PROGRESS_PERCENTAGE)); - if (progress < 100) + if (progress < 100) { value = 0; + } } data.model.setValue(property, value); @@ -298,9 +304,9 @@ public class Astrid2To3UpgradeHelper { if (property == Task.RECURRENCE) { LegacyRepeatInfo repeatInfo = LegacyRepeatInfo.fromSingleField(data.cursor.getInt(data.columnIndex)); - if (repeatInfo == null) + if (repeatInfo == null) { data.model.setValue(property, ""); - else { + } else { RRule rrule = repeatInfo.toRRule(); data.model.setValue(property, rrule.toIcal()); } @@ -328,8 +334,9 @@ public class Astrid2To3UpgradeHelper { HashMap> propertyMap, TYPE model, DatabaseDao dao) { - if (!checkIfDatabaseExists(context, legacyTable)) + if (!checkIfDatabaseExists(context, legacyTable)) { return; + } SQLiteDatabase upgradeDb = new Astrid2UpgradeHelper(context, legacyTable, null, 1).getReadableDatabase(); @@ -348,9 +355,9 @@ public class Astrid2To3UpgradeHelper { // special tweak for adding upgrade notes to tasks if (container.upgradeNotes != null) { - if (container.model.getValue(Task.NOTES).length() == 0) + if (container.model.getValue(Task.NOTES).length() == 0) { container.model.setValue(Task.NOTES, container.upgradeNotes.toString()); - else { + } else { container.model.setValue(Task.NOTES, container.model.getValue(Task.NOTES) + "\n\n" + container.upgradeNotes); @@ -379,8 +386,9 @@ public class Astrid2To3UpgradeHelper { Context context = ContextManager.getContext(); if (!checkIfDatabaseExists(context, tagsTable) || - !checkIfDatabaseExists(context, tagTaskTable)) + !checkIfDatabaseExists(context, tagTaskTable)) { return; + } SQLiteDatabase tagsDb = new Astrid2UpgradeHelper(context, tagsTable, null, 1).getReadableDatabase(); @@ -393,8 +401,9 @@ public class Astrid2To3UpgradeHelper { try { mapCursor = tagTaskDb.rawQuery("SELECT tag, task FROM " + tagTaskTable + " ORDER BY tag ASC", null); - if (tagCursor.getCount() == 0) + if (tagCursor.getCount() == 0) { return; + } Metadata metadata = new Metadata(); metadata.setValue(Metadata.KEY, TaskToTagMetadata.KEY); @@ -410,8 +419,9 @@ public class Astrid2To3UpgradeHelper { } if (mapTagId == tagId) { - if (tag == null) + if (tag == null) { tag = tagCursor.getString(1); + } long task = mapCursor.getLong(1); metadata.setValue(Metadata.TASK, task); metadata.setValue(Metadata.KEY, TaskToTagMetadata.KEY); @@ -422,8 +432,9 @@ public class Astrid2To3UpgradeHelper { } } finally { tagCursor.close(); - if (mapCursor != null) + if (mapCursor != null) { mapCursor.close(); + } tagsDb.close(); tagTaskDb.close(); } @@ -435,8 +446,9 @@ public class Astrid2To3UpgradeHelper { private void migrateAlarmsToMetadata() { Context context = ContextManager.getContext(); - if (!checkIfDatabaseExists(context, AlarmDatabase.NAME)) + if (!checkIfDatabaseExists(context, AlarmDatabase.NAME)) { return; + } AlarmDatabase alarmsDatabase = new AlarmDatabase(); DatabaseDao dao = new DatabaseDao( @@ -444,8 +456,9 @@ public class Astrid2To3UpgradeHelper { TodorooCursor cursor = dao.query(Query.select(TransitionalAlarm.PROPERTIES)); try { - if (cursor.getCount() == 0) + if (cursor.getCount() == 0) { return; + } Metadata metadata = new Metadata(); metadata.setValue(Metadata.KEY, AlarmFields.METADATA_KEY); diff --git a/astrid/src/com/todoroo/astrid/service/AstridDependencyInjector.java b/astrid/src/com/todoroo/astrid/service/AstridDependencyInjector.java index c7461d873..5e97c3f5b 100644 --- a/astrid/src/com/todoroo/astrid/service/AstridDependencyInjector.java +++ b/astrid/src/com/todoroo/astrid/service/AstridDependencyInjector.java @@ -142,11 +142,13 @@ public class AstridDependencyInjector extends AbstractDependencyInjector { * Install this service as the default Dependency Injector */ public static void initialize() { - if (instance != null) + if (instance != null) { return; + } synchronized (AstridDependencyInjector.class) { - if (instance == null) + if (instance == null) { instance = new AstridDependencyInjector(); + } DependencyInjectionService.getInstance().addInjector(instance); } } diff --git a/astrid/src/com/todoroo/astrid/service/GlobalEventReceiver.java b/astrid/src/com/todoroo/astrid/service/GlobalEventReceiver.java index e02277920..baea0ee92 100644 --- a/astrid/src/com/todoroo/astrid/service/GlobalEventReceiver.java +++ b/astrid/src/com/todoroo/astrid/service/GlobalEventReceiver.java @@ -32,8 +32,9 @@ public final class GlobalEventReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { - if (intent == null) + if (intent == null) { return; + } DependencyInjectionService.getInstance().inject(this); diff --git a/astrid/src/com/todoroo/astrid/service/MetadataService.java b/astrid/src/com/todoroo/astrid/service/MetadataService.java index 9b31aedd5..260b6c1ee 100644 --- a/astrid/src/com/todoroo/astrid/service/MetadataService.java +++ b/astrid/src/com/todoroo/astrid/service/MetadataService.java @@ -48,8 +48,9 @@ public class MetadataService { public void cleanup() { TodorooCursor cursor = metadataDao.fetchDangling(Metadata.ID); try { - if (cursor.getCount() == 0) + if (cursor.getCount() == 0) { return; + } for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { long id = cursor.getLong(0); @@ -95,8 +96,9 @@ public class MetadataService { * @param metadata */ public boolean save(Metadata metadata) { - if (!metadata.containsNonNullValue(Metadata.TASK)) + if (!metadata.containsNonNullValue(Metadata.TASK)) { throw new IllegalArgumentException("metadata needs to be attached to a task: " + metadata.getMergedValues()); //$NON-NLS-1$ + } return metadataDao.persist(metadata); } @@ -121,7 +123,9 @@ public class MetadataService { ContentValues values = metadatum.getMergedValues(); for (Entry entry : values.valueSet()) { if (entry.getKey().startsWith("value")) //$NON-NLS-1$ + { values.put(entry.getKey(), entry.getValue().toString()); + } } newMetadataValues.add(values); } @@ -150,9 +154,9 @@ public class MetadataService { if (callback != null) { callback.beforeDeleteMetadata(item); } - if (hardDelete) + if (hardDelete) { metadataDao.delete(id); - else { + } else { item.setValue(Metadata.DELETION_DATE, DateUtilities.now()); metadataDao.persist(item); } diff --git a/astrid/src/com/todoroo/astrid/service/PremiumUnlockService.java b/astrid/src/com/todoroo/astrid/service/PremiumUnlockService.java index 4d6e5645f..31f620c49 100644 --- a/astrid/src/com/todoroo/astrid/service/PremiumUnlockService.java +++ b/astrid/src/com/todoroo/astrid/service/PremiumUnlockService.java @@ -19,13 +19,16 @@ public class PremiumUnlockService { } public void checkForPremium() { - if (Preferences.getBoolean(PREF_KILL_SWITCH, false)) + if (Preferences.getBoolean(PREF_KILL_SWITCH, false)) { return; + } try { String response = restClient.get(PREM_SWITCH_URL).trim(); if ("OFF".equals(response)) //$NON-NLS-1$ + { Preferences.setBoolean(PREF_KILL_SWITCH, true); + } } catch (Exception e) { e.printStackTrace(); } diff --git a/astrid/src/com/todoroo/astrid/service/StartupService.java b/astrid/src/com/todoroo/astrid/service/StartupService.java index 5b595a852..b490443c8 100644 --- a/astrid/src/com/todoroo/astrid/service/StartupService.java +++ b/astrid/src/com/todoroo/astrid/service/StartupService.java @@ -160,8 +160,9 @@ public class StartupService { * Called when this application is started up */ public synchronized void onStartupApplication(final Activity context) { - if (hasStartedUp || context == null) + if (hasStartedUp || context == null) { return; + } // sets up context manager ContextManager.setContext(context); @@ -182,10 +183,11 @@ public class StartupService { if (context instanceof Activity) { AudioManager audioManager = (AudioManager) context.getSystemService( Context.AUDIO_SERVICE); - if (!Preferences.getBoolean(R.string.p_rmd_enabled, true)) + if (!Preferences.getBoolean(R.string.p_rmd_enabled, true)) { Toast.makeText(context, R.string.TLA_notification_disabled, Toast.LENGTH_LONG).show(); - else if (audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) == 0) + } else if (audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) == 0) { Toast.makeText(context, R.string.TLA_notification_volume_low, Toast.LENGTH_LONG).show(); + } } // read current version @@ -271,8 +273,9 @@ public class StartupService { gtasksSyncService.initialize(); // get and display update messages - if (finalLatestVersion != 0) + if (finalLatestVersion != 0) { new UpdateMessageService(context).processUpdates(); + } new PremiumUnlockService().checkForPremium(); @@ -287,8 +290,9 @@ public class StartupService { CalendarStartupReceiver.scheduleCalendarAlarms(context, false); // This needs to be after set preference defaults for the purposes of ab testing // check for task killers - if (!Constants.OEM) + if (!Constants.OEM) { showTaskKillerHelp(context); + } hasStartedUp = true; } @@ -351,8 +355,9 @@ public class StartupService { !context.getDatabasePath(database.getName()).exists()) { // we didn't have a database! restore latest file File directory = BackupConstants.defaultExportDirectory(); - if (!directory.exists()) + if (!directory.exists()) { return; + } File[] children = directory.listFiles(); AndroidUtilities.sortFilesByDateDesc(children); if (children.length > 0) { @@ -409,8 +414,9 @@ public class StartupService { private void checkMetadataStat(Criterion criterion, String statistic) { TodorooCursor sort = metadataService.query(Query.select(Metadata.ID).where(criterion).limit(1)); try { - if (sort.getCount() > 0) + if (sort.getCount() > 0) { StatisticsService.reportEvent(statistic); + } } finally { sort.close(); } @@ -425,8 +431,9 @@ public class StartupService { * @param context */ private static void showTaskKillerHelp(final Context context) { - if (!Preferences.getBoolean(P_TASK_KILLER_HELP, false)) + if (!Preferences.getBoolean(P_TASK_KILLER_HELP, false)) { return; + } // search for task killers. if they exist, show the help! PackageManager pm = context.getPackageManager(); @@ -434,10 +441,13 @@ public class StartupService { .getInstalledPackages(PackageManager.GET_PERMISSIONS); outer: for (PackageInfo app : apps) { - if (app == null || app.requestedPermissions == null) + if (app == null || app.requestedPermissions == null) { continue; + } if (app.packageName.startsWith("com.android")) //$NON-NLS-1$ + { continue; + } for (String permission : app.requestedPermissions) { if (Manifest.permission.RESTART_PACKAGES.equals(permission)) { CharSequence appName = app.applicationInfo.loadLabel(pm); diff --git a/astrid/src/com/todoroo/astrid/service/StatisticsService.java b/astrid/src/com/todoroo/astrid/service/StatisticsService.java index 2968ed594..2f084152c 100644 --- a/astrid/src/com/todoroo/astrid/service/StatisticsService.java +++ b/astrid/src/com/todoroo/astrid/service/StatisticsService.java @@ -26,8 +26,9 @@ public class StatisticsService { * @param context */ public static void sessionStart(Context context) { - if (dontCollectStatistics()) + if (dontCollectStatistics()) { return; + } if (localyticsSession != null) { localyticsSession.open(); // Multiple calls to open are ok, we just need to make sure it gets reopened after pause @@ -38,8 +39,9 @@ public class StatisticsService { localyticsSession.upload(); } - if (context instanceof Activity) + if (context instanceof Activity) { localyticsSession.tagScreen(context.getClass().getSimpleName()); + } } /** @@ -48,19 +50,22 @@ public class StatisticsService { * @param context */ public static void sessionStop(Context context) { - if (dontCollectStatistics()) + if (dontCollectStatistics()) { return; + } - if (localyticsSession != null) + if (localyticsSession != null) { localyticsSession.upload(); + } } /** * Indicate session was paused */ public static void sessionPause() { - if (dontCollectStatistics()) + if (dontCollectStatistics()) { return; + } if (localyticsSession != null) { localyticsSession.close(); @@ -84,19 +89,22 @@ public class StatisticsService { * @param event */ public static void reportEvent(String event, String... attributes) { - if (dontCollectStatistics()) + if (dontCollectStatistics()) { return; + } if (localyticsSession != null) { if (attributes.length > 0) { HashMap attrMap = new HashMap(); for (int i = 1; i < attributes.length; i += 2) { - if (attributes[i] != null) + if (attributes[i] != null) { attrMap.put(attributes[i - 1], attributes[i]); + } } localyticsSession.tagEvent(event, attrMap); - } else + } else { localyticsSession.tagEvent(event); + } } } diff --git a/astrid/src/com/todoroo/astrid/service/SyncV2Service.java b/astrid/src/com/todoroo/astrid/service/SyncV2Service.java index fe998e1cb..504bd5afa 100644 --- a/astrid/src/com/todoroo/astrid/service/SyncV2Service.java +++ b/astrid/src/com/todoroo/astrid/service/SyncV2Service.java @@ -41,15 +41,18 @@ public class SyncV2Service { public List activeProviders() { ArrayList actives = new ArrayList(); for (SyncV2Provider provider : providers) { - if (provider.isActive()) + if (provider.isActive()) { actives.add(provider); + } } return Collections.unmodifiableList(actives); } public boolean hasActiveProvider() { for (SyncV2Provider provider : providers) { - if (provider.isActive()) return true; + if (provider.isActive()) { + return true; + } } return false; } @@ -64,8 +67,9 @@ public class SyncV2Service { public boolean synchronizeActiveTasks(final boolean manual, SyncResultCallback callback) { final List active = activeProviders(); - if (active.size() == 0) + if (active.size() == 0) { return false; + } if (active.size() > 1) { // This should never happen anymore--they can't be active at the same time, but if for some reason they both are, just use ActFm active.get(1).synchronizeActiveTasks(manual, new WidgetUpdatingCallbackWrapper(callback)); @@ -85,8 +89,9 @@ public class SyncV2Service { */ public void synchronizeList(Object list, boolean manual, SyncResultCallback callback) { for (SyncV2Provider provider : providers) { - if (provider.isActive()) + if (provider.isActive()) { provider.synchronizeList(list, manual, new WidgetUpdatingCallbackWrapper(callback)); + } } } diff --git a/astrid/src/com/todoroo/astrid/service/TagDataService.java b/astrid/src/com/todoroo/astrid/service/TagDataService.java index e24904a73..ad885304b 100644 --- a/astrid/src/com/todoroo/astrid/service/TagDataService.java +++ b/astrid/src/com/todoroo/astrid/service/TagDataService.java @@ -95,8 +95,9 @@ public class TagDataService { public TagData getTagByName(String name, Property... properties) { TodorooCursor cursor = tagDataDao.query(Query.select(properties).where(TagData.NAME.eqCaseInsensitive(name))); try { - if (cursor.getCount() == 0) + if (cursor.getCount() == 0) { return null; + } cursor.moveToFirst(); return new TagData(cursor); } finally { @@ -116,25 +117,29 @@ public class TagDataService { public TodorooCursor fetchFiltered(String queryTemplate, CharSequence constraint, Property... properties) { Criterion whereConstraint = null; - if (constraint != null) + if (constraint != null) { whereConstraint = Functions.upper(TagData.NAME).like("%" + constraint.toString().toUpperCase() + "%"); + } if (queryTemplate == null) { - if (whereConstraint == null) + if (whereConstraint == null) { return tagDataDao.query(Query.select(properties)); - else + } else { return tagDataDao.query(Query.select(properties).where(whereConstraint)); + } } String sql; if (whereConstraint != null) { - if (!queryTemplate.toUpperCase().contains("WHERE")) + if (!queryTemplate.toUpperCase().contains("WHERE")) { sql = queryTemplate + " WHERE " + whereConstraint; - else + } else { sql = queryTemplate.replace("WHERE ", "WHERE " + whereConstraint + " AND "); - } else + } + } else { sql = queryTemplate; + } sql = PermaSql.replacePlaceholders(sql); @@ -143,29 +148,33 @@ public class TagDataService { private static Query queryForTagData(TagData tagData, Criterion extraCriterion, String userTableAlias, Property[] activityProperties, Property[] userProperties) { Criterion criteria; - if (tagData == null) + if (tagData == null) { criteria = UserActivity.DELETED_AT.eq(0); - else + } else { criteria = Criterion.and(UserActivity.DELETED_AT.eq(0), Criterion.or( Criterion.and(UserActivity.ACTION.eq(UserActivity.ACTION_TAG_COMMENT), UserActivity.TARGET_ID.eq(tagData.getUuid())), Criterion.and(UserActivity.ACTION.eq(UserActivity.ACTION_TASK_COMMENT), UserActivity.TARGET_ID.in(Query.select(TaskToTagMetadata.TASK_UUID) .from(Metadata.TABLE).where(Criterion.and(MetadataCriteria.withKey(TaskToTagMetadata.KEY), TaskToTagMetadata.TAG_UUID.eq(tagData.getUuid()))))))); + } - if (extraCriterion != null) + if (extraCriterion != null) { criteria = Criterion.and(criteria, extraCriterion); + } Query result = Query.select(AndroidUtilities.addToArray(Property.class, activityProperties, userProperties)).where(criteria); - if (!TextUtils.isEmpty(userTableAlias)) + if (!TextUtils.isEmpty(userTableAlias)) { result = result.join(Join.left(User.TABLE.as(userTableAlias), UserActivity.USER_UUID.eq(Field.field(userTableAlias + "." + User.UUID.name)))); //$NON-NLS-1$ + } return result; } public TodorooCursor getUserActivityWithExtraCriteria(TagData tagData, Criterion criterion) { - if (tagData == null) + if (tagData == null) { return userActivityDao.query(Query.select(UserActivity.PROPERTIES).where( criterion). orderBy(Order.desc(UserActivity.CREATED_AT))); + } return userActivityDao.query(queryForTagData(tagData, criterion, null, UserActivity.PROPERTIES, null).orderBy(Order.desc(UserActivity.CREATED_AT))); } @@ -175,10 +184,11 @@ public class TagDataService { .from(UserActivity.TABLE); Criterion historyCriterion; - if (tagData == null) + if (tagData == null) { historyCriterion = Criterion.none; - else + } else { historyCriterion = History.TAG_ID.eq(tagData.getUuid()); + } Query historyQuery = Query.select(AndroidUtilities.addToArray(Property.class, UpdateAdapter.HISTORY_PROPERTIES, userProperties)).from(History.TABLE) .where(historyCriterion) @@ -198,8 +208,9 @@ public class TagDataService { TagData tagData = new TagData(); if (!cursor.isAfterLast()) { tagData.readFromCursor(cursor); - if (!tagData.getValue(TagData.NAME).equals(featObject.getString("name"))) + if (!tagData.getValue(TagData.NAME).equals(featObject.getString("name"))) { TagService.getInstance().rename(tagData.getUuid(), featObject.getString("name"), true); + } cursor.moveToNext(); } ActFmSyncService.JsonHelper.featuredListFromJson(featObject, tagData); @@ -218,13 +229,15 @@ public class TagDataService { * @return */ public UserActivity getLatestUpdate(TagData tagData) { - if (RemoteModel.NO_UUID.equals(tagData.getValue(TagData.UUID))) + if (RemoteModel.NO_UUID.equals(tagData.getValue(TagData.UUID))) { return null; + } TodorooCursor updates = userActivityDao.query(queryForTagData(tagData, null, null, UserActivity.PROPERTIES, null).orderBy(Order.desc(UserActivity.CREATED_AT)).limit(1)); try { - if (updates.getCount() == 0) + if (updates.getCount() == 0) { return null; + } updates.moveToFirst(); return new UserActivity(updates); } finally { diff --git a/astrid/src/com/todoroo/astrid/service/TaskService.java b/astrid/src/com/todoroo/astrid/service/TaskService.java index 38451a202..f23f04ea0 100644 --- a/astrid/src/com/todoroo/astrid/service/TaskService.java +++ b/astrid/src/com/todoroo/astrid/service/TaskService.java @@ -180,8 +180,9 @@ public class TaskService { */ public Task clone(Task task) { Task newTask = fetchById(task.getId(), Task.PROPERTIES); - if (newTask == null) + if (newTask == null) { return new Task(); + } newTask.clearValue(Task.ID); newTask.clearValue(Task.UUID); TodorooCursor cursor = metadataDao.query( @@ -195,13 +196,16 @@ public class TaskService { for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { metadata.readFromCursor(cursor); - if (!metadata.containsNonNullValue(Metadata.KEY)) + if (!metadata.containsNonNullValue(Metadata.KEY)) { continue; + } - if (GtasksMetadata.METADATA_KEY.equals(metadata.getValue(Metadata.KEY))) + if (GtasksMetadata.METADATA_KEY.equals(metadata.getValue(Metadata.KEY))) { metadata.setValue(GtasksMetadata.ID, ""); //$NON-NLS-1$ - if (OpencrxCoreUtils.OPENCRX_ACTIVITY_METADATA_KEY.equals(metadata.getValue(Metadata.KEY))) + } + if (OpencrxCoreUtils.OPENCRX_ACTIVITY_METADATA_KEY.equals(metadata.getValue(Metadata.KEY))) { metadata.setValue(OpencrxCoreUtils.ACTIVITY_ID, 0L); + } metadata.setValue(Metadata.TASK, newId); metadata.clearValue(Metadata.ID); @@ -216,8 +220,9 @@ public class TaskService { public Task cloneReusableTask(Task task, String tagName, String tagUuid) { Task newTask = fetchById(task.getId(), Task.PROPERTIES); - if (newTask == null) + if (newTask == null) { return new Task(); + } newTask.clearValue(Task.ID); newTask.clearValue(Task.UUID); newTask.clearValue(Task.USER); @@ -240,9 +245,9 @@ public class TaskService { * @param model */ public void delete(Task item) { - if (!item.isSaved()) + if (!item.isSaved()) { return; - else if (item.containsValue(Task.TITLE) && item.getValue(Task.TITLE).length() == 0) { + } else if (item.containsValue(Task.TITLE) && item.getValue(Task.TITLE).length() == 0) { taskDao.delete(item.getId()); taskOutstandingDao.deleteWhere(TaskOutstanding.ENTITY_ID_PROPERTY.eq(item.getId())); item.setId(Task.NO_ID); @@ -272,8 +277,9 @@ public class TaskService { TodorooCursor cursor = taskDao.query( Query.select(Task.ID).where(TaskCriteria.hasNoTitle())); try { - if (cursor.getCount() == 0) + if (cursor.getCount() == 0) { return; + } for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { long id = cursor.getLong(0); @@ -296,25 +302,29 @@ public class TaskService { public TodorooCursor fetchFiltered(String queryTemplate, CharSequence constraint, Property... properties) { Criterion whereConstraint = null; - if (constraint != null) + if (constraint != null) { whereConstraint = Functions.upper(Task.TITLE).like("%" + constraint.toString().toUpperCase() + "%"); + } if (queryTemplate == null) { - if (whereConstraint == null) + if (whereConstraint == null) { return taskDao.query(Query.selectDistinct(properties)); - else + } else { return taskDao.query(Query.selectDistinct(properties).where(whereConstraint)); + } } String sql; if (whereConstraint != null) { - if (!queryTemplate.toUpperCase().contains("WHERE")) + if (!queryTemplate.toUpperCase().contains("WHERE")) { sql = queryTemplate + " WHERE " + whereConstraint; - else + } else { sql = queryTemplate.replace("WHERE ", "WHERE " + whereConstraint + " AND "); - } else + } + } else { sql = queryTemplate; + } sql = PermaSql.replacePlaceholders(sql); @@ -322,18 +332,21 @@ public class TaskService { } public boolean getUserActivationStatus() { - if (Preferences.getBoolean(PREF_USER_ACTVATED, false)) + if (Preferences.getBoolean(PREF_USER_ACTVATED, false)) { return true; + } TodorooCursor all = query(Query.select(Task.ID).limit(TOTAL_TASKS_FOR_ACTIVATION)); try { - if (all.getCount() < TOTAL_TASKS_FOR_ACTIVATION) + if (all.getCount() < TOTAL_TASKS_FOR_ACTIVATION) { return false; + } TodorooCursor completed = query(Query.select(Task.ID).where(TaskCriteria.completed()).limit(COMPLETED_TASKS_FOR_ACTIVATION)); try { - if (completed.getCount() < COMPLETED_TASKS_FOR_ACTIVATION) + if (completed.getCount() < COMPLETED_TASKS_FOR_ACTIVATION) { return false; + } } finally { completed.close(); } @@ -480,8 +493,9 @@ public class TaskService { original.setId(itemId); Task clone = clone(original); String userId = clone.getValue(Task.USER_ID); - if (!Task.USER_ID_SELF.equals(userId) && !ActFmPreferenceService.userId().equals(userId)) + if (!Task.USER_ID_SELF.equals(userId) && !ActFmPreferenceService.userId().equals(userId)) { clone.putTransitory(TRANS_ASSIGNED, true); + } clone.setValue(Task.CREATION_DATE, DateUtilities.now()); clone.setValue(Task.COMPLETION_DATE, 0L); clone.setValue(Task.DELETION_DATE, 0L); @@ -518,8 +532,9 @@ public class TaskService { * @return */ public static Task createWithValues(Task task, ContentValues values, String title) { - if (title != null) + if (title != null) { task.setValue(Task.TITLE, title); + } ArrayList tags = new ArrayList(); boolean quickAddMarkup = false; @@ -537,26 +552,30 @@ public class TaskService { for (Entry item : values.valueSet()) { String key = item.getKey(); Object value = item.getValue(); - if (value instanceof String) + if (value instanceof String) { value = PermaSql.replacePlaceholders((String) value); + } - for (Property property : Metadata.PROPERTIES) + for (Property property : Metadata.PROPERTIES) { if (property.name.equals(key)) { AndroidUtilities.putInto(forMetadata, key, value, true); continue outer; } + } AndroidUtilities.putInto(forTask, key, value, true); } task.mergeWithoutReplacement(forTask); } - if (!Task.USER_ID_SELF.equals(task.getValue(Task.USER_ID))) + if (!Task.USER_ID_SELF.equals(task.getValue(Task.USER_ID))) { task.putTransitory(TRANS_ASSIGNED, true); + } PluginServices.getTaskService().quickAdd(task, tags); - if (quickAddMarkup) + if (quickAddMarkup) { task.putTransitory(TRANS_QUICK_ADD_MARKUP, true); + } if (forMetadata != null && forMetadata.size() > 0) { Metadata metadata = new Metadata(); @@ -594,8 +613,9 @@ public class TaskService { private static Query queryForTask(Task task, String userTableAlias, Property[] activityProperties, Property[] userProperties) { Query result = Query.select(AndroidUtilities.addToArray(Property.class, activityProperties, userProperties)) .where(Criterion.and(UserActivity.ACTION.eq(UserActivity.ACTION_TASK_COMMENT), UserActivity.TARGET_ID.eq(task.getUuid()), UserActivity.DELETED_AT.eq(0))); - if (!TextUtils.isEmpty(userTableAlias)) + if (!TextUtils.isEmpty(userTableAlias)) { result = result.join(Join.left(User.TABLE.as(userTableAlias), UserActivity.USER_UUID.eq(Field.field(userTableAlias + "." + User.UUID.name)))); //$NON-NLS-1$ + } return result; } diff --git a/astrid/src/com/todoroo/astrid/service/ThemeService.java b/astrid/src/com/todoroo/astrid/service/ThemeService.java index 74a369170..30e94bce6 100644 --- a/astrid/src/com/todoroo/astrid/service/ThemeService.java +++ b/astrid/src/com/todoroo/astrid/service/ThemeService.java @@ -55,27 +55,29 @@ public class ThemeService { public static int getWidgetTheme() { String preference = Preferences.getStringValue(R.string.p_theme_widget); - if (TextUtils.isEmpty(preference) || THEME_WIDGET_SAME_AS_APP.equals(preference)) + if (TextUtils.isEmpty(preference) || THEME_WIDGET_SAME_AS_APP.equals(preference)) { return getTheme(); - else if (THEME_WIDGET_LEGACY.equals(preference)) + } else if (THEME_WIDGET_LEGACY.equals(preference)) { return TasksWidget.THEME_LEGACY; - else + } else { return getStyleForSetting(preference); + } } private static int getStyleForSetting(String setting) { - if (THEME_BLACK.equals(setting)) + if (THEME_BLACK.equals(setting)) { return R.style.Theme; - else if (THEME_TRANSPARENT.equals(setting)) + } else if (THEME_TRANSPARENT.equals(setting)) { return R.style.Theme_Transparent; - else if (THEME_TRANSPARENT_WHITE.equals(setting)) + } else if (THEME_TRANSPARENT_WHITE.equals(setting)) { return R.style.Theme_TransparentWhite; - else if (THEME_WHITE_RED.equals(setting)) + } else if (THEME_WHITE_RED.equals(setting)) { return R.style.Theme_White; - else if (THEME_WHITE_ALT.equals(setting)) + } else if (THEME_WHITE_ALT.equals(setting)) { return R.style.Theme_White_Alt; - else + } else { return R.style.Theme_White_Blue; + } } public static int getThemeColor() { @@ -98,15 +100,17 @@ public class ThemeService { int themeSetting = getTheme(); int theme; if (themeSetting == R.style.Theme || themeSetting == R.style.Theme_Transparent) { - if (ics) + if (ics) { theme = R.style.TEA_Dialog_ICS; - else + } else { theme = R.style.TEA_Dialog; + } } else { - if (ics) + if (ics) { theme = R.style.TEA_Dialog_White_ICS; - else + } else { theme = R.style.TEA_Dialog_White; + } } return theme; } @@ -125,10 +129,11 @@ public class ThemeService { public static int getDialogTextColor() { if (AndroidUtilities.getSdkVersion() >= 11) { int theme = getTheme(); - if (theme == R.style.Theme || theme == R.style.Theme_Transparent) + if (theme == R.style.Theme || theme == R.style.Theme_Transparent) { return android.R.color.white; - else + } else { return android.R.color.black; + } } else { return android.R.color.white; } @@ -136,8 +141,9 @@ public class ThemeService { public static String getDialogTextColorString() { int color = getDialogTextColor(); - if (color == android.R.color.white) + if (color == android.R.color.white) { return "white"; + } return "black"; } @@ -155,10 +161,12 @@ public class ThemeService { } public static int getFilterThemeFlags() { - if (forceFilterInvert) + if (forceFilterInvert) { return ThemeService.FLAG_INVERT; - if (AstridPreferences.useTabletLayout(ContextManager.getContext())) + } + if (AstridPreferences.useTabletLayout(ContextManager.getContext())) { return ThemeService.FLAG_FORCE_LIGHT; + } return 0; } @@ -180,8 +188,9 @@ public class ThemeService { } if (lightDrawable == R.drawable.icn_menu_refresh && - AstridPreferences.useTabletLayout(ContextManager.getContext())) + AstridPreferences.useTabletLayout(ContextManager.getContext())) { return R.drawable.icn_menu_refresh_tablet; + } if (theme == R.style.Theme_White_Alt) { switch (lightDrawable) { @@ -198,8 +207,9 @@ public class ThemeService { } } - if (!darkTheme) + if (!darkTheme) { return lightDrawable; + } switch (lightDrawable) { diff --git a/astrid/src/com/todoroo/astrid/service/UpdateMessagePreference.java b/astrid/src/com/todoroo/astrid/service/UpdateMessagePreference.java index c304b64ea..ff4222b64 100644 --- a/astrid/src/com/todoroo/astrid/service/UpdateMessagePreference.java +++ b/astrid/src/com/todoroo/astrid/service/UpdateMessagePreference.java @@ -24,8 +24,9 @@ public class UpdateMessagePreference extends PreferenceActivity { String prefsArray = getIntent().getStringExtra(TOKEN_PREFS_ARRAY); try { JSONArray array = new JSONArray(prefsArray); - if (array.length() == 0) + if (array.length() == 0) { finish(); + } for (int i = 0; i < array.length(); i++) { try { @@ -45,8 +46,9 @@ public class UpdateMessagePreference extends PreferenceActivity { String type = obj.optString("type", null); String key = obj.optString("key", null); String title = obj.optString("title", null); - if (type == null || key == null || title == null) + if (type == null || key == null || title == null) { return; + } Preference pref = null; if ("bool".equals(type)) { // We can add other types we want to support and handle the preference construction here @@ -56,8 +58,9 @@ public class UpdateMessagePreference extends PreferenceActivity { pref.setDefaultValue(Preferences.getBoolean(key, false)); } - if (pref == null) + if (pref == null) { return; + } if (obj.optBoolean("restart")) { pref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { diff --git a/astrid/src/com/todoroo/astrid/service/UpdateMessageService.java b/astrid/src/com/todoroo/astrid/service/UpdateMessageService.java index 3ba409cdd..f81d0d611 100644 --- a/astrid/src/com/todoroo/astrid/service/UpdateMessageService.java +++ b/astrid/src/com/todoroo/astrid/service/UpdateMessageService.java @@ -82,12 +82,14 @@ public class UpdateMessageService { public void processUpdates() { JSONArray updates = checkForUpdates(); - if (updates == null || updates.length() == 0) + if (updates == null || updates.length() == 0) { return; + } MessageTuple message = buildUpdateMessage(updates); - if (message == null || message.message.length() == 0) + if (message == null || message.message.length() == 0) { return; + } displayUpdateDialog(message); } @@ -118,8 +120,9 @@ public class UpdateMessageService { } protected void displayUpdateDialog(final MessageTuple message) { - if (activity == null) + if (activity == null) { return; + } if (message.linkText.size() > 0) { final DialogShower ds = new DialogShower() { @@ -200,15 +203,18 @@ public class UpdateMessageService { String plugin = update.optString("plugin", null); String notPlugin = update.optString("notplugin", null); - if (message == null) + if (message == null) { continue; + } if (plugin != null) { - if (!pluginConditionMatches(plugin)) + if (!pluginConditionMatches(plugin)) { continue; + } } if (notPlugin != null) { - if (pluginConditionMatches(notPlugin)) + if (pluginConditionMatches(notPlugin)) { continue; + } } MessageTuple toReturn = new MessageTuple(); @@ -217,8 +223,9 @@ public class UpdateMessageService { if ("screen".equals(type) || "pref".equals(type)) { String linkText = update.optString("link"); OnClickListener click = getClickListenerForUpdate(update, type); - if (click == null) + if (click == null) { continue; + } toReturn.linkText.add(linkText); toReturn.click.add(click); } else { @@ -226,11 +233,13 @@ public class UpdateMessageService { if (links != null) { for (int j = 0; j < links.length(); j++) { JSONObject link = links.optJSONObject(j); - if (link == null) + if (link == null) { continue; + } String linkText = link.optString("title"); - if (TextUtils.isEmpty(linkText)) + if (TextUtils.isEmpty(linkText)) { continue; + } final String url = link.optString("url"); OnClickListener click = new OnClickListener() { @@ -247,8 +256,9 @@ public class UpdateMessageService { } } - if (messageAlreadySeen(date, message)) + if (messageAlreadySeen(date, message)) { continue; + } return toReturn; } return null; @@ -257,11 +267,13 @@ public class UpdateMessageService { private OnClickListener getClickListenerForUpdate(JSONObject update, String type) { if ("pref".equals(type)) { try { - if (!update.has("action_list")) + if (!update.has("action_list")) { return null; + } JSONArray prefSpec = update.getJSONArray("action_list"); - if (prefSpec.length() == 0) + if (prefSpec.length() == 0) { return null; + } final String prefArray = prefSpec.toString(); return new View.OnClickListener() { @Override @@ -276,16 +288,19 @@ public class UpdateMessageService { } } else if ("screen".equals(type)) { try { - if (!update.has("action_list")) + if (!update.has("action_list")) { return null; + } JSONArray screens = update.getJSONArray("action_list"); - if (screens.length() == 0) + if (screens.length() == 0) { return null; + } final ArrayList screenList = new ArrayList(); for (int i = 0; i < screens.length(); i++) { String screen = screens.getString(i).trim(); - if (!TextUtils.isEmpty(screen)) + if (!TextUtils.isEmpty(screen)) { screenList.add(screen); + } } return new View.OnClickListener() { @Override @@ -304,22 +319,25 @@ public class UpdateMessageService { private boolean pluginConditionMatches(String plugin) { // handle internal plugin specially - if (PLUGIN_GTASKS.equals(plugin)) + if (PLUGIN_GTASKS.equals(plugin)) { return gtasksPreferenceService.isLoggedIn(); - else + } else { return addOnService.isInstalled(plugin); + } } private boolean messageAlreadySeen(String date, String message) { - if (date != null) + if (date != null) { message = date + message; + } String hash = AndroidUtilities.md5(message); TodorooCursor cursor = storeObjectDao.query(Query.select(StoreObject.ID). where(StoreObjectCriteria.byTypeAndItem(UpdateMessage.TYPE, hash))); try { - if (cursor.getCount() > 0) + if (cursor.getCount() > 0) { return true; + } } finally { cursor.close(); } @@ -342,8 +360,9 @@ public class UpdateMessageService { "actfm=" + (actFmPreferenceService.isLoggedIn() ? "1" : "0") + "&" + "premium=" + (ActFmPreferenceService.isPremiumUser() ? "1" : "0"); String result = restClient.get(url); //$NON-NLS-1$ - if (TextUtils.isEmpty(result)) + if (TextUtils.isEmpty(result)) { return null; + } return new JSONArray(result); } catch (IOException e) { diff --git a/astrid/src/com/todoroo/astrid/service/UpdateScreenFlow.java b/astrid/src/com/todoroo/astrid/service/UpdateScreenFlow.java index 27fa45283..e74527528 100644 --- a/astrid/src/com/todoroo/astrid/service/UpdateScreenFlow.java +++ b/astrid/src/com/todoroo/astrid/service/UpdateScreenFlow.java @@ -20,8 +20,9 @@ public class UpdateScreenFlow extends Activity { super.onCreate(savedInstanceState); screens = getIntent().getStringArrayListExtra(TOKEN_SCREENS); currIndex = 0; - if (screens.size() == 0) + if (screens.size() == 0) { finish(); + } startActivityFromString(screens.get(0)); } diff --git a/astrid/src/com/todoroo/astrid/service/UpgradeService.java b/astrid/src/com/todoroo/astrid/service/UpgradeService.java index a380fc0fe..7a9c92270 100644 --- a/astrid/src/com/todoroo/astrid/service/UpgradeService.java +++ b/astrid/src/com/todoroo/astrid/service/UpgradeService.java @@ -175,14 +175,16 @@ public final class UpgradeService { * @param to */ public void performUpgrade(final Activity context, final int from) { - if (from == 135) + if (from == 135) { AddOnService.recordOem(); + } if (from > 0 && from < V3_8_2) { - if (Preferences.getBoolean(R.string.p_transparent_deprecated, false)) + if (Preferences.getBoolean(R.string.p_transparent_deprecated, false)) { Preferences.setString(R.string.p_theme, "transparent"); //$NON-NLS-1$ - else + } else { Preferences.setString(R.string.p_theme, "black"); //$NON-NLS-1$ + } } if (from <= V3_9_1_1) { @@ -227,31 +229,38 @@ public final class UpgradeService { @Override public void run() { try { - if (from < V3_0_0) + if (from < V3_0_0) { new Astrid2To3UpgradeHelper().upgrade2To3(UpgradeActivity.this, from); + } - if (from < V3_1_0) + if (from < V3_1_0) { new Astrid2To3UpgradeHelper().upgrade3To3_1(UpgradeActivity.this, from); + } - if (from < V3_8_3_1) + if (from < V3_8_3_1) { new TagCaseMigrator().performTagCaseMigration(UpgradeActivity.this); + } - if (from < V3_8_4 && Preferences.getBoolean(R.string.p_showNotes, false)) + if (from < V3_8_4 && Preferences.getBoolean(R.string.p_showNotes, false)) { taskService.clearDetails(Task.NOTES.neq("")); //$NON-NLS-1$ + } - if (from < V4_0_6) + if (from < V4_0_6) { new DueDateTimeMigrator().migrateDueTimes(); + } - if (from < V4_4_2) + if (from < V4_4_2) { new SubtasksMetadataMigration().performMigration(); + } if (from < V4_6_0_BETA) { if (Preferences.getBoolean(R.string.p_use_filters, false)) { TodorooCursor cursor = PluginServices.getStoreObjectDao().query(Query.select(StoreObject.PROPERTIES).where( StoreObject.TYPE.eq(SavedFilter.TYPE)).limit(1)); try { - if (cursor.getCount() == 0) + if (cursor.getCount() == 0) { Preferences.setBoolean(R.string.p_use_filters, false); + } } finally { cursor.close(); } @@ -288,8 +297,9 @@ public final class UpgradeService { @Override public void onBackPressed() { // Don't allow the back button to finish this activity before things are done - if (finished) + if (finished) { super.onBackPressed(); + } } } @@ -308,8 +318,9 @@ public final class UpgradeService { } if (from < V4_6_3) { - if (ActFmPreferenceService.isPremiumUser()) + if (ActFmPreferenceService.isPremiumUser()) { Preferences.clear(NameMaps.PUSHED_AT_TAGS); + } Preferences.setLong(TaskListFragment.PREF_LAST_FEEDBACK_TIME, DateUtilities.now()); } } @@ -324,8 +335,9 @@ public final class UpgradeService { */ @SuppressWarnings("nls") public void showChangeLog(Context context, int from) { - if (!(context instanceof Activity) || from == 0) + if (!(context instanceof Activity) || from == 0) { return; + } Preferences.clear(TagCaseMigrator.PREF_SHOW_MIGRATION_ALERT); @@ -716,8 +728,9 @@ public final class UpgradeService { "Fixed bug with custom filters & tasks being hidden.", }); upgrade3To3_7(); - if (gtasksPreferenceService.isLoggedIn()) + if (gtasksPreferenceService.isLoggedIn()) { taskService.clearDetails(Criterion.all); + } Preferences.setBoolean(Eula.PREFERENCE_EULA_ACCEPTED, true); } if (from >= V3_0_0 && from < V3_6_0) { @@ -731,12 +744,13 @@ public final class UpgradeService { }); upgrade3To3_6(context); } - if (from >= V3_0_0 && from < V3_5_0) + if (from >= V3_0_0 && from < V3_5_0) { newVersionString(changeLog, "3.5.0 (10/25/10)", new String[]{ "Google Tasks Sync (beta!)", "Bug fix with RMilk & new tasks not getting synced", "Fixed Force Closes and other bugs", }); + } if (from >= V3_0_0 && from < V3_4_0) { newVersionString(changeLog, "3.4.0 (10/08/10)", new String[]{ "End User License Agreement", @@ -744,7 +758,7 @@ public final class UpgradeService { "Bug fixes with Producteev", }); } - if (from >= V3_0_0 && from < V3_3_0) + if (from >= V3_0_0 && from < V3_3_0) { newVersionString(changeLog, "3.3.0 (9/17/10)", new String[]{ "Fixed some RTM duplicated tasks issues", "UI updates based on your feedback", @@ -752,7 +766,8 @@ public final class UpgradeService { "Added preference option for selecting snooze style", "Hide until: now allows you to pick a specific time", }); - if (from >= V3_0_0 && from < V3_2_0) + } + if (from >= V3_0_0 && from < V3_2_0) { newVersionString(changeLog, "3.2.0 (8/16/10)", new String[]{ "Build your own custom filters from the Filter page", "Easy task sorting (in the task list menu)", @@ -761,7 +776,8 @@ public final class UpgradeService { "Select tags by drop-down box", "Cosmetic improvements, calendar & sync bug fixes", }); - if (from >= V3_0_0 && from < V3_1_0) + } + if (from >= V3_0_0 && from < V3_1_0) { newVersionString(changeLog, "3.1.0 (8/9/10)", new String[]{ "Linkify phone numbers, e-mails, and web pages", "Swipe L => R to go from tasks to filters", @@ -771,9 +787,11 @@ public final class UpgradeService { "FROYO: disabled moving app to SD card, it would break alarms and widget", "Also gone: a couple force closes, bugs with repeating tasks", }); + } - if (changeLog.length() == 0) + if (changeLog.length() == 0) { return; + } changeLog.append("Enjoy!"); String color = ThemeService.getDialogTextColorString(); @@ -792,11 +810,13 @@ public final class UpgradeService { */ @SuppressWarnings("nls") private void newVersionString(StringBuilder changeLog, String version, String[] changes) { - if (Constants.ASTRID_LITE) + if (Constants.ASTRID_LITE) { version = "0" + version.substring(1); + } changeLog.append("Version ").append(version).append(":
      "); - for (String change : changes) + for (String change : changes) { changeLog.append("
    • ").append(change).append("
    • \n"); + } changeLog.append("
    "); } diff --git a/astrid/src/com/todoroo/astrid/service/abtesting/ABChooser.java b/astrid/src/com/todoroo/astrid/service/abtesting/ABChooser.java index f5da460a3..7193a9bc1 100644 --- a/astrid/src/com/todoroo/astrid/service/abtesting/ABChooser.java +++ b/astrid/src/com/todoroo/astrid/service/abtesting/ABChooser.java @@ -55,7 +55,9 @@ public class ABChooser { */ private void makeChoiceForTest(String testKey, boolean newUser, boolean activatedUser) { int pref = readChoiceForTest(testKey); - if (pref > NO_OPTION) return; + if (pref > NO_OPTION) { + return; + } int chosen = NO_OPTION; if (abTests.isValidTestKey(testKey)) { @@ -88,8 +90,9 @@ public class ABChooser { * @param choiceIndex */ public void setChoiceForTest(String testKey, int choiceIndex) { - if (abTests.isValidTestKey(testKey)) + if (abTests.isValidTestKey(testKey)) { Preferences.setInt(testKey, choiceIndex); + } } /* @@ -99,13 +102,17 @@ public class ABChooser { private int chooseOption(int[] optionProbs) { int sum = 0; for (int opt : optionProbs) // Compute sum + { sum += opt; + } double rand = random.nextDouble() * sum; // Get uniformly distributed double between [0, sum) sum = 0; for (int i = 0; i < optionProbs.length; i++) { sum += optionProbs[i]; - if (rand <= sum) return i; + if (rand <= sum) { + return i; + } } return optionProbs.length - 1; } diff --git a/astrid/src/com/todoroo/astrid/service/abtesting/ABTestEventReportingService.java b/astrid/src/com/todoroo/astrid/service/abtesting/ABTestEventReportingService.java index 1fcc1f87f..1a8324706 100644 --- a/astrid/src/com/todoroo/astrid/service/abtesting/ABTestEventReportingService.java +++ b/astrid/src/com/todoroo/astrid/service/abtesting/ABTestEventReportingService.java @@ -89,8 +89,9 @@ public final class ABTestEventReportingService { private void pushAllUnreportedABTestEvents() { synchronized (ABTestEventReportingService.class) { - if (StatisticsService.dontCollectStatistics()) + if (StatisticsService.dontCollectStatistics()) { return; + } final TodorooCursor unreported = abTestEventDao.query(Query.select(ABTestEvent.PROPERTIES) .where(ABTestEvent.REPORTED.eq(0)) .orderBy(Order.asc(ABTestEvent.TEST_NAME), Order.asc(ABTestEvent.TIME_INTERVAL))); @@ -117,10 +118,12 @@ public final class ABTestEventReportingService { private void reportUserActivation() { synchronized (ABTestEventReportingService.class) { - if (StatisticsService.dontCollectStatistics()) + if (StatisticsService.dontCollectStatistics()) { return; - if (Preferences.getBoolean(PREF_REPORTED_ACTIVATION, false) || !taskService.getUserActivationStatus()) + } + if (Preferences.getBoolean(PREF_REPORTED_ACTIVATION, false) || !taskService.getUserActivationStatus()) { return; + } final TodorooCursor variants = abTestEventDao.query(Query.select(ABTestEvent.PROPERTIES) .groupBy(ABTestEvent.TEST_NAME)); @@ -175,8 +178,9 @@ public final class ABTestEventReportingService { for (events.moveToFirst(); !events.isAfterLast(); events.moveToNext()) { model.readFromCursor(events); if (!model.getValue(ABTestEvent.TEST_NAME).equals(lastTestKey)) { - if (testAcc != null) + if (testAcc != null) { result.put(testAcc); + } testAcc = jsonFromABTestEvent(model); lastTestKey = model.getValue(ABTestEvent.TEST_NAME); } else { @@ -188,8 +192,9 @@ public final class ABTestEventReportingService { } } - if (testAcc != null) + if (testAcc != null) { result.put(testAcc); + } return result; } @@ -202,10 +207,11 @@ public final class ABTestEventReportingService { JSONObject event = new JSONObject(); event.put(KEY_TEST, model.getValue(ABTestEvent.TEST_NAME)); event.put(KEY_VARIANT, model.getValue(ABTestEvent.TEST_VARIANT)); - if (model.getValue(ABTestEvent.ACTIVATED_USER) > 0) + if (model.getValue(ABTestEvent.ACTIVATED_USER) > 0) { event.put(KEY_INITIAL, true); - else + } else { event.put(KEY_ACTIVATION, true); + } result.put(event); } return result; diff --git a/astrid/src/com/todoroo/astrid/service/abtesting/ABTestInvoker.java b/astrid/src/com/todoroo/astrid/service/abtesting/ABTestInvoker.java index c1d5d8a86..03e928ff6 100644 --- a/astrid/src/com/todoroo/astrid/service/abtesting/ABTestInvoker.java +++ b/astrid/src/com/todoroo/astrid/service/abtesting/ABTestInvoker.java @@ -106,13 +106,15 @@ public class ABTestInvoker { List params = new ArrayList(); params.add(new BasicNameValuePair("apikey", API_KEY)); - if (payload != null) + if (payload != null) { params.add(new BasicNameValuePair("payload", payload.toString())); + } StringBuilder sigBuilder = new StringBuilder(); for (NameValuePair entry : params) { - if (entry.getValue() == null) + if (entry.getValue() == null) { continue; + } String key = entry.getName(); String value = entry.getValue(); diff --git a/astrid/src/com/todoroo/astrid/service/abtesting/ABTests.java b/astrid/src/com/todoroo/astrid/service/abtesting/ABTests.java index 2019ea04d..c240276de 100644 --- a/astrid/src/com/todoroo/astrid/service/abtesting/ABTests.java +++ b/astrid/src/com/todoroo/astrid/service/abtesting/ABTests.java @@ -45,10 +45,11 @@ public class ABTests { public synchronized int[] getProbsForTestKey(String key, boolean newUser) { if (bundles.containsKey(key)) { ABTestBundle bundle = bundles.get(key); - if (newUser) + if (newUser) { return bundle.newUserProbs; - else + } else { return bundle.existingUserProbs; + } } else { return null; } diff --git a/astrid/src/com/todoroo/astrid/ui/AstridDialog.java b/astrid/src/com/todoroo/astrid/ui/AstridDialog.java index 319716a51..b861a23fe 100644 --- a/astrid/src/com/todoroo/astrid/ui/AstridDialog.java +++ b/astrid/src/com/todoroo/astrid/ui/AstridDialog.java @@ -59,8 +59,9 @@ public class AstridDialog extends Dialog { for (View.OnClickListener l : listeners) { buttons[index].setOnClickListener(l); index++; - if (index >= buttons.length) + if (index >= buttons.length) { break; + } } return this; } diff --git a/astrid/src/com/todoroo/astrid/ui/AstridTimePicker.java b/astrid/src/com/todoroo/astrid/ui/AstridTimePicker.java index 76e49ce61..cc2a9ad32 100644 --- a/astrid/src/com/todoroo/astrid/ui/AstridTimePicker.java +++ b/astrid/src/com/todoroo/astrid/ui/AstridTimePicker.java @@ -54,10 +54,11 @@ public class AstridTimePicker extends LinearLayout { hours = (NumberPicker) findViewById(R.id.hours); minutes = (NumberPicker) findViewById(R.id.minutes); - if (Preferences.getBoolean(R.string.p_time_increment, false)) + if (Preferences.getBoolean(R.string.p_time_increment, false)) { minutes.setIncrementBy(5); - else + } else { minutes.setIncrementBy(1); + } setupButtonBackgrounds(context); @@ -174,8 +175,9 @@ public class AstridTimePicker extends LinearLayout { } public void setHasTime(boolean hasTime, boolean setChecked) { - if (setChecked) + if (setChecked) { noTimeCheck.setChecked(!hasTime); + } if (noTimeCheck.isChecked()) { @@ -193,8 +195,9 @@ public class AstridTimePicker extends LinearLayout { pmButton.setChecked(lastSelectionWasPm); } - if (listener != null) + if (listener != null) { listener.timePickerEnabledChanged(hasTime); + } } public boolean hasTime() { @@ -202,8 +205,9 @@ public class AstridTimePicker extends LinearLayout { } public void forceNoTime() { - if (!noTimeCheck.isChecked()) + if (!noTimeCheck.isChecked()) { noTimeCheck.performClick(); + } } public void setHours(int hour) { @@ -228,8 +232,9 @@ public class AstridTimePicker extends LinearLayout { int toReturn = hours.getCurrent(); if (!is24Hour) { if (toReturn == 12) { - if (amButton.isChecked()) + if (amButton.isChecked()) { toReturn = 0; + } } else if (pmButton.isChecked()) { toReturn += 12; } diff --git a/astrid/src/com/todoroo/astrid/ui/CalendarView.java b/astrid/src/com/todoroo/astrid/ui/CalendarView.java index 6bbe25a0d..b849a97f6 100644 --- a/astrid/src/com/todoroo/astrid/ui/CalendarView.java +++ b/astrid/src/com/todoroo/astrid/ui/CalendarView.java @@ -339,15 +339,17 @@ public class CalendarView extends View { int today = -1; Calendar todayCalendar = Calendar.getInstance(); if (calendar.get(Calendar.MONTH) == todayCalendar.get(Calendar.MONTH) && - calendar.get(Calendar.YEAR) == todayCalendar.get(Calendar.YEAR)) + calendar.get(Calendar.YEAR) == todayCalendar.get(Calendar.YEAR)) { today = todayCalendar.get(Calendar.DATE); + } int lastDateOfThisMonth = calendar.getActualMaximum(Calendar.DATE); calendar.set(Calendar.DATE, 1); // offset for day of week int firstDayOfMonth = calendar.get(Calendar.DAY_OF_WEEK) - firstDayOfWeek + Calendar.SUNDAY; - if (firstDayOfMonth == 0) + if (firstDayOfMonth == 0) { firstDayOfMonth = 7; + } boolean firstTime = true; int dayOfMonth = 1; Paint colorPaint; @@ -427,8 +429,9 @@ public class CalendarView extends View { currentHighlightDay = calendar.get(Calendar.DATE); this.invalidate(); - if (onSelectedDateListener != null) + if (onSelectedDateListener != null) { onSelectedDateListener.onSelectedDate(calendarDate); + } } else if ((x > rightArrowX - rightArrowWidth && x < (rightArrowX + rightArrowWidth)) && (y > rightArrowY - rightArrowHeight / 2 && y < (rightArrowY + 3 * rightArrowHeight / 2))) { Calendar calendar = Calendar.getInstance(); @@ -442,8 +445,9 @@ public class CalendarView extends View { currentHighlightDay = calendar.get(Calendar.DATE); this.invalidate(); - if (onSelectedDateListener != null) + if (onSelectedDateListener != null) { onSelectedDateListener.onSelectedDate(calendarDate); + } // Handle left-right arrow click -- end } else if (dayLeftArr != null) { // Check if clicked on date @@ -462,8 +466,9 @@ public class CalendarView extends View { calendarDate = calendar.getTime(); this.invalidate(); - if (onSelectedDateListener != null) + if (onSelectedDateListener != null) { onSelectedDateListener.onSelectedDate(calendarDate); + } } } } diff --git a/astrid/src/com/todoroo/astrid/ui/ContactListAdapter.java b/astrid/src/com/todoroo/astrid/ui/ContactListAdapter.java index ef16b0462..f6cdb09dd 100644 --- a/astrid/src/com/todoroo/astrid/ui/ContactListAdapter.java +++ b/astrid/src/com/todoroo/astrid/ui/ContactListAdapter.java @@ -110,17 +110,20 @@ public class ContactListAdapter extends CursorAdapter { protected Bitmap doInBackground(Uri... params) { uri = params[0]; InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(mContent, uri); - if (input == null) + if (input == null) { return null; + } return BitmapFactory.decodeStream(input); } @Override protected void onPostExecute(Bitmap bitmap) { - if (isCancelled()) + if (isCancelled()) { bitmap = null; - if (imageView != null && uri.equals(imageView.getTag()) && bitmap != null) + } + if (imageView != null && uri.equals(imageView.getTag()) && bitmap != null) { imageView.setImageBitmap(bitmap); + } } } @@ -129,8 +132,9 @@ public class ContactListAdapter extends CursorAdapter { if (cursor.getColumnIndex(Email.DATA) > -1) { int name = cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME); int email = cursor.getColumnIndexOrThrow(Email.DATA); - if (cursor.isNull(name)) + if (cursor.isNull(name)) { return cursor.getString(email); + } return cursor.getString(name) + " <" + cursor.getString(email) + ">"; } else { int name = cursor.getColumnIndexOrThrow(TagData.NAME.name); @@ -150,14 +154,16 @@ public class ContactListAdapter extends CursorAdapter { Cursor peopleCursor = mContent.query(uri, PEOPLE_PROJECTION, null, null, sort); - if (!completeSharedTags) + if (!completeSharedTags) { return peopleCursor; + } Criterion crit = Criterion.all; - if (constraint != null) + if (constraint != null) { crit = Functions.upper(TagData.NAME).like("%" + constraint.toString().toUpperCase() + "%"); - else + } else { crit = Criterion.none; + } Cursor tagCursor = tagDataService.query(Query.select(TagData.ID, TagData.NAME, TagData.PICTURE, TagData.THUMB). where(Criterion.and(TagData.USER_ID.eq(0), TagData.MEMBER_COUNT.gt(0), crit)).orderBy(Order.desc(TagData.NAME))); diff --git a/astrid/src/com/todoroo/astrid/ui/ContactsAutoComplete.java b/astrid/src/com/todoroo/astrid/ui/ContactsAutoComplete.java index 747b697ac..93750fc1b 100644 --- a/astrid/src/com/todoroo/astrid/ui/ContactsAutoComplete.java +++ b/astrid/src/com/todoroo/astrid/ui/ContactsAutoComplete.java @@ -62,8 +62,9 @@ public class ContactsAutoComplete extends AutoCompleteTextView { filterText = filterText.substring(filterText.lastIndexOf(getSeperator()) + 1); } - if (!TextUtils.isEmpty(filterText)) + if (!TextUtils.isEmpty(filterText)) { super.performFiltering(filterText, keyCode); + } } /** @@ -71,10 +72,11 @@ public class ContactsAutoComplete extends AutoCompleteTextView { */ @Override protected void replaceText(final CharSequence text) { - if (allowMultiple) + if (allowMultiple) { super.replaceText(previous + text + getSeperator()); - else + } else { super.replaceText(text); + } } // --- cursor stuff @@ -101,8 +103,9 @@ public class ContactsAutoComplete extends AutoCompleteTextView { public void setCompleteSharedTags(boolean value) { completeTags = value; - if (adapter != null) + if (adapter != null) { adapter.setCompleteSharedTags(value); + } } public void setAllowMultiple(boolean allowMultiple) { diff --git a/astrid/src/com/todoroo/astrid/ui/DateAndTimeDialog.java b/astrid/src/com/todoroo/astrid/ui/DateAndTimeDialog.java index f8a4d3c5e..ace3e3246 100644 --- a/astrid/src/com/todoroo/astrid/ui/DateAndTimeDialog.java +++ b/astrid/src/com/todoroo/astrid/ui/DateAndTimeDialog.java @@ -38,10 +38,11 @@ public class DateAndTimeDialog extends Dialog { public DateAndTimeDialog(Context context, long startDate, int contentView, int title) { super(context, ThemeService.getEditDialogTheme()); - if (title == 0) + if (title == 0) { requestWindowFeature(Window.FEATURE_NO_TITLE); - else + } else { setTitle(title); + } /** Design the dialog in main.xml file */ setContentView(contentView); @@ -60,8 +61,9 @@ public class DateAndTimeDialog extends Dialog { @Override public void onClick(View v) { dismiss(); - if (listener != null) + if (listener != null) { listener.onDateAndTimeSelected(dateAndTimePicker.constructDueDate()); + } } }); @@ -70,8 +72,9 @@ public class DateAndTimeDialog extends Dialog { public void onClick(View v) { cancelled = true; cancel(); - if (listener != null) + if (listener != null) { listener.onDateAndTimeCancelled(); + } } }); @@ -79,8 +82,9 @@ public class DateAndTimeDialog extends Dialog { @Override public void onCancel(DialogInterface dialog) { if (!cancelled) { // i.e. if back button pressed, which we treat as an "OK" - if (listener != null) + if (listener != null) { listener.onDateAndTimeSelected(dateAndTimePicker.constructDueDate()); + } } else { cancelled = false; // reset } diff --git a/astrid/src/com/todoroo/astrid/ui/DateAndTimePicker.java b/astrid/src/com/todoroo/astrid/ui/DateAndTimePicker.java index ec7fb9d05..fb9ddd4e3 100644 --- a/astrid/src/com/todoroo/astrid/ui/DateAndTimePicker.java +++ b/astrid/src/com/todoroo/astrid/ui/DateAndTimePicker.java @@ -72,9 +72,9 @@ public class DateAndTimePicker extends LinearLayout { calendarView = (CalendarView) findViewById(R.id.calendar); timePicker = (AstridTimePicker) findViewById(R.id.time_picker); - if (useShortcuts) + if (useShortcuts) { dateShortcuts = (LinearLayout) findViewById(R.id.date_shortcuts); - else { + } else { findViewById(R.id.date_shortcuts).setVisibility(View.GONE); dateShortcuts = (LinearLayout) timePicker.findViewById(R.id.date_shortcuts); } @@ -87,10 +87,11 @@ public class DateAndTimePicker extends LinearLayout { public void initializeWithDate(long dateValue) { Date date = new Date(dateValue); Date forCalendar; - if (dateValue > 0) + if (dateValue > 0) { forCalendar = getDateForCalendar(date); - else + } else { forCalendar = date; + } calendarView.setCalendarDate(forCalendar); if (Task.hasDueTime(dateValue)) { timePicker.setHours(date.getHours()); @@ -137,8 +138,9 @@ public class DateAndTimePicker extends LinearLayout { Date date = new Date(todayUrgency.dueDate); calendarView.setCalendarDate(date); calendarView.invalidate(); - if (todayUrgency.setting == Task.URGENCY_NONE) + if (todayUrgency.setting == Task.URGENCY_NONE) { timePicker.forceNoTime(); + } updateShortcutView(date); otherCallbacks(); } @@ -192,10 +194,11 @@ public class DateAndTimePicker extends LinearLayout { tb.setTextOn(label); tb.setTag(uv); if (i == 0) { - if (useShortcuts) + if (useShortcuts) { tb.setBackgroundDrawable(CustomBorderDrawable.customButton(cornerRadius, cornerRadius, cornerRadius, cornerRadius, onColorValue, offColorValue, borderColorValue, strokeWidth)); - else + } else { tb.setBackgroundDrawable(CustomBorderDrawable.customButton(cornerRadius, cornerRadius, cornerRadius, cornerRadius, onColorValue, offColorValue, borderColorValue, strokeWidth)); + } } else if (i == urgencyValues.size() - 2) { lp.topMargin = (int) (-1 * metrics.density); tb.setBackgroundDrawable(CustomBorderDrawable.customButton(cornerRadius, cornerRadius, cornerRadius, cornerRadius, onColorValue, offColorValue, borderColorValue, strokeWidth)); @@ -220,8 +223,9 @@ public class DateAndTimePicker extends LinearLayout { Date date = new Date(value.dueDate); calendarView.setCalendarDate(date); calendarView.invalidate(); - if (value.setting == Task.URGENCY_NONE) + if (value.setting == Task.URGENCY_NONE) { timePicker.forceNoTime(); + } updateShortcutView(date); otherCallbacks(); } @@ -248,8 +252,9 @@ public class DateAndTimePicker extends LinearLayout { } private void otherCallbacks() { - if (listener != null) + if (listener != null) { listener.onDateChanged(); + } } public long constructDueDate() { @@ -290,10 +295,11 @@ public class DateAndTimePicker extends LinearLayout { StringBuilder displayString = new StringBuilder(); Date d = new Date(forDate); if (d.getTime() > 0) { - if (hideYear) + if (hideYear) { displayString.append(DateUtilities.getDateStringHideYear(context, d)); - else + } else { displayString.append(DateUtilities.getDateString(context, d)); + } if (Task.hasDueTime(forDate) && !hideTime) { displayString.append(useNewline ? "\n" : ", "); //$NON-NLS-1$ //$NON-NLS-2$ displayString.append(DateUtilities.getTimeString(context, d)); diff --git a/astrid/src/com/todoroo/astrid/ui/DateChangedAlerts.java b/astrid/src/com/todoroo/astrid/ui/DateChangedAlerts.java index 5719d90ba..fc2c66476 100644 --- a/astrid/src/com/todoroo/astrid/ui/DateChangedAlerts.java +++ b/astrid/src/com/todoroo/astrid/ui/DateChangedAlerts.java @@ -62,8 +62,9 @@ public class DateChangedAlerts { public static void showQuickAddMarkupDialog(final AstridActivity activity, Task task, String originalText) { - if (!Preferences.getBoolean(PREF_SHOW_HELPERS, true)) + if (!Preferences.getBoolean(PREF_SHOW_HELPERS, true)) { return; + } final Dialog d = new Dialog(activity, R.style.ReminderDialog); final long taskId = task.getId(); @@ -97,8 +98,9 @@ public class DateChangedAlerts { } public static void showRepeatChangedDialog(final AstridActivity activity, Task task) { - if (!Preferences.getBoolean(PREF_SHOW_HELPERS, true)) + if (!Preferences.getBoolean(PREF_SHOW_HELPERS, true)) { return; + } final Dialog d = new Dialog(activity, R.style.ReminderDialog); d.setContentView(R.layout.astrid_reminder_view); @@ -134,8 +136,9 @@ public class DateChangedAlerts { public static void showRepeatTaskRescheduledDialog(final AstridActivity activity, final Task task, final long oldDueDate, final long newDueDate, final boolean lastTime) { - if (!Preferences.getBoolean(PREF_SHOW_HELPERS, true)) + if (!Preferences.getBoolean(PREF_SHOW_HELPERS, true)) { return; + } final Dialog d = new Dialog(activity, R.style.ReminderDialog); @@ -189,12 +192,13 @@ public class DateChangedAlerts { String encouragement = encouragements[(int) (Math.random() * encouragements.length)]; String speechBubbleText; - if (lastTime) + if (lastTime) { speechBubbleText = activity.getString(R.string.repeat_rescheduling_dialog_bubble_last_time, repeatUntilDateString, encouragement); - else if (!TextUtils.isEmpty(oldDueDateString)) + } else if (!TextUtils.isEmpty(oldDueDateString)) { speechBubbleText = activity.getString(R.string.repeat_rescheduling_dialog_bubble, encouragement, oldDueDateString, newDueDateString); - else + } else { speechBubbleText = activity.getString(R.string.repeat_rescheduling_dialog_bubble_no_date, encouragement, newDueDateString); + } ((TextView) d.findViewById(R.id.reminder_message)).setText(speechBubbleText); @@ -208,8 +212,9 @@ public class DateChangedAlerts { task.setValue(Task.DUE_DATE, oldDueDate); task.setValue(Task.COMPLETION_DATE, 0L); long hideUntil = task.getValue(Task.HIDE_UNTIL); - if (hideUntil > 0) + if (hideUntil > 0) { task.setValue(Task.HIDE_UNTIL, hideUntil - (newDueDate - oldDueDate)); + } PluginServices.getTaskService().save(task); Flags.set(Flags.REFRESH); } @@ -284,12 +289,14 @@ public class DateChangedAlerts { dueString = getRelativeDateAndTimeString(context, date); } - if (!TextUtils.isEmpty(dueString)) + if (!TextUtils.isEmpty(dueString)) { dueString = context.getString(R.string.TLA_quickadd_confirm_speech_bubble_date, dueString); + } int priority = task.getValue(Task.IMPORTANCE); - if (priority >= priorityStrings.length) + if (priority >= priorityStrings.length) { priority = priorityStrings.length - 1; + } String priorityString = priorityStrings[priority]; int color = context.getResources().getColor(colorsArray[priority]) - 0xff000000; priorityString = String.format("%s", Integer.toHexString(color), priorityString); @@ -306,9 +313,10 @@ public class DateChangedAlerts { @SuppressWarnings("nls") private static String getRelativeDateAndTimeString(Context context, long date) { String dueString = date > 0 ? DateUtilities.getRelativeDay(context, date, false) : ""; - if (Task.hasDueTime(date)) + if (Task.hasDueTime(date)) { dueString = String.format("%s at %s", dueString, //$NON-NLS-1$ DateUtilities.getTimeString(context, new Date(date))); + } return dueString; } diff --git a/astrid/src/com/todoroo/astrid/ui/DeadlineControlSet.java b/astrid/src/com/todoroo/astrid/ui/DeadlineControlSet.java index 8b708870a..9742fd66f 100644 --- a/astrid/src/com/todoroo/astrid/ui/DeadlineControlSet.java +++ b/astrid/src/com/todoroo/astrid/ui/DeadlineControlSet.java @@ -119,7 +119,9 @@ public class DeadlineControlSet extends PopupControlSet { protected String writeToModelAfterInitialized(Task task) { long dueDate = dateAndTimePicker.constructDueDate(); if (dueDate != task.getValue(Task.DUE_DATE)) // Clear snooze if due date has changed + { task.setValue(Task.REMINDER_SNOOZE, 0L); + } task.setValue(Task.DUE_DATE, dueDate); return null; } diff --git a/astrid/src/com/todoroo/astrid/ui/DeadlineTimePickerDialog.java b/astrid/src/com/todoroo/astrid/ui/DeadlineTimePickerDialog.java index 441863f81..ad0b0f1b6 100644 --- a/astrid/src/com/todoroo/astrid/ui/DeadlineTimePickerDialog.java +++ b/astrid/src/com/todoroo/astrid/ui/DeadlineTimePickerDialog.java @@ -123,10 +123,11 @@ public class DeadlineTimePickerDialog extends AlertDialog implements OnClickList public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mTimePicker.setEnabled(isChecked); - if (isChecked) + if (isChecked) { updateTitle(); - else + } else { setTitle(R.string.TEA_urgency_none); + } } }; mHasTime.setOnCheckedChangeListener(listener); diff --git a/astrid/src/com/todoroo/astrid/ui/DraggableListView.java b/astrid/src/com/todoroo/astrid/ui/DraggableListView.java index b13ebc25f..cbd73cb5b 100644 --- a/astrid/src/com/todoroo/astrid/ui/DraggableListView.java +++ b/astrid/src/com/todoroo/astrid/ui/DraggableListView.java @@ -243,8 +243,9 @@ public class DraggableListView extends ListView { @Override public boolean onTouchEvent(MotionEvent ev) { - if (mGestureDetector != null) + if (mGestureDetector != null) { mGestureDetector.onTouchEvent(ev); + } mTouchCurrentX = ev.getX(); mTouchCurrentY = ev.getY(); @@ -259,15 +260,17 @@ public class DraggableListView extends ListView { if (dragThread != null && mClickListener != null) { dragThread.interrupt(); dragThread = null; - if (action == MotionEvent.ACTION_UP) + if (action == MotionEvent.ACTION_UP) { mClickListener.onClick(viewAtPosition()); + } } else if (mSwipeListener != null && Math.abs(mTouchCurrentY - mTouchStartY) < MOVEMENT_THRESHOLD) { int dragPos = pointToPosition((int) mTouchCurrentX, (int) mTouchCurrentY); - if (mTouchCurrentX > mTouchStartX + SWIPE_THRESHOLD) + if (mTouchCurrentX > mTouchStartX + SWIPE_THRESHOLD) { mSwipeListener.swipeRight(dragPos); - else if (mTouchCurrentX < mTouchStartX - SWIPE_THRESHOLD) + } else if (mTouchCurrentX < mTouchStartX - SWIPE_THRESHOLD) { mSwipeListener.swipeLeft(dragPos); + } } } @@ -287,8 +290,9 @@ public class DraggableListView extends ListView { mTouchStartY = ev.getY(); case MotionEvent.ACTION_MOVE: - if (mDragging) + if (mDragging) { dragView(ev); + } // detect scrolling if (dragThread != null && (Math.abs(mTouchCurrentX - mTouchStartX) > MOVEMENT_THRESHOLD || @@ -300,8 +304,9 @@ public class DraggableListView extends ListView { break; } - if (mDragging) + if (mDragging) { return true; + } return super.onTouchEvent(ev); } @@ -309,8 +314,9 @@ public class DraggableListView extends ListView { private View viewAtPosition() { int itemNum = pointToPosition((int) mTouchCurrentX, (int) mTouchCurrentY); - if (itemNum == AdapterView.INVALID_POSITION) + if (itemNum == AdapterView.INVALID_POSITION) { return null; + } return (View) getChildAt(itemNum - getFirstVisiblePosition()); } @@ -365,13 +371,15 @@ public class DraggableListView extends ListView { int y = (int) mTouchCurrentY; int itemNum = pointToPosition(x, y); - if (itemNum == AdapterView.INVALID_POSITION) + if (itemNum == AdapterView.INVALID_POSITION) { return false; + } View item = (View) getChildAt(itemNum - getFirstVisiblePosition()); - if (!isDraggableRow(item)) + if (!isDraggableRow(item)) { return false; + } mDragPoint = new Point(x - item.getLeft(), y - item.getTop()); mCoordOffset = new Point((int) ev.getRawX() - x, (int) ev.getRawY() - y); @@ -436,12 +444,13 @@ public class DraggableListView extends ListView { mWindowParams.y = y - mDragPoint.y + mCoordOffset.y; - if (mDragPos == mFirstDragPos && x > mTouchStartX + SWIPE_THRESHOLD) + if (mDragPos == mFirstDragPos && x > mTouchStartX + SWIPE_THRESHOLD) { mDragView.setPadding(30, 1, 0, 1); - else if (mDragPos == mFirstDragPos && x < mTouchStartX - SWIPE_THRESHOLD) + } else if (mDragPos == mFirstDragPos && x < mTouchStartX - SWIPE_THRESHOLD) { mDragView.setPadding(-30, 2, 0, 2); - else + } else { mDragView.setPadding(0, 0, 0, 0); + } mWindowManager.updateViewLayout(mDragView, mWindowParams); @@ -449,8 +458,9 @@ public class DraggableListView extends ListView { if (itemnum >= 0) { if (ev.getAction() == MotionEvent.ACTION_DOWN || itemnum != mDragPos) { - if (mDragListener != null) + if (mDragListener != null) { mDragListener.drag(mDragPos, itemnum); + } mDragPos = itemnum; doExpansion(); } @@ -498,14 +508,16 @@ public class DraggableListView extends ListView { if (mDragging) { if (mSwipeListener != null && mDragPos == mFirstDragPos) { - if (mTouchCurrentX > mTouchStartX + SWIPE_THRESHOLD) + if (mTouchCurrentX > mTouchStartX + SWIPE_THRESHOLD) { mSwipeListener.swipeRight(mFirstDragPos); - else if (mTouchCurrentX < mTouchStartX - SWIPE_THRESHOLD) + } else if (mTouchCurrentX < mTouchStartX - SWIPE_THRESHOLD) { mSwipeListener.swipeLeft(mFirstDragPos); + } } else if (mDropListener != null && mDragPos != mFirstDragPos && mDragPos >= 0 && mDragPos < getCount()) { - if (mFirstDragPos < mDragPos) + if (mFirstDragPos < mDragPos) { mDragPos++; + } mDropListener.drop(mFirstDragPos, mDragPos); } } diff --git a/astrid/src/com/todoroo/astrid/ui/EditNotesControlSet.java b/astrid/src/com/todoroo/astrid/ui/EditNotesControlSet.java index 0a66bd74d..7c23adea4 100644 --- a/astrid/src/com/todoroo/astrid/ui/EditNotesControlSet.java +++ b/astrid/src/com/todoroo/astrid/ui/EditNotesControlSet.java @@ -34,10 +34,11 @@ public class EditNotesControlSet extends PopupControlSet { @Override protected void refreshDisplayView() { String textToUse; - if (initialized) + if (initialized) { textToUse = editText.getText().toString(); - else + } else { textToUse = model.getValue(Task.NOTES); + } if (TextUtils.isEmpty(textToUse)) { notesPreview.setText(R.string.TEA_notes_empty); diff --git a/astrid/src/com/todoroo/astrid/ui/EditTitleControlSet.java b/astrid/src/com/todoroo/astrid/ui/EditTitleControlSet.java index 9949a9775..bd0933eb7 100644 --- a/astrid/src/com/todoroo/astrid/ui/EditTitleControlSet.java +++ b/astrid/src/com/todoroo/astrid/ui/EditTitleControlSet.java @@ -119,8 +119,9 @@ public class EditTitleControlSet extends TaskEditControlSet implements Importanc int[] resourceArray = isRepeating ? (checked ? TaskAdapter.IMPORTANCE_REPEAT_RESOURCES_CHECKED : TaskAdapter.IMPORTANCE_REPEAT_RESOURCES) : (checked ? TaskAdapter.IMPORTANCE_RESOURCES_CHECKED : TaskAdapter.IMPORTANCE_RESOURCES); int valueToUse = importanceValue; - if (valueToUse >= resourceArray.length) + if (valueToUse >= resourceArray.length) { valueToUse = resourceArray.length - 1; + } if (valueToUse < resourceArray.length) { if (isRepeating) { completeBox.setImageResource(resourceArray[valueToUse]); @@ -129,10 +130,11 @@ public class EditTitleControlSet extends TaskEditControlSet implements Importanc } } - if (checked) + if (checked) { editText.setPaintFlags(editText.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); - else + } else { editText.setPaintFlags(editText.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG); + } } } diff --git a/astrid/src/com/todoroo/astrid/ui/FragmentPopover.java b/astrid/src/com/todoroo/astrid/ui/FragmentPopover.java index d7183356b..69cd1e2c1 100644 --- a/astrid/src/com/todoroo/astrid/ui/FragmentPopover.java +++ b/astrid/src/com/todoroo/astrid/ui/FragmentPopover.java @@ -76,8 +76,9 @@ public class FragmentPopover extends QuickActionWidget { @Override public void show(View anchor) { - if (isShowing()) + if (isShowing()) { return; + } super.show(anchor); } } diff --git a/astrid/src/com/todoroo/astrid/ui/HideUntilControlSet.java b/astrid/src/com/todoroo/astrid/ui/HideUntilControlSet.java index 6c966a020..40f3ebbd1 100644 --- a/astrid/src/com/todoroo/astrid/ui/HideUntilControlSet.java +++ b/astrid/src/com/todoroo/astrid/ui/HideUntilControlSet.java @@ -91,8 +91,9 @@ public class HideUntilControlSet extends PopupControlSet implements OnItemSelect if (specificDate > 0) { HideUntilValue[] updated = new HideUntilValue[values.length + 1]; - for (int i = 0; i < values.length; i++) + for (int i = 0; i < values.length; i++) { updated[i + 1] = values[i]; + } Date hideUntilAsDate = new Date(specificDate); if (hideUntilAsDate.getHours() == 0 && hideUntilAsDate.getMinutes() == 0 && hideUntilAsDate.getSeconds() == 0) { updated[0] = new HideUntilValue(DateUtilities.getDateString(activity, new Date(specificDate)), @@ -176,8 +177,9 @@ public class HideUntilControlSet extends PopupControlSet implements OnItemSelect int setting = Preferences.getIntegerFromString(R.string.p_default_hideUntil_key, Task.HIDE_UNTIL_NONE); selection = setting; - if (spinner != null) + if (spinner != null) { spinner.setSelection(selection); + } refreshDisplayView(); } @@ -187,7 +189,9 @@ public class HideUntilControlSet extends PopupControlSet implements OnItemSelect @Override public void onClick(View v) { if (spinner == null) // Force load + { getView(); + } spinner.performClick(); } }; @@ -203,8 +207,9 @@ public class HideUntilControlSet extends PopupControlSet implements OnItemSelect image.setImageResource(R.drawable.tea_icn_hide_gray); } else { String display = value.toString(); - if (value.setting != Task.HIDE_UNTIL_SPECIFIC_DAY && value.setting != Task.HIDE_UNTIL_SPECIFIC_DAY_TIME) + if (value.setting != Task.HIDE_UNTIL_SPECIFIC_DAY && value.setting != Task.HIDE_UNTIL_SPECIFIC_DAY_TIME) { display = display.toLowerCase(); + } auxDisplay.setText(activity.getString(R.string.TEA_hideUntil_display, display)); auxDisplay.setTextColor(themeColor); @@ -268,16 +273,19 @@ public class HideUntilControlSet extends PopupControlSet implements OnItemSelect @Override protected String writeToModelAfterInitialized(Task task) { - if (adapter == null || spinner == null) + if (adapter == null || spinner == null) { return null; + } HideUntilValue item = adapter.getItem(spinner.getSelectedItemPosition()); - if (item == null) + if (item == null) { return null; + } long value = task.createHideUntil(item.setting, item.date); task.setValue(Task.HIDE_UNTIL, value); - if (value != 0) + if (value != 0) { return activity.getString(R.string.TEA_hideUntil_message, DateAndTimePicker.getDisplayString(activity, value, false, false, false)); + } return null; } diff --git a/astrid/src/com/todoroo/astrid/ui/ImportanceControlSet.java b/astrid/src/com/todoroo/astrid/ui/ImportanceControlSet.java index 425919921..a2f867c21 100644 --- a/astrid/src/com/todoroo/astrid/ui/ImportanceControlSet.java +++ b/astrid/src/com/todoroo/astrid/ui/ImportanceControlSet.java @@ -59,9 +59,11 @@ public class ImportanceControlSet extends TaskEditControlSet { } public Integer getImportance() { - for (CompoundButton b : buttons) - if (b.isChecked()) + for (CompoundButton b : buttons) { + if (b.isChecked()) { return (Integer) b.getTag(); + } + } return null; } @@ -70,8 +72,9 @@ public class ImportanceControlSet extends TaskEditControlSet { } public void removeListener(ImportanceChangedListener listener) { - if (listeners.contains(listener)) + if (listeners.contains(listener)) { listeners.remove(listener); + } } @Override @@ -93,10 +96,12 @@ public class ImportanceControlSet extends TaskEditControlSet { button.setLayoutParams(params); StringBuilder label = new StringBuilder(); - if (i == max) + if (i == max) { label.append('\u25CB'); - for (int j = Task.IMPORTANCE_LEAST - 1; j >= i; j--) + } + for (int j = Task.IMPORTANCE_LEAST - 1; j >= i; j--) { label.append('!'); + } button.setTextColor(colors[i]); button.setTextOff(label); @@ -137,8 +142,9 @@ public class ImportanceControlSet extends TaskEditControlSet { @Override protected String writeToModelAfterInitialized(Task task) { - if (getImportance() != null) + if (getImportance() != null) { task.setValue(Task.IMPORTANCE, getImportance()); + } return null; } } diff --git a/astrid/src/com/todoroo/astrid/ui/MainMenuPopover.java b/astrid/src/com/todoroo/astrid/ui/MainMenuPopover.java index 2821a738e..2883f7afd 100644 --- a/astrid/src/com/todoroo/astrid/ui/MainMenuPopover.java +++ b/astrid/src/com/todoroo/astrid/ui/MainMenuPopover.java @@ -66,10 +66,11 @@ public class MainMenuPopover extends FragmentPopover implements InterceptTouchLi } }); - if (AstridPreferences.useTabletLayout(context)) + if (AstridPreferences.useTabletLayout(context)) { rowLayout = R.layout.main_menu_row_tablet; - else + } else { rowLayout = R.layout.main_menu_row; + } inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); @@ -108,19 +109,21 @@ public class MainMenuPopover extends FragmentPopover implements InterceptTouchLi private void addFixedItems() { int themeFlags = isTablet ? ThemeService.FLAG_FORCE_DARK : 0; - if (Preferences.getBoolean(R.string.p_show_menu_search, true)) + if (Preferences.getBoolean(R.string.p_show_menu_search, true)) { addMenuItem(R.string.TLA_menu_search, ThemeService.getDrawable(R.drawable.icn_menu_search, themeFlags), MAIN_MENU_ITEM_SEARCH, null, topFixed); + } addMenuItem(R.string.TLA_menu_lists, ThemeService.getDrawable(R.drawable.icn_menu_lists, themeFlags), MAIN_MENU_ITEM_LISTS, null, topFixed); // Lists item - if (Preferences.getBoolean(R.string.p_show_friends_view, false) && Preferences.getBoolean(R.string.p_show_menu_friends, true)) + if (Preferences.getBoolean(R.string.p_show_friends_view, false) && Preferences.getBoolean(R.string.p_show_menu_friends, true)) { addMenuItem(R.string.TLA_menu_friends, ThemeService.getDrawable(R.drawable.icn_menu_friends, themeFlags), MAIN_MENU_ITEM_FRIENDS, null, topFixed); + } addMenuItem(R.string.TLA_menu_settings, ThemeService.getDrawable(R.drawable.icn_menu_settings, themeFlags), @@ -135,8 +138,9 @@ public class MainMenuPopover extends FragmentPopover implements InterceptTouchLi public void setFixedItemVisibility(int index, int visibility, boolean top) { LinearLayout container = top ? topFixed : bottomFixed; - if (index < 0 || index >= container.getChildCount()) + if (index < 0 || index >= container.getChildCount()) { return; + } container.getChildAt(index).setVisibility(visibility); } @@ -171,15 +175,17 @@ public class MainMenuPopover extends FragmentPopover implements InterceptTouchLi // --- Private helpers --- private void addMenuItem(int title, int imageRes, int id, Intent customIntent, ViewGroup container) { - if (mListener != null && !mListener.shouldAddMenuItem(id)) + if (mListener != null && !mListener.shouldAddMenuItem(id)) { return; + } View item = setupItemWithParams(title, imageRes); addViewWithListener(item, container, id, customIntent); } private void addMenuItem(CharSequence title, Drawable image, int id, Intent customIntent, ViewGroup container) { - if (mListener != null && !mListener.shouldAddMenuItem(id)) + if (mListener != null && !mListener.shouldAddMenuItem(id)) { return; + } View item = setupItemWithParams(title, image); addViewWithListener(item, container, id, customIntent); } @@ -190,8 +196,9 @@ public class MainMenuPopover extends FragmentPopover implements InterceptTouchLi @Override public void onClick(View v) { dismiss(); - if (mListener != null) + if (mListener != null) { mListener.mainMenuItemSelected(id, customIntent); + } } }); } diff --git a/astrid/src/com/todoroo/astrid/ui/NNumberPickerDialog.java b/astrid/src/com/todoroo/astrid/ui/NNumberPickerDialog.java index 3371e4d9c..1b4a00b3b 100644 --- a/astrid/src/com/todoroo/astrid/ui/NNumberPickerDialog.java +++ b/astrid/src/com/todoroo/astrid/ui/NNumberPickerDialog.java @@ -80,10 +80,11 @@ public class NNumberPickerDialog extends AlertDialog implements OnClickListener if (separators != null && separators[i] != null) { TextView text = new TextView(context); text.setText(separators[i]); - if (separators[i].length() < 3) + if (separators[i].length() < 3) { text.setTextSize(48); - else + } else { text.setTextSize(20); + } text.setGravity(Gravity.CENTER); text.setLayoutParams(sepLayout); container.addView(text); @@ -96,8 +97,9 @@ public class NNumberPickerDialog extends AlertDialog implements OnClickListener } public void setInitialValues(int[] values) { - for (int i = 0; i < pickers.size(); i++) + for (int i = 0; i < pickers.size(); i++) { pickers.get(i).setCurrent(values[i]); + } } public void onClick(DialogInterface dialog, int which) { diff --git a/astrid/src/com/todoroo/astrid/ui/NumberPicker.java b/astrid/src/com/todoroo/astrid/ui/NumberPicker.java index 7b82b257f..6863ae15b 100644 --- a/astrid/src/com/todoroo/astrid/ui/NumberPicker.java +++ b/astrid/src/com/todoroo/astrid/ui/NumberPicker.java @@ -269,8 +269,9 @@ public class NumberPicker extends LinearLayout implements OnClickListener, private int notifyChange(int current) { if (mListener != null) { return mListener.onChanged(this, mCurrent, current); - } else + } else { return current; + } } @@ -303,8 +304,9 @@ public class NumberPicker extends LinearLayout implements OnClickListener, if ((val >= mStart) && (val <= mEnd)) { mPrevious = mCurrent; mCurrent = val; - if (notifyChange) + if (notifyChange) { notifyChange(mCurrent); + } } } updateView(); @@ -411,8 +413,9 @@ public class NumberPicker extends LinearLayout implements OnClickListener, return result; } - if (getMaxDigits() > 0 && result.length() > getMaxDigits()) + if (getMaxDigits() > 0 && result.length() > getMaxDigits()) { return ""; + } int val = getSelectedPos(result); diff --git a/astrid/src/com/todoroo/astrid/ui/PeopleContainer.java b/astrid/src/com/todoroo/astrid/ui/PeopleContainer.java index 25ee531ad..84ffd6990 100644 --- a/astrid/src/com/todoroo/astrid/ui/PeopleContainer.java +++ b/astrid/src/com/todoroo/astrid/ui/PeopleContainer.java @@ -81,15 +81,17 @@ public class PeopleContainer extends LinearLayout { for (int i = 0; i < getChildCount(); i++) { View view = getChildAt(i); TextView matching = (TextView) view.findViewById(R.id.text1); - if (matching.getText().equals(person)) + if (matching.getText().equals(person)) { return matching; + } } final View tagItem = inflater.inflate(R.layout.contact_edit_row, null); - if (person.length() == 0) + if (person.length() == 0) { addView(tagItem, getChildCount()); - else + } else { addView(tagItem); + } final ContactsAutoComplete textView = (ContactsAutoComplete) tagItem. findViewById(R.id.text1); textView.setText(person); @@ -101,23 +103,25 @@ public class PeopleContainer extends LinearLayout { } final ImageButton removeButton = (ImageButton) tagItem.findViewById(R.id.button1); - if (hideRemove) + if (hideRemove) { removeButton.setVisibility(View.GONE); - else - removeButton.setOnClickListener(new View.OnClickListener() { + } else { + removeButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { TextView lastView = getLastTextView(); - if (lastView == textView && textView.getText().length() == 0) + if (lastView == textView && textView.getText().length() == 0) { return; + } - if (getChildCount() > 1) + if (getChildCount() > 1) { removeView(tagItem); - else { + } else { textView.setText(""); //$NON-NLS-1$ textView.setEnabled(true); } } }); + } final AsyncImageView imageView = (AsyncImageView) tagItem. findViewById(R.id.icon); @@ -127,8 +131,9 @@ public class PeopleContainer extends LinearLayout { removeButton.setVisibility(View.GONE); } else { imageView.setDefaultImageDrawable(ResourceDrawableCache.getImageDrawableFromId(resources, R.drawable.icn_default_person_image)); - if (!hideRemove) + if (!hideRemove) { removeButton.setVisibility(View.VISIBLE); + } } @@ -159,8 +164,9 @@ public class PeopleContainer extends LinearLayout { removeButton.setVisibility(View.VISIBLE); } - if (onAddNewPerson != null) + if (onAddNewPerson != null) { onAddNewPerson.textChanged(s.toString()); + } } }); @@ -168,8 +174,9 @@ public class PeopleContainer extends LinearLayout { @SuppressWarnings("nls") @Override public boolean onEditorAction(TextView arg0, int actionId, KeyEvent arg2) { - if (actionId != EditorInfo.IME_NULL) + if (actionId != EditorInfo.IME_NULL) { return false; + } if (getLastTextView().getText().length() != 0) { addPerson("", "", false); } @@ -189,8 +196,9 @@ public class PeopleContainer extends LinearLayout { for (int i = getChildCount() - 1; i >= 0; i--) { View lastItem = getChildAt(i); TextView lastText = (TextView) lastItem.findViewById(R.id.text1); - if (lastText.isEnabled()) + if (lastText.isEnabled()) { return lastText; + } } return null; } @@ -210,8 +218,9 @@ public class PeopleContainer extends LinearLayout { JSONObject person = PeopleContainer.createUserJson(textView); if (person != null) { String email = person.optString("email"); //$NON-NLS-1$ - if (email.indexOf('@') != -1) + if (email.indexOf('@') != -1) { people.put(person); + } } } return people; @@ -229,23 +238,28 @@ public class PeopleContainer extends LinearLayout { TextView textView = getTextView(i); String text = textView.getText().toString(); - if (text.length() == 0) + if (text.length() == 0) { continue; + } - if (text.indexOf('@') == -1 && textView.isEnabled()) + if (text.indexOf('@') == -1 && textView.isEnabled()) { throw new ParseSharedException(textView, activity.getString(R.string.actfm_EPA_invalid_email, text)); + } if (peopleAsJSON) { JSONObject person = PeopleContainer.createUserJson(textView); if (person != null) { if (person.optBoolean("owner")) //$NON-NLS-1$ + { continue; + } String email = person.optString("email"); Long id = person.optLong("id", -1); if (!TextUtils.isEmpty(email) && !addedEmails.contains(email)) { addedEmails.add(email); - if (id > 0) + if (id > 0) { addedIds.add(id); + } peopleList.put(person); } else if (id > 0 && !addedIds.contains(id)) { addedIds.add(id); @@ -257,8 +271,9 @@ public class PeopleContainer extends LinearLayout { peopleList.put(text); } } - if (peopleList.length() > 0) + if (peopleList.length() > 0) { sharedWith.put("p", peopleList); + } return sharedWith; } @@ -298,8 +313,9 @@ public class PeopleContainer extends LinearLayout { name = person.getString("email"); } - if (owner) + if (owner) { name = name + " " + ContextManager.getString(R.string.actfm_list_owner); + } textView = addPerson(name, imageURL, hideRemove); @@ -318,12 +334,14 @@ public class PeopleContainer extends LinearLayout { */ @SuppressWarnings("nls") public static JSONObject createUserJson(TextView textView) { - if (textView.isEnabled() == false) + if (textView.isEnabled() == false) { return (JSONObject) textView.getTag(); + } String text = textView.getText().toString().trim(); - if (text.length() == 0) + if (text.length() == 0) { return null; + } JSONObject user = new JSONObject(); int bracket = text.lastIndexOf('<'); diff --git a/astrid/src/com/todoroo/astrid/ui/PopupControlSet.java b/astrid/src/com/todoroo/astrid/ui/PopupControlSet.java index 9843ba18c..8b5abc603 100644 --- a/astrid/src/com/todoroo/astrid/ui/PopupControlSet.java +++ b/astrid/src/com/todoroo/astrid/ui/PopupControlSet.java @@ -49,10 +49,11 @@ public abstract class PopupControlSet extends TaskEditControlSet { public PopupControlSet(Activity activity, int viewLayout, int displayViewLayout, final int title) { super(activity, viewLayout); - if (displayViewLayout != -1) + if (displayViewLayout != -1) { this.displayView = LayoutInflater.from(activity).inflate(displayViewLayout, null); - else + } else { this.displayView = null; + } titleString = (title > 0) ? activity.getString(title) : ""; //$NON-NLS-1$ @@ -69,10 +70,11 @@ public abstract class PopupControlSet extends TaskEditControlSet { protected Dialog buildDialog(String title, final PopupDialogClickListener okClickListener, DialogInterface.OnCancelListener cancelClickListener) { int theme = ThemeService.getEditDialogTheme(); dialog = new Dialog(activity, theme); - if (title.length() == 0) + if (title.length() == 0) { dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); - else + } else { dialog.setTitle(title); + } View v = getView(); @@ -82,8 +84,9 @@ public abstract class PopupControlSet extends TaskEditControlSet { dismiss.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { - if (okClickListener.onClick(dialog, 0)) + if (okClickListener.onClick(dialog, 0)) { DialogUtilities.dismissDialog(activity, dialog); + } } }); } @@ -94,10 +97,11 @@ public abstract class PopupControlSet extends TaskEditControlSet { if (AndroidUtilities.isTabletSized(activity)) { DisplayMetrics metrics = activity.getResources().getDisplayMetrics(); - if ((metrics.widthPixels / metrics.density) >= AndroidUtilities.MIN_TABLET_HEIGHT) + if ((metrics.widthPixels / metrics.density) >= AndroidUtilities.MIN_TABLET_HEIGHT) { params.width = (3 * metrics.widthPixels) / 5; - else if ((metrics.widthPixels / metrics.density) >= AndroidUtilities.MIN_TABLET_WIDTH) + } else if ((metrics.widthPixels / metrics.density) >= AndroidUtilities.MIN_TABLET_WIDTH) { params.width = (4 * metrics.widthPixels) / 5; + } } dialog.getWindow().setAttributes((android.view.WindowManager.LayoutParams) params); @@ -144,8 +148,9 @@ public abstract class PopupControlSet extends TaskEditControlSet { @Override public String writeToModel(Task task) { - if (initialized && dialog != null) + if (initialized && dialog != null) { dialog.dismiss(); + } return super.writeToModel(task); } diff --git a/astrid/src/com/todoroo/astrid/ui/QuickAddBar.java b/astrid/src/com/todoroo/astrid/ui/QuickAddBar.java index 22e999678..9064c6d88 100644 --- a/astrid/src/com/todoroo/astrid/ui/QuickAddBar.java +++ b/astrid/src/com/todoroo/astrid/ui/QuickAddBar.java @@ -201,8 +201,9 @@ public class QuickAddBar extends LinearLayout { public boolean onLongClick(View v) { Task task = quickAddTask(quickAddBox.getText().toString(), false); - if (task == null) + if (task == null) { return true; + } mListener.onTaskListItemClicked(task.getId(), true); return true; @@ -296,8 +297,9 @@ public class QuickAddBar extends LinearLayout { } try { - if (title != null) + if (title != null) { title = title.trim(); + } boolean assignedToMe = usePeopleControl ? peopleControl.willBeAssignedToMe() : true; if (!assignedToMe && !actFmPreferenceService.isLoggedIn()) { DialogInterface.OnClickListener okListener = new DialogInterface.OnClickListener() { @@ -322,11 +324,13 @@ public class QuickAddBar extends LinearLayout { } Task task = new Task(); - if (title != null) + if (title != null) { task.setValue(Task.TITLE, title); // need this for calendar + } - if (repeatControl.isRecurrenceSet()) + if (repeatControl.isRecurrenceSet()) { repeatControl.writeToModel(task); + } if (deadlineControl.isDeadlineSet()) { task.clearValue(Task.HIDE_UNTIL); deadlineControl.writeToModel(task); @@ -351,11 +355,13 @@ public class QuickAddBar extends LinearLayout { addToCalendar(task, title); - if (!TextUtils.isEmpty(title)) + if (!TextUtils.isEmpty(title)) { fragment.showTaskEditHelpPopover(); + } - if (activity instanceof TaskListActivity && !assignedToMe) + if (activity instanceof TaskListActivity && !assignedToMe) { ((TaskListActivity) activity).taskAssignedTo(assignedTo, assignedEmail, assignedId); + } TextView quickAdd = (TextView) findViewById(R.id.quickAddText); quickAdd.setText(""); //$NON-NLS-1$ @@ -414,8 +420,9 @@ public class QuickAddBar extends LinearLayout { * @return */ public static Task basicQuickAddTask(String title) { - if (TextUtils.isEmpty(title)) + if (TextUtils.isEmpty(title)) { return null; + } title = title.trim(); @@ -455,17 +462,19 @@ public class QuickAddBar extends LinearLayout { // if user wants, create the task directly (with defaultvalues) // after saying it Flags.set(Flags.TLA_RESUMED_FROM_VOICE_ADD); - if (Preferences.getBoolean(R.string.p_voiceInputCreatesTask, false)) + if (Preferences.getBoolean(R.string.p_voiceInputCreatesTask, false)) { quickAddTask(quickAddBox.getText().toString(), true); + } // the rest of onActivityResult is totally unrelated to // voicerecognition, so bail out return true; } else if (requestCode == TaskEditFragment.REQUEST_CODE_CONTACT) { - if (resultCode == Activity.RESULT_OK) + if (resultCode == Activity.RESULT_OK) { peopleControl.onActivityResult(requestCode, resultCode, data); - else + } else { peopleControl.assignToMe(); + } return true; } diff --git a/astrid/src/com/todoroo/astrid/ui/RandomReminderControlSet.java b/astrid/src/com/todoroo/astrid/ui/RandomReminderControlSet.java index dacd32f9d..25f68675e 100644 --- a/astrid/src/com/todoroo/astrid/ui/RandomReminderControlSet.java +++ b/astrid/src/com/todoroo/astrid/ui/RandomReminderControlSet.java @@ -45,8 +45,9 @@ public class RandomReminderControlSet extends TaskEditControlSet { @Override public void onItemSelected(AdapterView arg0, View arg1, int arg2, long arg3) { - if (periodSpinnerInitialized) + if (periodSpinnerInitialized) { settingCheckbox.setChecked(true); + } periodSpinnerInitialized = true; } @@ -66,8 +67,9 @@ public class RandomReminderControlSet extends TaskEditControlSet { // create hour array String[] hourStrings = activity.getResources().getStringArray(R.array.TEA_reminder_random_hours); hours = new int[hourStrings.length]; - for (int i = 0; i < hours.length; i++) + for (int i = 0; i < hours.length; i++) { hours[i] = Integer.parseInt(hourStrings[i]); + } } @Override @@ -85,9 +87,11 @@ public class RandomReminderControlSet extends TaskEditControlSet { } int i; - for (i = 0; i < hours.length - 1; i++) - if (hours[i] * DateUtilities.ONE_HOUR >= time) + for (i = 0; i < hours.length - 1; i++) { + if (hours[i] * DateUtilities.ONE_HOUR >= time) { break; + } + } periodSpinner.setSelection(i); settingCheckbox.setChecked(enabled); } @@ -97,10 +101,12 @@ public class RandomReminderControlSet extends TaskEditControlSet { if (settingCheckbox.isChecked()) { int hourValue = hours[periodSpinner.getSelectedItemPosition()]; task.setValue(Task.REMINDER_PERIOD, hourValue * DateUtilities.ONE_HOUR); - if (task.getSetValues().containsKey(Task.REMINDER_PERIOD.name)) + if (task.getSetValues().containsKey(Task.REMINDER_PERIOD.name)) { StatisticsService.reportEvent(StatisticsConstants.RANDOM_REMINDER_SAVED); - } else + } + } else { task.setValue(Task.REMINDER_PERIOD, 0L); + } return null; } diff --git a/astrid/src/com/todoroo/astrid/ui/ReminderControlSet.java b/astrid/src/com/todoroo/astrid/ui/ReminderControlSet.java index fb9d3471e..ff31154ac 100644 --- a/astrid/src/com/todoroo/astrid/ui/ReminderControlSet.java +++ b/astrid/src/com/todoroo/astrid/ui/ReminderControlSet.java @@ -51,10 +51,11 @@ public class ReminderControlSet extends PopupControlSet { } public void addViewToBody(View v) { - if (remindersBody != null) + if (remindersBody != null) { remindersBody.addView(v, 0); - else + } else { extraViews.add(v); + } } @@ -63,26 +64,30 @@ public class ReminderControlSet extends PopupControlSet { after.setChecked((flags & Task.NOTIFY_AFTER_DEADLINE) > 0); - if ((flags & Task.NOTIFY_MODE_NONSTOP) > 0) + if ((flags & Task.NOTIFY_MODE_NONSTOP) > 0) { mode.setSelection(2); - else if ((flags & Task.NOTIFY_MODE_FIVE) > 0) + } else if ((flags & Task.NOTIFY_MODE_FIVE) > 0) { mode.setSelection(1); - else + } else { mode.setSelection(0); + } } public int getValue() { int value = 0; - if (during.isChecked()) + if (during.isChecked()) { value |= Task.NOTIFY_AT_DEADLINE; - if (after.isChecked()) + } + if (after.isChecked()) { value |= Task.NOTIFY_AFTER_DEADLINE; + } value &= ~(Task.NOTIFY_MODE_FIVE | Task.NOTIFY_MODE_NONSTOP); - if (mode.getSelectedItemPosition() == 2) + if (mode.getSelectedItemPosition() == 2) { value |= Task.NOTIFY_MODE_NONSTOP; - else if (mode.getSelectedItemPosition() == 1) + } else if (mode.getSelectedItemPosition() == 1) { value |= Task.NOTIFY_MODE_FIVE; + } return value; } @@ -170,15 +175,17 @@ public class ReminderControlSet extends PopupControlSet { } int value; - if (initialized) + if (initialized) { value = getValue(); - else + } else { value = model.getValue(Task.REMINDER_FLAGS); + } boolean appendedWhen = false; if ((value & Task.NOTIFY_AT_DEADLINE) > 0) { - if (reminderCount > 0) + if (reminderCount > 0) { reminderString.append(" & "); //$NON-NLS-1$ + } reminderString.append(activity.getString(R.string.TEA_reminder_when)).append(" "); //$NON-NLS-1$ reminderString.append(activity.getString(R.string.TEA_reminder_due_short)); @@ -187,11 +194,13 @@ public class ReminderControlSet extends PopupControlSet { } if ((value & Task.NOTIFY_AFTER_DEADLINE) > 0 && reminderCount < 2) { - if (reminderCount > 0) + if (reminderCount > 0) { reminderString.append(" & "); //$NON-NLS-1$ + } - if (!appendedWhen) + if (!appendedWhen) { reminderString.append(activity.getString(R.string.TEA_reminder_when)).append(" "); //$NON-NLS-1$ + } reminderString.append(activity.getString(R.string.TEA_reminder_overdue_short)); reminderCount++; } diff --git a/astrid/src/com/todoroo/astrid/ui/TaskListFragmentPager.java b/astrid/src/com/todoroo/astrid/ui/TaskListFragmentPager.java index d194da2a5..4317a5432 100644 --- a/astrid/src/com/todoroo/astrid/ui/TaskListFragmentPager.java +++ b/astrid/src/com/todoroo/astrid/ui/TaskListFragmentPager.java @@ -36,8 +36,9 @@ public class TaskListFragmentPager extends ViewPager { @Override public void setAdapter(PagerAdapter adapter) { - if (!(adapter instanceof TaskListFragmentPagerAdapter)) + if (!(adapter instanceof TaskListFragmentPagerAdapter)) { throw new ClassCastException("TaskListFragmentPager requires an adapter of type TaskListFragmentPagerAdapter"); //$NON-NLS-1$ + } super.setAdapter(adapter); } @@ -80,11 +81,13 @@ public class TaskListFragmentPager extends ViewPager { @Override public boolean onInterceptTouchEvent(MotionEvent ev) { - if (checkForPeopleHeaderScroll(ev)) + if (checkForPeopleHeaderScroll(ev)) { return false; + } - if (Flags.check(Flags.TLFP_NO_INTERCEPT_TOUCH)) + if (Flags.check(Flags.TLFP_NO_INTERCEPT_TOUCH)) { return false; + } return super.onInterceptTouchEvent(ev); } @@ -98,8 +101,9 @@ public class TaskListFragmentPager extends ViewPager { if (peopleView != null) { Rect rect = new Rect(); peopleView.getHitRect(rect); - if (rect.contains((int) ev.getX(), (int) ev.getY())) + if (rect.contains((int) ev.getX(), (int) ev.getY())) { return true; + } } } } diff --git a/astrid/src/com/todoroo/astrid/ui/TimeDurationControlSet.java b/astrid/src/com/todoroo/astrid/ui/TimeDurationControlSet.java index db7f41697..c61463593 100644 --- a/astrid/src/com/todoroo/astrid/ui/TimeDurationControlSet.java +++ b/astrid/src/com/todoroo/astrid/ui/TimeDurationControlSet.java @@ -53,8 +53,9 @@ public class TimeDurationControlSet implements OnNNumberPickedListener, } public void setTimeDuration(Integer timeDurationInSeconds) { - if (timeDurationInSeconds == null) + if (timeDurationInSeconds == null) { timeDurationInSeconds = 0; + } timeDuration = timeDurationInSeconds; @@ -65,15 +66,17 @@ public class TimeDurationControlSet implements OnNNumberPickedListener, } String prefix = ""; - if (prefixResource != 0) + if (prefixResource != 0) { prefix = r.getString(prefixResource) + " "; + } timeButton.setText(prefix + DateUtils.formatElapsedTime(timeDuration)); int hours = timeDuration / 3600; int minutes = timeDuration / 60 - 60 * hours; initialValues = new int[]{hours, minutes}; - if (model != null) + if (model != null) { model.setValue(property, timeDuration); + } } /** @@ -104,8 +107,9 @@ public class TimeDurationControlSet implements OnNNumberPickedListener, @Override public int onChanged(NumberPicker picker, int oldVal, int newVal) { if (newVal < 0) { - if (hourPicker.getCurrent() == 0) + if (hourPicker.getCurrent() == 0) { return 0; + } hourPicker.setCurrent(hourPicker.getCurrent() - 1); return 60 + newVal; } else if (newVal > 59) { @@ -117,8 +121,9 @@ public class TimeDurationControlSet implements OnNNumberPickedListener, }); } - if (initialValues != null) + if (initialValues != null) { dialog.setInitialValues(initialValues); + } dialog.show(); } diff --git a/astrid/src/com/todoroo/astrid/ui/TouchInterceptingFrameLayout.java b/astrid/src/com/todoroo/astrid/ui/TouchInterceptingFrameLayout.java index 62256b271..1ca669722 100644 --- a/astrid/src/com/todoroo/astrid/ui/TouchInterceptingFrameLayout.java +++ b/astrid/src/com/todoroo/astrid/ui/TouchInterceptingFrameLayout.java @@ -26,8 +26,9 @@ public class TouchInterceptingFrameLayout extends FrameLayout { @Override public boolean dispatchKeyEvent(KeyEvent event) { - if (mListener != null && mListener.didInterceptTouch(event)) + if (mListener != null && mListener.didInterceptTouch(event)) { return true; + } return super.dispatchKeyEvent(event); } diff --git a/astrid/src/com/todoroo/astrid/utility/AstridPreferenceSpec.java b/astrid/src/com/todoroo/astrid/utility/AstridPreferenceSpec.java index f8e27eaa7..9159b32a3 100644 --- a/astrid/src/com/todoroo/astrid/utility/AstridPreferenceSpec.java +++ b/astrid/src/com/todoroo/astrid/utility/AstridPreferenceSpec.java @@ -12,23 +12,26 @@ public abstract class AstridPreferenceSpec { public abstract void resetDefaults(); protected static void setPreference(SharedPreferences prefs, Editor editor, Resources r, int key, int value, boolean ifUnset) { - if (ifUnset) + if (ifUnset) { Preferences.setIfUnset(prefs, editor, r, key, value); - else + } else { Preferences.setString(r.getString(key), Integer.toString(value)); + } } protected static void setPreference(SharedPreferences prefs, Editor editor, Resources r, int key, boolean value, boolean ifUnset) { - if (ifUnset) + if (ifUnset) { Preferences.setIfUnset(prefs, editor, r, key, value); - else + } else { Preferences.setBoolean(r.getString(key), value); + } } protected static void setPreference(SharedPreferences prefs, Editor editor, Resources r, int key, String value, boolean ifUnset) { - if (ifUnset) + if (ifUnset) { Preferences.setIfUnset(prefs, editor, r, key, value); - else + } else { Preferences.setString(r.getString(key), value); + } } } diff --git a/astrid/src/com/todoroo/astrid/utility/AstridPreferences.java b/astrid/src/com/todoroo/astrid/utility/AstridPreferences.java index 145f6f918..adc3ddd0f 100644 --- a/astrid/src/com/todoroo/astrid/utility/AstridPreferences.java +++ b/astrid/src/com/todoroo/astrid/utility/AstridPreferences.java @@ -46,10 +46,11 @@ public class AstridPreferences { */ public static void setPreferenceDefaults() { AstridPreferenceSpec spec; - if (Constants.ASTRID_LITE) + if (Constants.ASTRID_LITE) { spec = new AstridLitePreferenceSpec(); - else + } else { spec = new AstridDefaultPreferenceSpec(); + } spec.setIfUnset(); @@ -61,10 +62,11 @@ public class AstridPreferences { public static void resetToDefaults() { AstridPreferenceSpec spec; - if (Constants.ASTRID_LITE) + if (Constants.ASTRID_LITE) { spec = new AstridLitePreferenceSpec(); - else + } else { spec = new AstridDefaultPreferenceSpec(); + } spec.resetDefaults(); } @@ -133,8 +135,9 @@ public class AstridPreferences { */ public static String getCurrentVersionName() { String versionName = Preferences.getStringValue(P_CURRENT_VERSION_NAME); - if (versionName == null) + if (versionName == null) { versionName = "0"; //$NON-NLS-1$ + } return versionName; } @@ -147,8 +150,9 @@ public class AstridPreferences { */ public static boolean canShowPopover() { long last = Preferences.getLong(P_LAST_POPOVER, 0); - if (System.currentTimeMillis() - last < MIN_POPOVER_TIME) + if (System.currentTimeMillis() - last < MIN_POPOVER_TIME) { return false; + } Preferences.setLong(P_LAST_POPOVER, System.currentTimeMillis()); return true; } diff --git a/astrid/src/com/todoroo/astrid/utility/ResourceDrawableCache.java b/astrid/src/com/todoroo/astrid/utility/ResourceDrawableCache.java index e76ada59e..53c4271dd 100644 --- a/astrid/src/com/todoroo/astrid/utility/ResourceDrawableCache.java +++ b/astrid/src/com/todoroo/astrid/utility/ResourceDrawableCache.java @@ -26,41 +26,50 @@ public class ResourceDrawableCache { public static Drawable getImageDrawableFromId(Resources r, int resId) { - if (r == null) + if (r == null) { r = ContextManager.getResources(); + } switch (resId) { case R.drawable.icn_default_person_image: - if (ICN_DEFAULT_PERSON_IMAGE == null) + if (ICN_DEFAULT_PERSON_IMAGE == null) { ICN_DEFAULT_PERSON_IMAGE = r.getDrawable(resId); + } return ICN_DEFAULT_PERSON_IMAGE; case R.drawable.icn_anyone: - if (ICN_ANYONE == null) + if (ICN_ANYONE == null) { ICN_ANYONE = r.getDrawable(resId); + } return ICN_ANYONE; case R.drawable.icn_anyone_transparent: - if (ICN_ANYONE_TRANSPARENT == null) + if (ICN_ANYONE_TRANSPARENT == null) { ICN_ANYONE_TRANSPARENT = r.getDrawable(resId); + } return ICN_ANYONE_TRANSPARENT; case R.drawable.icn_add_contact: - if (ICN_ADD_CONTACT == null) + if (ICN_ADD_CONTACT == null) { ICN_ADD_CONTACT = r.getDrawable(resId); + } return ICN_ADD_CONTACT; case R.drawable.default_list_0: - if (DEFAULT_LIST_0 == null) + if (DEFAULT_LIST_0 == null) { DEFAULT_LIST_0 = r.getDrawable(resId); + } return DEFAULT_LIST_0; case R.drawable.default_list_1: - if (DEFAULT_LIST_1 == null) + if (DEFAULT_LIST_1 == null) { DEFAULT_LIST_1 = r.getDrawable(resId); + } return DEFAULT_LIST_1; case R.drawable.default_list_2: - if (DEFAULT_LIST_2 == null) + if (DEFAULT_LIST_2 == null) { DEFAULT_LIST_2 = r.getDrawable(resId); + } return DEFAULT_LIST_2; case R.drawable.default_list_3: - if (DEFAULT_LIST_3 == null) + if (DEFAULT_LIST_3 == null) { DEFAULT_LIST_3 = r.getDrawable(resId); + } return DEFAULT_LIST_3; default: diff --git a/astrid/src/com/todoroo/astrid/utility/SyncMetadataService.java b/astrid/src/com/todoroo/astrid/utility/SyncMetadataService.java index 4d0bd2ffc..db1f9a100 100644 --- a/astrid/src/com/todoroo/astrid/utility/SyncMetadataService.java +++ b/astrid/src/com/todoroo/astrid/utility/SyncMetadataService.java @@ -117,11 +117,12 @@ abstract public class SyncMetadataService { public TodorooCursor getLocallyUpdated(Property... properties) { TodorooCursor tasks; long lastSyncDate = getUtilities().getLastSyncDate(); - if (lastSyncDate == 0) + if (lastSyncDate == 0) { tasks = taskDao.query(Query.select(Task.ID).where(Criterion.none)); - else + } else { tasks = taskDao.query(Query.select(Task.ID).where(Criterion.and(TaskCriteria.ownedByMe(), Task.MODIFICATION_DATE.gt(lastSyncDate))) .orderBy(Order.asc(Task.ID))); + } tasks = filterLocallyUpdated(tasks, lastSyncDate); return joinWithMetadata(tasks, true, properties); @@ -173,8 +174,9 @@ abstract public class SyncMetadataService { while (true) { left.moveToNext(); - if (left.isAfterLast()) + if (left.isAfterLast()) { break; + } long leftValue = left.getLong(0); // advance right until it is equal or bigger @@ -183,13 +185,15 @@ abstract public class SyncMetadataService { } if (right.isAfterLast()) { - if (!both) + if (!both) { matchingRows.add(leftValue); + } continue; } - if ((right.getLong(0) == leftValue) == both) + if ((right.getLong(0) == leftValue) == both) { matchingRows.add(leftValue); + } } } @@ -199,14 +203,16 @@ abstract public class SyncMetadataService { * @param remoteTask */ public void findLocalMatch(TYPE remoteTask) { - if (remoteTask.task.getId() != Task.NO_ID) + if (remoteTask.task.getId() != Task.NO_ID) { return; + } TodorooCursor cursor = metadataDao.query(Query.select(Metadata.TASK). where(Criterion.and(MetadataCriteria.withKey(getMetadataKey()), getLocalMatchCriteria(remoteTask)))); try { - if (cursor.getCount() == 0) + if (cursor.getCount() == 0) { return; + } cursor.moveToFirst(); remoteTask.task.setId(cursor.get(Metadata.TASK)); } finally { @@ -259,8 +265,9 @@ abstract public class SyncMetadataService { TodorooCursor cursor = metadataDao.query(Query.select(Metadata.PROPERTIES).where( MetadataCriteria.byTaskAndwithKey(taskId, getMetadataKey()))); try { - if (cursor.getCount() == 0) + if (cursor.getCount() == 0) { return null; + } cursor.moveToFirst(); return new Metadata(cursor); } finally { diff --git a/astrid/src/com/todoroo/astrid/utility/TitleParser.java b/astrid/src/com/todoroo/astrid/utility/TitleParser.java index f612f7c88..81d9fb0f0 100644 --- a/astrid/src/com/todoroo/astrid/utility/TitleParser.java +++ b/astrid/src/com/todoroo/astrid/utility/TitleParser.java @@ -60,8 +60,9 @@ public class TitleParser { result = true; String tag = TitleParser.trimParenthesis(m.group(2)); String tagWithCase = tagService.getTagWithCase(tag); - if (!addedTags.contains(tagWithCase)) + if (!addedTags.contains(tagWithCase)) { tags.add(tagWithCase); + } addedTags.add(tagWithCase); } else { m = contextPattern.matcher(inputText); @@ -69,8 +70,9 @@ public class TitleParser { result = true; String tag = TitleParser.trimParenthesis(m.group(2)); String tagWithCase = tagService.getTagWithCase(tag); - if (!addedTags.contains(tagWithCase)) + if (!addedTags.contains(tagWithCase)) { tags.add(tagWithCase); + } addedTags.add(tagWithCase); } else { break; @@ -84,15 +86,19 @@ public class TitleParser { //helper method for priorityHelper. converts the string to a Task Importance private static int strToPriority(String priorityStr) { - if (priorityStr != null) + if (priorityStr != null) { priorityStr.toLowerCase().trim(); + } int priority = Task.IMPORTANCE_DO_OR_DIE; - if ("0".equals(priorityStr) || "!0".equals(priorityStr) || "least".equals(priorityStr) || "lowest".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; } @@ -117,8 +123,9 @@ public class TitleParser { int start = m.start() == 0 ? 0 : m.start() + 1; inputText = inputText.substring(0, start) + inputText.substring(m.end()); - } else + } else { break; + } } } task.setValue(Task.TITLE, inputText.trim()); @@ -132,10 +139,12 @@ public class TitleParser { return time; } String text = amPmString.toLowerCase().trim(); - if (text.equals("am") || text.equals("a.m") || text.equals("a")) + if (text.equals("am") || text.equals("a.m") || text.equals("a")) { time = Calendar.AM; - if (text.equals("pm") || text.equals("p.m") || text.equals("p")) + } + if (text.equals("pm") || text.equals("p.m") || text.equals("p")) { time = Calendar.PM; + } return time; } @@ -148,10 +157,12 @@ public class TitleParser { } private static String stripParens(String s) { - if (s.startsWith("(")) + if (s.startsWith("(")) { s = s.substring(1); - if (s.endsWith(")")) + } + if (s.endsWith(")")) { s = s.substring(0, s.length() - 1); + } return s; } @@ -160,8 +171,9 @@ public class TitleParser { //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 boolean dayHelper(Task task) { - if (task.containsNonNullValue(Task.DUE_DATE)) + if (task.containsNonNullValue(Task.DUE_DATE)) { return false; + } String inputText = task.getValue(Task.TITLE); Calendar cal = null; Boolean containsSpecificTime = false; @@ -242,8 +254,9 @@ public class TitleParser { dCal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(match.group(4))); if (match.group(6) != null && !(match.group(6).trim()).equals("")) { String yearString = match.group(6); - if (match.group(6).length() == 2) + if (match.group(6).length() == 2) { yearString = "20" + match.group(6); + } dCal.set(Calendar.YEAR, Integer.parseInt(yearString)); } @@ -314,12 +327,14 @@ public class TitleParser { setCalendarToDefaultTime(timeCal); timeCal.set(Calendar.HOUR, Integer.parseInt(m.group(2))); - if (m.group(3) != null && !m.group(3).trim().equals("")) + if (m.group(3) != null && !m.group(3).trim().equals("")) { timeCal.set(Calendar.MINUTE, Integer.parseInt(m.group(3))); - else + } else { timeCal.set(Calendar.MINUTE, 0); - if (Integer.parseInt(m.group(2)) <= 12) + } + if (Integer.parseInt(m.group(2)) <= 12) { 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(""))) { @@ -348,8 +363,9 @@ public class TitleParser { } if (cal != null) { //if at least one of the above has been called, write to task. else do nothing. - if (!TextUtils.isEmpty(inputText)) + if (!TextUtils.isEmpty(inputText)) { task.setValue(Task.TITLE, inputText); + } if (containsSpecificTime) { task.setValue(Task.DUE_DATE, Task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, cal.getTime().getTime())); } else { @@ -363,8 +379,9 @@ public class TitleParser { //Parses through the text and sets the frequency of the task. private static boolean repeatHelper(Task task) { - if (task.containsNonNullValue(Task.RECURRENCE)) + if (task.containsNonNullValue(Task.RECURRENCE)) { return false; + } String inputText = task.getValue(Task.TITLE); HashMap repeatTimes = new HashMap(); repeatTimes.put("(?i)\\bevery ?\\w{0,6} days?\\b", Frequency.DAILY); @@ -433,9 +450,9 @@ public class TitleParser { Matcher m = pattern.matcher(inputText); if (m.find() && m.group(1) != null) { String intervalStr = m.group(1); - if (wordsToNum.containsKey(intervalStr)) + if (wordsToNum.containsKey(intervalStr)) { interval = wordsToNum.get(intervalStr); - else { + } else { try { interval = Integer.parseInt(intervalStr); } catch (NumberFormatException e) { diff --git a/astrid/src/com/todoroo/astrid/voice/VoiceInputAssistant.java b/astrid/src/com/todoroo/astrid/voice/VoiceInputAssistant.java index 60c9f6eb1..0344d08b6 100644 --- a/astrid/src/com/todoroo/astrid/voice/VoiceInputAssistant.java +++ b/astrid/src/com/todoroo/astrid/voice/VoiceInputAssistant.java @@ -129,8 +129,9 @@ public class VoiceInputAssistant { */ public VoiceInputAssistant(ImageButton voiceButton, int requestCode) { this(voiceButton); - if (requestCode == VOICE_RECOGNITION_REQUEST_CODE) + if (requestCode == VOICE_RECOGNITION_REQUEST_CODE) { throw new InvalidParameterException("You have to specify a unique requestCode for this VoiceInputAssistant!"); + } this.requestCode = requestCode; } @@ -165,8 +166,9 @@ public class VoiceInputAssistant { */ public VoiceInputAssistant(Activity activity, ImageButton voiceButton, int requestCode) { this(activity, voiceButton); - if (requestCode == VOICE_RECOGNITION_REQUEST_CODE) + if (requestCode == VOICE_RECOGNITION_REQUEST_CODE) { throw new InvalidParameterException("You have to specify a unique requestCode for this VoiceInputAssistant!"); + } this.requestCode = requestCode; } @@ -182,12 +184,13 @@ public class VoiceInputAssistant { intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1); intent.putExtra(RecognizerIntent.EXTRA_PROMPT, ContextManager.getContext().getString(prompt)); String detailMessage = "Error! No Fragment or Activity was registered to handle this voiceinput-request!"; - if (activity != null) + if (activity != null) { activity.startActivityForResult(intent, requestCode); - else if (fragment != null) + } else if (fragment != null) { fragment.startActivityForResult(intent, requestCode); - else + } else { Log.e("Astrid VoiceInputAssistant", detailMessage, new IllegalStateException(detailMessage)); + } } /** @@ -223,10 +226,11 @@ public class VoiceInputAssistant { recognizedSpeech = recognizedSpeech.substring(0, 1).toUpperCase() + recognizedSpeech.substring(1).toLowerCase(); - if (append) + if (append) { textField.setText((textField.getText() + " " + recognizedSpeech).trim()); - else + } else { textField.setText(recognizedSpeech); + } } } } @@ -278,17 +282,19 @@ public class VoiceInputAssistant { public void showVoiceInputMarketSearch(DialogInterface.OnClickListener onFail) { String packageName; - if (AndroidUtilities.getSdkVersion() <= 7) + if (AndroidUtilities.getSdkVersion() <= 7) { packageName = "com.google.android.voicesearch.x"; - else + } else { packageName = "com.google.android.voicesearch"; + } // User wants to install voice search, take them to the market Intent marketIntent = Constants.MARKET_STRATEGY.generateMarketLink(packageName); if (activity != null) { try { - if (marketIntent == null) + if (marketIntent == null) { throw new ActivityNotFoundException("No market link supplied"); //$NON-NLS-1$ + } activity.startActivity(marketIntent); } catch (ActivityNotFoundException ane) { DialogUtilities.okDialog(activity, diff --git a/astrid/src/com/todoroo/astrid/voice/VoiceOutputService.java b/astrid/src/com/todoroo/astrid/voice/VoiceOutputService.java index eb2588a30..4bf8e80a2 100644 --- a/astrid/src/com/todoroo/astrid/voice/VoiceOutputService.java +++ b/astrid/src/com/todoroo/astrid/voice/VoiceOutputService.java @@ -60,11 +60,13 @@ public class VoiceOutputService { public static VoiceOutputAssistant getVoiceOutputInstance() { if (AndroidUtilities.getSdkVersion() >= MIN_TTS_VERSION) { - if (outputAssistant == null) + if (outputAssistant == null) { outputAssistant = new Api6VoiceOutputAssistant(); + } } else { - if (outputAssistant == null) + if (outputAssistant == null) { outputAssistant = new NullVoiceOutputAssistant(); + } } return outputAssistant; diff --git a/astrid/src/com/todoroo/astrid/voice/VoiceRecognizer.java b/astrid/src/com/todoroo/astrid/voice/VoiceRecognizer.java index 907bfeda3..86b1652de 100644 --- a/astrid/src/com/todoroo/astrid/voice/VoiceRecognizer.java +++ b/astrid/src/com/todoroo/astrid/voice/VoiceRecognizer.java @@ -64,13 +64,15 @@ public class VoiceRecognizer { public static VoiceRecognizer instantiateVoiceRecognizer(Context context, RecognizerApiListener listener, ImageButton voiceAddButton) { synchronized (VoiceRecognizer.class) { - if (instance == null) + if (instance == null) { instance = new VoiceRecognizer(); + } } if (speechRecordingAvailable(context)) { - if (instance.recognizerApi != null) + if (instance.recognizerApi != null) { instance.recognizerApi.destroy(); + } instance.recognizerApi = new RecognizerApi(context); instance.recognizerApi.setListener(listener); @@ -88,15 +90,17 @@ public class VoiceRecognizer { context.getString(R.string.audio_encoding)); } else { int prompt = R.string.voice_edit_title_prompt; - if (Preferences.getBoolean(R.string.p_voiceInputCreatesTask, false)) + if (Preferences.getBoolean(R.string.p_voiceInputCreatesTask, false)) { prompt = R.string.voice_create_prompt; + } voiceInputAssistant.startVoiceRecognitionActivity(fragment, prompt); } } public boolean handleActivityResult(int requestCode, int resultCode, Intent data, EditText textField) { - if (instance != null && instance.voiceInputAssistant != null) + if (instance != null && instance.voiceInputAssistant != null) { return instance.voiceInputAssistant.handleActivityResult(requestCode, resultCode, data, textField); + } return false; } @@ -108,8 +112,9 @@ public class VoiceRecognizer { } public void cancel() { - if (instance != null && instance.recognizerApi != null) + if (instance != null && instance.recognizerApi != null) { instance.recognizerApi.cancel(); + } } public void convert(String filePath) { diff --git a/astrid/src/com/todoroo/astrid/welcome/HelpInfoPopover.java b/astrid/src/com/todoroo/astrid/welcome/HelpInfoPopover.java index 26c035484..bc89086fa 100644 --- a/astrid/src/com/todoroo/astrid/welcome/HelpInfoPopover.java +++ b/astrid/src/com/todoroo/astrid/welcome/HelpInfoPopover.java @@ -68,18 +68,21 @@ public class HelpInfoPopover extends QuickActionWidget { @Override protected int getArrowLeftMargin(View arrow) { - if (measuredWidth > 0) + if (measuredWidth > 0) { return (measuredWidth - arrow.getMeasuredWidth()) / 2; + } - if (tablet) + if (tablet) { return mRect.width() / 4; + } return mRect.width() / 2; } @Override protected int getShowAtX() { - if (measuredWidth > 0) + if (measuredWidth > 0) { return mRect.left + (mRect.width() - measuredWidth) / 2; + } return mRect.left; } diff --git a/astrid/src/com/todoroo/astrid/welcome/tutorial/WelcomeWalkthrough.java b/astrid/src/com/todoroo/astrid/welcome/tutorial/WelcomeWalkthrough.java index 79d855d63..569a17b7d 100644 --- a/astrid/src/com/todoroo/astrid/welcome/tutorial/WelcomeWalkthrough.java +++ b/astrid/src/com/todoroo/astrid/welcome/tutorial/WelcomeWalkthrough.java @@ -101,8 +101,9 @@ public class WelcomeWalkthrough extends ActFmLoginActivity { if (simpleLogin != null && !TextUtils.isEmpty(email)) { initializeSimpleUI(email); } else { - if (mAdapter != null && mAdapter.layouts[mAdapter.layouts.length - 1] != getLoginPageLayout()) + if (mAdapter != null && mAdapter.layouts[mAdapter.layouts.length - 1] != getLoginPageLayout()) { mAdapter.changeLoginPage(getLoginPageLayout()); + } super.initializeUI(); } } @@ -157,8 +158,9 @@ public class WelcomeWalkthrough extends ActFmLoginActivity { } }); } finally { - if (dismissDialog) + if (dismissDialog) { DialogUtilities.dismissDialog(WelcomeWalkthrough.this, pd); + } } } }.start(); @@ -223,11 +225,13 @@ public class WelcomeWalkthrough extends ActFmLoginActivity { } }; View title = currentView.findViewById(R.id.welcome_walkthrough_title); - if (title != null) + if (title != null) { title.setOnClickListener(done); + } View image = currentView.findViewById(R.id.welcome_walkthrough_image); - if (image != null) + if (image != null) { image.setOnClickListener(done); + } } } ((CirclePageIndicator) mIndicator).setVisibility(currentPage == mAdapter.getCount() - 1 ? View.GONE : View.VISIBLE); diff --git a/astrid/src/com/todoroo/astrid/widget/TasksWidget.java b/astrid/src/com/todoroo/astrid/widget/TasksWidget.java index cd64ab4db..20f225a5c 100644 --- a/astrid/src/com/todoroo/astrid/widget/TasksWidget.java +++ b/astrid/src/com/todoroo/astrid/widget/TasksWidget.java @@ -86,8 +86,9 @@ public class TasksWidget extends AppWidgetProvider { * @param id */ public static void updateWidgets(Context context) { - if (suppressUpdateFlag > 0 && DateUtilities.now() - suppressUpdateFlag < SUPPRESS_TIME) + if (suppressUpdateFlag > 0 && DateUtilities.now() - suppressUpdateFlag < SUPPRESS_TIME) { return; + } suppressUpdateFlag = 0; context.startService(new Intent(context, TasksWidget.WidgetUpdateService.class)); @@ -142,8 +143,9 @@ public class TasksWidget extends AppWidgetProvider { AppWidgetManager manager = AppWidgetManager.getInstance(this); int extrasId = AppWidgetManager.INVALID_APPWIDGET_ID; - if (intent != null) + if (intent != null) { extrasId = intent.getIntExtra(EXTRA_WIDGET_ID, extrasId); + } if (extrasId == AppWidgetManager.INVALID_APPWIDGET_ID) { int[] ids; try { @@ -181,8 +183,9 @@ public class TasksWidget extends AppWidgetProvider { Filter filter = null; try { filter = getFilter(context, widgetId); - if (SubtasksHelper.isTagFilter(filter)) + if (SubtasksHelper.isTagFilter(filter)) { ((FilterWithCustomIntent) filter).customTaskList = new ComponentName(context, TagViewFragment.class); // In case legacy widget was created with subtasks fragment + } views.setTextViewText(R.id.widget_title, filter.title); views.removeAllViews(R.id.taskbody); @@ -207,15 +210,17 @@ public class TasksWidget extends AppWidgetProvider { Resources r = context.getResources(); int textColor = r .getColor(isDarkTheme() ? R.color.widget_text_color_dark : R.color.widget_text_color_light); - if (isLegacyTheme()) + if (isLegacyTheme()) { textColor = r.getColor(android.R.color.white); + } textContent = task.getValue(Task.TITLE); - if (task.isCompleted()) + if (task.isCompleted()) { textColor = r.getColor(R.color.task_list_done); - else if (task.hasDueDate() && task.isOverdue()) + } else if (task.hasDueDate() && task.isOverdue()) { textColor = r.getColor(R.color.task_list_overdue); + } RemoteViews row = new RemoteViews(Constants.PACKAGE, R.layout.widget_row); @@ -226,8 +231,9 @@ public class TasksWidget extends AppWidgetProvider { RemoteViews separator = new RemoteViews(Constants.PACKAGE, R.layout.widget_separator); boolean isLastRow = (i == cursor.getCount() - 1) || (i == numberOfTasks - 1); - if (!isLastRow) + if (!isLastRow) { views.addView(R.id.taskbody, separator); + } } for (; i < numberOfTasks; i++) { RemoteViews row = new RemoteViews(Constants.PACKAGE, R.layout.widget_row); @@ -239,8 +245,9 @@ public class TasksWidget extends AppWidgetProvider { // can happen if database is not ready Log.e("WIDGET-UPDATE", "Error updating widget", e); } finally { - if (cursor != null) + if (cursor != null) { cursor.close(); + } } Intent listIntent = new Intent(context, TaskListActivity.class); @@ -266,8 +273,9 @@ public class TasksWidget extends AppWidgetProvider { PendingIntent pListIntent = PendingIntent.getActivity(context, widgetId, listIntent, PendingIntent.FLAG_CANCEL_CURRENT); - if (pListIntent != null) + if (pListIntent != null) { views.setOnClickPendingIntent(R.id.taskbody, pListIntent); + } Intent editIntent; @@ -275,8 +283,9 @@ public class TasksWidget extends AppWidgetProvider { if (tablet) { editIntent = new Intent(context, TaskListActivity.class); editIntent.putExtra(TaskListActivity.OPEN_TASK, 0L); - } else + } else { editIntent = new Intent(context, TaskEditActivity.class); + } editIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK); editIntent.putExtra(TaskEditFragment.OVERRIDE_FINISH_ANIM, false); @@ -376,10 +385,11 @@ public class TasksWidget extends AppWidgetProvider { DisplayMetrics metrics = new DisplayMetrics(); display.getMetrics(metrics); - if (metrics.density <= 0.75) + if (metrics.density <= 0.75) { return 4; - else + } else { return 5; + } } private Filter getFilter(Context context, int widgetId) { @@ -387,14 +397,17 @@ public class TasksWidget extends AppWidgetProvider { // base our filter off the inbox filter, replace stuff if we have it Filter filter = CoreFilterExposer.buildInboxFilter(getResources()); String sql = Preferences.getStringValue(WidgetConfigActivity.PREF_SQL + widgetId); - if (sql != null) + if (sql != null) { filter.setSqlQuery(sql); + } String title = Preferences.getStringValue(WidgetConfigActivity.PREF_TITLE + widgetId); - if (title != null) + if (title != null) { filter.title = title; + } String contentValues = Preferences.getStringValue(WidgetConfigActivity.PREF_VALUES + widgetId); - if (contentValues != null) + if (contentValues != null) { filter.valuesForNewTasks = AndroidUtilities.contentValuesFromSerializedString(contentValues); + } String customComponent = Preferences.getStringValue(WidgetConfigActivity.PREF_CUSTOM_INTENT + widgetId); @@ -419,20 +432,23 @@ public class TasksWidget extends AppWidgetProvider { Preferences.setString(WidgetConfigActivity.PREF_TITLE + widgetId, filter.title); ContentValues newTaskValues = filter.valuesForNewTasks; String contentValuesString = null; - if (newTaskValues != null) + if (newTaskValues != null) { contentValuesString = AndroidUtilities.contentValuesToSerializedString(newTaskValues); + } Preferences.setString(WidgetConfigActivity.PREF_VALUES + widgetId, contentValuesString); if (filter instanceof FilterWithCustomIntent) { String flattenedExtras = AndroidUtilities.bundleToSerializedString(((FilterWithCustomIntent) filter).customExtras); - if (flattenedExtras != null) + if (flattenedExtras != null) { Preferences.setString(WidgetConfigActivity.PREF_CUSTOM_EXTRAS + widgetId, flattenedExtras); + } } } } else { tagData = tagDataService.getTagByName(filter.title, TagData.ID); - if (tagData != null) + if (tagData != null) { Preferences.setLong(WidgetConfigActivity.PREF_TAG_ID + widgetId, tagData.getId()); + } } return filter; diff --git a/astrid/src/com/todoroo/astrid/widget/WidgetConfigActivity.java b/astrid/src/com/todoroo/astrid/widget/WidgetConfigActivity.java index 1cb732c9f..94848d9a8 100644 --- a/astrid/src/com/todoroo/astrid/widget/WidgetConfigActivity.java +++ b/astrid/src/com/todoroo/astrid/widget/WidgetConfigActivity.java @@ -144,8 +144,9 @@ abstract public class WidgetConfigActivity extends ListActivity { if (filterListItem != null && filterListItem instanceof Filter) { sql = ((Filter) filterListItem).getSqlQuery(); ContentValues values = ((Filter) filterListItem).valuesForNewTasks; - if (values != null) + if (values != null) { contentValuesString = AndroidUtilities.contentValuesToSerializedString(values); + } title = ((Filter) filterListItem).title; } @@ -158,9 +159,10 @@ abstract public class WidgetConfigActivity extends ListActivity { Preferences.setString(WidgetConfigActivity.PREF_CUSTOM_INTENT + mAppWidgetId, flattenedName); String flattenedExtras = AndroidUtilities.bundleToSerializedString(((FilterWithCustomIntent) filterListItem).customExtras); - if (flattenedExtras != null) + if (flattenedExtras != null) { Preferences.setString(WidgetConfigActivity.PREF_CUSTOM_EXTRAS + mAppWidgetId, flattenedExtras); + } } } diff --git a/facebook/facebook/src/com/facebook/android/Util.java b/facebook/facebook/src/com/facebook/android/Util.java index 231c1e78c..f038135cd 100644 --- a/facebook/facebook/src/com/facebook/android/Util.java +++ b/facebook/facebook/src/com/facebook/android/Util.java @@ -55,7 +55,9 @@ public final class Util { */ @Deprecated public static String encodePostBody(Bundle parameters, String boundary) { - if (parameters == null) return ""; + if (parameters == null) { + return ""; + } StringBuilder sb = new StringBuilder(); for (String key : parameters.keySet()) { @@ -86,7 +88,11 @@ public final class Util { continue; } - if (first) first = false; else sb.append("&"); + if (first) { + first = false; + } else { + sb.append("&"); + } sb.append(URLEncoder.encode(key) + "=" + URLEncoder.encode(parameters.getString(key))); } diff --git a/facebook/facebook/src/com/facebook/model/GraphObject.java b/facebook/facebook/src/com/facebook/model/GraphObject.java index 9b78f062a..103980101 100644 --- a/facebook/facebook/src/com/facebook/model/GraphObject.java +++ b/facebook/facebook/src/com/facebook/model/GraphObject.java @@ -656,8 +656,9 @@ public interface GraphObject { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; + } if (getClass() != obj.getClass()) { return false; }