Add braces to control flow statements

pull/14/head
Alex Baker 11 years ago
parent 4ab8d98bf1
commit 54fbbd9b6c

@ -2,6 +2,7 @@
<profile version="1.0" is_locked="false">
<option name="myName" value="Project Default" />
<option name="myLocal" value="false" />
<inspection_tool class="ControlFlowStatementWithoutBraces" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="MissingOverrideAnnotation" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoreObjectMethods" value="true" />
<option name="ignoreAnonymousClassMethods" value="false" />

@ -126,8 +126,9 @@ abstract public class AbstractDatabase {
*/
public final Table getTable(Class<? extends AbstractModel> 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$
}
@ -150,8 +151,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());
}
@ -164,8 +166,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();
@ -192,8 +195,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();
}
@ -304,8 +308,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(')');

@ -92,12 +92,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;
}
@ -115,10 +118,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;
}
@ -128,8 +132,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());
}
@ -159,10 +164,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;
}
@ -177,8 +184,9 @@ public abstract class AbstractModel implements Parcelable, Cloneable {
* Reads all properties from the supplied cursor and store
*/
public synchronized void readPropertiesFromCursor(TodorooCursor<? extends AbstractModel> cursor) {
if (values == null)
if (values == null) {
values = new ContentValues();
}
// clears user-set values
setValues = null;
@ -198,29 +206,28 @@ public abstract class AbstractModel implements Parcelable, Cloneable {
*/
public synchronized <TYPE> TYPE getValue(Property<TYPE> 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$
"Model Error: Did not read property " + property.name); //$NON-NLS-1$
}
// resolve properties that were retrieved with a different type than accessed
try {
if(value instanceof String && property instanceof LongProperty)
return (TYPE) Long.valueOf((String)value);
else if(value instanceof String && property instanceof IntegerProperty)
return (TYPE) Integer.valueOf((String)value);
else if(value instanceof String && property instanceof DoubleProperty)
return (TYPE) Double.valueOf((String)value);
else if(value instanceof Integer && property instanceof LongProperty)
return (TYPE) Long.valueOf(((Number)value).longValue());
if(value instanceof String && property instanceof LongProperty) {
return (TYPE) Long.valueOf((String) value);
} else if(value instanceof String && property instanceof IntegerProperty) {
return (TYPE) Integer.valueOf((String) value);
} else if(value instanceof String && property instanceof DoubleProperty) {
return (TYPE) Double.valueOf((String) value);
} else if(value instanceof Integer && property instanceof LongProperty) {
return (TYPE) Long.valueOf(((Number) value).longValue());
}
return (TYPE) value;
} catch (NumberFormatException e) {
return (TYPE) getDefaultValues().get(property.name);
@ -235,22 +242,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);
}
}
/**
@ -265,10 +275,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;
}
@ -278,10 +290,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;
}
@ -295,17 +309,20 @@ public abstract class AbstractModel implements Parcelable, Cloneable {
Property<TYPE> property, TYPE newValue) {
// we've already decided to save it, so overwrite old value
if (setValues.containsKey(property.getColumnName()))
return true;
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
@ -317,10 +334,12 @@ public abstract class AbstractModel implements Parcelable, Cloneable {
*/
public synchronized <TYPE> void setValue(Property<TYPE> 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);
}
@ -329,8 +348,9 @@ public abstract class AbstractModel implements Parcelable, Cloneable {
* Merges content values with those coming from another source
*/
public synchronized <TYPE> void mergeWith(ContentValues other) {
if (setValues == null)
if (setValues == null) {
setValues = new ContentValues();
}
setValues.putAll(other);
}
@ -339,11 +359,13 @@ public abstract class AbstractModel implements Parcelable, Cloneable {
* keeping the existing value if one already exists
*/
public synchronized <TYPE> void mergeWithoutReplacement(ContentValues other) {
if (setValues == null)
if (setValues == null) {
setValues = new ContentValues();
}
for (Entry<String, Object> item : other.valueSet()) {
if (setValues.containsKey(item.getKey()))
if (setValues.containsKey(item.getKey())) {
continue;
}
AndroidUtilities.putInto(setValues, item.getKey(), item.getValue(), true);
}
}
@ -353,10 +375,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());
}
}
/**
@ -366,10 +390,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);
}
}
/**
@ -386,26 +411,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<String, Object>();
}
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<String> getAllTransitoryKeys() {
if (transitoryData == null)
if (transitoryData == null) {
return null;
}
return transitoryData.keySet();
}
@ -427,19 +456,23 @@ public abstract class AbstractModel implements Parcelable, Cloneable {
*/
protected static Property<?>[] generateProperties(Class<? extends AbstractModel> cls) {
ArrayList<Property<?>> properties = new ArrayList<Property<?>>();
if(cls.getSuperclass() != AbstractModel.class)
if(cls.getSuperclass() != AbstractModel.class) {
properties.addAll(Arrays.asList(generateProperties(
(Class<? extends AbstractModel>) cls.getSuperclass())));
(Class<? extends AbstractModel>) 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);
@ -467,8 +500,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<Double> property, Object value) {

@ -47,8 +47,9 @@ public class ContentResolverDao<TYPE extends AbstractModel> {
public ContentResolverDao(Class<TYPE> 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();
@ -87,8 +88,9 @@ public class ContentResolverDao<TYPE extends AbstractModel> {
* @return
*/
public TodorooCursor<TYPE> 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<TYPE>(cursor, query.getFields());
}
@ -101,10 +103,12 @@ public class ContentResolverDao<TYPE extends AbstractModel> {
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());
@ -142,8 +146,9 @@ public class ContentResolverDao<TYPE extends AbstractModel> {
TodorooCursor<TYPE> 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<TYPE> constructor = modelClass.getConstructor(TodorooCursor.class);
return constructor.newInstance(cursor);

@ -54,8 +54,9 @@ public class DatabaseDao<TYPE extends AbstractModel> {
public DatabaseDao(Class<TYPE> modelClass) {
DependencyInjectionService.getInstance().inject(this);
this.modelClass = modelClass;
if(debug == null)
if(debug == null) {
debug = false;
}
}
public DatabaseDao(Class<TYPE> modelClass, AbstractDatabase database) {
@ -79,8 +80,9 @@ public class DatabaseDao<TYPE extends AbstractModel> {
* @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<TYPE extends AbstractModel> {
*/
public TodorooCursor<TYPE> 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<TYPE>(cursor, query.getFields());
}
@ -132,8 +135,9 @@ public class DatabaseDao<TYPE extends AbstractModel> {
*/
public TodorooCursor<TYPE> 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<TYPE>(database.getDatabase().query(table.name,
fields, selection, selectionArgs, null, null, null),
properties);
@ -158,8 +162,9 @@ public class DatabaseDao<TYPE extends AbstractModel> {
protected TYPE returnFetchResult(TodorooCursor<TYPE> cursor) {
try {
if (cursor.getCount() == 0)
if (cursor.getCount() == 0) {
return null;
}
Constructor<TYPE> constructor = modelClass.getConstructor(TodorooCursor.class);
return constructor.newInstance(cursor);
} catch (SecurityException e) {
@ -231,8 +236,9 @@ public class DatabaseDao<TYPE extends AbstractModel> {
toUpdate.close();
}
if (toUpdate.getCount() == 0)
if (toUpdate.getCount() == 0) {
return 0;
}
synchronized (database) {
database.getDatabase().beginTransactionWithListener(new SQLiteTransactionListener() {
@ -280,7 +286,9 @@ public class DatabaseDao<TYPE extends AbstractModel> {
ContentValues values = item.getSetValues();
if (values.size() == 0) // nothing changed
{
return true;
}
return saveExisting(item);
}
@ -318,11 +326,15 @@ public class DatabaseDao<TYPE extends AbstractModel> {
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);
@ -351,8 +363,9 @@ public class DatabaseDao<TYPE extends AbstractModel> {
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;
}
};
@ -372,7 +385,9 @@ public class DatabaseDao<TYPE extends AbstractModel> {
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() {

@ -104,13 +104,15 @@ public abstract class Property<TYPE> extends Field implements Cloneable {
*/
public Property<TYPE> cloneAs(String tableAlias, String columnAlias) {
Table aliasedTable = this.table;
if (!TextUtils.isEmpty(tableAlias))
if (!TextUtils.isEmpty(tableAlias)) {
aliasedTable = table.as(tableAlias);
}
try {
Property<TYPE> newInstance = this.getClass().getConstructor(Table.class, String.class).newInstance(aliasedTable, this.name);
if(!TextUtils.isEmpty(columnAlias))
if(!TextUtils.isEmpty(columnAlias)) {
return (Property<TYPE>) newInstance.as(columnAlias);
}
return newInstance;
} catch (Exception e) {
throw new RuntimeException(e);
@ -301,8 +303,9 @@ public abstract class Property<TYPE> extends Field implements Cloneable {
}
public String getColumnName() {
if (hasAlias())
if (hasAlias()) {
return alias;
}
return name;
}

@ -66,21 +66,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;
}
}

@ -101,31 +101,35 @@ public class TodorooCursor<TYPE extends AbstractModel> extends CursorWrapper {
public Object visitDouble(Property<Double> 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<Integer> 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<Long> 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<String> 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);
}

@ -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;
}

@ -47,8 +47,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) {
@ -74,12 +75,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;
}
@ -97,10 +101,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) {
@ -150,8 +155,9 @@ public class DependencyInjectionService {
* @return
*/
public synchronized static DependencyInjectionService getInstance() {
if(instance == null)
if(instance == null) {
instance = new DependencyInjectionService();
}
return instance;
}

@ -43,8 +43,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 {
@ -67,10 +68,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() {
@ -128,13 +130,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);
}
}
}
@ -157,8 +161,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);
}
}

@ -107,8 +107,9 @@ public class HttpRestClient implements RestClient {
public void process(
final HttpRequest request,
final HttpContext context) throws HttpException, IOException {
if (!request.containsHeader("Accept-Encoding"))
request.addHeader("Accept-Encoding", "gzip");
if (!request.containsHeader("Accept-Encoding")) {
request.addHeader("Accept-Encoding", "gzip");
}
}
});
@ -192,8 +193,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);
@ -218,14 +220,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);

@ -32,13 +32,21 @@ public abstract class DBObject<T extends 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) return false;
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;
}
@ -64,8 +72,9 @@ public abstract class DBObject<T extends 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();
}

@ -23,8 +23,9 @@ public class Field extends DBObject<Field> {
}
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<Field> {
*/
@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);
}

@ -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();

@ -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);
}
}
}

@ -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) {
@ -251,12 +254,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();
@ -266,24 +271,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());
}
@ -299,18 +310,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());
}
}
}

@ -58,8 +58,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();
}

@ -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);
}
}
/**

@ -93,10 +93,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;
}
@ -115,8 +117,9 @@ public class AndroidUtilities {
bis.close();
}
} finally {
if(is != null)
if(is != null) {
is.close();
}
}
}
@ -151,10 +154,11 @@ public class AndroidUtilities {
*/
public static void startExternalIntent(Context context, Intent intent, int request) {
try {
if(request > -1 && context instanceof Activity)
((Activity)context).startActivityForResult(intent, request);
else
if(request > -1 && context instanceof Activity) {
((Activity) context).startActivityForResult(intent, request);
} else {
context.startActivity(intent);
}
} catch (Exception e) {
getExceptionService().displayAndReportError(context,
"start-external-intent-" + intent.toString(), //$NON-NLS-1$
@ -187,25 +191,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());
}
}
/**
@ -215,25 +220,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
@ -258,9 +264,11 @@ public class AndroidUtilities {
* @return
*/
public static <TYPE> 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;
}
@ -271,9 +279,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;
}
@ -293,18 +303,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);
}
@ -313,8 +324,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));
@ -328,8 +340,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<ContentValues>() {
@ -362,8 +375,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<Bundle>() {
@ -423,8 +437,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();
@ -438,8 +453,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;
@ -452,10 +468,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);
}
@ -493,8 +511,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;
@ -512,16 +531,19 @@ public class AndroidUtilities {
* @return first view (by DFS) if found, or null if none
*/
public static <TYPE> TYPE findViewByType(View view, Class<TYPE> 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;
@ -540,8 +562,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 {
@ -573,8 +596,9 @@ public class AndroidUtilities {
*/
public static <KEY, VALUE> KEY findKeyInMap(Map<KEY, VALUE> map, VALUE value){
for (Entry<KEY, VALUE> entry: map.entrySet()) {
if(entry.getValue().equals(value))
if(entry.getValue().equals(value)) {
return entry.getKey();
}
}
return null;
}
@ -620,8 +644,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);
@ -639,8 +664,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),
@ -799,17 +825,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;
}
@ -819,11 +848,13 @@ public class AndroidUtilities {
private static ExceptionService exceptionService = null;
private static ExceptionService getExceptionService() {
if(exceptionService == null)
synchronized(AndroidUtilities.class) {
if(exceptionService == null)
if(exceptionService == null) {
synchronized (AndroidUtilities.class) {
if (exceptionService == null) {
exceptionService = new ExceptionService();
}
}
}
return exceptionService;
}
@ -835,11 +866,13 @@ public class AndroidUtilities {
*/
public static <TYPE> 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;
}
@ -888,7 +921,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;
@ -932,8 +967,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) {
@ -974,8 +1010,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;
}

@ -27,15 +27,17 @@ 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);
}
/** Convert date into unixtime */
public static final long dateToUnixtime(Date date) {
if(date == null)
if(date == null) {
return 0;
}
return date.getTime();
}
@ -85,8 +87,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);
}
@ -134,12 +137,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())){
@ -166,20 +171,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);
}
}
/**
@ -231,33 +240,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;
}
@ -292,8 +308,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$
@ -313,12 +330,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);
}

@ -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() {
@ -217,8 +221,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 {

@ -37,8 +37,9 @@ public class Pair<L, R> {
@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());

@ -33,8 +33,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);
}
}
/**
@ -61,8 +63,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);
}
}
/* ======================================================================
@ -73,8 +76,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 {
@ -133,8 +137,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);

@ -68,14 +68,15 @@ abstract public class TodorooPreferenceActivity extends PreferenceActivity {
updatePreferences(group, null);
} else {
Object value = null;
if(preference instanceof ListPreference)
value = ((ListPreference)preference).getValue();
else if(preference instanceof CheckBoxPreference)
value = ((CheckBoxPreference)preference).isChecked();
else if(preference instanceof EditTextPreference)
value = ((EditTextPreference)preference).getText();
else if(preference instanceof RingtonePreference)
if(preference instanceof ListPreference) {
value = ((ListPreference) preference).getValue();
} else if(preference instanceof CheckBoxPreference) {
value = ((CheckBoxPreference) preference).isChecked();
} else if(preference instanceof EditTextPreference) {
value = ((EditTextPreference) preference).getText();
} else if(preference instanceof RingtonePreference) {
value = getPreferenceManager().getSharedPreferences().getString(preference.getKey(), null);
}
updatePreferences(preference, value);

@ -112,8 +112,9 @@ public class Filter extends FilterListItem {
}
public String getSqlQuery() {
if (filterOverride != null)
if (filterOverride != null) {
return filterOverride;
}
return sqlQuery;
}
@ -156,23 +157,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;
}

@ -78,10 +78,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;

@ -86,10 +86,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());

@ -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;
}

@ -62,8 +62,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)) {

@ -61,8 +61,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());
}

@ -48,26 +48,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;
}
@ -78,8 +83,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;
}
@ -107,8 +113,9 @@ public class SortHelper {
default:
order = defaultTaskOrder();
}
if (sortType != SORT_ALPHA)
if (sortType != SORT_ALPHA) {
order.addSecondaryExpression(Order.asc(Task.TITLE));
}
return order;
}

@ -78,22 +78,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) {
@ -145,8 +148,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);
@ -171,11 +175,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;
@ -185,8 +192,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")) {

@ -252,10 +252,11 @@ public final class TagData extends RemoteModel {
/** Checks whether task is deleted. Will return false if DELETION_DATE not read */
public boolean isDeleted() {
// assume false if we didn't load deletion date
if(!containsValue(DELETION_DATE))
if(!containsValue(DELETION_DATE)) {
return false;
else
} else {
return getValue(DELETION_DATE) > 0;
}
}
}

@ -224,8 +224,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) ||
@ -233,8 +234,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;
}
@ -378,10 +380,11 @@ public final class Task extends RemoteModel {
/** Checks whether task is deleted. Will return false if DELETION_DATE not read */
public boolean isDeleted() {
// assume false if we didn't load deletion date
if(!containsValue(DELETION_DATE))
if(!containsValue(DELETION_DATE)) {
return false;
else
} else {
return getValue(DELETION_DATE) > 0;
}
}
/** Checks whether task is hidden. Requires HIDDEN_UNTIL */
@ -458,8 +461,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) {
@ -505,8 +509,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) {
@ -523,8 +528,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));
}

@ -159,24 +159,29 @@ public class TaskApiDao extends ContentResolverDao<Task> {
/** @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;
}

@ -149,19 +149,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();
}

@ -68,13 +68,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);
}
@ -154,10 +156,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;
}
}

@ -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;
}

@ -170,8 +170,9 @@ public abstract class SyncProvider<TYPE extends SyncContainer> {
((Activity) context).runOnUiThread(new Runnable() {
@Override
public void run() {
if(showSyncToast)
if(showSyncToast) {
makeSyncToast(context);
}
}
});
}
@ -223,8 +224,9 @@ public abstract class SyncProvider<TYPE extends SyncContainer> {
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);
}
@ -241,10 +243,11 @@ public abstract class SyncProvider<TYPE extends SyncContainer> {
@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";
}
@ -262,21 +265,24 @@ public abstract class SyncProvider<TYPE extends SyncContainer> {
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 extends SyncContainer> {
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<TYPE extends SyncContainer> {
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<TYPE>)data.remoteUpdated, local);

@ -87,8 +87,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);
}
}
});
}
@ -108,12 +109,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
@ -175,8 +177,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) {
@ -271,8 +274,9 @@ abstract public class SyncProviderPreferences extends TodorooPreferenceActivity
break;
}
}
if (resource == null)
if (resource == null) {
return lastError;
}
return r.getString(resource.intValue(), service);
}

@ -164,8 +164,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) {

@ -69,16 +69,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() {
@ -86,6 +88,7 @@ abstract public class SyncV2BackgroundService extends Service {
context.sendBroadcast(new Intent(AstridApiConstants.BROADCAST_EVENT_REFRESH));
}
});
}
}
@Override
@ -163,10 +166,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;
}
}

@ -88,8 +88,9 @@ abstract public class SyncV2Provider {
utilities.recordSuccessfulSync();
utilities.reportLastError();
utilities.stopOngoing();
if (callback != null)
if (callback != null) {
callback.finished();
}
}
@Override

@ -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())
return;
if(Thread.currentThread().isInterrupted()) {
return;
}
if(mDragView != null && mDragPos == mFirstDragPos &&
Math.abs(mDragCurrentX - mDragStartX) < 10) {
@ -474,10 +475,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);
}
}
}
}

@ -66,8 +66,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
}
@ -119,13 +120,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);
}
}
}
@ -174,12 +177,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;
@ -213,8 +218,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);
@ -228,10 +234,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;
@ -254,20 +261,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;
}
@ -334,8 +347,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"));
@ -361,14 +375,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;
}

@ -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<String> adapter = new ArrayAdapter<String>(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<String> adapter = new ArrayAdapter<String>(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();
}
}
}
};
@ -174,10 +181,12 @@ public class ActFmCameraModule {
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);

@ -73,8 +73,9 @@ public class ActFmGoogleAuthActivity extends ListActivity {
accountManager = new GoogleAccountManager(this);
Account[] accounts = accountManager.getAccounts();
ArrayList<String> accountNames = new ArrayList<String>();
for (Account a : accounts)
for (Account a : accounts) {
accountNames.add(a.name);
}
nameArray = accountNames.toArray(new String[accountNames.size()]);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, nameArray));
@ -133,8 +134,9 @@ public class ActFmGoogleAuthActivity extends ListActivity {
}
});
} finally {
if (dismissDialog)
if (dismissDialog) {
DialogUtilities.dismissDialog(ActFmGoogleAuthActivity.this, pd);
}
}
}
}.start();

@ -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());
@ -297,14 +299,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);
@ -370,8 +374,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]);
}
}
});
@ -414,8 +419,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]);
}
}
});
@ -493,8 +499,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;
}
@ -511,8 +518,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;
}
@ -571,9 +579,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
@ -849,8 +858,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();
@ -885,12 +895,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);
@ -907,8 +918,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(
@ -935,8 +947,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);
@ -951,11 +964,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);
}
}
}

@ -77,9 +77,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) {
@ -87,6 +87,7 @@ public class ActFmPreferences extends SyncProviderPreferences {
return true;
}
});
}
findPreference(getString(R.string.actfm_account_type)).setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
@ -140,20 +141,23 @@ 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

@ -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);

@ -212,10 +212,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);
}
}
});
@ -230,8 +231,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));
@ -284,8 +286,9 @@ public abstract class CommentsFragment extends SherlockListFragment {
listView.setVisibility(View.VISIBLE);
}
if (activity instanceof CommentsActivity)
if (activity instanceof CommentsActivity) {
setLastViewed();
}
}
@ -302,8 +305,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);
}
@ -324,7 +328,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() {
@ -332,6 +336,7 @@ public abstract class CommentsFragment extends SherlockListFragment {
refreshUpdatesList();
}
});
}
}
}
@ -351,8 +356,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();

@ -156,8 +156,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);
}
@ -295,8 +296,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);
@ -346,8 +348,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;
}
}
@ -358,23 +361,28 @@ public class EditPeopleControlSet extends PopupControlSet {
ArrayList<AssignedToUser> users = new ArrayList<AssignedToUser>();
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);
@ -384,15 +392,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;
}
@ -437,8 +448,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++;
}
@ -483,8 +495,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) {
@ -574,8 +587,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;
}
@ -602,8 +616,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 {
@ -613,8 +628,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
@ -626,9 +642,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))) {
@ -651,8 +668,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");
@ -663,8 +681,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, "");
}
@ -694,10 +713,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) {
@ -731,14 +751,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))) {
@ -788,8 +810,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);
}
@ -807,8 +830,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)) {
@ -816,8 +840,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);
}
@ -826,10 +851,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

@ -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);
@ -139,12 +142,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
@ -178,8 +183,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);
}
}
}

@ -134,10 +134,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);
}
@ -181,16 +182,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);
}
@ -318,8 +321,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;
@ -336,8 +340,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) {
@ -394,7 +399,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);
@ -438,13 +445,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()));
@ -599,22 +608,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)),

@ -164,8 +164,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;
}
@ -203,14 +204,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);
}
}
}
@ -239,22 +242,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<TagData> cursor;
if (!RemoteModel.isUuidEmpty(uuid)) {
@ -295,8 +302,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();
@ -326,8 +334,9 @@ public class TagViewFragment extends TaskListFragment {
}
TaskListActivity tla = (TaskListActivity) getActivity();
if (tla != null)
if (tla != null) {
tla.setCommentsCount(unreadCount);
}
}
}
@ -336,8 +345,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) {
@ -464,8 +474,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;
@ -553,8 +564,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$
@ -571,13 +583,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")
@ -590,14 +603,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);
@ -626,21 +641,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();
@ -654,8 +671,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();
}
@ -688,10 +706,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
@ -760,10 +780,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;
@ -803,9 +824,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;
}

@ -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);
}
}
}

@ -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());
@ -166,17 +169,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());
@ -202,8 +208,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");
@ -218,11 +225,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());
@ -244,17 +253,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<String, Object>(getParameters[i].toString() + "[]",
list.get(j)));
} else
params.add(new Pair<String, Object>(getParameters[i].toString(), getParameters[i+1]));
}
} else {
params.add(new Pair<String, Object>(getParameters[i].toString(), getParameters[i + 1]));
}
}
params.add(new Pair<String, Object>("app_id", APP_ID));
boolean syncMethod = "synchronize".equals(method);
if (!syncMethod)
if (!syncMethod) {
params.add(new Pair<String, Object>("time", System.currentTimeMillis() / 1000L));
}
if(token != null) {
boolean foundTokenKey = false;
for (Pair<String, Object> curr : params) {
@ -263,8 +275,9 @@ public class ActFmInvoker {
break;
}
}
if (!foundTokenKey)
if (!foundTokenKey) {
params.add(new Pair<String, Object>("token", token));
}
}
Collections.sort(params, new Comparator<Pair<String, Object>>() {
@ -272,8 +285,9 @@ public class ActFmInvoker {
public int compare(Pair<String, Object> object1,
Pair<String, Object> object2) {
int result = object1.getLeft().compareTo(object2.getLeft());
if(result == 0)
if(result == 0) {
return object1.getRight().toString().compareTo(object2.getRight().toString());
}
return result;
}
});
@ -284,26 +298,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<String, Object> 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);
}

@ -50,8 +50,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();
}
@ -60,10 +61,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);
}
}
/**
@ -79,8 +81,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));
@ -130,8 +133,9 @@ public class ActFmPreferenceService extends SyncProviderUtilities {
}
public synchronized static void reloadThisUser() {
if (user == null)
if (user == null) {
return;
}
populateUser();
}
@ -151,8 +155,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);
@ -171,18 +176,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;
}
@ -192,19 +200,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();
}

@ -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<Object> params = new ArrayList<Object>();
params.add("purchase_token"); params.add(purchaseToken);
@ -98,8 +101,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;
@ -107,15 +111,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();
}
}
}
@ -150,13 +156,15 @@ public final class ActFmSyncService {
/** invoke authenticated method against the server */
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++)
parameters[i+2] = getParameters[i];
for(int i = 0; i < getParameters.length; i++) {
parameters[i + 2] = getParameters[i];
}
return actFmInvoker.invoke(method, parameters);
}
@ -165,8 +173,9 @@ public final class ActFmSyncService {
}
private boolean checkForToken() {
if(!actFmPreferenceService.isLoggedIn())
if(!actFmPreferenceService.isLoggedIn()) {
return false;
}
token = actFmPreferenceService.getToken();
return true;
}
@ -199,19 +208,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"))
model.setFlag(TagData.FLAGS, TagData.FLAG_SILENT,json.getBoolean("is_silent"));
if(json.has("is_silent")) {
model.setFlag(TagData.FLAGS, TagData.FLAG_SILENT, json.getBoolean("is_silent"));
}
if(!json.isNull("description"))
if(!json.isNull("description")) {
model.setValue(TagData.TAG_DESCRIPTION, json.getString("description"));
}
if(json.has("members")) {
JSONArray members = json.getJSONArray("members");
@ -219,11 +233,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"));
}
}
}

@ -208,17 +208,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();
}
@ -227,10 +230,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() {
@ -260,8 +264,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
}
@ -281,8 +286,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()) {
@ -293,8 +299,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--;
@ -355,10 +362,11 @@ public class ActFmSyncThread {
SyncMessageCallback r = pendingCallbacks.remove(message);
if (r != null && !callbacksExecutedThisLoop.contains(r)) {
List<JSONArray> errorList = errorMap.get(i);
if (errorList == null || errorList.isEmpty())
if (errorList == null || errorList.isEmpty()) {
r.runOnSuccess();
else
} else {
r.runOnErrors(errorList);
}
callbacksExecutedThisLoop.add(r);
}
@ -498,15 +506,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 {

@ -121,20 +121,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) {

@ -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);

@ -78,8 +78,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
@ -100,8 +101,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);
@ -114,8 +116,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();
}
}
// --------------
@ -131,8 +134,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);
@ -141,8 +145,9 @@ public class AstridNewSyncMigrator {
} catch (Exception e){
Crittercism.logHandledException(e);
} finally {
if (emergentTags != null)
if (emergentTags != null) {
emergentTags.close();
}
}
// --------------
@ -171,16 +176,18 @@ public class AstridNewSyncMigrator {
assertUUIDsExist(tasksQuery, new Task(), taskDao, taskOutstandingDao, new TaskOutstanding(), NameMaps.syncableProperties(NameMaps.TABLE_ID_TASKS), new UUIDAssertionExtras<Task>() {
@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) {
@ -220,10 +227,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);
@ -238,8 +246,9 @@ public class AstridNewSyncMigrator {
Log.e(LOG_TAG, "Error migrating recurrence", e);
Crittercism.logHandledException(e);
} finally {
if (tasksWithRecurrence != null)
if (tasksWithRecurrence != null) {
tasksWithRecurrence.close();
}
}
// --------------
@ -264,10 +273,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;
}
@ -289,8 +299,9 @@ public class AstridNewSyncMigrator {
Log.e(LOG_TAG, "Error migrating updates", e);
Crittercism.logHandledException(e);
} finally {
if (updates != null)
if (updates != null) {
updates.close();
}
}
@ -321,8 +332,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;
@ -331,23 +343,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);
@ -359,8 +377,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();
}
}
// --------------
@ -369,8 +388,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);
@ -387,8 +407,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);
@ -427,8 +448,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();
}
}
// --------------
@ -447,23 +469,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);
@ -475,8 +501,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();
}
}
// --------------
@ -505,15 +532,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);
@ -527,8 +556,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);
@ -567,8 +597,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);
@ -578,8 +609,9 @@ public class AstridNewSyncMigrator {
Log.e(LOG_TAG, "Error asserting UUIDs", e);
Crittercism.logHandledException(e);
} finally {
if (cursor != null)
if (cursor != null) {
cursor.close();
}
}
}
@ -591,8 +623,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);
@ -603,12 +636,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());
}
}
@ -617,12 +652,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());
}
}

@ -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();
}
}
}

@ -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));

@ -15,10 +15,11 @@ public class TaskListMetadataSyncDatabaseListener extends SyncDatabaseListener<T
@Override
protected void enqueueMessage(TaskListMetadata model, ClientToServerMessage<?> 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);
}
}
}

@ -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) {

@ -86,15 +86,18 @@ public class ChangesHappened<TYPE extends RemoteModel, OE extends OutstandingEnt
this.changes = new ArrayList<OE>();
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<TYPE extends RemoteModel, OE extends OutstandingEnt
}
private JSONArray changesToJSON(MultipartEntity entity) {
if (!RemoteModel.NO_UUID.equals(uuid))
if (!RemoteModel.NO_UUID.equals(uuid)) {
populateChanges();
}
JSONArray array = new JSONArray();
AtomicInteger uploadCounter = new AtomicInteger();
@ -145,25 +149,29 @@ public class ChangesHappened<TYPE extends RemoteModel, OE extends OutstandingEnt
changeJson.put("value", name);
} else {
Property<?> 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<TYPE extends RemoteModel, OE extends OutstandingEnt
// (e.g. empty task title, etc.)
private boolean validateValue(Property<?> 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<TYPE extends RemoteModel, OE extends OutstandingEnt
try {
JSONObject obj = new JSONObject(value);
String path = obj.optString("path");
if (TextUtils.isEmpty(path))
if (TextUtils.isEmpty(path)) {
return null;
}
File f = new File(path);
if (!f.exists())
if (!f.exists()) {
return null;
}
return obj;
} catch (JSONException e) {
@ -255,8 +266,9 @@ public class ChangesHappened<TYPE extends RemoteModel, OE extends OutstandingEnt
public Object visitInteger(Property<Integer> 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<TYPE extends RemoteModel, OE extends OutstandingEnt
if (l != null) {
if (property.checkFlag(Property.PROP_FLAG_DATE)) {
boolean includeTime = true;
if (Task.DUE_DATE.equals(property) && !Task.hasDueTime(l))
if (Task.DUE_DATE.equals(property) && !Task.hasDueTime(l)) {
includeTime = false;
}
return DateUtilities.timeToIso8601(l, includeTime);
}
return l;
@ -292,16 +305,19 @@ public class ChangesHappened<TYPE extends RemoteModel, OE extends OutstandingEnt
@Override
public Object visitString(Property<String> 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;
}

@ -74,10 +74,11 @@ public abstract class ClientToServerMessage<TYPE extends RemoteModel> {
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<TYPE extends RemoteModel> {
@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;
}

@ -46,18 +46,20 @@ public class ConstructOutstandingTableFromMasterTable<TYPE extends RemoteModel,
OE oe = outstandingDao.getModelClass().newInstance();
for (items.moveToFirst(); !items.isAfterLast(); items.moveToNext()) {
long createdAt;
if (createdAtProperty != null)
if (createdAtProperty != null) {
createdAt = items.get(createdAtProperty);
else
} else {
createdAt = DateUtilities.now();
}
long itemId = items.get(AbstractModel.ID_PROPERTY);
for (Property<?> 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);

@ -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);
}
}
}

@ -71,16 +71,18 @@ public class FetchHistory<TYPE extends RemoteModel> {
@Override
public void run() {
String token = actFmPreferenceService.getToken();
if (TextUtils.isEmpty(token) || TextUtils.isEmpty(uuid))
if (TextUtils.isEmpty(token) || TextUtils.isEmpty(uuid)) {
return;
}
ArrayList<Object> params = new ArrayList<Object>();
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);
@ -111,8 +113,9 @@ public class FetchHistory<TYPE extends RemoteModel> {
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"));
@ -145,8 +148,9 @@ public class FetchHistory<TYPE extends RemoteModel> {
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);
@ -164,8 +168,9 @@ public class FetchHistory<TYPE extends RemoteModel> {
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"));
@ -185,8 +190,9 @@ public class FetchHistory<TYPE extends RemoteModel> {
Log.e(ERROR_TAG, "Error getting model history", e);
}
if (done != null)
if (done != null) {
done.runOnSuccess();
}
}
}).start();
}

@ -87,19 +87,22 @@ public class JSONChangeToPropertyVisitor implements PropertyVisitor<Void, String
public Void visitString(Property<String> 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);
}

@ -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();
}

@ -71,13 +71,15 @@ public class MakeChanges<TYPE extends RemoteModel> extends ServerToClientMessage
private static <T extends RemoteModel> void saveOrUpdateModelAfterChanges(RemoteModelDao<T> 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<TYPE extends RemoteModel> 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<TYPE extends RemoteModel> 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<TYPE extends RemoteModel> 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<TYPE extends RemoteModel> 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<TYPE extends RemoteModel> 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<TYPE extends RemoteModel> 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<TYPE extends RemoteModel> 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<TYPE extends RemoteModel> 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<TYPE extends RemoteModel> 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();

@ -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<Property<?>> baseSet, Set<String> excluded) {
Set<Property<?>> result = new HashSet<Property<?>>();
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 <A, B> B mapColumnName(String table, A col, Map<A, B> taskMap, Map<A, B> tagMap, Map<A, B> userMap,
Map<A, B> userActivityMap, Map<A, B> taskAttachmentMap, Map<A, B> taskListMetadataMap, Map<A, B> waitingOnMeMap) {
Map<A, B> 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;
}

@ -50,25 +50,30 @@ public class NowBriefed<TYPE extends RemoteModel> 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<TYPE extends RemoteModel> 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 {

@ -72,14 +72,16 @@ public class ReplayOutstandingEntries<T extends RemoteModel, OE extends Outstand
for (; !outstanding.isAfterLast(); outstanding.moveToNext()) {
instance.clear();
instance.readPropertiesFromCursor(outstanding);
if (instance.getValue(OutstandingEntry.ENTITY_ID_PROPERTY) != id)
if (instance.getValue(OutstandingEntry.ENTITY_ID_PROPERTY) != id) {
break;
}
count ++;
String column = instance.getValue(OutstandingEntry.COLUMN_STRING_PROPERTY);
Property<?> 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<T extends RemoteModel, OE extends Outstand
@Override
public Void visitInteger(Property<Integer> 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<Long> 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<Double> 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;
}

@ -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;
}

@ -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<Task>(json, PluginServices.getTaskDao());
else if (NameMaps.TABLE_ID_TAGS.equals(table))
} else if (NameMaps.TABLE_ID_TAGS.equals(table)) {
return new MakeChanges<TagData>(json, PluginServices.getTagDataDao());
else if (NameMaps.TABLE_ID_USERS.equals(table))
} else if (NameMaps.TABLE_ID_USERS.equals(table)) {
return new MakeChanges<User>(json, PluginServices.getUserDao());
else if (NameMaps.TABLE_ID_USER_ACTIVITY.equals(table))
} else if (NameMaps.TABLE_ID_USER_ACTIVITY.equals(table)) {
return new MakeChanges<UserActivity>(json, PluginServices.getUserActivityDao());
else if (NameMaps.TABLE_ID_ATTACHMENTS.equals(table))
} else if (NameMaps.TABLE_ID_ATTACHMENTS.equals(table)) {
return new MakeChanges<TaskAttachment>(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<TaskListMetadata>(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<WaitingOnMe>(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<Task>(json, PluginServices.getTaskDao());
else if (NameMaps.TABLE_ID_TAGS.equals(table))
} else if (NameMaps.TABLE_ID_TAGS.equals(table)) {
return new NowBriefed<TagData>(json, PluginServices.getTagDataDao());
else if (NameMaps.TABLE_ID_USER_ACTIVITY.equals(table))
} else if (NameMaps.TABLE_ID_USER_ACTIVITY.equals(table)) {
return new NowBriefed<UserActivity>(json, PluginServices.getUserActivityDao());
else if (NameMaps.TABLE_ID_USERS.equals(table))
} else if (NameMaps.TABLE_ID_USERS.equals(table)) {
return new NowBriefed<User>(json, PluginServices.getUserDao());
else if (NameMaps.TABLE_ID_ATTACHMENTS.equals(table))
} else if (NameMaps.TABLE_ID_ATTACHMENTS.equals(table)) {
return new NowBriefed<TaskAttachment>(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<TaskListMetadata>(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<WaitingOnMe>(json, PluginServices.getWaitingOnMeDao());
else
} else {
return null;
}
}
}

@ -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);

@ -48,8 +48,9 @@ public final class AlarmControlSet extends TaskEditControlSet {
alertsContainer.removeAllViews();
TodorooCursor<Metadata> 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();
}
@ -71,8 +72,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);
}
@ -81,13 +83,15 @@ public final class AlarmControlSet extends TaskEditControlSet {
LinkedHashSet<Long> alarms = new LinkedHashSet<Long>();
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;
}

@ -31,12 +31,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);
@ -58,15 +60,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 "<img src='silk_clock'/> " + durationString; //$NON-NLS-1$

@ -46,8 +46,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;
}
@ -184,8 +186,9 @@ public class AlarmService {
*/
@SuppressWarnings("nls")
private void scheduleAlarm(Metadata alarm) {
if(alarm == null)
if(alarm == null) {
return;
}
long taskId = alarm.getValue(Metadata.TASK);
@ -194,12 +197,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));
", " + alarm.getId() + ") set for " + new Date(time));
}
am.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
}
}

@ -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<Metadata> cursor = AlarmService.getInstance().getAlarms(taskId);
try {
if(cursor.getCount() == 0)
if(cursor.getCount() == 0) {
return;
}
Metadata metadata = new Metadata();
LinkedHashSet<Long> alarms = new LinkedHashSet<Long>(cursor.getCount());

@ -63,8 +63,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);
}
}
});
@ -104,10 +105,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
@ -143,8 +145,9 @@ public class BackupPreferences extends TodorooPreferenceActivity {
preference.setSummary(subtitle);
View view = findViewById(R.id.status);
if(view != null)
if(view != null) {
view.setBackgroundColor(statusColor);
}
}
}

@ -127,13 +127,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<File>() {
@Override
@ -142,8 +144,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$
}
}
}

@ -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 {

@ -107,8 +107,9 @@ public class TasksXmlExporter {
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(false);
progressDialog.show();
if(context instanceof Activity)
progressDialog.setOwnerActivity((Activity)context);
if(context instanceof Activity) {
progressDialog.setOwnerActivity((Activity) context);
}
}
new Thread(new Runnable() {
@ -119,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();
@ -224,9 +228,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);
@ -301,8 +307,9 @@ public class TasksXmlExporter {
public Void visitString(Property<String> 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
@ -322,15 +329,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);
}
}
}
});

@ -108,8 +108,9 @@ public class TasksXmlImporter {
progressDialog.setIndeterminate(true);
try {
progressDialog.show();
if(context instanceof Activity)
progressDialog.setOwnerActivity((Activity)context);
if(context instanceof Activity) {
progressDialog.setOwnerActivity((Activity) context);
}
} catch (BadTokenException e) {
// Running from a unit test or some such thing
}
@ -147,14 +148,15 @@ public class TasksXmlImporter {
// Process <astrid ... >
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 + "'");
format + "'");
}
}
}
}
@ -164,8 +166,9 @@ public class TasksXmlImporter {
handler.post(new Runnable() {
@Override
public void run() {
if(progressDialog.isShowing() && context instanceof Activity)
DialogUtilities.dismissDialog((Activity) context, progressDialog);
if(progressDialog.isShowing() && context instanceof Activity) {
DialogUtilities.dismissDialog((Activity) context, progressDialog);
}
showSummary();
}
});
@ -220,8 +223,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)) {
@ -270,12 +274,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) {
@ -289,13 +295,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);
@ -319,8 +327,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);
@ -352,18 +361,20 @@ public class TasksXmlImporter {
public Void visitInteger(Property<Integer> 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<Long> 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;
}
@ -371,9 +382,10 @@ public class TasksXmlImporter {
public Void visitDouble(Property<Double> 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;
}
@ -381,8 +393,9 @@ public class TasksXmlImporter {
public Void visitString(Property<String> property,
AbstractModel data) {
String value = xpp.getAttributeValue(null, property.name);
if(value != null)
if(value != null) {
data.setValue(property, value);
}
return null;
}
@ -408,11 +421,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 <task ... >
currentTask = parseTask();
} else if (currentTask != null) {
@ -523,10 +536,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;
}
@ -577,11 +591,12 @@ public class TasksXmlImporter {
}
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,
@ -628,8 +643,9 @@ public class TasksXmlImporter {
}
}
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;

@ -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();
}

@ -64,13 +64,15 @@ public final class CoreFilterExposer extends BroadcastReceiver implements Astrid
List<FilterListItem> filters = new ArrayList<FilterListItem>(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()]);
@ -140,8 +142,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);

@ -110,16 +110,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) {
@ -154,8 +156,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);
@ -178,10 +181,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);
}
}
/**
@ -367,8 +371,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);
}
}
@ -376,8 +381,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) {
@ -393,8 +399,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();
@ -418,9 +425,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(") ");
}
@ -463,8 +470,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:
@ -480,9 +488,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(") ");
@ -512,7 +520,9 @@ public class CustomFilterActivity extends SherlockFragmentActivity {
private <V> V getNth(int index, Map<?,V> 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");

@ -52,10 +52,12 @@ public class CustomFilterAdapter extends ArrayAdapter<CriterionInstance> {
@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
@ -70,14 +72,16 @@ public class CustomFilterAdapter extends ArrayAdapter<CriterionInstance> {
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<CriterionInstance> {
@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<CriterionInstance> {
@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<CriterionInstance> {
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);

@ -79,9 +79,10 @@ public final class CustomFilterExposer extends BroadcastReceiver implements Astr
boolean useCustomFilters = Preferences.getBoolean(R.string.p_use_filters, true);
StoreObjectDao dao = PluginServices.getStoreObjectDao();
TodorooCursor<StoreObject> cursor = null;
if (useCustomFilters)
if (useCustomFilters) {
cursor = dao.query(Query.select(StoreObject.PROPERTIES).where(
StoreObject.TYPE.eq(SavedFilter.TYPE)).orderBy(Order.asc(SavedFilter.NAME)));
StoreObject.TYPE.eq(SavedFilter.TYPE)).orderBy(Order.asc(SavedFilter.NAME)));
}
try {
ArrayList<Filter> list = new ArrayList<Filter>();
@ -99,8 +100,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();
@ -121,8 +123,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();
}
}
}
@ -183,8 +186,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());
}

@ -64,27 +64,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);
}
}
}

@ -38,15 +38,18 @@ import com.todoroo.astrid.notes.NotesAction;
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();
@ -56,8 +59,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();
@ -95,8 +99,9 @@ public class LinkActionExposer {
}
// no intents -> no item
else
else {
return null;
}
Resources r = context.getResources();
Drawable icon;
@ -108,8 +113,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);
@ -119,9 +125,9 @@ public class LinkActionExposer {
private static final HashMap<Integer, BitmapDrawable> IMAGE_CACHE = new HashMap<Integer, BitmapDrawable>();
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;

@ -246,8 +246,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();
@ -287,8 +288,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();

@ -130,8 +130,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;
@ -248,8 +249,9 @@ public final class PluginServices {
if(cursor.getCount() > 0) {
cursor.moveToNext();
return new Metadata(cursor);
} else
} else {
return null;
}
} finally {
cursor.close();
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save