Add braces to control flow statements

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

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

@ -126,8 +126,9 @@ abstract public class AbstractDatabase {
*/ */
public final Table getTable(Class<? extends AbstractModel> modelType) { public final Table getTable(Class<? extends AbstractModel> modelType) {
for(Table table : getTables()) { for(Table table : getTables()) {
if(table.modelClass.equals(modelType)) if(table.modelClass.equals(modelType)) {
return table; return table;
}
} }
throw new UnsupportedOperationException("Unknown model class " + modelType); //$NON-NLS-1$ throw new UnsupportedOperationException("Unknown model class " + modelType); //$NON-NLS-1$
} }
@ -150,8 +151,9 @@ abstract public class AbstractDatabase {
protected synchronized final void initializeHelper() { protected synchronized final void initializeHelper() {
if(helper == null) { if(helper == null) {
if(ContextManager.getContext() == null) if(ContextManager.getContext() == null) {
throw new NullPointerException("Null context creating database helper"); throw new NullPointerException("Null context creating database helper");
}
helper = new DatabaseHelper(ContextManager.getContext(), helper = new DatabaseHelper(ContextManager.getContext(),
getName(), null, getVersion()); getName(), null, getVersion());
} }
@ -164,8 +166,9 @@ abstract public class AbstractDatabase {
public synchronized final void openForWriting() { public synchronized final void openForWriting() {
initializeHelper(); initializeHelper();
if(database != null && !database.isReadOnly() && database.isOpen()) if(database != null && !database.isReadOnly() && database.isOpen()) {
return; return;
}
try { try {
database = helper.getWritableDatabase(); database = helper.getWritableDatabase();
@ -192,8 +195,9 @@ abstract public class AbstractDatabase {
*/ */
public synchronized final void openForReading() { public synchronized final void openForReading() {
initializeHelper(); initializeHelper();
if(database != null && database.isOpen()) if(database != null && database.isOpen()) {
return; return;
}
database = helper.getReadableDatabase(); database = helper.getReadableDatabase();
} }
@ -304,8 +308,9 @@ abstract public class AbstractDatabase {
sql.append("CREATE TABLE IF NOT EXISTS ").append(table.name).append('('). sql.append("CREATE TABLE IF NOT EXISTS ").append(table.name).append('(').
append(AbstractModel.ID_PROPERTY).append(" INTEGER PRIMARY KEY AUTOINCREMENT"); append(AbstractModel.ID_PROPERTY).append(" INTEGER PRIMARY KEY AUTOINCREMENT");
for(Property<?> property : table.getProperties()) { for(Property<?> property : table.getProperties()) {
if(AbstractModel.ID_PROPERTY.name.equals(property.name)) if(AbstractModel.ID_PROPERTY.name.equals(property.name)) {
continue; continue;
}
sql.append(',').append(property.accept(sqlVisitor, null)); sql.append(',').append(property.accept(sqlVisitor, null));
} }
sql.append(')'); sql.append(')');

@ -92,12 +92,15 @@ public abstract class AbstractModel implements Parcelable, Cloneable {
ContentValues mergedValues = new ContentValues(); ContentValues mergedValues = new ContentValues();
ContentValues defaultValues = getDefaultValues(); ContentValues defaultValues = getDefaultValues();
if(defaultValues != null) if(defaultValues != null) {
mergedValues.putAll(defaultValues); mergedValues.putAll(defaultValues);
if(values != null) }
if(values != null) {
mergedValues.putAll(values); mergedValues.putAll(values);
if(setValues != null) }
if(setValues != null) {
mergedValues.putAll(setValues); mergedValues.putAll(setValues);
}
return mergedValues; 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. * saved - future saves will not need to write all the data as before.
*/ */
public void markSaved() { public void markSaved() {
if(values == null) if(values == null) {
values = setValues; values = setValues;
else if(setValues != null) } else if(setValues != null) {
values.putAll(setValues); values.putAll(setValues);
}
setValues = null; setValues = null;
} }
@ -128,8 +132,9 @@ public abstract class AbstractModel implements Parcelable, Cloneable {
*/ */
@Override @Override
public boolean equals(Object other) { public boolean equals(Object other) {
if(other == null || other.getClass() != getClass()) if(other == null || other.getClass() != getClass()) {
return false; return false;
}
return getMergedValues().equals(((AbstractModel)other).getMergedValues()); return getMergedValues().equals(((AbstractModel)other).getMergedValues());
} }
@ -159,10 +164,12 @@ public abstract class AbstractModel implements Parcelable, Cloneable {
} catch (CloneNotSupportedException e) { } catch (CloneNotSupportedException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
if(setValues != null) if(setValues != null) {
clone.setValues = new ContentValues(setValues); clone.setValues = new ContentValues(setValues);
if(values != null) }
if(values != null) {
clone.values = new ContentValues(values); clone.values = new ContentValues(values);
}
return clone; return clone;
} }
@ -177,8 +184,9 @@ public abstract class AbstractModel implements Parcelable, Cloneable {
* Reads all properties from the supplied cursor and store * Reads all properties from the supplied cursor and store
*/ */
public synchronized void readPropertiesFromCursor(TodorooCursor<? extends AbstractModel> cursor) { public synchronized void readPropertiesFromCursor(TodorooCursor<? extends AbstractModel> cursor) {
if (values == null) if (values == null) {
values = new ContentValues(); values = new ContentValues();
}
// clears user-set values // clears user-set values
setValues = null; setValues = null;
@ -198,29 +206,28 @@ public abstract class AbstractModel implements Parcelable, Cloneable {
*/ */
public synchronized <TYPE> TYPE getValue(Property<TYPE> property) { public synchronized <TYPE> TYPE getValue(Property<TYPE> property) {
Object value; Object value;
if(setValues != null && setValues.containsKey(property.getColumnName())) if(setValues != null && setValues.containsKey(property.getColumnName())) {
value = setValues.get(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()); value = values.get(property.getColumnName());
} else if(getDefaultValues().containsKey(property.getColumnName())) {
else if(getDefaultValues().containsKey(property.getColumnName()))
value = getDefaultValues().get(property.getColumnName()); value = getDefaultValues().get(property.getColumnName());
} else {
else
throw new UnsupportedOperationException( 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 // resolve properties that were retrieved with a different type than accessed
try { try {
if(value instanceof String && property instanceof LongProperty) if(value instanceof String && property instanceof LongProperty) {
return (TYPE) Long.valueOf((String)value); return (TYPE) Long.valueOf((String) value);
else if(value instanceof String && property instanceof IntegerProperty) } else if(value instanceof String && property instanceof IntegerProperty) {
return (TYPE) Integer.valueOf((String)value); return (TYPE) Integer.valueOf((String) value);
else if(value instanceof String && property instanceof DoubleProperty) } else if(value instanceof String && property instanceof DoubleProperty) {
return (TYPE) Double.valueOf((String)value); return (TYPE) Double.valueOf((String) value);
else if(value instanceof Integer && property instanceof LongProperty) } else if(value instanceof Integer && property instanceof LongProperty) {
return (TYPE) Long.valueOf(((Number)value).longValue()); return (TYPE) Long.valueOf(((Number) value).longValue());
}
return (TYPE) value; return (TYPE) value;
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
return (TYPE) getDefaultValues().get(property.name); return (TYPE) getDefaultValues().get(property.name);
@ -235,22 +242,25 @@ public abstract class AbstractModel implements Parcelable, Cloneable {
abstract public long getId(); abstract public long getId();
protected long getIdHelper(LongProperty id) { protected long getIdHelper(LongProperty id) {
if(setValues != null && setValues.containsKey(id.name)) if(setValues != null && setValues.containsKey(id.name)) {
return setValues.getAsLong(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); return values.getAsLong(id.name);
else } else {
return NO_ID; return NO_ID;
}
} }
public void setId(long id) { public void setId(long id) {
if (setValues == null) if (setValues == null) {
setValues = new ContentValues(); setValues = new ContentValues();
}
if(id == NO_ID) if(id == NO_ID) {
clearValue(ID_PROPERTY); clearValue(ID_PROPERTY);
else } else {
setValues.put(ID_PROPERTY_NAME, id); 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 * @return true if setValues or values contains this property
*/ */
public boolean containsValue(Property<?> property) { public boolean containsValue(Property<?> property) {
if(setValues != null && setValues.containsKey(property.getColumnName())) if(setValues != null && setValues.containsKey(property.getColumnName())) {
return true; return true;
if(values != null && values.containsKey(property.getColumnName())) }
if(values != null && values.containsKey(property.getColumnName())) {
return true; return true;
}
return false; return false;
} }
@ -278,10 +290,12 @@ public abstract class AbstractModel implements Parcelable, Cloneable {
* stored is not null * stored is not null
*/ */
public boolean containsNonNullValue(Property<?> property) { 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; 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 values.get(property.getColumnName()) != null;
}
return false; return false;
} }
@ -295,17 +309,20 @@ public abstract class AbstractModel implements Parcelable, Cloneable {
Property<TYPE> property, TYPE newValue) { Property<TYPE> property, TYPE newValue) {
// we've already decided to save it, so overwrite old value // we've already decided to save it, so overwrite old value
if (setValues.containsKey(property.getColumnName())) if (setValues.containsKey(property.getColumnName())) {
return true; return true;
}
// values contains this key, we should check it out // values contains this key, we should check it out
if(values != null && values.containsKey(property.getColumnName())) { if(values != null && values.containsKey(property.getColumnName())) {
TYPE value = getValue(property); TYPE value = getValue(property);
if (value == null) { if (value == null) {
if (newValue == null) if (newValue == null) {
return false; return false;
} else if (value.equals(newValue)) }
} else if (value.equals(newValue)) {
return false; return false;
}
} }
// otherwise, good to save // otherwise, good to save
@ -317,10 +334,12 @@ public abstract class AbstractModel implements Parcelable, Cloneable {
*/ */
public synchronized <TYPE> void setValue(Property<TYPE> property, public synchronized <TYPE> void setValue(Property<TYPE> property,
TYPE value) { TYPE value) {
if (setValues == null) if (setValues == null) {
setValues = new ContentValues(); setValues = new ContentValues();
if (!shouldSaveValue(property, value)) }
if (!shouldSaveValue(property, value)) {
return; return;
}
saver.save(property, setValues, value); 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 * Merges content values with those coming from another source
*/ */
public synchronized <TYPE> void mergeWith(ContentValues other) { public synchronized <TYPE> void mergeWith(ContentValues other) {
if (setValues == null) if (setValues == null) {
setValues = new ContentValues(); setValues = new ContentValues();
}
setValues.putAll(other); setValues.putAll(other);
} }
@ -339,11 +359,13 @@ public abstract class AbstractModel implements Parcelable, Cloneable {
* keeping the existing value if one already exists * keeping the existing value if one already exists
*/ */
public synchronized <TYPE> void mergeWithoutReplacement(ContentValues other) { public synchronized <TYPE> void mergeWithoutReplacement(ContentValues other) {
if (setValues == null) if (setValues == null) {
setValues = new ContentValues(); setValues = new ContentValues();
}
for (Entry<String, Object> item : other.valueSet()) { for (Entry<String, Object> item : other.valueSet()) {
if (setValues.containsKey(item.getKey())) if (setValues.containsKey(item.getKey())) {
continue; continue;
}
AndroidUtilities.putInto(setValues, item.getKey(), item.getValue(), true); AndroidUtilities.putInto(setValues, item.getKey(), item.getValue(), true);
} }
} }
@ -353,10 +375,12 @@ public abstract class AbstractModel implements Parcelable, Cloneable {
* @param property * @param property
*/ */
public synchronized void clearValue(Property<?> 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()); setValues.remove(property.getColumnName());
if(values != null && values.containsKey(property.getColumnName())) }
if(values != null && values.containsKey(property.getColumnName())) {
values.remove(property.getColumnName()); values.remove(property.getColumnName());
}
} }
/** /**
@ -366,10 +390,11 @@ public abstract class AbstractModel implements Parcelable, Cloneable {
* @param value * @param value
*/ */
public void setFlag(IntegerProperty property, int flag, boolean value) { public void setFlag(IntegerProperty property, int flag, boolean value) {
if(value) if(value) {
setValue(property, getValue(property) | flag); setValue(property, getValue(property) | flag);
else } else {
setValue(property, getValue(property) & ~flag); setValue(property, getValue(property) & ~flag);
}
} }
/** /**
@ -386,26 +411,30 @@ public abstract class AbstractModel implements Parcelable, Cloneable {
// --- setting and retrieving flags // --- setting and retrieving flags
public synchronized void putTransitory(String key, Object value) { public synchronized void putTransitory(String key, Object value) {
if(transitoryData == null) if(transitoryData == null) {
transitoryData = new HashMap<String, Object>(); transitoryData = new HashMap<String, Object>();
}
transitoryData.put(key, value); transitoryData.put(key, value);
} }
public Object getTransitory(String key) { public Object getTransitory(String key) {
if(transitoryData == null) if(transitoryData == null) {
return null; return null;
}
return transitoryData.get(key); return transitoryData.get(key);
} }
public Object clearTransitory(String key) { public Object clearTransitory(String key) {
if (transitoryData == null) if (transitoryData == null) {
return null; return null;
}
return transitoryData.remove(key); return transitoryData.remove(key);
} }
public Set<String> getAllTransitoryKeys() { public Set<String> getAllTransitoryKeys() {
if (transitoryData == null) if (transitoryData == null) {
return null; return null;
}
return transitoryData.keySet(); return transitoryData.keySet();
} }
@ -427,19 +456,23 @@ public abstract class AbstractModel implements Parcelable, Cloneable {
*/ */
protected static Property<?>[] generateProperties(Class<? extends AbstractModel> cls) { protected static Property<?>[] generateProperties(Class<? extends AbstractModel> cls) {
ArrayList<Property<?>> properties = new ArrayList<Property<?>>(); ArrayList<Property<?>> properties = new ArrayList<Property<?>>();
if(cls.getSuperclass() != AbstractModel.class) if(cls.getSuperclass() != AbstractModel.class) {
properties.addAll(Arrays.asList(generateProperties( properties.addAll(Arrays.asList(generateProperties(
(Class<? extends AbstractModel>) cls.getSuperclass()))); (Class<? extends AbstractModel>) cls.getSuperclass())));
}
// a property is public, static & extends Property // a property is public, static & extends Property
for(Field field : cls.getFields()) { for(Field field : cls.getFields()) {
if((field.getModifiers() & Modifier.STATIC) == 0) if((field.getModifiers() & Modifier.STATIC) == 0) {
continue; continue;
if(!Property.class.isAssignableFrom(field.getType())) }
if(!Property.class.isAssignableFrom(field.getType())) {
continue; continue;
}
try { try {
if(((Property<?>) field.get(null)).table == null) if(((Property<?>) field.get(null)).table == null) {
continue; continue;
}
properties.add((Property<?>) field.get(null)); properties.add((Property<?>) field.get(null));
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
throw new RuntimeException(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 // we don't allow null values, as they indicate unset properties
// when the database was written // when the database was written
if(value != null) if(value != null) {
property.accept(this, value); property.accept(this, value);
}
} }
public Void visitDouble(Property<Double> property, Object 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) { public ContentResolverDao(Class<TYPE> modelClass, Context context, Uri baseUri) {
DependencyInjectionService.getInstance().inject(this); DependencyInjectionService.getInstance().inject(this);
this.modelClass = modelClass; this.modelClass = modelClass;
if(debug == null) if(debug == null) {
debug = false; debug = false;
}
this.baseUri = baseUri; this.baseUri = baseUri;
cr = context.getContentResolver(); cr = context.getContentResolver();
@ -87,8 +88,9 @@ public class ContentResolverDao<TYPE extends AbstractModel> {
* @return * @return
*/ */
public TodorooCursor<TYPE> query(Query query) { public TodorooCursor<TYPE> query(Query query) {
if(debug) if(debug) {
Log.i("SQL-" + modelClass.getSimpleName(), query.toString()); //$NON-NLS-1$ Log.i("SQL-" + modelClass.getSimpleName(), query.toString()); //$NON-NLS-1$
}
Cursor cursor = query.queryContentResolver(cr, baseUri); Cursor cursor = query.queryContentResolver(cr, baseUri);
return new TodorooCursor<TYPE>(cursor, query.getFields()); return new TodorooCursor<TYPE>(cursor, query.getFields());
} }
@ -101,10 +103,12 @@ public class ContentResolverDao<TYPE extends AbstractModel> {
public boolean save(TYPE model) { public boolean save(TYPE model) {
writeTransitoriesToModelContentValues(model); writeTransitoriesToModelContentValues(model);
if(model.isSaved()) { if(model.isSaved()) {
if(model.getSetValues() == null) if(model.getSetValues() == null) {
return false; 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; return true;
}
} }
Uri uri = cr.insert(baseUri, model.getMergedValues()); Uri uri = cr.insert(baseUri, model.getMergedValues());
long id = Long.parseLong(uri.getLastPathSegment()); long id = Long.parseLong(uri.getLastPathSegment());
@ -142,8 +146,9 @@ public class ContentResolverDao<TYPE extends AbstractModel> {
TodorooCursor<TYPE> cursor = query( TodorooCursor<TYPE> cursor = query(
Query.select(properties).where(AbstractModel.ID_PROPERTY.eq(id))); Query.select(properties).where(AbstractModel.ID_PROPERTY.eq(id)));
try { try {
if (cursor.getCount() == 0) if (cursor.getCount() == 0) {
return null; return null;
}
cursor.moveToFirst(); cursor.moveToFirst();
Constructor<TYPE> constructor = modelClass.getConstructor(TodorooCursor.class); Constructor<TYPE> constructor = modelClass.getConstructor(TodorooCursor.class);
return constructor.newInstance(cursor); return constructor.newInstance(cursor);

@ -54,8 +54,9 @@ public class DatabaseDao<TYPE extends AbstractModel> {
public DatabaseDao(Class<TYPE> modelClass) { public DatabaseDao(Class<TYPE> modelClass) {
DependencyInjectionService.getInstance().inject(this); DependencyInjectionService.getInstance().inject(this);
this.modelClass = modelClass; this.modelClass = modelClass;
if(debug == null) if(debug == null) {
debug = false; debug = false;
}
} }
public DatabaseDao(Class<TYPE> modelClass, AbstractDatabase database) { public DatabaseDao(Class<TYPE> modelClass, AbstractDatabase database) {
@ -79,8 +80,9 @@ public class DatabaseDao<TYPE extends AbstractModel> {
* @param database * @param database
*/ */
public void setDatabase(AbstractDatabase database) { public void setDatabase(AbstractDatabase database) {
if(database == this.database) if(database == this.database) {
return; return;
}
this.database = database; this.database = database;
table = database.getTable(modelClass); table = database.getTable(modelClass);
outstandingTable = database.getOutstandingTable(modelClass); outstandingTable = database.getOutstandingTable(modelClass);
@ -116,8 +118,9 @@ public class DatabaseDao<TYPE extends AbstractModel> {
*/ */
public TodorooCursor<TYPE> query(Query query) { public TodorooCursor<TYPE> query(Query query) {
query.from(table); query.from(table);
if(debug) if(debug) {
Log.i("SQL-" + modelClass.getSimpleName(), query.toString()); //$NON-NLS-1$ Log.i("SQL-" + modelClass.getSimpleName(), query.toString()); //$NON-NLS-1$
}
Cursor cursor = database.rawQuery(query.toString(), null); Cursor cursor = database.rawQuery(query.toString(), null);
return new TodorooCursor<TYPE>(cursor, query.getFields()); 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) { public TodorooCursor<TYPE> rawQuery(String selection, String[] selectionArgs, Property<?>... properties) {
String[] fields = new String[properties.length]; 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; fields[i] = properties[i].name;
}
return new TodorooCursor<TYPE>(database.getDatabase().query(table.name, return new TodorooCursor<TYPE>(database.getDatabase().query(table.name,
fields, selection, selectionArgs, null, null, null), fields, selection, selectionArgs, null, null, null),
properties); properties);
@ -158,8 +162,9 @@ public class DatabaseDao<TYPE extends AbstractModel> {
protected TYPE returnFetchResult(TodorooCursor<TYPE> cursor) { protected TYPE returnFetchResult(TodorooCursor<TYPE> cursor) {
try { try {
if (cursor.getCount() == 0) if (cursor.getCount() == 0) {
return null; return null;
}
Constructor<TYPE> constructor = modelClass.getConstructor(TodorooCursor.class); Constructor<TYPE> constructor = modelClass.getConstructor(TodorooCursor.class);
return constructor.newInstance(cursor); return constructor.newInstance(cursor);
} catch (SecurityException e) { } catch (SecurityException e) {
@ -231,8 +236,9 @@ public class DatabaseDao<TYPE extends AbstractModel> {
toUpdate.close(); toUpdate.close();
} }
if (toUpdate.getCount() == 0) if (toUpdate.getCount() == 0) {
return 0; return 0;
}
synchronized (database) { synchronized (database) {
database.getDatabase().beginTransactionWithListener(new SQLiteTransactionListener() { database.getDatabase().beginTransactionWithListener(new SQLiteTransactionListener() {
@ -280,7 +286,9 @@ public class DatabaseDao<TYPE extends AbstractModel> {
ContentValues values = item.getSetValues(); ContentValues values = item.getSetValues();
if (values.size() == 0) // nothing changed if (values.size() == 0) // nothing changed
{
return true; return true;
}
return saveExisting(item); return saveExisting(item);
} }
@ -318,11 +326,15 @@ public class DatabaseDao<TYPE extends AbstractModel> {
result.set(op.makeChange()); result.set(op.makeChange());
if(result.get()) { if(result.get()) {
if (recordOutstanding && ((numOutstanding = createOutstandingEntries(item.getId(), values)) != -1)) // Create entries for setValues in outstanding table if (recordOutstanding && ((numOutstanding = createOutstandingEntries(item.getId(), values)) != -1)) // Create entries for setValues in outstanding table
{
database.getDatabase().setTransactionSuccessful(); database.getDatabase().setTransactionSuccessful();
}
} }
} finally { } finally {
if (recordOutstanding) // commit transaction if (recordOutstanding) // commit transaction
{
database.getDatabase().endTransaction(); database.getDatabase().endTransaction();
}
} }
if (result.get()) { if (result.get()) {
onModelUpdated(item, recordOutstanding && numOutstanding > 0); onModelUpdated(item, recordOutstanding && numOutstanding > 0);
@ -351,8 +363,9 @@ public class DatabaseDao<TYPE extends AbstractModel> {
long newRow = database.insert(table.name, long newRow = database.insert(table.name,
AbstractModel.ID_PROPERTY.name, item.getMergedValues()); AbstractModel.ID_PROPERTY.name, item.getMergedValues());
boolean result = newRow >= 0; boolean result = newRow >= 0;
if (result) if (result) {
item.setId(newRow); item.setId(newRow);
}
return result; return result;
} }
}; };
@ -372,7 +385,9 @@ public class DatabaseDao<TYPE extends AbstractModel> {
public boolean saveExisting(final TYPE item) { public boolean saveExisting(final TYPE item) {
final ContentValues values = item.getSetValues(); final ContentValues values = item.getSetValues();
if(values == null || values.size() == 0) // nothing changed if(values == null || values.size() == 0) // nothing changed
{
return true; return true;
}
DatabaseChangeOp update = new DatabaseChangeOp() { DatabaseChangeOp update = new DatabaseChangeOp() {
@Override @Override
public boolean makeChange() { public boolean makeChange() {

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

@ -66,21 +66,24 @@ public final class Table extends SqlTable {
*/ */
@SuppressWarnings("nls") @SuppressWarnings("nls")
public Field field(Property<?> property) { public Field field(Property<?> property) {
if(alias != null) if(alias != null) {
return Field.field(alias + "." + property.name); return Field.field(alias + "." + property.name);
}
return Field.field(name + "." + property.name); return Field.field(name + "." + property.name);
} }
@Override @Override
public String toString() { public String toString() {
if(hasAlias()) if(hasAlias()) {
return expression + " AS " + alias; //$NON-NLS-1$ return expression + " AS " + alias; //$NON-NLS-1$
}
return expression; return expression;
} }
public String name() { public String name() {
if(hasAlias()) if(hasAlias()) {
return alias; return alias;
}
return name; return name;
} }
} }

@ -101,31 +101,35 @@ public class TodorooCursor<TYPE extends AbstractModel> extends CursorWrapper {
public Object visitDouble(Property<Double> property, public Object visitDouble(Property<Double> property,
TodorooCursor<?> cursor) { TodorooCursor<?> cursor) {
int column = columnIndex(property, 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 null;
}
return cursor.getDouble(column); return cursor.getDouble(column);
} }
public Object visitInteger(Property<Integer> property, public Object visitInteger(Property<Integer> property,
TodorooCursor<?> cursor) { TodorooCursor<?> cursor) {
int column = columnIndex(property, 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 null;
}
return cursor.getInt(column); return cursor.getInt(column);
} }
public Object visitLong(Property<Long> property, TodorooCursor<?> cursor) { public Object visitLong(Property<Long> property, TodorooCursor<?> cursor) {
int column = columnIndex(property, 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 null;
}
return cursor.getLong(column); return cursor.getLong(column);
} }
public Object visitString(Property<String> property, public Object visitString(Property<String> property,
TodorooCursor<?> cursor) { TodorooCursor<?> cursor) {
int column = columnIndex(property, 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 null;
}
return cursor.getString(column); return cursor.getString(column);
} }

@ -28,10 +28,12 @@ public final class ContextManager {
* @param context * @param context
*/ */
public static void setContext(Context context) { public static void setContext(Context context) {
if(context == null || context.getApplicationContext() == null) if(context == null || context.getApplicationContext() == null) {
return; return;
if(ContextManager.context != null && !(context instanceof Activity)) }
if(ContextManager.context != null && !(context instanceof Activity)) {
return; return;
}
ContextManager.context = context; ContextManager.context = context;
} }

@ -47,8 +47,9 @@ public class DependencyInjectionService {
Class<?> cls = caller.getClass(); Class<?> cls = caller.getClass();
while(cls != null) { while(cls != null) {
String packageName = cls.getPackage().getName(); String packageName = cls.getPackage().getName();
if(!isQualifiedPackage(packageName)) if(!isQualifiedPackage(packageName)) {
break; break;
}
for(Field field : cls.getDeclaredFields()) { for(Field field : cls.getDeclaredFields()) {
if(field.getAnnotation(Autowired.class) != null) { if(field.getAnnotation(Autowired.class) != null) {
@ -74,12 +75,15 @@ public class DependencyInjectionService {
@SuppressWarnings("nls") @SuppressWarnings("nls")
private boolean isQualifiedPackage(String packageName) { private boolean isQualifiedPackage(String packageName) {
if(packageName.startsWith("com.todoroo")) if(packageName.startsWith("com.todoroo")) {
return true; return true;
if(packageName.startsWith("com.timsu")) }
if(packageName.startsWith("com.timsu")) {
return true; return true;
if(packageName.startsWith("org.weloveastrid")) }
if(packageName.startsWith("org.weloveastrid")) {
return true; return true;
}
return false; return false;
} }
@ -97,10 +101,11 @@ public class DependencyInjectionService {
throws IllegalStateException, IllegalArgumentException, throws IllegalStateException, IllegalArgumentException,
IllegalAccessException { IllegalAccessException {
if(field.getType().isPrimitive()) if(field.getType().isPrimitive()) {
throw new IllegalStateException(String.format( throw new IllegalStateException(String.format(
"Tried to dependency-inject primative field '%s' of type '%s'", "Tried to dependency-inject primative field '%s' of type '%s'",
field.getName(), field.getType())); field.getName(), field.getType()));
}
// field has already been processed, ignore // field has already been processed, ignore
if (field.get(caller) != null) { if (field.get(caller) != null) {
@ -150,8 +155,9 @@ public class DependencyInjectionService {
* @return * @return
*/ */
public synchronized static DependencyInjectionService getInstance() { public synchronized static DependencyInjectionService getInstance() {
if(instance == null) if(instance == null) {
instance = new DependencyInjectionService(); instance = new DependencyInjectionService();
}
return instance; return instance;
} }

@ -43,8 +43,9 @@ public class ExceptionService {
* @param error Exception encountered. Message will be displayed to user * @param error Exception encountered. Message will be displayed to user
*/ */
public void reportError(String name, Throwable error) { public void reportError(String name, Throwable error) {
if(errorReporters == null) if(errorReporters == null) {
return; return;
}
for(ErrorReporter reporter : errorReporters) { for(ErrorReporter reporter : errorReporters) {
try { try {
@ -67,10 +68,11 @@ public class ExceptionService {
final String messageToDisplay; final String messageToDisplay;
// pretty up the message when displaying to user // pretty up the message when displaying to user
if(error == null) if(error == null) {
messageToDisplay = context.getString(R.string.DLG_error_generic); messageToDisplay = context.getString(R.string.DLG_error_generic);
else } else {
messageToDisplay = context.getString(R.string.DLG_error, error); messageToDisplay = context.getString(R.string.DLG_error, error);
}
((Activity)context).runOnUiThread(new Runnable() { ((Activity)context).runOnUiThread(new Runnable() {
public void run() { public void run() {
@ -128,13 +130,15 @@ public class ExceptionService {
} }
} }
if(tag == null) if(tag == null) {
tag = "unknown-" + name; //$NON-NLS-1$ tag = "unknown-" + name; //$NON-NLS-1$
}
if(error == null) if(error == null) {
Log.e(tag, "Exception: " + name); //$NON-NLS-1$ Log.e(tag, "Exception: " + name); //$NON-NLS-1$
else } else {
Log.e(tag, error.toString(), error); Log.e(tag, error.toString(), error);
}
} }
} }
@ -157,8 +161,9 @@ public class ExceptionService {
} }
public void uncaughtException(Thread thread, Throwable ex) { public void uncaughtException(Thread thread, Throwable ex) {
if(exceptionService != null) if(exceptionService != null) {
exceptionService.reportError("uncaught", ex); //$NON-NLS-1$ exceptionService.reportError("uncaught", ex); //$NON-NLS-1$
}
defaultUEH.uncaughtException(thread, ex); defaultUEH.uncaughtException(thread, ex);
} }
} }

@ -107,8 +107,9 @@ public class HttpRestClient implements RestClient {
public void process( public void process(
final HttpRequest request, final HttpRequest request,
final HttpContext context) throws HttpException, IOException { final HttpContext context) throws HttpException, IOException {
if (!request.containsHeader("Accept-Encoding")) if (!request.containsHeader("Accept-Encoding")) {
request.addHeader("Accept-Encoding", "gzip"); request.addHeader("Accept-Encoding", "gzip");
}
} }
}); });
@ -192,8 +193,9 @@ public class HttpRestClient implements RestClient {
* @throws IOException * @throws IOException
*/ */
public synchronized String get(String url) throws IOException { public synchronized String get(String url) throws IOException {
if(debug) if(debug) {
Log.d("http-rest-client-get", url); //$NON-NLS-1$ Log.d("http-rest-client-get", url); //$NON-NLS-1$
}
try { try {
HttpGet httpGet = new HttpGet(url); HttpGet httpGet = new HttpGet(url);
@ -218,14 +220,16 @@ public class HttpRestClient implements RestClient {
* @throws IOException * @throws IOException
*/ */
public synchronized String post(String url, HttpEntity data, Header... headers) 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$ Log.d("http-rest-client-post", url + " | " + data); //$NON-NLS-1$ //$NON-NLS-2$
}
try { try {
HttpPost httpPost = new HttpPost(url); HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(data); httpPost.setEntity(data);
for(Header header : headers) for(Header header : headers) {
httpPost.addHeader(header); httpPost.addHeader(header);
}
HttpResponse response = getClient().execute(httpPost); HttpResponse response = getClient().execute(httpPost);
return processHttpResponse(response); return processHttpResponse(response);

@ -32,13 +32,21 @@ public abstract class DBObject<T extends DBObject<?>> implements Cloneable {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) {
if (o == null || getClass() != o.getClass()) return false; return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DBObject<?> dbObject = (DBObject<?>) o; DBObject<?> dbObject = (DBObject<?>) o;
if (alias != null ? !alias.equals(dbObject.alias) : dbObject.alias != null) return false; if (alias != null ? !alias.equals(dbObject.alias) : dbObject.alias != null) {
if (expression != null ? !expression.equals(dbObject.expression) : dbObject.expression != null) return false; return false;
}
if (expression != null ? !expression.equals(dbObject.expression) : dbObject.expression != null) {
return false;
}
return true; return true;
} }
@ -64,8 +72,9 @@ public abstract class DBObject<T extends DBObject<?>> implements Cloneable {
sb.append(SPACE).append(AS).append(SPACE).append(alias); sb.append(SPACE).append(AS).append(SPACE).append(alias);
} else { } else {
int pos = expression.indexOf('.'); int pos = expression.indexOf('.');
if(pos > 0) if(pos > 0) {
sb.append(SPACE).append(AS).append(SPACE).append(expression.substring(pos + 1)); sb.append(SPACE).append(AS).append(SPACE).append(expression.substring(pos + 1));
}
} }
return sb.toString(); return sb.toString();
} }

@ -23,8 +23,9 @@ public class Field extends DBObject<Field> {
} }
public Criterion eq(Object value) { public Criterion eq(Object value) {
if(value == null) if(value == null) {
return UnaryCriterion.isNull(this); return UnaryCriterion.isNull(this);
}
return UnaryCriterion.eq(this, value); return UnaryCriterion.eq(this, value);
} }
@ -38,15 +39,17 @@ public class Field extends DBObject<Field> {
*/ */
@SuppressWarnings("nls") @SuppressWarnings("nls")
public Criterion eqCaseInsensitive(String value) { public Criterion eqCaseInsensitive(String value) {
if(value == null) if(value == null) {
return UnaryCriterion.isNull(this); return UnaryCriterion.isNull(this);
}
String escaped = value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_"); String escaped = value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_");
return UnaryCriterion.like(this, escaped, "\\"); return UnaryCriterion.like(this, escaped, "\\");
} }
public Criterion neq(Object value) { public Criterion neq(Object value) {
if(value == null) if(value == null) {
return UnaryCriterion.isNotNull(this); return UnaryCriterion.isNotNull(this);
}
return UnaryCriterion.neq(this, value); 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("("); 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++) { for (int i = 0; i < criterions.length; i++) {
sb.append(criterions[i]); sb.append(criterions[i]);
if (i < criterions.length - 1) if (i < criterions.length - 1) {
sb.append(SPACE).append(AND).append(SPACE); sb.append(SPACE).append(AND).append(SPACE);
}
} }
sb.append(")"); sb.append(")");
return sb.toString(); return sb.toString();

@ -56,9 +56,10 @@ public class Order {
} }
public Order reverse() { public Order reverse() {
if(orderType == OrderType.ASC) if(orderType == OrderType.ASC) {
return new Order(expression, OrderType.DESC); return new Order(expression, OrderType.DESC);
else } else {
return new Order(expression, OrderType.ASC); return new Order(expression, OrderType.ASC);
}
} }
} }

@ -125,8 +125,9 @@ public final class Query {
visitLimitClause(sql); visitLimitClause(sql);
} else { } else {
if(groupBies.size() > 0 || orders.size() > 0 || 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$ throw new IllegalStateException("Can't have extras AND query template"); //$NON-NLS-1$
}
sql.append(queryTemplate); sql.append(queryTemplate);
} }
@ -198,8 +199,9 @@ public final class Query {
private void visitSelectClause(StringBuilder sql) { private void visitSelectClause(StringBuilder sql) {
sql.append(SELECT).append(SPACE); sql.append(SELECT).append(SPACE);
if(distinct) if(distinct) {
sql.append(DISTINCT).append(SPACE); sql.append(DISTINCT).append(SPACE);
}
if (fields.isEmpty()) { if (fields.isEmpty()) {
sql.append(ALL).append(SPACE); sql.append(ALL).append(SPACE);
return; return;
@ -211,8 +213,9 @@ public final class Query {
} }
private void visitLimitClause(StringBuilder sql) { private void visitLimitClause(StringBuilder sql) {
if(limits > -1) if(limits > -1) {
sql.append(LIMIT).append(SPACE).append(limits).append(SPACE); sql.append(LIMIT).append(SPACE).append(limits).append(SPACE);
}
} }
public SqlTable as(String alias) { public SqlTable as(String alias) {
@ -251,12 +254,14 @@ public final class Query {
public Cursor queryContentResolver(ContentResolver cr, Uri baseUri) { public Cursor queryContentResolver(ContentResolver cr, Uri baseUri) {
Uri 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$ throw new UnsupportedOperationException("can't perform join in content resolver query"); //$NON-NLS-1$
}
String[] projection = new String[fields.size()]; 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(); projection[i] = fields.get(i).toString();
}
StringBuilder groupByClause = new StringBuilder(); StringBuilder groupByClause = new StringBuilder();
StringBuilder selectionClause = new StringBuilder(); StringBuilder selectionClause = new StringBuilder();
@ -266,24 +271,30 @@ public final class Query {
selectionClause, orderClause, groupByClause); selectionClause, orderClause, groupByClause);
} else { } else {
if(groupBies.size() > 0) { if(groupBies.size() > 0) {
for (Field groupBy : groupBies) for (Field groupBy : groupBies) {
groupByClause.append(SPACE).append(groupBy).append(COMMA); groupByClause.append(SPACE).append(groupBy).append(COMMA);
if(groupByClause.length() > 0) }
if(groupByClause.length() > 0) {
groupByClause.deleteCharAt(groupByClause.length() - 1); groupByClause.deleteCharAt(groupByClause.length() - 1);
}
} }
for (Criterion criterion : criterions) for (Criterion criterion : criterions) {
selectionClause.append(criterion).append(SPACE); selectionClause.append(criterion).append(SPACE);
}
for (Order order : orders) for (Order order : orders) {
orderClause.append(SPACE).append(order).append(COMMA); orderClause.append(SPACE).append(order).append(COMMA);
if(orderClause.length() > 0) }
if(orderClause.length() > 0) {
orderClause.deleteCharAt(orderClause.length() - 1); orderClause.deleteCharAt(orderClause.length() - 1);
}
} }
if(groupByClause.length() > 0) if(groupByClause.length() > 0) {
uri = Uri.withAppendedPath(baseUri, AstridApiConstants.GROUP_BY_URI + uri = Uri.withAppendedPath(baseUri, AstridApiConstants.GROUP_BY_URI +
groupByClause.toString().trim()); groupByClause.toString().trim());
}
return cr.query(uri, projection, selectionClause.toString(), null, return cr.query(uri, projection, selectionClause.toString(), null,
orderClause.toString()); orderClause.toString());
} }
@ -299,18 +310,21 @@ public final class Query {
Pattern where = Pattern.compile("WHERE (.*?)(LIMIT|HAVING|GROUP|ORDER|\\Z)"); Pattern where = Pattern.compile("WHERE (.*?)(LIMIT|HAVING|GROUP|ORDER|\\Z)");
Matcher whereMatcher = where.matcher(queryTemplate); Matcher whereMatcher = where.matcher(queryTemplate);
if(whereMatcher.find()) if(whereMatcher.find()) {
selectionClause.append(whereMatcher.group(1).trim()); selectionClause.append(whereMatcher.group(1).trim());
}
Pattern group = Pattern.compile("GROUP BY (.*?)(LIMIT|HAVING|ORDER|\\Z)"); Pattern group = Pattern.compile("GROUP BY (.*?)(LIMIT|HAVING|ORDER|\\Z)");
Matcher groupMatcher = group.matcher(queryTemplate); Matcher groupMatcher = group.matcher(queryTemplate);
if(groupMatcher.find()) if(groupMatcher.find()) {
groupByClause.append(groupMatcher.group(1).trim()); groupByClause.append(groupMatcher.group(1).trim());
}
Pattern order = Pattern.compile("ORDER BY (.*?)(LIMIT|HAVING|\\Z)"); Pattern order = Pattern.compile("ORDER BY (.*?)(LIMIT|HAVING|\\Z)");
Matcher orderMatcher = order.matcher(queryTemplate); Matcher orderMatcher = order.matcher(queryTemplate);
if(orderMatcher.find()) if(orderMatcher.find()) {
orderClause.append(orderMatcher.group(1).trim()); orderClause.append(orderMatcher.group(1).trim());
}
} }
} }

@ -58,8 +58,9 @@ public final class QueryTemplate {
visitWhereClause(sql); visitWhereClause(sql);
visitGroupByClause(sql); visitGroupByClause(sql);
visitOrderByClause(sql); visitOrderByClause(sql);
if(limit != null) if(limit != null) {
sql.append(LIMIT).append(SPACE).append(limit); sql.append(LIMIT).append(SPACE).append(limit);
}
return sql.toString(); return sql.toString();
} }

@ -38,12 +38,13 @@ public class UnaryCriterion extends Criterion {
@SuppressWarnings("nls") @SuppressWarnings("nls")
protected void afterPopulateOperator(StringBuilder sb) { protected void afterPopulateOperator(StringBuilder sb) {
if(value == null) if(value == null) {
return; return;
else if(value instanceof String) } else if(value instanceof String) {
sb.append("'").append(sanitize((String) value)).append("'"); sb.append("'").append(sanitize((String) value)).append("'");
else } else {
sb.append(value); sb.append(value);
}
} }
/** /**

@ -93,10 +93,12 @@ public class AndroidUtilities {
ConnectivityManager manager = (ConnectivityManager) ConnectivityManager manager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE); context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo(); NetworkInfo info = manager.getActiveNetworkInfo();
if (info == null) if (info == null) {
return false; return false;
if (info.getState() != State.CONNECTED) }
if (info.getState() != State.CONNECTED) {
return false; return false;
}
return true; return true;
} }
@ -115,8 +117,9 @@ public class AndroidUtilities {
bis.close(); bis.close();
} }
} finally { } finally {
if(is != null) if(is != null) {
is.close(); is.close();
}
} }
} }
@ -151,10 +154,11 @@ public class AndroidUtilities {
*/ */
public static void startExternalIntent(Context context, Intent intent, int request) { public static void startExternalIntent(Context context, Intent intent, int request) {
try { try {
if(request > -1 && context instanceof Activity) if(request > -1 && context instanceof Activity) {
((Activity)context).startActivityForResult(intent, request); ((Activity) context).startActivityForResult(intent, request);
else } else {
context.startActivity(intent); context.startActivity(intent);
}
} catch (Exception e) { } catch (Exception e) {
getExceptionService().displayAndReportError(context, getExceptionService().displayAndReportError(context,
"start-external-intent-" + intent.toString(), //$NON-NLS-1$ "start-external-intent-" + intent.toString(), //$NON-NLS-1$
@ -187,25 +191,26 @@ public class AndroidUtilities {
* @param value * @param value
*/ */
public static void putInto(ContentValues target, String key, Object value, boolean errorOnFail) { 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); target.put(key, (Boolean) value);
else if (value instanceof Byte) } else if (value instanceof Byte) {
target.put(key, (Byte) value); target.put(key, (Byte) value);
else if (value instanceof Double) } else if (value instanceof Double) {
target.put(key, (Double) value); target.put(key, (Double) value);
else if (value instanceof Float) } else if (value instanceof Float) {
target.put(key, (Float) value); target.put(key, (Float) value);
else if (value instanceof Integer) } else if (value instanceof Integer) {
target.put(key, (Integer) value); target.put(key, (Integer) value);
else if (value instanceof Long) } else if (value instanceof Long) {
target.put(key, (Long) value); target.put(key, (Long) value);
else if (value instanceof Short) } else if (value instanceof Short) {
target.put(key, (Short) value); target.put(key, (Short) value);
else if (value instanceof String) } else if (value instanceof String) {
target.put(key, (String) value); target.put(key, (String) value);
else if (errorOnFail) } else if (errorOnFail) {
throw new UnsupportedOperationException("Could not handle type " + //$NON-NLS-1$ throw new UnsupportedOperationException("Could not handle type " + //$NON-NLS-1$
value.getClass()); value.getClass());
}
} }
/** /**
@ -215,25 +220,26 @@ public class AndroidUtilities {
* @param value * @param value
*/ */
public static void putInto(Bundle target, String key, Object value, boolean errorOnFail) { 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); target.putBoolean(key, (Boolean) value);
else if (value instanceof Byte) } else if (value instanceof Byte) {
target.putByte(key, (Byte) value); target.putByte(key, (Byte) value);
else if (value instanceof Double) } else if (value instanceof Double) {
target.putDouble(key, (Double) value); target.putDouble(key, (Double) value);
else if (value instanceof Float) } else if (value instanceof Float) {
target.putFloat(key, (Float) value); target.putFloat(key, (Float) value);
else if (value instanceof Integer) } else if (value instanceof Integer) {
target.putInt(key, (Integer) value); target.putInt(key, (Integer) value);
else if (value instanceof Long) } else if (value instanceof Long) {
target.putLong(key, (Long) value); target.putLong(key, (Long) value);
else if (value instanceof Short) } else if (value instanceof Short) {
target.putShort(key, (Short) value); target.putShort(key, (Short) value);
else if (value instanceof String) } else if (value instanceof String) {
target.putString(key, (String) value); target.putString(key, (String) value);
else if (errorOnFail) } else if (errorOnFail) {
throw new UnsupportedOperationException("Could not handle type " + //$NON-NLS-1$ throw new UnsupportedOperationException("Could not handle type " + //$NON-NLS-1$
value.getClass()); value.getClass());
}
} }
// --- serialization // --- serialization
@ -258,9 +264,11 @@ public class AndroidUtilities {
* @return * @return
*/ */
public static <TYPE> int indexOf(TYPE[] array, TYPE value) { public static <TYPE> int indexOf(TYPE[] array, TYPE value) {
for(int i = 0; i < array.length; i++) for(int i = 0; i < array.length; i++) {
if(array[i].equals(value)) if (array[i].equals(value)) {
return i; return i;
}
}
return -1; return -1;
} }
@ -271,9 +279,11 @@ public class AndroidUtilities {
* @return * @return
*/ */
public static int indexOf(int[] array, int value) { public static int indexOf(int[] array, int value) {
for (int i = 0; i < array.length; i++) for (int i = 0; i < array.length; i++) {
if (array[i] == value) if (array[i] == value) {
return i; return i;
}
}
return -1; return -1;
} }
@ -293,18 +303,19 @@ public class AndroidUtilities {
String key, Object value) { String key, Object value) {
result.append(key.replace(SERIALIZATION_SEPARATOR, SEPARATOR_ESCAPE)).append( result.append(key.replace(SERIALIZATION_SEPARATOR, SEPARATOR_ESCAPE)).append(
SERIALIZATION_SEPARATOR); SERIALIZATION_SEPARATOR);
if(value instanceof Integer) if(value instanceof Integer) {
result.append('i').append(value); result.append('i').append(value);
else if(value instanceof Double) } else if(value instanceof Double) {
result.append('d').append(value); result.append('d').append(value);
else if(value instanceof Long) } else if(value instanceof Long) {
result.append('l').append(value); 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)); 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); result.append('b').append(value);
else } else {
throw new UnsupportedOperationException(value.getClass().toString()); throw new UnsupportedOperationException(value.getClass().toString());
}
result.append(SERIALIZATION_SEPARATOR); result.append(SERIALIZATION_SEPARATOR);
} }
@ -313,8 +324,9 @@ public class AndroidUtilities {
*/ */
public static String bundleToSerializedString(Bundle source) { public static String bundleToSerializedString(Bundle source) {
StringBuilder result = new StringBuilder(); StringBuilder result = new StringBuilder();
if (source == null) if (source == null) {
return null; return null;
}
for(String key : source.keySet()) { for(String key : source.keySet()) {
addSerialized(result, key, source.get(key)); addSerialized(result, key, source.get(key));
@ -328,8 +340,9 @@ public class AndroidUtilities {
* @return * @return
*/ */
public static ContentValues contentValuesFromSerializedString(String string) { public static ContentValues contentValuesFromSerializedString(String string) {
if(string == null) if(string == null) {
return new ContentValues(); return new ContentValues();
}
ContentValues result = new ContentValues(); ContentValues result = new ContentValues();
fromSerialized(string, result, new SerializedPut<ContentValues>() { fromSerialized(string, result, new SerializedPut<ContentValues>() {
@ -362,8 +375,9 @@ public class AndroidUtilities {
* @return * @return
*/ */
public static Bundle bundleFromSerializedString(String string) { public static Bundle bundleFromSerializedString(String string) {
if(string == null) if(string == null) {
return new Bundle(); return new Bundle();
}
Bundle result = new Bundle(); Bundle result = new Bundle();
fromSerialized(string, result, new SerializedPut<Bundle>() { fromSerialized(string, result, new SerializedPut<Bundle>() {
@ -423,8 +437,9 @@ public class AndroidUtilities {
*/ */
@SuppressWarnings("nls") @SuppressWarnings("nls")
public static ContentValues contentValuesFromString(String string) { public static ContentValues contentValuesFromString(String string) {
if(string == null) if(string == null) {
return null; return null;
}
String[] pairs = string.split("="); String[] pairs = string.split("=");
ContentValues result = new ContentValues(); ContentValues result = new ContentValues();
@ -438,8 +453,9 @@ public class AndroidUtilities {
} else { } else {
newKey = pairs[i]; newKey = pairs[i];
} }
if(key != null) if(key != null) {
result.put(key.trim(), pairs[i].trim()); result.put(key.trim(), pairs[i].trim());
}
key = newKey; key = newKey;
} }
return result; return result;
@ -452,10 +468,12 @@ public class AndroidUtilities {
* @return * @return
*/ */
public static boolean equals(Object a, Object b) { public static boolean equals(Object a, Object b) {
if(a == null && b == null) if(a == null && b == null) {
return true; return true;
if(a == null) }
if(a == null) {
return false; return false;
}
return a.equals(b); return a.equals(b);
} }
@ -493,8 +511,9 @@ public class AndroidUtilities {
while ((bytes = source.read(buffer)) != -1) { while ((bytes = source.read(buffer)) != -1) {
if (bytes == 0) { if (bytes == 0) {
bytes = source.read(); bytes = source.read();
if (bytes < 0) if (bytes < 0) {
break; break;
}
dest.write(bytes); dest.write(bytes);
dest.flush(); dest.flush();
continue; continue;
@ -512,16 +531,19 @@ public class AndroidUtilities {
* @return first view (by DFS) if found, or null if none * @return first view (by DFS) if found, or null if none
*/ */
public static <TYPE> TYPE findViewByType(View view, Class<TYPE> type) { public static <TYPE> TYPE findViewByType(View view, Class<TYPE> type) {
if(view == null) if(view == null) {
return null; return null;
if(type.isInstance(view)) }
if(type.isInstance(view)) {
return (TYPE) view; return (TYPE) view;
}
if(view instanceof ViewGroup) { if(view instanceof ViewGroup) {
ViewGroup group = (ViewGroup) view; ViewGroup group = (ViewGroup) view;
for(int i = 0; i < group.getChildCount(); i++) { for(int i = 0; i < group.getChildCount(); i++) {
TYPE v = findViewByType(group.getChildAt(i), type); TYPE v = findViewByType(group.getChildAt(i), type);
if(v != null) if(v != null) {
return v; return v;
}
} }
} }
return null; return null;
@ -540,8 +562,9 @@ public class AndroidUtilities {
*/ */
public static void copyDatabases(Context context, String folder) { public static void copyDatabases(Context context, String folder) {
File folderFile = new File(folder); File folderFile = new File(folder);
if(!folderFile.exists()) if(!folderFile.exists()) {
folderFile.mkdir(); folderFile.mkdir();
}
for(String db : context.databaseList()) { for(String db : context.databaseList()) {
File dbFile = context.getDatabasePath(db); File dbFile = context.getDatabasePath(db);
try { try {
@ -573,8 +596,9 @@ public class AndroidUtilities {
*/ */
public static <KEY, VALUE> KEY findKeyInMap(Map<KEY, VALUE> map, VALUE value){ public static <KEY, VALUE> KEY findKeyInMap(Map<KEY, VALUE> map, VALUE value){
for (Entry<KEY, VALUE> entry: map.entrySet()) { for (Entry<KEY, VALUE> entry: map.entrySet()) {
if(entry.getValue().equals(value)) if(entry.getValue().equals(value)) {
return entry.getKey(); return entry.getKey();
}
} }
return null; return null;
} }
@ -620,8 +644,9 @@ public class AndroidUtilities {
*/ */
public static Object callApiMethod(int minSdk, Object receiver, public static Object callApiMethod(int minSdk, Object receiver,
String methodName, Class<?>[] params, Object... args) { String methodName, Class<?>[] params, Object... args) {
if(getSdkVersion() < minSdk) if(getSdkVersion() < minSdk) {
return null; return null;
}
return AndroidUtilities.callMethod(receiver.getClass(), return AndroidUtilities.callMethod(receiver.getClass(),
receiver, methodName, params, args); receiver, methodName, params, args);
@ -639,8 +664,9 @@ public class AndroidUtilities {
@SuppressWarnings("nls") @SuppressWarnings("nls")
public static Object callApiStaticMethod(int minSdk, String className, public static Object callApiStaticMethod(int minSdk, String className,
String methodName, Class<?>[] params, Object... args) { String methodName, Class<?>[] params, Object... args) {
if(getSdkVersion() < minSdk) if(getSdkVersion() < minSdk) {
return null; return null;
}
try { try {
return AndroidUtilities.callMethod(Class.forName(className), return AndroidUtilities.callMethod(Class.forName(className),
@ -799,17 +825,20 @@ public class AndroidUtilities {
originalListLength = list.length; originalListLength = list.length;
length += list.length; length += list.length;
} }
if (newItems != null) if (newItems != null) {
length += newItems.length; length += newItems.length;
}
T[] newList = (T[]) Array.newInstance(type, length); T[] newList = (T[]) Array.newInstance(type, length);
if (list != null) { if (list != null) {
for(int i = 0; i < list.length; i++) for(int i = 0; i < list.length; i++) {
newList[i] = list[i]; newList[i] = list[i];
}
} }
if (newItems != null) { if (newItems != null) {
for(int i = 0; i < newItems.length; i++) for(int i = 0; i < newItems.length; i++) {
newList[originalListLength + i] = newItems[i]; newList[originalListLength + i] = newItems[i];
}
} }
return newList; return newList;
} }
@ -819,11 +848,13 @@ public class AndroidUtilities {
private static ExceptionService exceptionService = null; private static ExceptionService exceptionService = null;
private static ExceptionService getExceptionService() { private static ExceptionService getExceptionService() {
if(exceptionService == null) if(exceptionService == null) {
synchronized(AndroidUtilities.class) { synchronized (AndroidUtilities.class) {
if(exceptionService == null) if (exceptionService == null) {
exceptionService = new ExceptionService(); exceptionService = new ExceptionService();
}
} }
}
return exceptionService; return exceptionService;
} }
@ -835,11 +866,13 @@ public class AndroidUtilities {
*/ */
public static <TYPE> TYPE[] concat(TYPE[] dest, TYPE[] source, TYPE... additional) { public static <TYPE> TYPE[] concat(TYPE[] dest, TYPE[] source, TYPE... additional) {
int i = 0; 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]; dest[i] = source[i];
}
int base = i; int base = i;
for(; i < dest.length; i++) for(; i < dest.length; i++) {
dest[i] = additional[i - base]; dest[i] = additional[i - base];
}
return dest; return dest;
} }
@ -888,7 +921,9 @@ public class AndroidUtilities {
*/ */
public static boolean isTabletSized(Context context) { public static boolean isTabletSized(Context context) {
if (context.getPackageManager().hasSystemFeature("com.google.android.tv")) //$NON-NLS-1$ if (context.getPackageManager().hasSystemFeature("com.google.android.tv")) //$NON-NLS-1$
{
return true; return true;
}
int size = context.getResources().getConfiguration().screenLayout int size = context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK; & Configuration.SCREENLAYOUT_SIZE_MASK;
@ -932,8 +967,9 @@ public class AndroidUtilities {
* @param popup * @param popup
*/ */
public static void tryDismissPopup(Activity activity, final PopupWindow popup) { public static void tryDismissPopup(Activity activity, final PopupWindow popup) {
if (popup == null) if (popup == null) {
return; return;
}
try { try {
popup.dismiss(); popup.dismiss();
} catch (Exception e) { } catch (Exception e) {
@ -974,8 +1010,9 @@ public class AndroidUtilities {
String extension = ""; String extension = "";
if (index > 0) { if (index > 0) {
extension = file.substring(index + 1); extension = file.substring(index + 1);
if (!extension.matches("\\w+")) if (!extension.matches("\\w+")) {
extension = ""; extension = "";
}
} }
return extension; return extension;
} }

@ -27,15 +27,17 @@ public class DateUtilities {
/** Convert unixtime into date */ /** Convert unixtime into date */
public static final Date unixtimeToDate(long millis) { public static final Date unixtimeToDate(long millis) {
if(millis == 0) if(millis == 0) {
return null; return null;
}
return new Date(millis); return new Date(millis);
} }
/** Convert date into unixtime */ /** Convert date into unixtime */
public static final long dateToUnixtime(Date date) { public static final long dateToUnixtime(Date date) {
if(date == null) if(date == null) {
return 0; return 0;
}
return date.getTime(); return date.getTime();
} }
@ -85,8 +87,9 @@ public class DateUtilities {
static Boolean is24HourOverride = null; static Boolean is24HourOverride = null;
public static boolean is24HourFormat(Context context) { public static boolean is24HourFormat(Context context) {
if(is24HourOverride != null) if(is24HourOverride != null) {
return is24HourOverride; return is24HourOverride;
}
return DateFormat.is24HourFormat(context); return DateFormat.is24HourFormat(context);
} }
@ -134,12 +137,14 @@ public class DateUtilities {
// united states, you are special // united states, you are special
Locale locale = Locale.getDefault(); Locale locale = Locale.getDefault();
if (arrayBinaryContains(locale.getLanguage(), "ja", "ko", "zh") 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'$'"; value = "'#' d'$'";
else } else {
value = "d'$' '#'"; value = "d'$' '#'";
if (includeYear) }
if (includeYear) {
value += ", yyyy"; value += ", yyyy";
}
if (arrayBinaryContains(locale.getLanguage(), "ja", "zh")){ if (arrayBinaryContains(locale.getLanguage(), "ja", "zh")){
standardDate = new SimpleDateFormat(value).format(date).replace("#", month).replace("$", "\u65E5"); //$NON-NLS-1$ standardDate = new SimpleDateFormat(value).format(date).replace("#", month).replace("$", "\u65E5"); //$NON-NLS-1$
}else if ("ko".equals(Locale.getDefault().getLanguage())){ }else if ("ko".equals(Locale.getDefault().getLanguage())){
@ -166,20 +171,24 @@ public class DateUtilities {
Locale locale = Locale.getDefault(); Locale locale = Locale.getDefault();
// united states, you are special // united states, you are special
if (arrayBinaryContains(locale.getLanguage(), "ja", "ko", "zh") 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"; value = "'#' d";
else } else {
value = "d '#'"; value = "d '#'";
}
if (date.getYear() != (new Date()).getYear()) { if (date.getYear() != (new Date()).getYear()) {
value = value + "\nyyyy"; value = value + "\nyyyy";
} }
if (arrayBinaryContains(locale.getLanguage(), "ja", "zh")) //$NON-NLS-1$ if (arrayBinaryContains(locale.getLanguage(), "ja", "zh")) //$NON-NLS-1$
{
return new SimpleDateFormat(value).format(date).replace("#", month) + "\u65E5"; //$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$ return new SimpleDateFormat(value).format(date).replace("#", month) + "\uC77C"; //$NON-NLS-1$
else } else {
return new SimpleDateFormat(value).format(date).replace("#", month); return new SimpleDateFormat(value).format(date).replace("#", month);
}
} }
/** /**
@ -231,33 +240,40 @@ public class DateUtilities {
long today = clearTime(new Date()); long today = clearTime(new Date());
long input = clearTime(new Date(date)); long input = clearTime(new Date(date));
if(today == input) if(today == input) {
return context.getString(R.string.today).toLowerCase(); 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(); 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(); return context.getString(abbreviated ? R.string.yest : R.string.yesterday).toLowerCase();
}
if(today + DateUtilities.ONE_WEEK >= input && if(today + DateUtilities.ONE_WEEK >= input &&
today - DateUtilities.ONE_WEEK <= input) today - DateUtilities.ONE_WEEK <= input) {
return abbreviated ? DateUtilities.getWeekdayShort(new Date(date)) : DateUtilities.getWeekday(new Date(date)); return abbreviated ? DateUtilities.getWeekdayShort(new Date(date)) : DateUtilities.getWeekday(new Date(date));
}
return DateUtilities.getDateStringHideYear(context, new Date(date)); return DateUtilities.getDateStringHideYear(context, new Date(date));
} }
public static boolean isEndOfMonth(Date d) { public static boolean isEndOfMonth(Date d) {
int date = d.getDate(); int date = d.getDate();
if (date < 28) if (date < 28) {
return false; return false;
}
int month = d.getMonth(); int month = d.getMonth();
if (month == Calendar.FEBRUARY) if (month == Calendar.FEBRUARY) {
return date >= 28; 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 >= 30;
}
return date >= 31; return date >= 31;
} }
@ -292,8 +308,9 @@ public class DateUtilities {
} }
public static long parseIso8601(String iso8601String) throws ParseException { public static long parseIso8601(String iso8601String) throws ParseException {
if (iso8601String == null) if (iso8601String == null) {
return 0; return 0;
}
String formatString; String formatString;
if (isoStringHasTime(iso8601String)) { // Time exists if (isoStringHasTime(iso8601String)) { // Time exists
iso8601String = iso8601String.replace("Z", "+00:00"); //$NON-NLS-1$ //$NON-NLS-2$ 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) { public static String timeToIso8601(long time, boolean includeTime) {
if (time == 0) if (time == 0) {
return null; return null;
}
Date date = new Date(time); Date date = new Date(time);
String formatString = "yyyy-MM-dd'T'HH:mm:ssZ"; //$NON-NLS-1$ String formatString = "yyyy-MM-dd'T'HH:mm:ssZ"; //$NON-NLS-1$
if (!includeTime) if (!includeTime) {
formatString = "yyyy-MM-dd"; //$NON-NLS-1$ formatString = "yyyy-MM-dd"; //$NON-NLS-1$
}
return new SimpleDateFormat(formatString).format(date); return new SimpleDateFormat(formatString).format(date);
} }

@ -29,8 +29,9 @@ public class DialogUtilities {
public static void viewDialog(final Activity activity, final String text, public static void viewDialog(final Activity activity, final String text,
final View view, final DialogInterface.OnClickListener okListener, final View view, final DialogInterface.OnClickListener okListener,
final DialogInterface.OnClickListener cancelListener) { final DialogInterface.OnClickListener cancelListener) {
if(activity.isFinishing()) if(activity.isFinishing()) {
return; return;
}
tryOnUiThread(activity, new Runnable() { tryOnUiThread(activity, new Runnable() {
public void run() { public void run() {
@ -76,8 +77,9 @@ public class DialogUtilities {
*/ */
public static void okDialog(final Activity activity, final String text, public static void okDialog(final Activity activity, final String text,
final DialogInterface.OnClickListener okListener) { final DialogInterface.OnClickListener okListener) {
if(activity.isFinishing()) if(activity.isFinishing()) {
return; return;
}
tryOnUiThread(activity, new Runnable() { tryOnUiThread(activity, new Runnable() {
public void run() { public void run() {
@ -101,8 +103,9 @@ public class DialogUtilities {
public static void okDialog(final Activity activity, final String title, public static void okDialog(final Activity activity, final String title,
final int icon, final CharSequence text, final int icon, final CharSequence text,
final DialogInterface.OnClickListener okListener) { final DialogInterface.OnClickListener okListener) {
if(activity.isFinishing()) if(activity.isFinishing()) {
return; return;
}
tryOnUiThread(activity, new Runnable() { tryOnUiThread(activity, new Runnable() {
public void run() { public void run() {
@ -157,8 +160,9 @@ public class DialogUtilities {
final int icon, final int icon,
final DialogInterface.OnClickListener okListener, final DialogInterface.OnClickListener okListener,
final DialogInterface.OnClickListener cancelListener) { final DialogInterface.OnClickListener cancelListener) {
if(activity.isFinishing()) if(activity.isFinishing()) {
return; return;
}
tryOnUiThread(activity, new Runnable() { tryOnUiThread(activity, new Runnable() {
public void run() { public void run() {
@ -217,8 +221,9 @@ public class DialogUtilities {
* @param dialog * @param dialog
*/ */
public static void dismissDialog(Activity activity, final Dialog dialog) { public static void dismissDialog(Activity activity, final Dialog dialog) {
if(dialog == null) if(dialog == null) {
return; return;
}
tryOnUiThread(activity, new Runnable() { tryOnUiThread(activity, new Runnable() {
public void run() { public void run() {
try { try {

@ -37,8 +37,9 @@ public class Pair<L, R> {
@Override @Override
public final boolean equals(Object o) { public final boolean equals(Object o) {
if (!(o instanceof Pair<?, ?>)) if (!(o instanceof Pair<?, ?>)) {
return false; return false;
}
final Pair<?, ?> other = (Pair<?, ?>) o; final Pair<?, ?> other = (Pair<?, ?>) o;
return equal(getLeft(), other.getLeft()) && equal(getRight(), other.getRight()); 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) { public static void setIfUnset(SharedPreferences prefs, Editor editor, Resources r, int keyResource, int value) {
String key = r.getString(keyResource); String key = r.getString(keyResource);
if(!prefs.contains(key)) if(!prefs.contains(key)) {
editor.putString(key, Integer.toString(value)); 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) { public static void setIfUnset(SharedPreferences prefs, Editor editor, Resources r, int keyResource, boolean value) {
String key = r.getString(keyResource); 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); 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) { public static void setIfUnset(SharedPreferences prefs, Editor editor, Resources r, int keyResource, String value) {
String key = r.getString(keyResource); 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); editor.putString(key, value);
}
} }
/* ====================================================================== /* ======================================================================
@ -73,8 +76,9 @@ public class Preferences {
/** Get preferences object from the context */ /** Get preferences object from the context */
public static SharedPreferences getPrefs(Context context) { public static SharedPreferences getPrefs(Context context) {
if(preferences != null) if(preferences != null) {
return preferences; return preferences;
}
context = context.getApplicationContext(); context = context.getApplicationContext();
try { try {
@ -133,8 +137,9 @@ public class Preferences {
Context context = ContextManager.getContext(); Context context = ContextManager.getContext();
Resources r = context.getResources(); Resources r = context.getResources();
String value = getPrefs(context).getString(r.getString(keyResource), null); String value = getPrefs(context).getString(r.getString(keyResource), null);
if(value == null) if(value == null) {
return defaultValue; return defaultValue;
}
try { try {
return Integer.parseInt(value); return Integer.parseInt(value);

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

@ -112,8 +112,9 @@ public class Filter extends FilterListItem {
} }
public String getSqlQuery() { public String getSqlQuery() {
if (filterOverride != null) if (filterOverride != null) {
return filterOverride; return filterOverride;
}
return sqlQuery; return sqlQuery;
} }
@ -156,23 +157,30 @@ public class Filter extends FilterListItem {
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) if (this == obj) {
return true; return true;
if (obj == null) }
if (obj == null) {
return false; return false;
if (getClass() != obj.getClass()) }
if (getClass() != obj.getClass()) {
return false; return false;
}
Filter other = (Filter) obj; Filter other = (Filter) obj;
if (sqlQuery == null) { if (sqlQuery == null) {
if (other.sqlQuery != null) if (other.sqlQuery != null) {
return false; return false;
} else if (!sqlQuery.equals(other.sqlQuery)) }
} else if (!sqlQuery.equals(other.sqlQuery)) {
return false; return false;
}
if (title == null) { if (title == null) {
if (other.title != null) if (other.title != null) {
return false; return false;
} else if (!title.equals(other.title)) }
} else if (!title.equals(other.title)) {
return false; return false;
}
return true; return true;
} }

@ -78,10 +78,11 @@ public class FilterCategory extends FilterListItem {
FilterCategory.class.getClassLoader()); FilterCategory.class.getClassLoader());
item.children = new Filter[parcelableChildren.length]; item.children = new Filter[parcelableChildren.length];
for(int i = 0; i < item.children.length; i++) { 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]; item.children[i] = (Filter) parcelableChildren[i];
else } else {
item.children[i] = null; item.children[i] = null;
}
} }
return item; return item;

@ -86,10 +86,11 @@ public class FilterCategoryWithNewButton extends FilterCategory {
FilterCategoryWithNewButton.class.getClassLoader()); FilterCategoryWithNewButton.class.getClassLoader());
item.children = new Filter[parcelableChildren.length]; item.children = new Filter[parcelableChildren.length];
for(int i = 0; i < item.children.length; i++) { 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]; item.children[i] = (Filter) parcelableChildren[i];
else } else {
item.children[i] = null; item.children[i] = null;
}
} }
item.intent = source.readParcelable(PendingIntent.class.getClassLoader()); item.intent = source.readParcelable(PendingIntent.class.getClassLoader());

@ -46,8 +46,9 @@ public class FilterWithCustomIntent extends Filter {
Intent intent = new Intent(); Intent intent = new Intent();
intent.putExtra("filter", this); //$NON-NLS-1$ intent.putExtra("filter", this); //$NON-NLS-1$
intent.setComponent(new ComponentName(AstridApiConstants.ASTRID_PACKAGE, "com.todoroo.astrid.activity.TaskListActivity")); //$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); intent.putExtras(customExtras);
}
return intent; return intent;
} }

@ -62,8 +62,9 @@ public final class PermaSql {
/** Replace placeholder strings with actual */ /** Replace placeholder strings with actual */
public static String replacePlaceholders(String value) { 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())); value = value.replace(VALUE_NOW, Long.toString(DateUtilities.now()));
}
if(value.contains(VALUE_EOD) || value.contains(VALUE_EOD_DAY_AFTER) || if(value.contains(VALUE_EOD) || value.contains(VALUE_EOD_DAY_AFTER) ||
value.contains(VALUE_EOD_NEXT_WEEK) || value.contains(VALUE_EOD_TOMORROW) || value.contains(VALUE_EOD_NEXT_WEEK) || value.contains(VALUE_EOD_TOMORROW) ||
value.contains(VALUE_EOD_YESTERDAY) || value.contains(VALUE_EOD_NEXT_MONTH)) { value.contains(VALUE_EOD_YESTERDAY) || value.contains(VALUE_EOD_NEXT_MONTH)) {

@ -61,8 +61,9 @@ public class SyncAction implements Parcelable {
*/ */
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if(!(o instanceof SyncAction)) if(!(o instanceof SyncAction)) {
return false; return false;
}
SyncAction other = (SyncAction) o; SyncAction other = (SyncAction) o;
return label.equals(other.label) && intent.getTargetPackage().equals(other.intent.getTargetPackage()); return label.equals(other.label) && intent.getTargetPackage().equals(other.intent.getTargetPackage());
} }

@ -48,26 +48,31 @@ public class SortHelper {
@SuppressWarnings("nls") @SuppressWarnings("nls")
public static String adjustQueryForFlagsAndSort(String originalSql, int flags, int sort) { public static String adjustQueryForFlagsAndSort(String originalSql, int flags, int sort) {
// sort // sort
if(originalSql == null) if(originalSql == null) {
originalSql = ""; originalSql = "";
}
if(!originalSql.toUpperCase().contains("ORDER BY")) { if(!originalSql.toUpperCase().contains("ORDER BY")) {
Order order = orderForSortType(sort); Order order = orderForSortType(sort);
if((flags & FLAG_REVERSE_SORT) > 0) if((flags & FLAG_REVERSE_SORT) > 0) {
order = order.reverse(); order = order.reverse();
}
originalSql += " ORDER BY " + order; originalSql += " ORDER BY " + order;
} }
// flags // flags
if((flags & FLAG_SHOW_COMPLETED) > 0) if((flags & FLAG_SHOW_COMPLETED) > 0) {
originalSql = originalSql.replace(Task.COMPLETION_DATE.eq(0).toString(), originalSql = originalSql.replace(Task.COMPLETION_DATE.eq(0).toString(),
Criterion.all.toString()); Criterion.all.toString());
if((flags & FLAG_SHOW_HIDDEN) > 0) }
if((flags & FLAG_SHOW_HIDDEN) > 0) {
originalSql = originalSql.replace(TaskCriteria.isVisible().toString(), originalSql = originalSql.replace(TaskCriteria.isVisible().toString(),
Criterion.all.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(), originalSql = originalSql.replace(Task.DELETION_DATE.eq(0).toString(),
Criterion.all.toString()); Criterion.all.toString());
}
return originalSql; return originalSql;
} }
@ -78,8 +83,9 @@ public class SortHelper {
public static int setManualSort(int flags, boolean status) { public static int setManualSort(int flags, boolean status) {
flags = (flags & ~FLAG_DRAG_DROP); flags = (flags & ~FLAG_DRAG_DROP);
if(status) if(status) {
flags |= FLAG_DRAG_DROP; flags |= FLAG_DRAG_DROP;
}
return flags; return flags;
} }
@ -107,8 +113,9 @@ public class SortHelper {
default: default:
order = defaultTaskOrder(); order = defaultTaskOrder();
} }
if (sortType != SORT_ALPHA) if (sortType != SORT_ALPHA) {
order.addSecondaryExpression(Order.asc(Task.TITLE)); order.addSecondaryExpression(Order.asc(Task.TITLE));
}
return order; return order;
} }

@ -78,22 +78,25 @@ abstract public class RemoteModel extends AbstractModel {
abstract public String getUuid(); abstract public String getUuid();
protected String getUuidHelper(StringProperty uuid) { protected String getUuidHelper(StringProperty uuid) {
if(setValues != null && setValues.containsKey(uuid.name)) if(setValues != null && setValues.containsKey(uuid.name)) {
return setValues.getAsString(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); return values.getAsString(uuid.name);
else } else {
return NO_UUID; return NO_UUID;
}
} }
public void setUuid(String uuid) { public void setUuid(String uuid) {
if (setValues == null) if (setValues == null) {
setValues = new ContentValues(); setValues = new ContentValues();
}
if(NO_UUID.equals(uuid)) if(NO_UUID.equals(uuid)) {
clearValue(UUID_PROPERTY); clearValue(UUID_PROPERTY);
else } else {
setValues.put(UUID_PROPERTY_NAME, uuid); setValues.put(UUID_PROPERTY_NAME, uuid);
}
} }
public static boolean isUuidEmpty(String uuid) { public static boolean isUuidEmpty(String uuid) {
@ -145,8 +148,9 @@ abstract public class RemoteModel extends AbstractModel {
File dir = context.getExternalFilesDir(PICTURES_DIRECTORY); File dir = context.getExternalFilesDir(PICTURES_DIRECTORY);
if (dir != null) { if (dir != null) {
File file = new File(dir + File.separator + DateUtilities.now() + ".jpg"); File file = new File(dir + File.separator + DateUtilities.now() + ".jpg");
if (file.exists()) if (file.exists()) {
return null; return null;
}
try { try {
FileOutputStream fos = new FileOutputStream(file); FileOutputStream fos = new FileOutputStream(file);
@ -171,11 +175,14 @@ abstract public class RemoteModel extends AbstractModel {
public static String getPictureUrl(String value, String size) { public static String getPictureUrl(String value, String size) {
try { try {
if (value == null) if (value == null) {
return null; return null;
}
JSONObject pictureJson = new JSONObject(value); JSONObject pictureJson = new JSONObject(value);
if (pictureJson.has("path")) // Unpushed encoded bitmap //$NON-NLS-1$ if (pictureJson.has("path")) // Unpushed encoded bitmap //$NON-NLS-1$
{
return null; return null;
}
return pictureJson.optString(size); return pictureJson.optString(size);
} catch (JSONException e) { } catch (JSONException e) {
return value; return value;
@ -185,8 +192,9 @@ abstract public class RemoteModel extends AbstractModel {
@SuppressWarnings("nls") @SuppressWarnings("nls")
public static Bitmap getPictureBitmap(String value) { public static Bitmap getPictureBitmap(String value) {
try { try {
if (value == null) if (value == null) {
return null; return null;
}
if (value.contains("path")) { if (value.contains("path")) {
JSONObject pictureJson = new JSONObject(value); JSONObject pictureJson = new JSONObject(value);
if (pictureJson.has("path")) { 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 */ /** Checks whether task is deleted. Will return false if DELETION_DATE not read */
public boolean isDeleted() { public boolean isDeleted() {
// assume false if we didn't load deletion date // assume false if we didn't load deletion date
if(!containsValue(DELETION_DATE)) if(!containsValue(DELETION_DATE)) {
return false; return false;
else } else {
return getValue(DELETION_DATE) > 0; 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 final String USER_ID_SELF = "0";
public static boolean isRealUserId(String userId) { public static boolean isRealUserId(String userId) {
if (userId == null) if (userId == null) {
return false; return false;
}
return !(Task.USER_ID_SELF.equals(userId) || return !(Task.USER_ID_SELF.equals(userId) ||
Task.USER_ID_UNASSIGNED.equals(userId) || Task.USER_ID_UNASSIGNED.equals(userId) ||
Task.USER_ID_EMAIL.equals(userId) || Task.USER_ID_EMAIL.equals(userId) ||
@ -233,8 +234,9 @@ public final class Task extends RemoteModel {
} }
public static boolean userIdIsEmail(String userId) { public static boolean userIdIsEmail(String userId) {
if (userId == null) if (userId == null) {
return false; return false;
}
return userId.indexOf('@') >= 0; 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 */ /** Checks whether task is deleted. Will return false if DELETION_DATE not read */
public boolean isDeleted() { public boolean isDeleted() {
// assume false if we didn't load deletion date // assume false if we didn't load deletion date
if(!containsValue(DELETION_DATE)) if(!containsValue(DELETION_DATE)) {
return false; return false;
else } else {
return getValue(DELETION_DATE) > 0; return getValue(DELETION_DATE) > 0;
}
} }
/** Checks whether task is hidden. Requires HIDDEN_UNTIL */ /** Checks whether task is hidden. Requires HIDDEN_UNTIL */
@ -458,8 +461,9 @@ public final class Task extends RemoteModel {
throw new IllegalArgumentException("Unknown setting " + setting); throw new IllegalArgumentException("Unknown setting " + setting);
} }
if(date <= 0) if(date <= 0) {
return date; return date;
}
Date dueDate = new Date(date / 1000L * 1000L); // get rid of millis Date dueDate = new Date(date / 1000L * 1000L); // get rid of millis
if(setting != URGENCY_SPECIFIC_DAY_TIME) { if(setting != URGENCY_SPECIFIC_DAY_TIME) {
@ -505,8 +509,9 @@ public final class Task extends RemoteModel {
throw new IllegalArgumentException("Unknown setting " + setting); throw new IllegalArgumentException("Unknown setting " + setting);
} }
if(date <= 0) if(date <= 0) {
return date; return date;
}
Date hideUntil = new Date(date / 1000L * 1000L); // get rid of millis Date hideUntil = new Date(date / 1000L * 1000L); // get rid of millis
if(setting != HIDE_UNTIL_SPECIFIC_DAY_TIME && setting != HIDE_UNTIL_DUE_TIME) { if(setting != HIDE_UNTIL_SPECIFIC_DAY_TIME && setting != HIDE_UNTIL_DUE_TIME) {
@ -523,8 +528,9 @@ public final class Task extends RemoteModel {
* Checks whether this due date has a due time or only a date * Checks whether this due date has a due time or only a date
*/ */
public boolean hasDueTime() { public boolean hasDueTime() {
if(!hasDueDate()) if(!hasDueDate()) {
return false; return false;
}
return hasDueTime(getValue(Task.DUE_DATE)); 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 */ /** @return true if task change shouldn't be broadcast */
public static boolean insignificantChange(ContentValues values) { public static boolean insignificantChange(ContentValues values) {
if(values == null || values.size() == 0) if(values == null || values.size() == 0) {
return true; return true;
}
if(values.containsKey(Task.DETAILS_DATE.name) && if(values.containsKey(Task.DETAILS_DATE.name) &&
values.size() <= 3) values.size() <= 3) {
return true; return true;
}
if(values.containsKey(Task.REMINDER_LAST.name) && if(values.containsKey(Task.REMINDER_LAST.name) &&
values.size() <= 2) values.size() <= 2) {
return true; return true;
}
if(values.containsKey(Task.REMINDER_SNOOZE.name) && if(values.containsKey(Task.REMINDER_SNOOZE.name) &&
values.size() <= 2) values.size() <= 2) {
return true; return true;
}
if(values.containsKey(Task.TIMER_START.name) && if(values.containsKey(Task.TIMER_START.name) &&
values.size() <= 2) values.size() <= 2) {
return true; return true;
}
return false; return false;
} }

@ -149,19 +149,23 @@ public final class User extends RemoteModel {
public String getDisplayName(StringProperty nameProperty, StringProperty firstNameProperty, StringProperty lastNameProperty) { public String getDisplayName(StringProperty nameProperty, StringProperty firstNameProperty, StringProperty lastNameProperty) {
String name = getCheckedString(nameProperty); String name = getCheckedString(nameProperty);
if (!(TextUtils.isEmpty(name) || "null".equals(name))) if (!(TextUtils.isEmpty(name) || "null".equals(name))) {
return name; return name;
}
String firstName = getCheckedString(firstNameProperty); String firstName = getCheckedString(firstNameProperty);
boolean firstNameEmpty = TextUtils.isEmpty(firstName) || "null".equals(firstName); boolean firstNameEmpty = TextUtils.isEmpty(firstName) || "null".equals(firstName);
String lastName = getCheckedString(lastNameProperty); String lastName = getCheckedString(lastNameProperty);
boolean lastNameEmpty = TextUtils.isEmpty(lastName) || "null".equals(lastName); boolean lastNameEmpty = TextUtils.isEmpty(lastName) || "null".equals(lastName);
if (firstNameEmpty && lastNameEmpty) if (firstNameEmpty && lastNameEmpty) {
return getCheckedString(EMAIL); return getCheckedString(EMAIL);
}
StringBuilder nameBuilder = new StringBuilder(); StringBuilder nameBuilder = new StringBuilder();
if (!firstNameEmpty) if (!firstNameEmpty) {
nameBuilder.append(firstName).append(" "); nameBuilder.append(firstName).append(" ");
if (!lastNameEmpty) }
if (!lastNameEmpty) {
nameBuilder.append(lastName); nameBuilder.append(lastName);
}
return nameBuilder.toString().trim(); return nameBuilder.toString().trim();
} }

@ -68,13 +68,15 @@ abstract public class SyncBackgroundService extends Service {
/** Start the actual synchronization */ /** Start the actual synchronization */
private void startSynchronization(Context context) { private void startSynchronization(Context context) {
if(context == null || context.getResources() == null) if(context == null || context.getResources() == null) {
return; return;
}
ContextManager.setContext(context); ContextManager.setContext(context);
if(!getSyncUtilities().isLoggedIn()) if(!getSyncUtilities().isLoggedIn()) {
return; return;
}
getSyncProvider().synchronize(context); getSyncProvider().synchronize(context);
} }
@ -154,10 +156,11 @@ abstract public class SyncBackgroundService extends Service {
long lastSyncDate = getSyncUtilities().getLastSyncDate(); long lastSyncDate = getSyncUtilities().getLastSyncDate();
// if user never synchronized, give them a full offset period before bg sync // 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()); return Math.max(0, lastSyncDate + interval - DateUtilities.now());
else } else {
return interval; return interval;
}
} }

@ -30,8 +30,9 @@ public class SyncContainer {
*/ */
public Metadata findMetadata(String key) { public Metadata findMetadata(String key) {
for(Metadata item : metadata) { for(Metadata item : metadata) {
if(AndroidUtilities.equals(key, item.getValue(Metadata.KEY))) if(AndroidUtilities.equals(key, item.getValue(Metadata.KEY))) {
return item; return item;
}
} }
return null; return null;
} }

@ -170,8 +170,9 @@ public abstract class SyncProvider<TYPE extends SyncContainer> {
((Activity) context).runOnUiThread(new Runnable() { ((Activity) context).runOnUiThread(new Runnable() {
@Override @Override
public void run() { public void run() {
if(showSyncToast) if(showSyncToast) {
makeSyncToast(context); makeSyncToast(context);
}
} }
}); });
} }
@ -223,8 +224,9 @@ public abstract class SyncProvider<TYPE extends SyncContainer> {
length = data.remoteUpdated.size(); length = data.remoteUpdated.size();
for(int i = 0; i < length; i++) { for(int i = 0; i < length; i++) {
TYPE remote = data.remoteUpdated.get(i); TYPE remote = data.remoteUpdated.get(i);
if(remote.task.getId() != Task.NO_ID) if(remote.task.getId() != Task.NO_ID) {
continue; continue;
}
remoteNewTaskNameMap.put(remote.task.getValue(Task.TITLE), i); remoteNewTaskNameMap.put(remote.task.getValue(Task.TITLE), i);
} }
@ -241,10 +243,11 @@ public abstract class SyncProvider<TYPE extends SyncContainer> {
@SuppressWarnings("nls") @SuppressWarnings("nls")
protected String getFinalSyncStatus() { protected String getFinalSyncStatus() {
if (getUtilities().getLastError() != null || getUtilities().getLastAttemptedSyncDate() != 0) { if (getUtilities().getLastError() != null || getUtilities().getLastAttemptedSyncDate() != 0) {
if (getUtilities().getLastAttemptedSyncDate() == 0) if (getUtilities().getLastAttemptedSyncDate() == 0) {
return "errors"; return "errors";
else } else {
return "failed"; return "failed";
}
} else { } else {
return "success"; return "success";
} }
@ -262,21 +265,24 @@ public abstract class SyncProvider<TYPE extends SyncContainer> {
private final int check(TYPE o1, TYPE o2, LongProperty property) { private final int check(TYPE o1, TYPE o2, LongProperty property) {
long o1Property = o1.task.getValue(property); long o1Property = o1.task.getValue(property);
long o2Property = o2.task.getValue(property); long o2Property = o2.task.getValue(property);
if(o1Property != 0 && o2Property != 0) if(o1Property != 0 && o2Property != 0) {
return 0; return 0;
else if(o1Property != 0) } else if(o1Property != 0) {
return -1; return -1;
else if(o2Property != 0) } else if(o2Property != 0) {
return 1; return 1;
}
return SENTINEL; return SENTINEL;
} }
public int compare(TYPE o1, TYPE o2) { public int compare(TYPE o1, TYPE o2) {
int comparison = check(o1, o2, Task.DELETION_DATE); int comparison = check(o1, o2, Task.DELETION_DATE);
if(comparison != SENTINEL) if(comparison != SENTINEL) {
return comparison; return comparison;
}
comparison = check(o1, o2, Task.COMPLETION_DATE); comparison = check(o1, o2, Task.COMPLETION_DATE);
if(comparison != SENTINEL) if(comparison != SENTINEL) {
return comparison; return comparison;
}
return 0; return 0;
} }
}); });
@ -286,8 +292,9 @@ public abstract class SyncProvider<TYPE extends SyncContainer> {
TYPE remote = data.remoteUpdated.get(i); TYPE remote = data.remoteUpdated.get(i);
// don't synchronize new & deleted tasks // don't synchronize new & deleted tasks
if(!remote.task.isSaved() && (remote.task.isDeleted())) if(!remote.task.isSaved() && (remote.task.isDeleted())) {
continue; continue;
}
try { try {
write(remote); write(remote);
@ -304,8 +311,9 @@ public abstract class SyncProvider<TYPE extends SyncContainer> {
data.localUpdated.moveToNext(); data.localUpdated.moveToNext();
TYPE local = read(data.localUpdated); TYPE local = read(data.localUpdated);
try { try {
if(local.task == null) if(local.task == null) {
continue; continue;
}
// if there is a conflict, merge // if there is a conflict, merge
int remoteIndex = matchTask((ArrayList<TYPE>)data.remoteUpdated, local); int remoteIndex = matchTask((ArrayList<TYPE>)data.remoteUpdated, local);

@ -87,8 +87,9 @@ abstract public class SyncProviderPreferences extends TodorooPreferenceActivity
@Override @Override
public void onChildViewAdded(View parent, View child) { public void onChildViewAdded(View parent, View child) {
View view = findViewById(R.id.status); View view = findViewById(R.id.status);
if(view != null) if(view != null) {
view.setBackgroundColor(statusColor); view.setBackgroundColor(statusColor);
}
} }
}); });
} }
@ -108,12 +109,13 @@ abstract public class SyncProviderPreferences extends TodorooPreferenceActivity
int index = AndroidUtilities.indexOf( int index = AndroidUtilities.indexOf(
r.getStringArray(R.array.sync_SPr_interval_values), r.getStringArray(R.array.sync_SPr_interval_values),
(String) value); (String) value);
if (index <= 0) if (index <= 0) {
preference.setSummary(R.string.sync_SPr_interval_desc_disabled); preference.setSummary(R.string.sync_SPr_interval_desc_disabled);
else } else {
preference.setSummary(r.getString( preference.setSummary(r.getString(
R.string.sync_SPr_interval_desc, R.string.sync_SPr_interval_desc,
r.getStringArray(R.array.sync_SPr_interval_entries)[index])); r.getStringArray(R.array.sync_SPr_interval_entries)[index]));
}
} }
// status // status
@ -175,8 +177,9 @@ abstract public class SyncProviderPreferences extends TodorooPreferenceActivity
}); });
View view = findViewById(R.id.status); View view = findViewById(R.id.status);
if(view != null) if(view != null) {
view.setBackgroundColor(statusColor); view.setBackgroundColor(statusColor);
}
} }
else if (r.getString(R.string.sync_SPr_key_last_error).equals(preference.getKey())) { else if (r.getString(R.string.sync_SPr_key_last_error).equals(preference.getKey())) {
if (getUtilities().getLastError() != null) { if (getUtilities().getLastError() != null) {
@ -271,8 +274,9 @@ abstract public class SyncProviderPreferences extends TodorooPreferenceActivity
break; break;
} }
} }
if (resource == null) if (resource == null) {
return lastError; return lastError;
}
return r.getString(resource.intValue(), service); return r.getString(resource.intValue(), service);
} }

@ -164,8 +164,9 @@ abstract public class SyncProviderUtilities {
String value = getPrefs().getString( String value = getPrefs().getString(
ContextManager.getContext().getString( ContextManager.getContext().getString(
getSyncIntervalKey()), null); getSyncIntervalKey()), null);
if (value == null) if (value == null) {
return 0; return 0;
}
try { try {
return Integer.parseInt(value); return Integer.parseInt(value);
} catch (Exception e) { } catch (Exception e) {

@ -69,16 +69,18 @@ abstract public class SyncV2BackgroundService extends Service {
/** Start the actual synchronization */ /** Start the actual synchronization */
private void startSynchronization(final Context context) { private void startSynchronization(final Context context) {
if(context == null || context.getResources() == null) if(context == null || context.getResources() == null) {
return; return;
}
ContextManager.setContext(context); ContextManager.setContext(context);
if(!getSyncUtilities().isLoggedIn()) if(!getSyncUtilities().isLoggedIn()) {
return; return;
}
SyncV2Provider provider = getSyncProvider(); SyncV2Provider provider = getSyncProvider();
if (provider.isActive()) if (provider.isActive()) {
provider.synchronizeActiveTasks(false, new SyncResultCallbackAdapter() { provider.synchronizeActiveTasks(false, new SyncResultCallbackAdapter() {
@Override @Override
public void finished() { public void finished() {
@ -86,6 +88,7 @@ abstract public class SyncV2BackgroundService extends Service {
context.sendBroadcast(new Intent(AstridApiConstants.BROADCAST_EVENT_REFRESH)); context.sendBroadcast(new Intent(AstridApiConstants.BROADCAST_EVENT_REFRESH));
} }
}); });
}
} }
@Override @Override
@ -163,10 +166,11 @@ abstract public class SyncV2BackgroundService extends Service {
long lastSyncDate = getSyncUtilities().getLastSyncDate(); long lastSyncDate = getSyncUtilities().getLastSyncDate();
// if user never synchronized, give them a full offset period before bg sync // 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()); return Math.max(0, lastSyncDate + interval - DateUtilities.now());
else } else {
return interval; return interval;
}
} }

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

@ -419,8 +419,9 @@ public class TouchListView extends ErrorCatchingListView {
private final Runnable longPressRunnable = new Runnable() { private final Runnable longPressRunnable = new Runnable() {
public void run() { public void run() {
AndroidUtilities.sleepDeep(1000L); AndroidUtilities.sleepDeep(1000L);
if(Thread.currentThread().isInterrupted()) if(Thread.currentThread().isInterrupted()) {
return; return;
}
if(mDragView != null && mDragPos == mFirstDragPos && if(mDragView != null && mDragPos == mFirstDragPos &&
Math.abs(mDragCurrentX - mDragStartX) < 10) { Math.abs(mDragCurrentX - mDragStartX) < 10) {
@ -474,10 +475,11 @@ public class TouchListView extends ErrorCatchingListView {
if(mDragPos == mFirstDragPos && if(mDragPos == mFirstDragPos &&
Math.abs(mDragCurrentX - mDragStartX) < 10) { Math.abs(mDragCurrentX - mDragStartX) < 10) {
long pressTime = System.currentTimeMillis() - mDragStartTime; long pressTime = System.currentTimeMillis() - mDragStartTime;
if(pressTime < 1000) if(pressTime < 1000) {
mClickListener.onClick(mOriginalView); mClickListener.onClick(mOriginalView);
else } else {
mClickListener.onLongClick(mOriginalView); mClickListener.onLongClick(mOriginalView);
}
} }
} }
} }

@ -66,8 +66,9 @@ public class GCMIntentService extends GCMBaseIntentService {
if(AndroidUtilities.getSdkVersion() > 8) { //Gingerbread and above if(AndroidUtilities.getSdkVersion() > 8) { //Gingerbread and above
//the following uses relection to get android.os.Build.SERIAL to avoid having to build with Gingerbread //the following uses relection to get android.os.Build.SERIAL to avoid having to build with Gingerbread
try { try {
if(!Build.UNKNOWN.equals(Build.SERIAL)) if(!Build.UNKNOWN.equals(Build.SERIAL)) {
id = Build.SERIAL; id = Build.SERIAL;
}
} catch(Exception e) { } catch(Exception e) {
// Ah well // Ah well
} }
@ -119,13 +120,15 @@ public class GCMIntentService extends GCMBaseIntentService {
@Override @Override
protected void onMessage(Context context, Intent intent) { protected void onMessage(Context context, Intent intent) {
if (actFmPreferenceService.isLoggedIn()) { if (actFmPreferenceService.isLoggedIn()) {
if(intent.hasExtra("web_update")) if(intent.hasExtra("web_update")) {
if (DateUtilities.now() - actFmPreferenceService.getLastSyncDate() > MIN_MILLIS_BETWEEN_FULL_SYNCS && !actFmPreferenceService.isOngoing()) if (DateUtilities.now() - actFmPreferenceService.getLastSyncDate() > MIN_MILLIS_BETWEEN_FULL_SYNCS && !actFmPreferenceService.isOngoing()) {
new ActFmSyncV2Provider().synchronizeActiveTasks(false, refreshOnlyCallback); new ActFmSyncV2Provider().synchronizeActiveTasks(false, refreshOnlyCallback);
else } else {
handleWebUpdate(intent); handleWebUpdate(intent);
else }
} else {
handleMessage(intent); handleMessage(intent);
}
} }
} }
@ -174,12 +177,14 @@ public class GCMIntentService extends GCMBaseIntentService {
private void handleMessage(Intent intent) { private void handleMessage(Intent intent) {
String message = intent.getStringExtra("alert"); String message = intent.getStringExtra("alert");
Context context = ContextManager.getContext(); Context context = ContextManager.getContext();
if(TextUtils.isEmpty(message)) if(TextUtils.isEmpty(message)) {
return; return;
}
long lastNotification = Preferences.getLong(PREF_LAST_GCM, 0); long lastNotification = Preferences.getLong(PREF_LAST_GCM, 0);
if(DateUtilities.now() - lastNotification < 5000L) if(DateUtilities.now() - lastNotification < 5000L) {
return; return;
}
Preferences.setLong(PREF_LAST_GCM, DateUtilities.now()); Preferences.setLong(PREF_LAST_GCM, DateUtilities.now());
Intent notifyIntent = null; Intent notifyIntent = null;
int notifId; int notifId;
@ -213,8 +218,9 @@ public class GCMIntentService extends GCMBaseIntentService {
return; return;
} }
if (notifyIntent == null) if (notifyIntent == null) {
return; return;
}
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
notifyIntent.putExtra(TaskListActivity.TOKEN_SOURCE, Constants.SOURCE_C2DM); notifyIntent.putExtra(TaskListActivity.TOKEN_SOURCE, Constants.SOURCE_C2DM);
@ -228,10 +234,11 @@ public class GCMIntentService extends GCMBaseIntentService {
Notification notification = new Notification(icon, Notification notification = new Notification(icon,
message, System.currentTimeMillis()); message, System.currentTimeMillis());
String title; String title;
if(intent.hasExtra("title")) if(intent.hasExtra("title")) {
title = "Astrid: " + intent.getStringExtra("title"); title = "Astrid: " + intent.getStringExtra("title");
else } else {
title = ContextManager.getString(R.string.app_name); title = ContextManager.getString(R.string.app_name);
}
notification.setLatestEventInfo(ContextManager.getContext(), title, notification.setLatestEventInfo(ContextManager.getContext(), title,
message, pendingIntent); message, pendingIntent);
notification.flags |= Notification.FLAG_AUTO_CANCEL; notification.flags |= Notification.FLAG_AUTO_CANCEL;
@ -254,20 +261,26 @@ public class GCMIntentService extends GCMBaseIntentService {
private int calculateIcon(Intent intent) { private int calculateIcon(Intent intent) {
if(intent.hasExtra("type")) { if(intent.hasExtra("type")) {
String type = intent.getStringExtra("type"); String type = intent.getStringExtra("type");
if("f".equals(type)) if("f".equals(type)) {
return R.drawable.notif_c2dm_done; return R.drawable.notif_c2dm_done;
if("s".equals(type)) }
if("s".equals(type)) {
return R.drawable.notif_c2dm_assign; return R.drawable.notif_c2dm_assign;
if("l".equals(type)) }
if("l".equals(type)) {
return R.drawable.notif_c2dm_assign; return R.drawable.notif_c2dm_assign;
}
} else { } else {
String message = intent.getStringExtra("alert"); String message = intent.getStringExtra("alert");
if(message.contains(" finished ")) if(message.contains(" finished ")) {
return R.drawable.notif_c2dm_done; return R.drawable.notif_c2dm_done;
if(message.contains(" invited you to ")) }
if(message.contains(" invited you to ")) {
return R.drawable.notif_c2dm_assign; 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_assign;
}
} }
return R.drawable.notif_c2dm_msg; return R.drawable.notif_c2dm_msg;
} }
@ -334,8 +347,9 @@ public class GCMIntentService extends GCMBaseIntentService {
update.setValue(UserActivity.ACTION, "tag_comment"); update.setValue(UserActivity.ACTION, "tag_comment");
update.setValue(UserActivity.TARGET_NAME, intent.getStringExtra("title")); update.setValue(UserActivity.TARGET_NAME, intent.getStringExtra("title"));
String message = intent.getStringExtra("alert"); String message = intent.getStringExtra("alert");
if(message.contains(":")) if(message.contains(":")) {
message = message.substring(message.indexOf(':') + 2); message = message.substring(message.indexOf(':') + 2);
}
update.setValue(UserActivity.MESSAGE, message); update.setValue(UserActivity.MESSAGE, message);
update.setValue(UserActivity.CREATED_AT, DateUtilities.now()); update.setValue(UserActivity.CREATED_AT, DateUtilities.now());
update.setValue(UserActivity.TARGET_ID, intent.getStringExtra("tag_id")); update.setValue(UserActivity.TARGET_ID, intent.getStringExtra("tag_id"));
@ -361,14 +375,26 @@ public class GCMIntentService extends GCMBaseIntentService {
private boolean shouldLaunchActivity(Intent intent) { private boolean shouldLaunchActivity(Intent intent) {
if(intent.hasExtra("type")) { if(intent.hasExtra("type")) {
String type = intent.getStringExtra("type"); String type = intent.getStringExtra("type");
if("f".equals(type)) return true; if("f".equals(type)) {
if("s".equals(type)) return false; return true;
if("l".equals(type)) return false; }
if("s".equals(type)) {
return false;
}
if("l".equals(type)) {
return false;
}
} else { } else {
String message = intent.getStringExtra("alert"); String message = intent.getStringExtra("alert");
if(message.contains(" finished ")) return true; if(message.contains(" finished ")) {
if(message.contains(" invited you to ")) return false; return true;
if(message.contains(" sent you ")) return false; }
if(message.contains(" invited you to ")) {
return false;
}
if(message.contains(" sent you ")) {
return false;
}
} }
return true; return true;
} }

@ -44,12 +44,14 @@ public class ActFmCameraModule {
PackageManager pm = activity.getPackageManager(); PackageManager pm = activity.getPackageManager();
final boolean cameraAvailable = pm.queryIntentActivities(cameraIntent, 0).size() > 0; 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_camera));
}
options.add(activity.getString(R.string.actfm_picture_gallery)); options.add(activity.getString(R.string.actfm_picture_gallery));
if (clearImageOption != null) if (clearImageOption != null) {
options.add(activity.getString(R.string.actfm_picture_clear)); options.add(activity.getString(R.string.actfm_picture_clear));
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity, ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity,
android.R.layout.simple_spinner_dropdown_item, options.toArray(new String[options.size()])); 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.startActivityForResult(Intent.createChooser(intent,
activity.getString(R.string.actfm_TVA_tag_picture)), REQUEST_CODE_PICTURE); activity.getString(R.string.actfm_TVA_tag_picture)), REQUEST_CODE_PICTURE);
} else { } else {
if (clearImageOption != null) if (clearImageOption != null) {
clearImageOption.clearImage(); clearImageOption.clearImage();
}
} }
} }
}; };
@ -90,13 +93,15 @@ public class ActFmCameraModule {
final Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); final Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
PackageManager pm = fragment.getActivity().getPackageManager(); PackageManager pm = fragment.getActivity().getPackageManager();
final boolean cameraAvailable = pm.queryIntentActivities(cameraIntent, 0).size() > 0; 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_camera));
}
options.add(fragment.getString(R.string.actfm_picture_gallery)); options.add(fragment.getString(R.string.actfm_picture_gallery));
if (clearImageOption != null) if (clearImageOption != null) {
options.add(fragment.getString(R.string.actfm_picture_clear)); options.add(fragment.getString(R.string.actfm_picture_clear));
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(fragment.getActivity(), ArrayAdapter<String> adapter = new ArrayAdapter<String>(fragment.getActivity(),
android.R.layout.simple_spinner_dropdown_item, options.toArray(new String[options.size()])); 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) { public void onClick(DialogInterface d, int which) {
if(which == 0 && cameraAvailable) { if(which == 0 && cameraAvailable) {
lastTempFile = getTempFile(fragment.getActivity()); lastTempFile = getTempFile(fragment.getActivity());
if (lastTempFile != null) if (lastTempFile != null) {
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(lastTempFile)); cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(lastTempFile));
}
fragment.startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA); fragment.startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA);
} else if ((which == 1 && cameraAvailable) || (which == 0 && !cameraAvailable)) { } else if ((which == 1 && cameraAvailable) || (which == 0 && !cameraAvailable)) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT); Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
@ -116,8 +122,9 @@ public class ActFmCameraModule {
fragment.startActivityForResult(Intent.createChooser(intent, fragment.startActivityForResult(Intent.createChooser(intent,
fragment.getString(R.string.actfm_TVA_tag_picture)), REQUEST_CODE_PICTURE); fragment.getString(R.string.actfm_TVA_tag_picture)), REQUEST_CODE_PICTURE);
} else { } else {
if (clearImageOption != null) if (clearImageOption != null) {
clearImageOption.clearImage(); clearImageOption.clearImage();
}
} }
} }
}; };
@ -174,10 +181,12 @@ public class ActFmCameraModule {
lastTempFile.deleteOnExit(); lastTempFile.deleteOnExit();
lastTempFile = null; lastTempFile = null;
} }
else else {
bitmap = null; bitmap = null;
} else }
} else {
bitmap = data.getParcelableExtra("data"); //$NON-NLS-1$ bitmap = data.getParcelableExtra("data"); //$NON-NLS-1$
}
if(bitmap != null) { if(bitmap != null) {
activity.setResult(Activity.RESULT_OK); activity.setResult(Activity.RESULT_OK);
cameraResult.handleCameraResult(bitmap); cameraResult.handleCameraResult(bitmap);

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

@ -196,11 +196,13 @@ public class ActFmLoginActivity extends SherlockFragmentActivity {
ContextManager.setContext(this); ContextManager.setContext(this);
setContentView(getContentViewResource()); setContentView(getContentViewResource());
if(getTitleResource() != 0) if(getTitleResource() != 0) {
setTitle(getTitleResource()); setTitle(getTitleResource());
}
if (getSupportActionBar() != null) if (getSupportActionBar() != null) {
getSupportActionBar().hide(); getSupportActionBar().hide();
}
rand = new Random(DateUtilities.now()); rand = new Random(DateUtilities.now());
@ -297,14 +299,16 @@ public class ActFmLoginActivity extends SherlockFragmentActivity {
protected void initializeUI() { protected void initializeUI() {
errors = (TextView) findViewById(R.id.error); errors = (TextView) findViewById(R.id.error);
LoginButton loginButton = (LoginButton) findViewById(R.id.fb_login); LoginButton loginButton = (LoginButton) findViewById(R.id.fb_login);
if(loginButton == null) if(loginButton == null) {
return; return;
}
loginButton.setReadPermissions(Arrays.asList("email", "offline_access")); loginButton.setReadPermissions(Arrays.asList("email", "offline_access"));
View googleLogin = findViewById(R.id.gg_login); View googleLogin = findViewById(R.id.gg_login);
if(AmazonMarketStrategy.isKindleFire()) if(AmazonMarketStrategy.isKindleFire()) {
googleLogin.setVisibility(View.GONE); googleLogin.setVisibility(View.GONE);
}
googleLogin.setOnClickListener(googleListener); googleLogin.setOnClickListener(googleListener);
View fbLogin = findViewById(R.id.fb_login_dummy); View fbLogin = findViewById(R.id.fb_login_dummy);
@ -370,8 +374,9 @@ public class ActFmLoginActivity extends SherlockFragmentActivity {
getCredentials(new OnGetCredentials() { getCredentials(new OnGetCredentials() {
@Override @Override
public void getCredentials(String[] accounts) { public void getCredentials(String[] accounts) {
if (accounts != null && accounts.length > 0) if (accounts != null && accounts.length > 0) {
email.setText(accounts[0]); email.setText(accounts[0]);
}
} }
}); });
@ -414,8 +419,9 @@ public class ActFmLoginActivity extends SherlockFragmentActivity {
getCredentials(new OnGetCredentials() { getCredentials(new OnGetCredentials() {
@Override @Override
public void getCredentials(String[] accounts) { public void getCredentials(String[] accounts) {
if (accounts != null && accounts.length > 0) if (accounts != null && accounts.length > 0) {
email.setText(accounts[0]); email.setText(accounts[0]);
}
} }
}); });
@ -493,8 +499,9 @@ public class ActFmLoginActivity extends SherlockFragmentActivity {
char last = 'a'; char last = 'a';
for (int i = 0; i < chars.length; i++) { for (int i = 0; i < chars.length; i++) {
char r = acceptable.charAt(rand.nextInt(acceptable.length())); char r = acceptable.charAt(rand.nextInt(acceptable.length()));
while (!checkSimilar(last, r)) while (!checkSimilar(last, r)) {
r = acceptable.charAt(rand.nextInt(acceptable.length())); r = acceptable.charAt(rand.nextInt(acceptable.length()));
}
last = r; last = r;
chars[i] = r; chars[i] = r;
} }
@ -511,8 +518,9 @@ public class ActFmLoginActivity extends SherlockFragmentActivity {
|| (oSimilar.indexOf(last) > 0 && oSimilar.indexOf(check) > 0) || (oSimilar.indexOf(last) > 0 && oSimilar.indexOf(check) > 0)
|| (puncSimilar.indexOf(last) > 0 && puncSimilar.indexOf(check) > 0); || (puncSimilar.indexOf(last) > 0 && puncSimilar.indexOf(check) > 0);
if (match) if (match) {
return false; return false;
}
return true; return true;
} }
@ -571,9 +579,10 @@ public class ActFmLoginActivity extends SherlockFragmentActivity {
@SuppressWarnings("nls") @SuppressWarnings("nls")
public void authenticate(final String email, final String firstName, final String lastName, final String provider, public void authenticate(final String email, final String firstName, final String lastName, final String provider,
final String secret) { final String secret) {
if (progressDialog == null) if (progressDialog == null) {
progressDialog = DialogUtilities.progressDialog(this, progressDialog = DialogUtilities.progressDialog(this,
getString(R.string.DLG_please_wait)); getString(R.string.DLG_please_wait));
}
new Thread() { new Thread() {
@Override @Override
@ -849,8 +858,9 @@ public class ActFmLoginActivity extends SherlockFragmentActivity {
Preferences.setString(ActFmPreferenceService.PREF_PICTURE, Preferences.setString(ActFmPreferenceService.PREF_PICTURE,
result.optString("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(); Toast.makeText(this, R.string.actfm_ALA_user_exists_sync_alert, Toast.LENGTH_LONG).show();
}
ActFmPreferenceService.reloadThisUser(); ActFmPreferenceService.reloadThisUser();
@ -885,12 +895,13 @@ public class ActFmLoginActivity extends SherlockFragmentActivity {
JSONObject result = ae.result; JSONObject result = ae.result;
if (result != null && result.has("code")) { if (result != null && result.has("code")) {
String code = result.optString("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); 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); 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); message = getString(R.string.actfm_ALA_error_user_not_found);
}
} }
} }
errors.setText(message); errors.setText(message);
@ -907,8 +918,9 @@ public class ActFmLoginActivity extends SherlockFragmentActivity {
super.onActivityResult(requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data); uiHelper.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CANCELED) if (resultCode == RESULT_CANCELED) {
return; return;
}
if (requestCode == REQUEST_CODE_GOOGLE_ACCOUNTS && data != null && credentialsListener != null) { if (requestCode == REQUEST_CODE_GOOGLE_ACCOUNTS && data != null && credentialsListener != null) {
String accounts[] = data.getStringArrayExtra( String accounts[] = data.getStringArrayExtra(
@ -935,8 +947,9 @@ public class ActFmLoginActivity extends SherlockFragmentActivity {
// errors.setVisibility(View.GONE); // errors.setVisibility(View.GONE);
// } // }
else if (requestCode == REQUEST_CODE_GOOGLE) { else if (requestCode == REQUEST_CODE_GOOGLE) {
if (data == null) if (data == null) {
return; return;
}
String email = data.getStringExtra(ActFmGoogleAuthActivity.RESULT_EMAIL); String email = data.getStringExtra(ActFmGoogleAuthActivity.RESULT_EMAIL);
String token = data.getStringExtra(ActFmGoogleAuthActivity.RESULT_TOKEN); String token = data.getStringExtra(ActFmGoogleAuthActivity.RESULT_TOKEN);
authenticate(email, email, "", "google", token); authenticate(email, email, "", "google", token);
@ -951,11 +964,12 @@ public class ActFmLoginActivity extends SherlockFragmentActivity {
public void getCredentials(OnGetCredentials onGetCredentials) { public void getCredentials(OnGetCredentials onGetCredentials) {
credentialsListener = onGetCredentials; credentialsListener = onGetCredentials;
if (Integer.parseInt(Build.VERSION.SDK) >= 7) if (Integer.parseInt(Build.VERSION.SDK) >= 7) {
credentialsListener.getCredentials(ModernAuthManager.getAccounts(this)); credentialsListener.getCredentials(ModernAuthManager.getAccounts(this));
else } else {
GoogleLoginServiceHelper.getAccount(this, GoogleLoginServiceHelper.getAccount(this,
REQUEST_CODE_GOOGLE_ACCOUNTS, false); REQUEST_CODE_GOOGLE_ACCOUNTS, false);
}
} }
} }

@ -77,9 +77,9 @@ public class ActFmPreferences extends SyncProviderPreferences {
PreferenceScreen screen = getPreferenceScreen(); PreferenceScreen screen = getPreferenceScreen();
Preference inAppBilling = findPreference(getString(R.string.actfm_inapp_billing)); 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); screen.removePreference(inAppBilling);
else } else {
inAppBilling.setOnPreferenceClickListener(new OnPreferenceClickListener() { inAppBilling.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override @Override
public boolean onPreferenceClick(Preference preference) { public boolean onPreferenceClick(Preference preference) {
@ -87,6 +87,7 @@ public class ActFmPreferences extends SyncProviderPreferences {
return true; return true;
} }
}); });
}
findPreference(getString(R.string.actfm_account_type)).setOnPreferenceClickListener(new OnPreferenceClickListener() { findPreference(getString(R.string.actfm_account_type)).setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override @Override
@ -140,20 +141,23 @@ public class ActFmPreferences extends SyncProviderPreferences {
String title = actFmPreferenceService.getLoggedInUserName(); String title = actFmPreferenceService.getLoggedInUserName();
String email = Preferences.getStringValue(ActFmPreferenceService.PREF_EMAIL); String email = Preferences.getStringValue(ActFmPreferenceService.PREF_EMAIL);
if (!TextUtils.isEmpty(email)) { if (!TextUtils.isEmpty(email)) {
if (!TextUtils.isEmpty(title)) if (!TextUtils.isEmpty(title)) {
title += "\n"; //$NON-NLS-1$ title += "\n"; //$NON-NLS-1$
}
title += email; title += email;
} }
status.setTitle(getString(R.string.actfm_status_title_logged_in, title)); status.setTitle(getString(R.string.actfm_status_title_logged_in, title));
} }
else else {
status.setTitle(R.string.sync_SPr_group_status); status.setTitle(R.string.sync_SPr_group_status);
}
if (r.getString(R.string.actfm_https_key).equals(preference.getKey())) { if (r.getString(R.string.actfm_https_key).equals(preference.getKey())) {
if ((Boolean)value) if ((Boolean)value) {
preference.setSummary(R.string.actfm_https_enabled); preference.setSummary(R.string.actfm_https_enabled);
else } else {
preference.setSummary(R.string.actfm_https_disabled); preference.setSummary(R.string.actfm_https_disabled);
}
} else if (r.getString(R.string.actfm_account_type).equals(preference.getKey())) { } else if (r.getString(R.string.actfm_account_type).equals(preference.getKey())) {
if (ActFmPreferenceService.isPremiumUser()) { if (ActFmPreferenceService.isPremiumUser()) {
// Premium user // Premium user

@ -36,8 +36,9 @@ public class ActFmSyncActionExposer extends BroadcastReceiver {
DependencyInjectionService.getInstance().inject(this); DependencyInjectionService.getInstance().inject(this);
// if we aren't logged in, don't expose sync action // if we aren't logged in, don't expose sync action
if(!actFmPreferenceService.isLoggedIn()) if(!actFmPreferenceService.isLoggedIn()) {
return; return;
}
SyncAction syncAction = new SyncAction(context.getString(R.string.actfm_APr_header), SyncAction syncAction = new SyncAction(context.getString(R.string.actfm_APr_header),
null); null);

@ -212,10 +212,11 @@ public abstract class CommentsFragment extends SherlockListFragment {
pictureButton.setOnClickListener(new View.OnClickListener() { pictureButton.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
if (picture != null) if (picture != null) {
ActFmCameraModule.showPictureLauncher(CommentsFragment.this, clearImage); ActFmCameraModule.showPictureLauncher(CommentsFragment.this, clearImage);
else } else {
ActFmCameraModule.showPictureLauncher(CommentsFragment.this, null); ActFmCameraModule.showPictureLauncher(CommentsFragment.this, null);
}
} }
}); });
@ -230,8 +231,9 @@ public abstract class CommentsFragment extends SherlockListFragment {
protected void refreshUpdatesList() { protected void refreshUpdatesList() {
Activity activity = getActivity(); Activity activity = getActivity();
View view = getView(); View view = getView();
if (activity == null || view == null) if (activity == null || view == null) {
return; return;
}
Cursor cursor = null; Cursor cursor = null;
ListView listView = ((ListView) view.findViewById(android.R.id.list)); ListView listView = ((ListView) view.findViewById(android.R.id.list));
@ -284,8 +286,9 @@ public abstract class CommentsFragment extends SherlockListFragment {
listView.setVisibility(View.VISIBLE); listView.setVisibility(View.VISIBLE);
} }
if (activity instanceof CommentsActivity) if (activity instanceof CommentsActivity) {
setLastViewed(); setLastViewed();
}
} }
@ -302,8 +305,9 @@ public abstract class CommentsFragment extends SherlockListFragment {
int historyCount = 0; int historyCount = 0;
Cursor c = updateAdapter.getCursor(); Cursor c = updateAdapter.getCursor();
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { 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++; historyCount++;
}
} }
loadMoreHistory(historyCount, doneRunnable); loadMoreHistory(historyCount, doneRunnable);
} }
@ -324,7 +328,7 @@ public abstract class CommentsFragment extends SherlockListFragment {
public void runOnSuccess() { public void runOnSuccess() {
synchronized (this) { synchronized (this) {
Activity activity = getActivity(); Activity activity = getActivity();
if (activity != null) if (activity != null) {
activity.runOnUiThread(new Runnable() { activity.runOnUiThread(new Runnable() {
@Override @Override
public void run() { public void run() {
@ -332,6 +336,7 @@ public abstract class CommentsFragment extends SherlockListFragment {
refreshUpdatesList(); refreshUpdatesList();
} }
}); });
}
} }
} }
@ -351,8 +356,9 @@ public abstract class CommentsFragment extends SherlockListFragment {
@Override @Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
if(menu.size() > 0) if(menu.size() > 0) {
return; return;
}
MenuItem item; MenuItem item;
boolean showCommentsRefresh = actFmPreferenceService.isLoggedIn(); boolean showCommentsRefresh = actFmPreferenceService.isLoggedIn();

@ -156,8 +156,9 @@ public class EditPeopleControlSet extends PopupControlSet {
@Override @Override
public void readFromTask(Task sourceTask) { public void readFromTask(Task sourceTask) {
setTask(sourceTask); setTask(sourceTask);
if (!dontClearAssignedCustom) if (!dontClearAssignedCustom) {
assignedCustom.setText(""); //$NON-NLS-1$ assignedCustom.setText(""); //$NON-NLS-1$
}
dontClearAssignedCustom = false; dontClearAssignedCustom = false;
setUpData(task, null); setUpData(task, null);
} }
@ -295,8 +296,9 @@ public class EditPeopleControlSet extends PopupControlSet {
.put(CONTACT_CHOOSER_USER, true)); .put(CONTACT_CHOOSER_USER, true));
int contactsIndex = addUnassigned ? 2 : 1; int contactsIndex = addUnassigned ? 2 : 1;
boolean addContactPicker = Preferences.getBoolean(R.string.p_use_contact_picker, true) && contactPickerAvailable(); boolean addContactPicker = Preferences.getBoolean(R.string.p_use_contact_picker, true) && contactPickerAvailable();
if (addContactPicker) if (addContactPicker) {
coreUsers.add(contactsIndex, contactPickerUser); coreUsers.add(contactsIndex, contactPickerUser);
}
if (assignedIndex == 0) { if (assignedIndex == 0) {
assignedIndex = findAssignedIndex(t, coreUsers, listUsers, astridUsers); assignedIndex = findAssignedIndex(t, coreUsers, listUsers, astridUsers);
@ -346,8 +348,9 @@ public class EditPeopleControlSet extends PopupControlSet {
return Long.toString(value); return Long.toString(value);
} catch (JSONException e) { } catch (JSONException e) {
String value = obj.optString("id"); //$NON-NLS-1$ String value = obj.optString("id"); //$NON-NLS-1$
if (TextUtils.isEmpty(value)) if (TextUtils.isEmpty(value)) {
value = defaultValue; value = defaultValue;
}
return value; return value;
} }
} }
@ -358,23 +361,28 @@ public class EditPeopleControlSet extends PopupControlSet {
ArrayList<AssignedToUser> users = new ArrayList<AssignedToUser>(); ArrayList<AssignedToUser> users = new ArrayList<AssignedToUser>();
for(int i = 0; i < jsonUsers.size(); i++) { for(int i = 0; i < jsonUsers.size(); i++) {
JSONObject person = jsonUsers.get(i); JSONObject person = jsonUsers.get(i);
if(person == null) if(person == null) {
continue; continue;
}
String id = getLongOrStringId(person, Task.USER_ID_EMAIL); 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; continue;
}
userIds.add(id); userIds.add(id);
String email = person.optString("email"); String email = person.optString("email");
if(!TextUtils.isEmpty(email) && emails.contains(email)) if(!TextUtils.isEmpty(email) && emails.contains(email)) {
continue; continue;
}
emails.add(email); emails.add(email);
String name = person.optString("name"); 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); 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); name = activity.getString(R.string.actfm_EPA_unassigned);
}
AssignedToUser atu = new AssignedToUser(name, person); AssignedToUser atu = new AssignedToUser(name, person);
users.add(atu); users.add(atu);
@ -384,15 +392,18 @@ public class EditPeopleControlSet extends PopupControlSet {
user.label += " (" + user.user.optString("email") + ")"; user.label += " (" + user.user.optString("email") + ")";
names.put(name, null); names.put(name, null);
} }
if(!TextUtils.isEmpty(email)) if(!TextUtils.isEmpty(email)) {
atu.label += " (" + email + ")"; atu.label += " (" + email + ")";
}
} else if(TextUtils.isEmpty(name) || "null".equals(name)) { } else if(TextUtils.isEmpty(name) || "null".equals(name)) {
if(!TextUtils.isEmpty(email)) if(!TextUtils.isEmpty(email)) {
atu.label = email; atu.label = email;
else } else {
users.remove(atu); users.remove(atu);
} else }
} else {
names.put(name, atu); names.put(name, atu);
}
} }
return users; return users;
} }
@ -437,8 +448,9 @@ public class EditPeopleControlSet extends PopupControlSet {
} }
if (getLongOrStringId(user, Task.USER_ID_EMAIL).equals(assignedId) || if (getLongOrStringId(user, Task.USER_ID_EMAIL).equals(assignedId) ||
(user.optString("email").equals(assignedEmail) && (user.optString("email").equals(assignedEmail) &&
!(TextUtils.isEmpty(assignedEmail)))) !(TextUtils.isEmpty(assignedEmail)))) {
return index; return index;
}
} }
index++; index++;
} }
@ -483,8 +495,9 @@ public class EditPeopleControlSet extends PopupControlSet {
@SuppressWarnings("nls") @SuppressWarnings("nls")
@Override @Override
public View getView(int position, View convertView, ViewGroup parent) { 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); convertView = activity.getLayoutInflater().inflate(R.layout.assigned_adapter_row, parent, false);
}
CheckedTextView ctv = (CheckedTextView) convertView.findViewById(android.R.id.text1); CheckedTextView ctv = (CheckedTextView) convertView.findViewById(android.R.id.text1);
super.getView(position, ctv, parent); super.getView(position, ctv, parent);
if (assignedList.getCheckedItemPosition() == position + positionOffset) { if (assignedList.getCheckedItemPosition() == position + positionOffset) {
@ -574,8 +587,9 @@ public class EditPeopleControlSet extends PopupControlSet {
@Override @Override
public String writeToModel(Task t) { public String writeToModel(Task t) {
if (initialized && dialog != null) if (initialized && dialog != null) {
dialog.dismiss(); dialog.dismiss();
}
// do nothing else, we use a separate method // do nothing else, we use a separate method
return null; return null;
} }
@ -602,8 +616,9 @@ public class EditPeopleControlSet extends PopupControlSet {
*/ */
@SuppressWarnings("nls") @SuppressWarnings("nls")
public boolean saveSharingSettings(String toast) { public boolean saveSharingSettings(String toast) {
if(task == null) if(task == null) {
return false; return false;
}
boolean dirty = false; boolean dirty = false;
try { try {
@ -613,8 +628,9 @@ public class EditPeopleControlSet extends PopupControlSet {
userJson = PeopleContainer.createUserJson(assignedCustom); userJson = PeopleContainer.createUserJson(assignedCustom);
assignedView = assignedCustom; assignedView = assignedCustom;
} else { } else {
if (!loadedUI || assignedList.getCheckedItemPosition() == ListView.INVALID_POSITION) if (!loadedUI || assignedList.getCheckedItemPosition() == ListView.INVALID_POSITION) {
return true; return true;
}
AssignedToUser item = (AssignedToUser) assignedList.getAdapter().getItem(assignedList.getCheckedItemPosition()); AssignedToUser item = (AssignedToUser) assignedList.getAdapter().getItem(assignedList.getCheckedItemPosition());
if (item != null) { if (item != null) {
if (item.equals(contactPickerUser)) { //don't want to ever set the user as the fake contact picker user 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) { if (userJson != null) {
String email = userJson.optString("email"); String email = userJson.optString("email");
if (!TextUtils.isEmpty(email) && email.indexOf('@') == -1) if (!TextUtils.isEmpty(email) && email.indexOf('@') == -1) {
throw new ParseSharedException(assignedView, throw new ParseSharedException(assignedView,
activity.getString(R.string.actfm_EPA_invalid_email, userJson.optString("email"))); activity.getString(R.string.actfm_EPA_invalid_email, userJson.optString("email")));
}
} }
if(userJson == null || Task.USER_ID_SELF.equals(getLongOrStringId(userJson, Task.USER_ID_EMAIL))) { if(userJson == null || Task.USER_ID_SELF.equals(getLongOrStringId(userJson, Task.USER_ID_EMAIL))) {
@ -651,8 +668,9 @@ public class EditPeopleControlSet extends PopupControlSet {
} catch (JSONException e) { } catch (JSONException e) {
// sad times // sad times
taskUserId = task.getValue(Task.USER_ID); taskUserId = task.getValue(Task.USER_ID);
if (Task.userIdIsEmail(taskUserId)) if (Task.userIdIsEmail(taskUserId)) {
taskUserEmail = taskUserId; taskUserEmail = taskUserId;
}
} }
String userId = getLongOrStringId(userJson, Task.USER_ID_EMAIL); String userId = getLongOrStringId(userJson, Task.USER_ID_EMAIL);
String userEmail = userJson.optString("email"); String userEmail = userJson.optString("email");
@ -663,8 +681,9 @@ public class EditPeopleControlSet extends PopupControlSet {
dirty = match ? dirty : true; dirty = match ? dirty : true;
String willAssignToId = getLongOrStringId(userJson, Task.USER_ID_EMAIL); String willAssignToId = getLongOrStringId(userJson, Task.USER_ID_EMAIL);
task.setValue(Task.USER_ID, willAssignToId); 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_ID, userEmail);
}
task.setValue(Task.USER, ""); task.setValue(Task.USER, "");
} }
@ -694,10 +713,11 @@ public class EditPeopleControlSet extends PopupControlSet {
task.putTransitory(TaskService.TRANS_ASSIGNED, true); task.putTransitory(TaskService.TRANS_ASSIGNED, true);
if (assignedView == assignedCustom) if (assignedView == assignedCustom) {
StatisticsService.reportEvent(StatisticsConstants.TASK_ASSIGNED_EMAIL); 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); StatisticsService.reportEvent(StatisticsConstants.TASK_ASSIGNED_PICKER);
}
return true; return true;
} catch (ParseSharedException e) { } catch (ParseSharedException e) {
@ -731,14 +751,16 @@ public class EditPeopleControlSet extends PopupControlSet {
userJson = PeopleContainer.createUserJson(assignedCustom); userJson = PeopleContainer.createUserJson(assignedCustom);
} else { } else {
if (!hasLoadedUI() || assignedList.getCheckedItemPosition() == ListView.INVALID_POSITION) { if (!hasLoadedUI() || assignedList.getCheckedItemPosition() == ListView.INVALID_POSITION) {
if (task != null) if (task != null) {
return task.getValue(Task.USER_ID) == Task.USER_ID_SELF; return task.getValue(Task.USER_ID) == Task.USER_ID_SELF;
else } else {
return true; return true;
}
} }
AssignedToUser item = (AssignedToUser) assignedList.getAdapter().getItem(assignedList.getCheckedItemPosition()); AssignedToUser item = (AssignedToUser) assignedList.getAdapter().getItem(assignedList.getCheckedItemPosition());
if (item != null) if (item != null) {
userJson = item.user; userJson = item.user;
}
} }
if(userJson == null || Task.USER_ID_SELF.equals(getLongOrStringId(userJson, Task.USER_ID_EMAIL))) { if(userJson == null || Task.USER_ID_SELF.equals(getLongOrStringId(userJson, Task.USER_ID_EMAIL))) {
@ -788,8 +810,9 @@ public class EditPeopleControlSet extends PopupControlSet {
assignedCustom.setText(email); assignedCustom.setText(email);
dontClearAssignedCustom = true; dontClearAssignedCustom = true;
refreshDisplayView(); refreshDisplayView();
if (dialog != null) if (dialog != null) {
dialog.dismiss(); dialog.dismiss();
}
} else { } else {
DialogUtilities.okDialog(activity, activity.getString(R.string.TEA_contact_error), null); 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()); displayString = activity.getString(R.string.TEA_assigned_to, assignedCustom.getText());
} else { } else {
AssignedToUser user = (AssignedToUser) assignedList.getAdapter().getItem(assignedList.getCheckedItemPosition()); AssignedToUser user = (AssignedToUser) assignedList.getAdapter().getItem(assignedList.getCheckedItemPosition());
if (user == null) if (user == null) {
user = (AssignedToUser) assignedList.getAdapter().getItem(0); user = (AssignedToUser) assignedList.getAdapter().getItem(0);
}
String id = getLongOrStringId(user.user, Task.USER_ID_IGNORE); String id = getLongOrStringId(user.user, Task.USER_ID_IGNORE);
if (Task.USER_ID_UNASSIGNED.equals(id)) { if (Task.USER_ID_UNASSIGNED.equals(id)) {
@ -816,8 +840,9 @@ public class EditPeopleControlSet extends PopupControlSet {
displayString = activity.getString(R.string.actfm_EPA_unassigned); displayString = activity.getString(R.string.actfm_EPA_unassigned);
} else { } else {
String userString = user.toString(); String userString = user.toString();
if (Task.USER_ID_SELF.equals(id)) if (Task.USER_ID_SELF.equals(id)) {
userString = userString.toLowerCase(); userString = userString.toLowerCase();
}
displayString = activity.getString(R.string.TEA_assigned_to, userString); displayString = activity.getString(R.string.TEA_assigned_to, userString);
} }
@ -826,10 +851,11 @@ public class EditPeopleControlSet extends PopupControlSet {
assignedDisplay.setTextColor(unassigned ? unsetColor : themeColor); assignedDisplay.setTextColor(unassigned ? unsetColor : themeColor);
assignedDisplay.setText(displayString); assignedDisplay.setText(displayString);
if (unassigned) if (unassigned) {
image.setImageResource(R.drawable.tea_icn_assign_gray); 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)); image.setImageResource(ThemeService.getTaskEditDrawable(R.drawable.tea_icn_assign, R.drawable.tea_icn_assign_lightblue));
}
} }
@Override @Override

@ -66,8 +66,9 @@ public class TagCommentsFragment extends CommentsFragment {
protected void loadModelFromIntent(Intent intent) { protected void loadModelFromIntent(Intent intent) {
if (tagData == null) { if (tagData == null) {
long id = intent.getLongExtra(TagViewFragment.EXTRA_TAG_DATA, 0); long id = intent.getLongExtra(TagViewFragment.EXTRA_TAG_DATA, 0);
if (id > 0) if (id > 0) {
tagData = tagDataService.fetchById(id, TagData.PROPERTIES); tagData = tagDataService.fetchById(id, TagData.PROPERTIES);
}
} }
} }
@ -120,7 +121,9 @@ public class TagCommentsFragment extends CommentsFragment {
@Override @Override
protected void populateListHeader(ViewGroup header) { protected void populateListHeader(ViewGroup header) {
if (header == null) return; if (header == null) {
return;
}
TextView tagTitle = (TextView) header.findViewById(R.id.tag_title); TextView tagTitle = (TextView) header.findViewById(R.id.tag_title);
String tagName = tagData.getValue(TagData.NAME); String tagName = tagData.getValue(TagData.NAME);
tagTitle.setText(tagName); tagTitle.setText(tagName);
@ -139,12 +142,14 @@ public class TagCommentsFragment extends CommentsFragment {
imageView.setDefaultImageDrawable(ResourceDrawableCache.getImageDrawableFromId(getResources(), TagService.getDefaultImageIDForTag(tagData.getUuid()))); imageView.setDefaultImageDrawable(ResourceDrawableCache.getImageDrawableFromId(getResources(), TagService.getDefaultImageIDForTag(tagData.getUuid())));
String imageUrl = tagData.getPictureUrl(TagData.PICTURE, RemoteModel.PICTURE_MEDIUM); String imageUrl = tagData.getPictureUrl(TagData.PICTURE, RemoteModel.PICTURE_MEDIUM);
Bitmap imageBitmap = null; Bitmap imageBitmap = null;
if (TextUtils.isEmpty(imageUrl)) if (TextUtils.isEmpty(imageUrl)) {
imageBitmap = tagData.getPictureBitmap(TagData.PICTURE); imageBitmap = tagData.getPictureBitmap(TagData.PICTURE);
if (imageBitmap != null) }
if (imageBitmap != null) {
imageView.setImageBitmap(imageBitmap); imageView.setImageBitmap(imageBitmap);
else } else {
imageView.setUrl(imageUrl); imageView.setUrl(imageUrl);
}
} }
@Override @Override
@ -178,8 +183,9 @@ public class TagCommentsFragment extends CommentsFragment {
if(tagData != null && RemoteModel.isValidUuid(tagData.getValue(TagData.UUID))) { if(tagData != null && RemoteModel.isValidUuid(tagData.getValue(TagData.UUID))) {
Preferences.setLong(UPDATES_LAST_VIEWED + tagData.getValue(TagData.UUID), DateUtilities.now()); Preferences.setLong(UPDATES_LAST_VIEWED + tagData.getValue(TagData.UUID), DateUtilities.now());
Activity activity = getActivity(); Activity activity = getActivity();
if (activity instanceof TaskListActivity) if (activity instanceof TaskListActivity) {
((TaskListActivity) activity).setCommentsCount(0); ((TaskListActivity) activity).setCommentsCount(0);
}
} }
} }

@ -134,10 +134,11 @@ public class TagSettingsActivity extends SherlockFragmentActivity {
params.height = LayoutParams.WRAP_CONTENT; params.height = LayoutParams.WRAP_CONTENT;
DisplayMetrics metrics = getResources().getDisplayMetrics(); 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; 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; params.width = (4 * metrics.widthPixels) / 5;
}
getWindow().setAttributes((android.view.WindowManager.LayoutParams) params); getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
} }
@ -181,16 +182,18 @@ public class TagSettingsActivity extends SherlockFragmentActivity {
isDialog = AstridPreferences.useTabletLayout(this); isDialog = AstridPreferences.useTabletLayout(this);
if (isDialog) { if (isDialog) {
setTheme(ThemeService.getDialogTheme()); setTheme(ThemeService.getDialogTheme());
if (AndroidUtilities.getSdkVersion() < 14) if (AndroidUtilities.getSdkVersion() < 14) {
requestWindowFeature(Window.FEATURE_NO_TITLE); requestWindowFeature(Window.FEATURE_NO_TITLE);
}
} else { } else {
ThemeService.applyTheme(this); ThemeService.applyTheme(this);
ActionBar actionBar = getSupportActionBar(); ActionBar actionBar = getSupportActionBar();
if (Preferences.getBoolean(R.string.p_save_and_cancel, false)) { 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); actionBar.setLogo(R.drawable.ic_menu_save_blue_alt);
else } else {
actionBar.setLogo(R.drawable.ic_menu_save); actionBar.setLogo(R.drawable.ic_menu_save);
}
} else { } else {
actionBar.setLogo(null); actionBar.setLogo(null);
} }
@ -318,8 +321,9 @@ public class TagSettingsActivity extends SherlockFragmentActivity {
if (setBitmap != null) { if (setBitmap != null) {
JSONObject pictureJson = RemoteModel.PictureHelper.savePictureJson(this, setBitmap); JSONObject pictureJson = RemoteModel.PictureHelper.savePictureJson(this, setBitmap);
if (pictureJson != null) if (pictureJson != null) {
tagData.setValue(TagData.PICTURE, pictureJson.toString()); tagData.setValue(TagData.PICTURE, pictureJson.toString());
}
} }
JSONArray members; JSONArray members;
@ -336,8 +340,9 @@ public class TagSettingsActivity extends SherlockFragmentActivity {
DialogUtilities.okDialog(this, e.message, null); DialogUtilities.okDialog(this, e.message, null);
return; return;
} }
if (members == null) if (members == null) {
members = new JSONArray(); members = new JSONArray();
}
if(members.length() > 0 && !actFmPreferenceService.isLoggedIn()) { if(members.length() > 0 && !actFmPreferenceService.isLoggedIn()) {
if(newName.length() > 0 && oldName.length() == 0) { if(newName.length() > 0 && oldName.length() == 0) {
@ -394,7 +399,9 @@ public class TagSettingsActivity extends SherlockFragmentActivity {
} }
private void saveTagPictureLocally(Bitmap bitmap) { private void saveTagPictureLocally(Bitmap bitmap) {
if (bitmap == null) return; if (bitmap == null) {
return;
}
try { try {
String tagPicture = RemoteModel.PictureHelper.getPictureHash(tagData); String tagPicture = RemoteModel.PictureHelper.getPictureHash(tagData);
imageCache.put(tagPicture, bitmap); imageCache.put(tagPicture, bitmap);
@ -438,13 +445,15 @@ public class TagSettingsActivity extends SherlockFragmentActivity {
String imageUrl = tagData.getPictureUrl(TagData.PICTURE, RemoteModel.PICTURE_MEDIUM); String imageUrl = tagData.getPictureUrl(TagData.PICTURE, RemoteModel.PICTURE_MEDIUM);
Bitmap imageBitmap = null; Bitmap imageBitmap = null;
if (TextUtils.isEmpty(imageUrl)) if (TextUtils.isEmpty(imageUrl)) {
imageBitmap = tagData.getPictureBitmap(TagData.PICTURE); imageBitmap = tagData.getPictureBitmap(TagData.PICTURE);
}
if (imageBitmap != null) if (imageBitmap != null) {
picture.setImageBitmap(imageBitmap); picture.setImageBitmap(imageBitmap);
else } else {
picture.setUrl(imageUrl); picture.setUrl(imageUrl);
}
if (!isNewTag) { if (!isNewTag) {
ImageView shortcut = (ImageView) findViewById(R.id.create_shortcut); ImageView shortcut = (ImageView) findViewById(R.id.create_shortcut);
shortcut.setImageBitmap(FilterListFragment.superImposeListIcon(this, picture.getImageBitmap(), tagData.getUuid())); shortcut.setImageBitmap(FilterListFragment.superImposeListIcon(this, picture.getImageBitmap(), tagData.getUuid()));
@ -599,22 +608,25 @@ public class TagSettingsActivity extends SherlockFragmentActivity {
break; break;
case android.R.id.home: case android.R.id.home:
saveSettings(); saveSettings();
if (!isFinishing()) if (!isFinishing()) {
finish(); finish();
}
break; break;
} }
return super.onOptionsItemSelected(item); return super.onOptionsItemSelected(item);
} }
protected void showDeleteDialog(TagData td) { protected void showDeleteDialog(TagData td) {
if(td == null) if(td == null) {
return; return;
}
int string; 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; string = R.string.DLG_leave_this_shared_tag_question;
else } else {
string = R.string.DLG_delete_this_tag_question; string = R.string.DLG_delete_this_tag_question;
}
DialogUtilities.okCancelDialog(this, getString(string, td.getValue(TagData.NAME)), 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); ((EditText) getView().findViewById(R.id.quickAddText)).setOnTouchListener(onTouch);
View membersEdit = getView().findViewById(R.id.members_edit); View membersEdit = getView().findViewById(R.id.members_edit);
if (membersEdit != null) if (membersEdit != null) {
membersEdit.setOnClickListener(settingsListener); membersEdit.setOnClickListener(settingsListener);
}
originalFilter = filter; originalFilter = filter;
} }
@ -203,14 +204,16 @@ public class TagViewFragment extends TaskListFragment {
} }
private void showListSettingsPopover() { private void showListSettingsPopover() {
if (!AstridPreferences.canShowPopover()) if (!AstridPreferences.canShowPopover()) {
return; return;
}
if (!Preferences.getBoolean(R.string.p_showed_list_settings_help, false)) { if (!Preferences.getBoolean(R.string.p_showed_list_settings_help, false)) {
Preferences.setBoolean(R.string.p_showed_list_settings_help, true); Preferences.setBoolean(R.string.p_showed_list_settings_help, true);
View tabView = getView().findViewById(R.id.members_edit); View tabView = getView().findViewById(R.id.members_edit);
if (tabView != null) if (tabView != null) {
HelpInfoPopover.showPopover(getActivity(), tabView, HelpInfoPopover.showPopover(getActivity(), tabView,
R.string.help_popover_list_settings, null); R.string.help_popover_list_settings, null);
}
} }
} }
@ -239,22 +242,26 @@ public class TagViewFragment extends TaskListFragment {
@Override @Override
protected void initializeData() { protected void initializeData() {
synchronized(this) { synchronized(this) {
if(dataLoaded) if(dataLoaded) {
return; return;
}
dataLoaded = true; dataLoaded = true;
} }
TaskListActivity activity = (TaskListActivity) getActivity(); TaskListActivity activity = (TaskListActivity) getActivity();
String tag = extras.getString(EXTRA_TAG_NAME); String tag = extras.getString(EXTRA_TAG_NAME);
String uuid = RemoteModel.NO_UUID; String uuid = RemoteModel.NO_UUID;
if (extras.containsKey(EXTRA_TAG_UUID)) if (extras.containsKey(EXTRA_TAG_UUID)) {
uuid = extras.getString(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)); 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; return;
}
TodorooCursor<TagData> cursor; TodorooCursor<TagData> cursor;
if (!RemoteModel.isUuidEmpty(uuid)) { if (!RemoteModel.isUuidEmpty(uuid)) {
@ -295,8 +302,9 @@ public class TagViewFragment extends TaskListFragment {
@Override @Override
public void loadTaskListContent(boolean requery) { public void loadTaskListContent(boolean requery) {
super.loadTaskListContent(requery); super.loadTaskListContent(requery);
if(taskAdapter == null || taskAdapter.getCursor() == null) if(taskAdapter == null || taskAdapter.getCursor() == null) {
return; return;
}
int count = taskAdapter.getCursor().getCount(); int count = taskAdapter.getCursor().getCount();
@ -326,8 +334,9 @@ public class TagViewFragment extends TaskListFragment {
} }
TaskListActivity tla = (TaskListActivity) getActivity(); TaskListActivity tla = (TaskListActivity) getActivity();
if (tla != null) if (tla != null) {
tla.setCommentsCount(unreadCount); tla.setCommentsCount(unreadCount);
}
} }
} }
@ -336,8 +345,9 @@ public class TagViewFragment extends TaskListFragment {
@Override @Override
protected void initiateAutomaticSyncImpl() { protected void initiateAutomaticSyncImpl() {
if (!isCurrentTaskListFragment()) if (!isCurrentTaskListFragment()) {
return; return;
}
if (tagData != null) { if (tagData != null) {
long lastAutosync = tagData.getValue(TagData.LAST_AUTOSYNC); long lastAutosync = tagData.getValue(TagData.LAST_AUTOSYNC);
if(DateUtilities.now() - lastAutosync > AUTOSYNC_INTERVAL) { if(DateUtilities.now() - lastAutosync > AUTOSYNC_INTERVAL) {
@ -464,8 +474,9 @@ public class TagViewFragment extends TaskListFragment {
getView().findViewById(R.id.members_header).setVisibility(View.GONE); getView().findViewById(R.id.members_header).setVisibility(View.GONE);
return; return;
} }
if (tagData == null) if (tagData == null) {
return; return;
}
LinearLayout membersView = (LinearLayout)getView().findViewById(R.id.shared_with); LinearLayout membersView = (LinearLayout)getView().findViewById(R.id.shared_with);
membersView.setOnClickListener(settingsListener); membersView.setOnClickListener(settingsListener);
boolean addedMembers = false; boolean addedMembers = false;
@ -553,8 +564,9 @@ public class TagViewFragment extends TaskListFragment {
} else { } else {
owner = ActFmPreferenceService.thisUser(); owner = ActFmPreferenceService.thisUser();
} }
if (owner != null) if (owner != null) {
addImageForMember(membersView, owner); addImageForMember(membersView, owner);
}
JSONObject unassigned = new JSONObject(); JSONObject unassigned = new JSONObject();
unassigned.put("id", Task.USER_ID_UNASSIGNED); //$NON-NLS-1$ 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); View filterAssigned = getView().findViewById(R.id.filter_assigned);
if (filterAssigned != null) if (filterAssigned != null) {
filterAssigned.setOnClickListener(new OnClickListener() { filterAssigned.setOnClickListener(new OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
resetAssignedFilter(); resetAssignedFilter();
} }
}); });
}
} }
@SuppressWarnings("nls") @SuppressWarnings("nls")
@ -590,14 +603,16 @@ public class TagViewFragment extends TaskListFragment {
image.setDefaultImageDrawable(ResourceDrawableCache.getImageDrawableFromId(resources, R.drawable.icn_default_person_image)); 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.setDefaultImageDrawable(ResourceDrawableCache.getImageDrawableFromId(resources, R.drawable.icn_anyone));
}
image.setScaleType(ImageView.ScaleType.FIT_CENTER); image.setScaleType(ImageView.ScaleType.FIT_CENTER);
try { try {
final String id = Long.toString(member.optLong("id", -2)); final String id = Long.toString(member.optLong("id", -2));
if (ActFmPreferenceService.userId().equals(id)) if (ActFmPreferenceService.userId().equals(id)) {
member = ActFmPreferenceService.thisUser(); member = ActFmPreferenceService.thisUser();
}
final JSONObject memberToUse = member; final JSONObject memberToUse = member;
final String memberName = displayName(memberToUse); final String memberName = displayName(memberToUse);
@ -626,21 +641,23 @@ public class TagViewFragment extends TaskListFragment {
// New filter // New filter
currentId = id; currentId = id;
Criterion assignedCriterion; 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)); 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 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); assignedCriterion = Task.USER_ID.eq(id);
}
Criterion assigned = Criterion.and(TaskCriteria.activeAndVisible(), assignedCriterion); Criterion assigned = Criterion.and(TaskCriteria.activeAndVisible(), assignedCriterion);
filter = TagFilterExposer.filterFromTag(getActivity(), new Tag(tagData), assigned); filter = TagFilterExposer.filterFromTag(getActivity(), new Tag(tagData), assigned);
TextView filterByAssigned = (TextView) getView().findViewById(R.id.filter_assigned); TextView filterByAssigned = (TextView) getView().findViewById(R.id.filter_assigned);
if (filterByAssigned != null) { if (filterByAssigned != null) {
filterByAssigned.setVisibility(View.VISIBLE); 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)); filterByAssigned.setText(getString(R.string.actfm_TVA_filter_by_unassigned));
else } else {
filterByAssigned.setText(getString(R.string.actfm_TVA_filtered_by_assign, displayName)); filterByAssigned.setText(getString(R.string.actfm_TVA_filtered_by_assign, displayName));
}
} }
isBeingFiltered.set(true); isBeingFiltered.set(true);
setUpTaskList(); setUpTaskList();
@ -654,8 +671,9 @@ public class TagViewFragment extends TaskListFragment {
isBeingFiltered.set(false); isBeingFiltered.set(false);
filter = originalFilter; filter = originalFilter;
View filterAssigned = getView().findViewById(R.id.filter_assigned); View filterAssigned = getView().findViewById(R.id.filter_assigned);
if (filterAssigned != null) if (filterAssigned != null) {
filterAssigned.setVisibility(View.GONE); filterAssigned.setVisibility(View.GONE);
}
setUpTaskList(); setUpTaskList();
} }
@ -688,10 +706,12 @@ public class TagViewFragment extends TaskListFragment {
@SuppressWarnings("nls") @SuppressWarnings("nls")
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
if(!intent.hasExtra("tag_id")) if(!intent.hasExtra("tag_id")) {
return; 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; return;
}
getActivity().runOnUiThread(new Runnable() { getActivity().runOnUiThread(new Runnable() {
@Override @Override
@ -760,10 +780,11 @@ public class TagViewFragment extends TaskListFragment {
((TaskListActivity) activity).setListsTitle(filter.title); ((TaskListActivity) activity).setListsTitle(filter.title);
FilterListFragment flf = ((TaskListActivity) activity).getFilterListFragment(); FilterListFragment flf = ((TaskListActivity) activity).getFilterListFragment();
if (flf != null) { if (flf != null) {
if (!onActivityResult) if (!onActivityResult) {
flf.refresh(); flf.refresh();
else } else {
flf.clear(); flf.clear();
}
} }
} }
taskAdapter = null; taskAdapter = null;
@ -803,9 +824,9 @@ public class TagViewFragment extends TaskListFragment {
protected void toggleDragDrop(boolean newState) { protected void toggleDragDrop(boolean newState) {
Class<?> customComponent; Class<?> customComponent;
if(newState) if(newState) {
customComponent = SubtasksTagListFragment.class; customComponent = SubtasksTagListFragment.class;
else { } else {
filter.setFilterQueryOverride(null); filter.setFilterQueryOverride(null);
customComponent = TagViewFragment.class; customComponent = TagViewFragment.class;
} }

@ -42,8 +42,9 @@ public class WaitingOnMeFragment extends TaskListFragment {
new OnCompletedTaskListener() { new OnCompletedTaskListener() {
@Override @Override
public void onCompletedTask(Task item, boolean newState) { public void onCompletedTask(Task item, boolean newState) {
if (newState == true) if (newState == true) {
onTaskCompleted(item); onTaskCompleted(item);
}
} }
}); });
} }
@ -61,10 +62,11 @@ public class WaitingOnMeFragment extends TaskListFragment {
super.setTaskAppearance(viewHolder, task); super.setTaskAppearance(viewHolder, task);
TextView nameView = viewHolder.nameView; 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); nameView.setTypeface(null, Typeface.BOLD);
else } else {
nameView.setTypeface(null, 0); nameView.setTypeface(null, 0);
}
} }
} }

@ -132,16 +132,19 @@ public class ActFmInvoker {
try { try {
String request = createFetchUrl(api, method, getParameters); String request = createFetchUrl(api, method, getParameters);
if (SYNC_DEBUG) if (SYNC_DEBUG) {
Log.e("act-fm-invoke", request); Log.e("act-fm-invoke", request);
}
String response = restClient.get(request); String response = restClient.get(request);
JSONObject object = new JSONObject(response); JSONObject object = new JSONObject(response);
if (SYNC_DEBUG) if (SYNC_DEBUG) {
AndroidUtilities.logJSONObject("act-fm-invoke-response", object); 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); throw new ActFmServiceException(object.getString("message"), object);
}
return object; return object;
} catch (JSONException e) { } catch (JSONException e) {
throw new IOException(e.getMessage()); throw new IOException(e.getMessage());
@ -166,17 +169,20 @@ public class ActFmInvoker {
try { try {
String request = createFetchUrl(null, method, getParameters); String request = createFetchUrl(null, method, getParameters);
if (SYNC_DEBUG) if (SYNC_DEBUG) {
Log.e("act-fm-post", request); Log.e("act-fm-post", request);
}
String response = restClient.post(request, data); String response = restClient.post(request, data);
JSONObject object = new JSONObject(response); JSONObject object = new JSONObject(response);
if (SYNC_DEBUG) if (SYNC_DEBUG) {
AndroidUtilities.logJSONObject("act-fm-post-response", object); 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); throw new ActFmServiceException(object.getString("message"), object);
}
return object; return object;
} catch (JSONException e) { } catch (JSONException e) {
throw new IOException(e.getMessage()); throw new IOException(e.getMessage());
@ -202,8 +208,9 @@ public class ActFmInvoker {
} }
String request = createFetchUrl("api/" + API_VERSION, "synchronize", params); String request = createFetchUrl("api/" + API_VERSION, "synchronize", params);
if (SYNC_DEBUG) if (SYNC_DEBUG) {
Log.e("act-fm-post", request); Log.e("act-fm-post", request);
}
Charset chars; Charset chars;
try { try {
chars = Charset.forName("UTF-8"); chars = Charset.forName("UTF-8");
@ -218,11 +225,13 @@ public class ActFmInvoker {
String response = restClient.post(request, entity); String response = restClient.post(request, entity);
JSONObject object = new JSONObject(response); JSONObject object = new JSONObject(response);
if (SYNC_DEBUG) if (SYNC_DEBUG) {
AndroidUtilities.logJSONObject("act-fm-post-response", object); 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); throw new ActFmServiceException(object.getString("message"), object);
}
return object; return object;
} catch (JSONException e) { } catch (JSONException e) {
throw new IOException(e.getMessage()); throw new IOException(e.getMessage());
@ -244,17 +253,20 @@ public class ActFmInvoker {
for(int i = 0; i < getParameters.length; i += 2) { for(int i = 0; i < getParameters.length; i += 2) {
if(getParameters[i+1] instanceof ArrayList) { if(getParameters[i+1] instanceof ArrayList) {
ArrayList<?> list = (ArrayList<?>) getParameters[i+1]; 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() + "[]", params.add(new Pair<String, Object>(getParameters[i].toString() + "[]",
list.get(j))); 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)); params.add(new Pair<String, Object>("app_id", APP_ID));
boolean syncMethod = "synchronize".equals(method); boolean syncMethod = "synchronize".equals(method);
if (!syncMethod) if (!syncMethod) {
params.add(new Pair<String, Object>("time", System.currentTimeMillis() / 1000L)); params.add(new Pair<String, Object>("time", System.currentTimeMillis() / 1000L));
}
if(token != null) { if(token != null) {
boolean foundTokenKey = false; boolean foundTokenKey = false;
for (Pair<String, Object> curr : params) { for (Pair<String, Object> curr : params) {
@ -263,8 +275,9 @@ public class ActFmInvoker {
break; break;
} }
} }
if (!foundTokenKey) if (!foundTokenKey) {
params.add(new Pair<String, Object>("token", token)); params.add(new Pair<String, Object>("token", token));
}
} }
Collections.sort(params, new Comparator<Pair<String, Object>>() { Collections.sort(params, new Comparator<Pair<String, Object>>() {
@ -272,8 +285,9 @@ public class ActFmInvoker {
public int compare(Pair<String, Object> object1, public int compare(Pair<String, Object> object1,
Pair<String, Object> object2) { Pair<String, Object> object2) {
int result = object1.getLeft().compareTo(object2.getLeft()); int result = object1.getLeft().compareTo(object2.getLeft());
if(result == 0) if(result == 0) {
return object1.getRight().toString().compareTo(object2.getRight().toString()); return object1.getRight().toString().compareTo(object2.getRight().toString());
}
return result; return result;
} }
}); });
@ -284,26 +298,30 @@ public class ActFmInvoker {
customApi = true; customApi = true;
url = url.replace("api", api); 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; url = "https:" + url;
else } else {
url = "http:" + url; url = "http:" + url;
}
StringBuilder requestBuilder = new StringBuilder(url); StringBuilder requestBuilder = new StringBuilder(url);
if (!customApi) if (!customApi) {
requestBuilder.append(API_VERSION).append("/"); requestBuilder.append(API_VERSION).append("/");
}
requestBuilder.append(method).append('?'); requestBuilder.append(method).append('?');
StringBuilder sigBuilder = new StringBuilder(method); StringBuilder sigBuilder = new StringBuilder(method);
for(Pair<String, Object> entry : params) { for(Pair<String, Object> entry : params) {
if(entry.getRight() == null) if(entry.getRight() == null) {
continue; continue;
}
String key = entry.getLeft(); String key = entry.getLeft();
String value = entry.getRight().toString(); String value = entry.getRight().toString();
String encoded = URLEncoder.encode(value, "UTF-8"); 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('&'); requestBuilder.append(key).append('=').append(encoded).append('&');
}
sigBuilder.append(key).append(value); sigBuilder.append(key).append(value);
} }

@ -50,8 +50,9 @@ public class ActFmPreferenceService extends SyncProviderUtilities {
@Override @Override
public boolean shouldShowToast() { public boolean shouldShowToast() {
if(Preferences.getBoolean(AstridPreferences.P_FIRST_TASK, true)) if(Preferences.getBoolean(AstridPreferences.P_FIRST_TASK, true)) {
return false; return false;
}
return super.shouldShowToast(); return super.shouldShowToast();
} }
@ -60,10 +61,11 @@ public class ActFmPreferenceService extends SyncProviderUtilities {
@Override @Override
public void setToken(String setting) { public void setToken(String setting) {
super.setToken(setting); super.setToken(setting);
if (TextUtils.isEmpty(setting)) if (TextUtils.isEmpty(setting)) {
RemoteModelDao.setOutstandingEntryFlags(RemoteModelDao.OUTSTANDING_FLAG_UNINITIALIZED); RemoteModelDao.setOutstandingEntryFlags(RemoteModelDao.OUTSTANDING_FLAG_UNINITIALIZED);
else } else {
RemoteModelDao.setOutstandingEntryFlags(RemoteModelDao.OUTSTANDING_ENTRY_FLAG_ENQUEUE_MESSAGES | RemoteModelDao.OUTSTANDING_ENTRY_FLAG_RECORD_OUTSTANDING); 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() { public static String userId() {
try { try {
String value = Preferences.getStringValue(PREF_USER_ID); String value = Preferences.getStringValue(PREF_USER_ID);
if (value == null) if (value == null) {
return Long.toString(Preferences.getLong(PREF_USER_ID, -2L)); return Long.toString(Preferences.getLong(PREF_USER_ID, -2L));
}
return value; return value;
} catch (Exception e) { } catch (Exception e) {
return Long.toString(Preferences.getLong(PREF_USER_ID, -2L)); return Long.toString(Preferences.getLong(PREF_USER_ID, -2L));
@ -130,8 +133,9 @@ public class ActFmPreferenceService extends SyncProviderUtilities {
} }
public synchronized static void reloadThisUser() { public synchronized static void reloadThisUser() {
if (user == null) if (user == null) {
return; return;
}
populateUser(); populateUser();
} }
@ -151,8 +155,9 @@ public class ActFmPreferenceService extends SyncProviderUtilities {
} }
public static boolean isPremiumUser() { public static boolean isPremiumUser() {
if (Preferences.getBoolean(PremiumUnlockService.PREF_KILL_SWITCH, false)) if (Preferences.getBoolean(PremiumUnlockService.PREF_KILL_SWITCH, false)) {
return true; return true;
}
if (Preferences.getBoolean(BillingConstants.PREF_NEEDS_SERVER_UPDATE, false)) { if (Preferences.getBoolean(BillingConstants.PREF_NEEDS_SERVER_UPDATE, false)) {
return Preferences.getBoolean(PREF_LOCAL_PREMIUM, false); return Preferences.getBoolean(PREF_LOCAL_PREMIUM, false);
@ -171,18 +176,21 @@ public class ActFmPreferenceService extends SyncProviderUtilities {
String name = Preferences.getStringValue(PREF_NAME); String name = Preferences.getStringValue(PREF_NAME);
if (TextUtils.isEmpty(name)) { if (TextUtils.isEmpty(name)) {
String firstName = Preferences.getStringValue(PREF_FIRST_NAME); String firstName = Preferences.getStringValue(PREF_FIRST_NAME);
if (!TextUtils.isEmpty(firstName)) if (!TextUtils.isEmpty(firstName)) {
name = firstName; name = firstName;
}
String lastName = Preferences.getStringValue(PREF_FIRST_NAME); String lastName = Preferences.getStringValue(PREF_FIRST_NAME);
if (!TextUtils.isEmpty(lastName)) { if (!TextUtils.isEmpty(lastName)) {
if (!TextUtils.isEmpty(name)) if (!TextUtils.isEmpty(name)) {
name += " "; //$NON-NLS-1$ name += " "; //$NON-NLS-1$
}
name += lastName; name += lastName;
} }
if (name == null) if (name == null) {
name = ""; //$NON-NLS-1$ name = ""; //$NON-NLS-1$
}
} }
return name; return name;
} }
@ -192,19 +200,23 @@ public class ActFmPreferenceService extends SyncProviderUtilities {
JSONObject thisUser = thisUser(); JSONObject thisUser = thisUser();
String name = thisUser.optString("name"); String name = thisUser.optString("name");
if (!(TextUtils.isEmpty(name) || "null".equals(name))) if (!(TextUtils.isEmpty(name) || "null".equals(name))) {
return name; return name;
}
String firstName = thisUser.optString("first_name"); String firstName = thisUser.optString("first_name");
boolean firstNameEmpty = TextUtils.isEmpty(firstName) || "null".equals(firstName); boolean firstNameEmpty = TextUtils.isEmpty(firstName) || "null".equals(firstName);
String lastName = thisUser.optString("last_name"); String lastName = thisUser.optString("last_name");
boolean lastNameEmpty = TextUtils.isEmpty(lastName) || "null".equals(lastName); boolean lastNameEmpty = TextUtils.isEmpty(lastName) || "null".equals(lastName);
if (firstNameEmpty && lastNameEmpty) if (firstNameEmpty && lastNameEmpty) {
return thisUser.optString("email"); return thisUser.optString("email");
}
StringBuilder nameBuilder = new StringBuilder(); StringBuilder nameBuilder = new StringBuilder();
if (!firstNameEmpty) if (!firstNameEmpty) {
nameBuilder.append(firstName).append(" "); nameBuilder.append(firstName).append(" ");
if (!lastNameEmpty) }
if (!lastNameEmpty) {
nameBuilder.append(lastName); nameBuilder.append(lastName);
}
return nameBuilder.toString().trim(); return nameBuilder.toString().trim();
} }

@ -67,13 +67,15 @@ public final class ActFmSyncService {
// --- data fetch methods // --- data fetch methods
public int fetchFeaturedLists(int serverTime) throws JSONException, IOException { public int fetchFeaturedLists(int serverTime) throws JSONException, IOException {
if (!checkForToken()) if (!checkForToken()) {
return 0; return 0;
}
JSONObject result = actFmInvoker.invoke("featured_lists", JSONObject result = actFmInvoker.invoke("featured_lists",
"token", token, "modified_after", serverTime); "token", token, "modified_after", serverTime);
JSONArray featuredLists = result.getJSONArray("list"); JSONArray featuredLists = result.getJSONArray("list");
if (featuredLists.length() > 0) if (featuredLists.length() > 0) {
Preferences.setBoolean(FeaturedListFilterExposer.PREF_SHOULD_SHOW_FEATURED_LISTS, true); Preferences.setBoolean(FeaturedListFilterExposer.PREF_SHOULD_SHOW_FEATURED_LISTS, true);
}
for (int i = 0; i < featuredLists.length(); i++) { for (int i = 0; i < featuredLists.length(); i++) {
JSONObject featObject = featuredLists.getJSONObject(i); JSONObject featObject = featuredLists.getJSONObject(i);
@ -87,8 +89,9 @@ public final class ActFmSyncService {
String purchaseToken = Preferences.getStringValue(BillingConstants.PREF_PURCHASE_TOKEN); String purchaseToken = Preferences.getStringValue(BillingConstants.PREF_PURCHASE_TOKEN);
String productId = Preferences.getStringValue(BillingConstants.PREF_PRODUCT_ID); String productId = Preferences.getStringValue(BillingConstants.PREF_PRODUCT_ID);
try { try {
if (!checkForToken()) if (!checkForToken()) {
throw new ActFmServiceException("Not logged in", null); throw new ActFmServiceException("Not logged in", null);
}
ArrayList<Object> params = new ArrayList<Object>(); ArrayList<Object> params = new ArrayList<Object>();
params.add("purchase_token"); params.add(purchaseToken); 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()])); actFmInvoker.invoke("premium_update_android", params.toArray(new Object[params.size()]));
Preferences.setBoolean(BillingConstants.PREF_NEEDS_SERVER_UPDATE, false); Preferences.setBoolean(BillingConstants.PREF_NEEDS_SERVER_UPDATE, false);
if (onSuccess != null) if (onSuccess != null) {
onSuccess.run(); onSuccess.run();
}
} catch (Exception e) { } catch (Exception e) {
if (e instanceof ActFmServiceException) { if (e instanceof ActFmServiceException) {
ActFmServiceException ae = (ActFmServiceException)e; 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 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(ActFmPreferenceService.PREF_LOCAL_PREMIUM, false);
Preferences.setBoolean(BillingConstants.PREF_NEEDS_SERVER_UPDATE, false); Preferences.setBoolean(BillingConstants.PREF_NEEDS_SERVER_UPDATE, false);
if (onInvalidToken != null) if (onInvalidToken != null) {
onInvalidToken.run(); onInvalidToken.run();
}
return; return;
} }
} }
} }
Preferences.setBoolean(BillingConstants.PREF_NEEDS_SERVER_UPDATE, true); Preferences.setBoolean(BillingConstants.PREF_NEEDS_SERVER_UPDATE, true);
if (onRecoverableError != null) if (onRecoverableError != null) {
onRecoverableError.run(); onRecoverableError.run();
}
} }
} }
@ -150,13 +156,15 @@ public final class ActFmSyncService {
/** invoke authenticated method against the server */ /** invoke authenticated method against the server */
public JSONObject invoke(String method, Object... getParameters) throws IOException, public JSONObject invoke(String method, Object... getParameters) throws IOException,
ActFmServiceException { ActFmServiceException {
if(!checkForToken()) if(!checkForToken()) {
throw new ActFmServiceException("not logged in", null); throw new ActFmServiceException("not logged in", null);
}
Object[] parameters = new Object[getParameters.length + 2]; Object[] parameters = new Object[getParameters.length + 2];
parameters[0] = "token"; parameters[0] = "token";
parameters[1] = token; parameters[1] = token;
for(int i = 0; i < getParameters.length; i++) for(int i = 0; i < getParameters.length; i++) {
parameters[i+2] = getParameters[i]; parameters[i + 2] = getParameters[i];
}
return actFmInvoker.invoke(method, parameters); return actFmInvoker.invoke(method, parameters);
} }
@ -165,8 +173,9 @@ public final class ActFmSyncService {
} }
private boolean checkForToken() { private boolean checkForToken() {
if(!actFmPreferenceService.isLoggedIn()) if(!actFmPreferenceService.isLoggedIn()) {
return false; return false;
}
token = actFmPreferenceService.getToken(); token = actFmPreferenceService.getToken();
return true; return true;
} }
@ -199,19 +208,24 @@ public final class ActFmSyncService {
model.setValue(TagData.UUID, Long.toString(json.getLong("id"))); model.setValue(TagData.UUID, Long.toString(json.getLong("id")));
model.setValue(TagData.NAME, json.getString("name")); model.setValue(TagData.NAME, json.getString("name"));
if (featuredList) if (featuredList) {
model.setFlag(TagData.FLAGS, TagData.FLAG_FEATURED, true); model.setFlag(TagData.FLAGS, TagData.FLAG_FEATURED, true);
}
if(json.has("picture")) if(json.has("picture")) {
model.setValue(TagData.PICTURE, json.optString("picture", "")); model.setValue(TagData.PICTURE, json.optString("picture", ""));
if(json.has("thumb")) }
if(json.has("thumb")) {
model.setValue(TagData.THUMB, json.optString("thumb", "")); model.setValue(TagData.THUMB, json.optString("thumb", ""));
}
if(json.has("is_silent")) if(json.has("is_silent")) {
model.setFlag(TagData.FLAGS, TagData.FLAG_SILENT,json.getBoolean("is_silent")); 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")); model.setValue(TagData.TAG_DESCRIPTION, json.getString("description"));
}
if(json.has("members")) { if(json.has("members")) {
JSONArray members = json.getJSONArray("members"); JSONArray members = json.getJSONArray("members");
@ -219,11 +233,13 @@ public final class ActFmSyncService {
model.setValue(TagData.MEMBER_COUNT, members.length()); 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")); 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")); model.setValue(TagData.TASK_COUNT, json.getInt("tasks"));
}
} }
} }

@ -208,17 +208,20 @@ public class ActFmSyncThread {
public static void clearTablePushedAtValues() { public static void clearTablePushedAtValues() {
String[] pushedAtPrefs = new String[] { NameMaps.PUSHED_AT_TASKS, NameMaps.PUSHED_AT_TAGS, NameMaps.PUSHED_AT_ACTIVITY, 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 }; 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); Preferences.clear(key);
}
} }
public synchronized void enqueueMessage(ClientToServerMessage<?> message, SyncMessageCallback callback) { 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; return;
}
if (!pendingMessages.contains(message)) { if (!pendingMessages.contains(message)) {
pendingMessages.add(message); pendingMessages.add(message);
if (callback != null) if (callback != null) {
pendingCallbacks.put(message, callback); pendingCallbacks.put(message, callback);
}
synchronized(monitor) { synchronized(monitor) {
monitor.notifyAll(); monitor.notifyAll();
} }
@ -227,10 +230,11 @@ public class ActFmSyncThread {
public synchronized void setTimeForBackgroundSync(boolean isTimeForBackgroundSync) { public synchronized void setTimeForBackgroundSync(boolean isTimeForBackgroundSync) {
this.isTimeForBackgroundSync = isTimeForBackgroundSync; this.isTimeForBackgroundSync = isTimeForBackgroundSync;
if (isTimeForBackgroundSync) if (isTimeForBackgroundSync) {
synchronized (monitor) { synchronized (monitor) {
monitor.notifyAll(); monitor.notifyAll();
} }
}
} }
public static final SyncMessageCallback DEFAULT_REFRESH_RUNNABLE = new SyncMessageCallback() { public static final SyncMessageCallback DEFAULT_REFRESH_RUNNABLE = new SyncMessageCallback() {
@ -260,8 +264,9 @@ public class ActFmSyncThread {
monitor.wait(); 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?) 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); syncMigration = Preferences.getBoolean(AstridNewSyncMigrator.PREF_SYNC_MIGRATION, false);
}
} catch (InterruptedException e) { } catch (InterruptedException e) {
// Ignored // Ignored
} }
@ -281,8 +286,9 @@ public class ActFmSyncThread {
while (messageBatch.size() < batchSize && !pendingMessages.isEmpty()) { while (messageBatch.size() < batchSize && !pendingMessages.isEmpty()) {
ClientToServerMessage<?> message = pendingMessages.remove(0); ClientToServerMessage<?> message = pendingMessages.remove(0);
if (message != null) if (message != null) {
messageBatch.add(message); messageBatch.add(message);
}
} }
if (!messageBatch.isEmpty() && checkForToken()) { if (!messageBatch.isEmpty() && checkForToken()) {
@ -293,8 +299,9 @@ public class ActFmSyncThread {
ClientToServerMessage<?> message = messageBatch.get(i); ClientToServerMessage<?> message = messageBatch.get(i);
boolean success = payload.addMessage(message, entity); boolean success = payload.addMessage(message, entity);
if (success) { if (success) {
if (message instanceof ChangesHappened) if (message instanceof ChangesHappened) {
containsChangesHappened = true; containsChangesHappened = true;
}
} else { } else {
messageBatch.remove(i); messageBatch.remove(i);
i--; i--;
@ -355,10 +362,11 @@ public class ActFmSyncThread {
SyncMessageCallback r = pendingCallbacks.remove(message); SyncMessageCallback r = pendingCallbacks.remove(message);
if (r != null && !callbacksExecutedThisLoop.contains(r)) { if (r != null && !callbacksExecutedThisLoop.contains(r)) {
List<JSONArray> errorList = errorMap.get(i); List<JSONArray> errorList = errorMap.get(i);
if (errorList == null || errorList.isEmpty()) if (errorList == null || errorList.isEmpty()) {
r.runOnSuccess(); r.runOnSuccess();
else } else {
r.runOnErrors(errorList); r.runOnErrors(errorList);
}
callbacksExecutedThisLoop.add(r); callbacksExecutedThisLoop.add(r);
} }
@ -498,15 +506,17 @@ public class ActFmSyncThread {
} }
private boolean checkForToken() { private boolean checkForToken() {
if(!actFmPreferenceService.isLoggedIn()) if(!actFmPreferenceService.isLoggedIn()) {
return false; return false;
}
token = actFmPreferenceService.getToken(); token = actFmPreferenceService.getToken();
return true; return true;
} }
public static void syncLog(String message) { public static void syncLog(String message) {
if (ActFmInvoker.SYNC_DEBUG) if (ActFmInvoker.SYNC_DEBUG) {
Log.e(ERROR_TAG, message); Log.e(ERROR_TAG, message);
}
} }
public static class NetworkStateChangedReceiver extends BroadcastReceiver { public static class NetworkStateChangedReceiver extends BroadcastReceiver {

@ -121,20 +121,27 @@ public class ActFmSyncV2Provider extends SyncV2Provider {
try { try {
JSONObject status = actFmSyncService.invoke("user_status"); //$NON-NLS-1$ 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"))); 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")); 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")); 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")); 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")); Preferences.setBoolean(ActFmPreferenceService.PREF_PREMIUM, status.optBoolean("premium"));
if (status.has("email")) }
if (status.has("email")) {
Preferences.setString(ActFmPreferenceService.PREF_EMAIL, status.optString("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")); Preferences.setString(ActFmPreferenceService.PREF_PICTURE, status.optString("picture"));
}
ActFmPreferenceService.reloadThisUser(); ActFmPreferenceService.reloadThisUser();
} catch (IOException e) { } catch (IOException e) {

@ -31,8 +31,9 @@ public class ActFmSyncWaitingPool {
private final Runnable delayMessageRunnable = new Runnable() { private final Runnable delayMessageRunnable = new Runnable() {
@Override @Override
public void run() { public void run() {
if (pendingMessages.isEmpty()) if (pendingMessages.isEmpty()) {
return; return;
}
AndroidUtilities.sleepDeep(WAIT_TIME); AndroidUtilities.sleepDeep(WAIT_TIME);
while (!pendingMessages.isEmpty()) { while (!pendingMessages.isEmpty()) {
ActFmSyncThread.getInstance().enqueueMessage(pendingMessages.remove(0), ActFmSyncThread.DEFAULT_REFRESH_RUNNABLE); ActFmSyncThread.getInstance().enqueueMessage(pendingMessages.remove(0), ActFmSyncThread.DEFAULT_REFRESH_RUNNABLE);

@ -78,8 +78,9 @@ public class AstridNewSyncMigrator {
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void performMigration() { public void performMigration() {
if (Preferences.getBoolean(PREF_SYNC_MIGRATION, false)) if (Preferences.getBoolean(PREF_SYNC_MIGRATION, false)) {
return; return;
}
// -------------- // --------------
// First ensure that a TagData object exists for each tag metadata // First ensure that a TagData object exists for each tag metadata
@ -100,8 +101,9 @@ public class AstridNewSyncMigrator {
tag.clear(); tag.clear();
tag.readFromCursor(noTagData); tag.readFromCursor(noTagData);
if (ActFmInvoker.SYNC_DEBUG) if (ActFmInvoker.SYNC_DEBUG) {
Log.w(LOG_TAG, "CREATING TAG DATA " + tag.getValue(TaskToTagMetadata.TAG_NAME)); Log.w(LOG_TAG, "CREATING TAG DATA " + tag.getValue(TaskToTagMetadata.TAG_NAME));
}
newTagData.setValue(TagData.NAME, tag.getValue(TaskToTagMetadata.TAG_NAME)); newTagData.setValue(TagData.NAME, tag.getValue(TaskToTagMetadata.TAG_NAME));
tagDataService.save(newTagData); tagDataService.save(newTagData);
@ -114,8 +116,9 @@ public class AstridNewSyncMigrator {
Log.e(LOG_TAG, "Error creating tag data", e); Log.e(LOG_TAG, "Error creating tag data", e);
Crittercism.logHandledException(e); Crittercism.logHandledException(e);
} finally { } finally {
if (noTagData != null) if (noTagData != null) {
noTagData.close(); noTagData.close();
}
} }
// -------------- // --------------
@ -131,8 +134,9 @@ public class AstridNewSyncMigrator {
td.readFromCursor(emergentTags); td.readFromCursor(emergentTags);
String name = td.getValue(TagData.NAME); String name = td.getValue(TagData.NAME);
tagDataDao.delete(td.getId()); 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))); metadataService.deleteWhere(Criterion.and(MetadataCriteria.withKey(TaskToTagMetadata.KEY), TaskToTagMetadata.TAG_NAME.eq(name)));
}
} catch (Exception e) { } catch (Exception e) {
Log.e(LOG_TAG, "Error clearing emergent tags"); Log.e(LOG_TAG, "Error clearing emergent tags");
Crittercism.logHandledException(e); Crittercism.logHandledException(e);
@ -141,8 +145,9 @@ public class AstridNewSyncMigrator {
} catch (Exception e){ } catch (Exception e){
Crittercism.logHandledException(e); Crittercism.logHandledException(e);
} finally { } finally {
if (emergentTags != null) if (emergentTags != null) {
emergentTags.close(); 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>() { assertUUIDsExist(tasksQuery, new Task(), taskDao, taskOutstandingDao, new TaskOutstanding(), NameMaps.syncableProperties(NameMaps.TABLE_ID_TASKS), new UUIDAssertionExtras<Task>() {
@Override @Override
public boolean shouldCreateOutstandingEntries(Task instance) { 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 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); return (instance.getValue(Task.LAST_SYNC) < instance.getValue(Task.MODIFICATION_DATE)) && RemoteModelDao.getOutstandingEntryFlag(RemoteModelDao.OUTSTANDING_ENTRY_FLAG_RECORD_OUTSTANDING);
} }
@Override @Override
public void afterSave(Task instance, boolean createdOutstanding) { public void afterSave(Task instance, boolean createdOutstanding) {
if (createdOutstanding) if (createdOutstanding) {
tasksThatNeedTagSync.add(instance.getId()); tasksThatNeedTagSync.add(instance.getId());
}
} }
}); });
} catch (Exception e) { } catch (Exception e) {
@ -220,10 +227,11 @@ public class AstridNewSyncMigrator {
template.setFlag(Task.FLAGS, Task.FLAG_REPEAT_AFTER_COMPLETION, false); template.setFlag(Task.FLAGS, Task.FLAG_REPEAT_AFTER_COMPLETION, false);
recurrence = recurrence.replaceAll("BYDAY=;", ""); recurrence = recurrence.replaceAll("BYDAY=;", "");
if (fromCompletion.equals(recurrence)) if (fromCompletion.equals(recurrence)) {
recurrence = ""; recurrence = "";
else if (repeatAfterCompletion) } else if (repeatAfterCompletion) {
recurrence = recurrence + fromCompletion; recurrence = recurrence + fromCompletion;
}
template.setValue(Task.RECURRENCE, recurrence); template.setValue(Task.RECURRENCE, recurrence);
template.putTransitory(SyncFlags.GTASKS_SUPPRESS_SYNC, true); template.putTransitory(SyncFlags.GTASKS_SUPPRESS_SYNC, true);
@ -238,8 +246,9 @@ public class AstridNewSyncMigrator {
Log.e(LOG_TAG, "Error migrating recurrence", e); Log.e(LOG_TAG, "Error migrating recurrence", e);
Crittercism.logHandledException(e); Crittercism.logHandledException(e);
} finally { } finally {
if (tasksWithRecurrence != null) if (tasksWithRecurrence != null) {
tasksWithRecurrence.close(); tasksWithRecurrence.close();
}
} }
// -------------- // --------------
@ -264,10 +273,11 @@ public class AstridNewSyncMigrator {
userActivity.setValue(UserActivity.TARGET_ID, update.getValue(Update.TASK).toString()); userActivity.setValue(UserActivity.TARGET_ID, update.getValue(Update.TASK).toString());
} else if (update.getValue(Update.TASK_LOCAL) > 0) { } else if (update.getValue(Update.TASK_LOCAL) > 0) {
Task local = taskDao.fetch(update.getValue(Update.TASK_LOCAL), Task.UUID); 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()); userActivity.setValue(UserActivity.TARGET_ID, local.getUuid());
else } else {
setTarget = false; setTarget = false;
}
} else { } else {
setTarget = false; setTarget = false;
} }
@ -289,8 +299,9 @@ public class AstridNewSyncMigrator {
Log.e(LOG_TAG, "Error migrating updates", e); Log.e(LOG_TAG, "Error migrating updates", e);
Crittercism.logHandledException(e); Crittercism.logHandledException(e);
} finally { } finally {
if (updates != null) if (updates != null) {
updates.close(); updates.close();
}
} }
@ -321,8 +332,9 @@ public class AstridNewSyncMigrator {
m.readFromCursor(fmCursor); m.readFromCursor(fmCursor);
Task task = taskDao.fetch(m.getValue(Metadata.TASK), Task.UUID); 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; continue;
}
Long oldRemoteId = m.getValue(FileMetadata.REMOTE_ID); Long oldRemoteId = m.getValue(FileMetadata.REMOTE_ID);
boolean synced = false; boolean synced = false;
@ -331,23 +343,29 @@ public class AstridNewSyncMigrator {
attachment.setValue(TaskAttachment.UUID, Long.toString(oldRemoteId)); attachment.setValue(TaskAttachment.UUID, Long.toString(oldRemoteId));
} }
attachment.setValue(TaskAttachment.TASK_UUID, task.getUuid()); 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)); 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)); 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)); 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)); 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)); attachment.setValue(TaskAttachment.DELETED_AT, m.getValue(FileMetadata.DELETION_DATE));
}
if (synced) { if (synced) {
attachment.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true); attachment.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true);
} }
if (!ActFmPreferenceService.isPremiumUser()) if (!ActFmPreferenceService.isPremiumUser()) {
attachment.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true); attachment.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true);
}
taskAttachmentDao.createNew(attachment); taskAttachmentDao.createNew(attachment);
} catch (Exception e) { } catch (Exception e) {
Log.e(LOG_TAG, "Error migrating task attachment metadata", 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); Log.e(LOG_TAG, "Error migrating task attachment metadata", e);
Crittercism.logHandledException(e); Crittercism.logHandledException(e);
} finally { } finally {
if (fmCursor != null) if (fmCursor != null) {
fmCursor.close(); fmCursor.close();
}
} }
// -------------- // --------------
@ -369,8 +388,9 @@ public class AstridNewSyncMigrator {
TaskListMetadata tlm = new TaskListMetadata(); TaskListMetadata tlm = new TaskListMetadata();
try { try {
String activeTasksOrder = Preferences.getStringValue(SubtasksUpdater.ACTIVE_TASKS_ORDER); String activeTasksOrder = Preferences.getStringValue(SubtasksUpdater.ACTIVE_TASKS_ORDER);
if (TextUtils.isEmpty(activeTasksOrder)) if (TextUtils.isEmpty(activeTasksOrder)) {
activeTasksOrder = "[]"; activeTasksOrder = "[]";
}
activeTasksOrder = SubtasksHelper.convertTreeToRemoteIds(activeTasksOrder); activeTasksOrder = SubtasksHelper.convertTreeToRemoteIds(activeTasksOrder);
@ -387,8 +407,9 @@ public class AstridNewSyncMigrator {
try { try {
tlm.clear(); tlm.clear();
String todayTasksOrder = Preferences.getStringValue(SubtasksUpdater.TODAY_TASKS_ORDER); String todayTasksOrder = Preferences.getStringValue(SubtasksUpdater.TODAY_TASKS_ORDER);
if (TextUtils.isEmpty(todayTasksOrder)) if (TextUtils.isEmpty(todayTasksOrder)) {
todayTasksOrder = "[]"; todayTasksOrder = "[]";
}
todayTasksOrder = SubtasksHelper.convertTreeToRemoteIds(todayTasksOrder); todayTasksOrder = SubtasksHelper.convertTreeToRemoteIds(todayTasksOrder);
@ -427,8 +448,9 @@ public class AstridNewSyncMigrator {
Log.e(LOG_TAG, "Error migrating tag ordering", e); Log.e(LOG_TAG, "Error migrating tag ordering", e);
Crittercism.logHandledException(e); Crittercism.logHandledException(e);
} finally { } finally {
if (allTagData != null) if (allTagData != null) {
allTagData.close(); allTagData.close();
}
} }
// -------------- // --------------
@ -447,23 +469,27 @@ public class AstridNewSyncMigrator {
m.clear(); // Need this since some properties may be null m.clear(); // Need this since some properties may be null
m.readFromCursor(incompleteMetadata); 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)); 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 (!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"); Log.w(LOG_TAG, "No task uuid");
}
updateTaskUuid(m); updateTaskUuid(m);
} }
if (!m.containsNonNullValue(TaskToTagMetadata.TAG_UUID) || RemoteModel.isUuidEmpty(m.getValue(TaskToTagMetadata.TAG_UUID))) { 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"); Log.w(LOG_TAG, "No tag uuid");
}
updateTagUuid(m); updateTagUuid(m);
} }
if (m.getSetValues() != null && m.getSetValues().size() > 0) if (m.getSetValues() != null && m.getSetValues().size() > 0) {
metadataService.save(m); metadataService.save(m);
}
} catch (Exception e) { } catch (Exception e) {
Log.e(LOG_TAG, "Error validating task to tag metadata", 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); Log.e(LOG_TAG, "Error validating task to tag metadata", e);
Crittercism.logHandledException(e); Crittercism.logHandledException(e);
} finally { } finally {
if (incompleteMetadata != null) if (incompleteMetadata != null) {
incompleteMetadata.close(); incompleteMetadata.close();
}
} }
// -------------- // --------------
@ -505,15 +532,17 @@ public class AstridNewSyncMigrator {
m.readFromCursor(tagsAdded); m.readFromCursor(tagsAdded);
Long deletionDate = m.getValue(Metadata.DELETION_DATE); Long deletionDate = m.getValue(Metadata.DELETION_DATE);
String tagUuid = m.getValue(TaskToTagMetadata.TAG_UUID); String tagUuid = m.getValue(TaskToTagMetadata.TAG_UUID);
if (!RemoteModel.isValidUuid(tagUuid)) if (!RemoteModel.isValidUuid(tagUuid)) {
continue; continue;
}
TaskOutstanding to = new TaskOutstanding(); TaskOutstanding to = new TaskOutstanding();
to.setValue(OutstandingEntry.ENTITY_ID_PROPERTY, m.getValue(Metadata.TASK)); to.setValue(OutstandingEntry.ENTITY_ID_PROPERTY, m.getValue(Metadata.TASK));
to.setValue(OutstandingEntry.CREATED_AT_PROPERTY, DateUtilities.now()); to.setValue(OutstandingEntry.CREATED_AT_PROPERTY, DateUtilities.now());
String addedOrRemoved = NameMaps.TAG_ADDED_COLUMN; String addedOrRemoved = NameMaps.TAG_ADDED_COLUMN;
if (deletionDate != null && deletionDate > 0) if (deletionDate != null && deletionDate > 0) {
addedOrRemoved = NameMaps.TAG_REMOVED_COLUMN; addedOrRemoved = NameMaps.TAG_REMOVED_COLUMN;
}
to.setValue(OutstandingEntry.COLUMN_STRING_PROPERTY, addedOrRemoved); to.setValue(OutstandingEntry.COLUMN_STRING_PROPERTY, addedOrRemoved);
to.setValue(OutstandingEntry.VALUE_STRING_PROPERTY, tagUuid); 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); Log.e(LOG_TAG, "Error creating tag_added outstanding entries", e);
Crittercism.logHandledException(e); Crittercism.logHandledException(e);
} finally { } finally {
if (tagsAdded != null) if (tagsAdded != null) {
tagsAdded.close(); tagsAdded.close();
}
} }
Preferences.setBoolean(PREF_SYNC_MIGRATION, true); Preferences.setBoolean(PREF_SYNC_MIGRATION, true);
@ -567,8 +597,9 @@ public class AstridNewSyncMigrator {
createdOutstanding = true; createdOutstanding = true;
createOutstandingEntries(instance.getId(), dao, oeDao, oe, propertiesForOutstanding); createOutstandingEntries(instance.getId(), dao, oeDao, oe, propertiesForOutstanding);
} }
if (extras != null) if (extras != null) {
extras.afterSave(instance, createdOutstanding); extras.afterSave(instance, createdOutstanding);
}
} catch (Exception e) { } catch (Exception e) {
Log.e(LOG_TAG, "Error asserting UUIDs", e); Log.e(LOG_TAG, "Error asserting UUIDs", e);
Crittercism.logHandledException(e); Crittercism.logHandledException(e);
@ -578,8 +609,9 @@ public class AstridNewSyncMigrator {
Log.e(LOG_TAG, "Error asserting UUIDs", e); Log.e(LOG_TAG, "Error asserting UUIDs", e);
Crittercism.logHandledException(e); Crittercism.logHandledException(e);
} finally { } finally {
if (cursor != null) if (cursor != null) {
cursor.close(); cursor.close();
}
} }
} }
@ -591,8 +623,9 @@ public class AstridNewSyncMigrator {
oe.setValue(OutstandingEntry.ENTITY_ID_PROPERTY, id); oe.setValue(OutstandingEntry.ENTITY_ID_PROPERTY, id);
oe.setValue(OutstandingEntry.COLUMN_STRING_PROPERTY, property.name); oe.setValue(OutstandingEntry.COLUMN_STRING_PROPERTY, property.name);
Object value = instance.getValue(property); Object value = instance.getValue(property);
if (value == null) if (value == null) {
value = ""; value = "";
}
oe.setValue(OutstandingEntry.VALUE_STRING_PROPERTY, value.toString()); oe.setValue(OutstandingEntry.VALUE_STRING_PROPERTY, value.toString());
oe.setValue(OutstandingEntry.CREATED_AT_PROPERTY, now); oe.setValue(OutstandingEntry.CREATED_AT_PROPERTY, now);
oeDao.createNew(oe); oeDao.createNew(oe);
@ -603,12 +636,14 @@ public class AstridNewSyncMigrator {
long taskId = m.getValue(Metadata.TASK); long taskId = m.getValue(Metadata.TASK);
Task task = taskDao.fetch(taskId, Task.UUID); Task task = taskDao.fetch(taskId, Task.UUID);
if (task != null) { if (task != null) {
if (ActFmInvoker.SYNC_DEBUG) if (ActFmInvoker.SYNC_DEBUG) {
Log.w(LOG_TAG, "Linking with task uuid " + task.getValue(Task.UUID)); Log.w(LOG_TAG, "Linking with task uuid " + task.getValue(Task.UUID));
}
m.setValue(TaskToTagMetadata.TASK_UUID, task.getValue(Task.UUID)); m.setValue(TaskToTagMetadata.TASK_UUID, task.getValue(Task.UUID));
} else { } else {
if (ActFmInvoker.SYNC_DEBUG) if (ActFmInvoker.SYNC_DEBUG) {
Log.w(LOG_TAG, "Task not found, deleting link"); Log.w(LOG_TAG, "Task not found, deleting link");
}
m.setValue(Metadata.DELETION_DATE, DateUtilities.now()); m.setValue(Metadata.DELETION_DATE, DateUtilities.now());
} }
} }
@ -617,12 +652,14 @@ public class AstridNewSyncMigrator {
String tag = m.getValue(TaskToTagMetadata.TAG_NAME); String tag = m.getValue(TaskToTagMetadata.TAG_NAME);
TagData tagData = tagDataService.getTagByName(tag, TagData.UUID); TagData tagData = tagDataService.getTagByName(tag, TagData.UUID);
if (tagData != null) { if (tagData != null) {
if (ActFmInvoker.SYNC_DEBUG) if (ActFmInvoker.SYNC_DEBUG) {
Log.w(LOG_TAG, "Linking with tag uuid " + tagData.getValue(TagData.UUID)); Log.w(LOG_TAG, "Linking with tag uuid " + tagData.getValue(TagData.UUID));
}
m.setValue(TaskToTagMetadata.TAG_UUID, tagData.getValue(TagData.UUID)); m.setValue(TaskToTagMetadata.TAG_UUID, tagData.getValue(TagData.UUID));
} else { } else {
if (ActFmInvoker.SYNC_DEBUG) if (ActFmInvoker.SYNC_DEBUG) {
Log.w(LOG_TAG, "Tag not found, deleting link"); Log.w(LOG_TAG, "Tag not found, deleting link");
}
m.setValue(Metadata.DELETION_DATE, DateUtilities.now()); m.setValue(Metadata.DELETION_DATE, DateUtilities.now());
} }
} }

@ -67,8 +67,9 @@ public class EmptyTitleOutstandingEntryMigration {
} catch (Exception e) { } catch (Exception e) {
Log.e(ERROR_TAG, "Unhandled exception", e); //$NON-NLS-1$ Log.e(ERROR_TAG, "Unhandled exception", e); //$NON-NLS-1$
} finally { } finally {
if (outstandingWithTitle != null) if (outstandingWithTitle != null) {
outstandingWithTitle.close(); outstandingWithTitle.close();
}
} }
} }

@ -22,8 +22,9 @@ public class SyncUpgradePrompt {
private static long lastPromptDate = -1; private static long lastPromptDate = -1;
public static void showSyncUpgradePrompt(final Activity activity) { public static void showSyncUpgradePrompt(final Activity activity) {
if (lastPromptDate == -1) if (lastPromptDate == -1) {
lastPromptDate = Preferences.getLong(P_SYNC_UPGRADE_PROMPT, 0L); lastPromptDate = Preferences.getLong(P_SYNC_UPGRADE_PROMPT, 0L);
}
Dialog d = null; Dialog d = null;
if (DateUtilities.now() - lastPromptDate > DateUtilities.ONE_WEEK * 3) { if (DateUtilities.now() - lastPromptDate > DateUtilities.ONE_WEEK * 3) {
@ -69,8 +70,9 @@ public class SyncUpgradePrompt {
} }
} }
if (d != null) if (d != null) {
d.show(); d.show();
}
} }
private static void setLastPromptDate(long date) { private static void setLastPromptDate(long date) {
@ -103,8 +105,9 @@ public class SyncUpgradePrompt {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
d.dismiss(); d.dismiss();
if (listener1 != null) if (listener1 != null) {
listener1.run(); listener1.run();
}
} }
}); });
b1.setBackgroundColor(activity.getResources().getColor(tv.data)); b1.setBackgroundColor(activity.getResources().getColor(tv.data));
@ -120,8 +123,9 @@ public class SyncUpgradePrompt {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
d.dismiss(); d.dismiss();
if (listener2 != null) if (listener2 != null) {
listener2.run(); listener2.run();
}
} }
}); });
b2.setBackgroundColor(activity.getResources().getColor(tv.data)); b2.setBackgroundColor(activity.getResources().getColor(tv.data));

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

@ -21,20 +21,21 @@ public class AcknowledgeChange extends ServerToClientMessage {
public AcknowledgeChange(JSONObject json) { public AcknowledgeChange(JSONObject json) {
super(json); super(json);
String table = json.optString("table"); //$NON-NLS-1$ 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(); dao = PluginServices.getTaskOutstandingDao();
else if (NameMaps.TABLE_ID_TAGS.equals(table)) } else if (NameMaps.TABLE_ID_TAGS.equals(table)) {
dao = PluginServices.getTagOutstandingDao(); dao = PluginServices.getTagOutstandingDao();
else if (NameMaps.TABLE_ID_USER_ACTIVITY.equals(table)) } else if (NameMaps.TABLE_ID_USER_ACTIVITY.equals(table)) {
dao = PluginServices.getUserActivityOutstandingDao(); dao = PluginServices.getUserActivityOutstandingDao();
else if (NameMaps.TABLE_ID_ATTACHMENTS.equals(table)) } else if (NameMaps.TABLE_ID_ATTACHMENTS.equals(table)) {
dao = PluginServices.getTaskAttachmentOutstandingDao(); 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(); 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(); dao = PluginServices.getWaitingOnMeOutstandingDao();
else } else {
dao = null; dao = null;
}
} }
@Override @Override
@ -45,8 +46,9 @@ public class AcknowledgeChange extends ServerToClientMessage {
for (int i = 0; i < idsArray.length(); i++) { for (int i = 0; i < idsArray.length(); i++) {
try { try {
Long id = idsArray.getLong(i); Long id = idsArray.getLong(i);
if (id <= 0) if (id <= 0) {
continue; continue;
}
idsList.add(id); idsList.add(id);
} catch (JSONException e) { } catch (JSONException e) {

@ -86,15 +86,18 @@ public class ChangesHappened<TYPE extends RemoteModel, OE extends OutstandingEnt
this.changes = new ArrayList<OE>(); this.changes = new ArrayList<OE>();
if (!foundEntity) // Stop sending changes for entities that don't exist anymore if (!foundEntity) // Stop sending changes for entities that don't exist anymore
{
outstandingDao.deleteWhere(OutstandingEntry.ENTITY_ID_PROPERTY.eq(id)); outstandingDao.deleteWhere(OutstandingEntry.ENTITY_ID_PROPERTY.eq(id));
}
} }
@Override @Override
protected boolean serializeExtrasToJSON(JSONObject serializeTo, MultipartEntity entity) throws JSONException { protected boolean serializeExtrasToJSON(JSONObject serializeTo, MultipartEntity entity) throws JSONException {
// Process changes list and serialize to JSON // Process changes list and serialize to JSON
JSONArray changesJson = changesToJSON(entity); JSONArray changesJson = changesToJSON(entity);
if (changesJson == null || changesJson.length() == 0) if (changesJson == null || changesJson.length() == 0) {
return false; return false;
}
serializeTo.put(CHANGES_KEY, changesJson); serializeTo.put(CHANGES_KEY, changesJson);
return true; return true;
} }
@ -109,8 +112,9 @@ public class ChangesHappened<TYPE extends RemoteModel, OE extends OutstandingEnt
} }
private JSONArray changesToJSON(MultipartEntity entity) { private JSONArray changesToJSON(MultipartEntity entity) {
if (!RemoteModel.NO_UUID.equals(uuid)) if (!RemoteModel.NO_UUID.equals(uuid)) {
populateChanges(); populateChanges();
}
JSONArray array = new JSONArray(); JSONArray array = new JSONArray();
AtomicInteger uploadCounter = new AtomicInteger(); AtomicInteger uploadCounter = new AtomicInteger();
@ -145,25 +149,29 @@ public class ChangesHappened<TYPE extends RemoteModel, OE extends OutstandingEnt
changeJson.put("value", name); changeJson.put("value", name);
} else { } else {
Property<?> localProperty = NameMaps.localColumnNameToProperty(table, localColumn); 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); throw new RuntimeException("No local property found for local column " + localColumn + " in table " + table);
}
serverColumn = NameMaps.localColumnNameToServerColumnName(table, localColumn); 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); throw new RuntimeException("No server column found for local column " + localColumn + " in table " + table);
}
Object value = localProperty.accept(visitor, change); Object value = localProperty.accept(visitor, change);
if (!validateValue(localProperty, value)) if (!validateValue(localProperty, value)) {
return null; return null;
}
if (value == null) if (value == null) {
changeJson.put("value", JSONObject.NULL); changeJson.put("value", JSONObject.NULL);
else { } else {
if (localProperty.checkFlag(Property.PROP_FLAG_PICTURE) && value instanceof JSONObject) { if (localProperty.checkFlag(Property.PROP_FLAG_PICTURE) && value instanceof JSONObject) {
JSONObject json = (JSONObject) value; JSONObject json = (JSONObject) value;
String name = addToEntityFromFileJson(entity, json, uploadCounter); String name = addToEntityFromFileJson(entity, json, uploadCounter);
if (name != null) if (name != null) {
changeJson.put("value", name); changeJson.put("value", name);
}
} else { } else {
changeJson.put("value", value); changeJson.put("value", value);
} }
@ -223,8 +231,9 @@ public class ChangesHappened<TYPE extends RemoteModel, OE extends OutstandingEnt
// (e.g. empty task title, etc.) // (e.g. empty task title, etc.)
private boolean validateValue(Property<?> property, Object value) { private boolean validateValue(Property<?> property, Object value) {
if (Task.TITLE.equals(property)) { if (Task.TITLE.equals(property)) {
if (!(value instanceof String) || TextUtils.isEmpty((String) value)) if (!(value instanceof String) || TextUtils.isEmpty((String) value)) {
return false; return false;
}
} }
return true; return true;
} }
@ -233,11 +242,13 @@ public class ChangesHappened<TYPE extends RemoteModel, OE extends OutstandingEnt
try { try {
JSONObject obj = new JSONObject(value); JSONObject obj = new JSONObject(value);
String path = obj.optString("path"); String path = obj.optString("path");
if (TextUtils.isEmpty(path)) if (TextUtils.isEmpty(path)) {
return null; return null;
}
File f = new File(path); File f = new File(path);
if (!f.exists()) if (!f.exists()) {
return null; return null;
}
return obj; return obj;
} catch (JSONException e) { } catch (JSONException e) {
@ -255,8 +266,9 @@ public class ChangesHappened<TYPE extends RemoteModel, OE extends OutstandingEnt
public Object visitInteger(Property<Integer> property, OE data) { public Object visitInteger(Property<Integer> property, OE data) {
Integer i = data.getMergedValues().getAsInteger(OutstandingEntry.VALUE_STRING_PROPERTY.name); Integer i = data.getMergedValues().getAsInteger(OutstandingEntry.VALUE_STRING_PROPERTY.name);
if (i != null) { if (i != null) {
if (property.checkFlag(Property.PROP_FLAG_BOOLEAN)) if (property.checkFlag(Property.PROP_FLAG_BOOLEAN)) {
return i > 0; return i > 0;
}
return i; return i;
} else { } else {
return getAsString(data); return getAsString(data);
@ -269,8 +281,9 @@ public class ChangesHappened<TYPE extends RemoteModel, OE extends OutstandingEnt
if (l != null) { if (l != null) {
if (property.checkFlag(Property.PROP_FLAG_DATE)) { if (property.checkFlag(Property.PROP_FLAG_DATE)) {
boolean includeTime = true; boolean includeTime = true;
if (Task.DUE_DATE.equals(property) && !Task.hasDueTime(l)) if (Task.DUE_DATE.equals(property) && !Task.hasDueTime(l)) {
includeTime = false; includeTime = false;
}
return DateUtilities.timeToIso8601(l, includeTime); return DateUtilities.timeToIso8601(l, includeTime);
} }
return l; return l;
@ -292,16 +305,19 @@ public class ChangesHappened<TYPE extends RemoteModel, OE extends OutstandingEnt
@Override @Override
public Object visitString(Property<String> property, OE data) { public Object visitString(Property<String> property, OE data) {
String value = getAsString(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(); return ActFmPreferenceService.userId();
}
if (property.checkFlag(Property.PROP_FLAG_JSON)) { if (property.checkFlag(Property.PROP_FLAG_JSON)) {
if (TextUtils.isEmpty(value)) if (TextUtils.isEmpty(value)) {
return null; return null;
}
try { try {
if (value != null && value.startsWith("[")) if (value != null && value.startsWith("[")) {
return new JSONArray(value); return new JSONArray(value);
else } else {
return new JSONObject(value); return new JSONObject(value);
}
} catch (JSONException e) { } catch (JSONException e) {
return null; return null;
} }

@ -74,10 +74,11 @@ public abstract class ClientToServerMessage<TYPE extends RemoteModel> {
json.put(UUID_KEY, uuid); json.put(UUID_KEY, uuid);
String dateValue = DateUtilities.timeToIso8601(pushedAt, true); String dateValue = DateUtilities.timeToIso8601(pushedAt, true);
json.put(PUSHED_AT_KEY, dateValue != null ? dateValue : 0); json.put(PUSHED_AT_KEY, dateValue != null ? dateValue : 0);
if (serializeExtrasToJSON(json, entity)) if (serializeExtrasToJSON(json, entity)) {
return json; return json;
else } else {
return null; return null;
}
} catch (JSONException e) { } catch (JSONException e) {
Crittercism.logHandledException(e); Crittercism.logHandledException(e);
return null; return null;
@ -95,23 +96,30 @@ public abstract class ClientToServerMessage<TYPE extends RemoteModel> {
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) if (this == obj) {
return true; return true;
if (obj == null) }
if (obj == null) {
return false; return false;
if (getClass() != obj.getClass()) }
if (getClass() != obj.getClass()) {
return false; return false;
}
ClientToServerMessage<?> other = (ClientToServerMessage<?>) obj; ClientToServerMessage<?> other = (ClientToServerMessage<?>) obj;
if (table == null) { if (table == null) {
if (other.table != null) if (other.table != null) {
return false; return false;
} else if (!table.equals(other.table)) }
} else if (!table.equals(other.table)) {
return false; return false;
}
if (uuid == null) { if (uuid == null) {
if (other.uuid != null) if (other.uuid != null) {
return false; return false;
} else if (!uuid.equals(other.uuid)) }
} else if (!uuid.equals(other.uuid)) {
return false; return false;
}
return true; return true;
} }

@ -46,18 +46,20 @@ public class ConstructOutstandingTableFromMasterTable<TYPE extends RemoteModel,
OE oe = outstandingDao.getModelClass().newInstance(); OE oe = outstandingDao.getModelClass().newInstance();
for (items.moveToFirst(); !items.isAfterLast(); items.moveToNext()) { for (items.moveToFirst(); !items.isAfterLast(); items.moveToNext()) {
long createdAt; long createdAt;
if (createdAtProperty != null) if (createdAtProperty != null) {
createdAt = items.get(createdAtProperty); createdAt = items.get(createdAtProperty);
else } else {
createdAt = DateUtilities.now(); createdAt = DateUtilities.now();
}
long itemId = items.get(AbstractModel.ID_PROPERTY); long itemId = items.get(AbstractModel.ID_PROPERTY);
for (Property<?> p : syncableProperties) { for (Property<?> p : syncableProperties) {
oe.clear(); oe.clear();
oe.setValue(OutstandingEntry.ENTITY_ID_PROPERTY, itemId); oe.setValue(OutstandingEntry.ENTITY_ID_PROPERTY, itemId);
oe.setValue(OutstandingEntry.COLUMN_STRING_PROPERTY, p.name); oe.setValue(OutstandingEntry.COLUMN_STRING_PROPERTY, p.name);
Object value = items.get(p); Object value = items.get(p);
if (value == null) if (value == null) {
continue; continue;
}
oe.setValue(OutstandingEntry.VALUE_STRING_PROPERTY, value.toString()); oe.setValue(OutstandingEntry.VALUE_STRING_PROPERTY, value.toString());
oe.setValue(OutstandingEntry.CREATED_AT_PROPERTY, createdAt); oe.setValue(OutstandingEntry.CREATED_AT_PROPERTY, createdAt);

@ -15,8 +15,9 @@ public class Debug extends ServerToClientMessage {
@SuppressWarnings("nls") @SuppressWarnings("nls")
public void processMessage(String serverTime) { public void processMessage(String serverTime) {
String message = json.optString("message"); String message = json.optString("message");
if (!TextUtils.isEmpty(message)) if (!TextUtils.isEmpty(message)) {
Log.w("actfm-debug-message", message); Log.w("actfm-debug-message", message);
}
} }
} }

@ -71,16 +71,18 @@ public class FetchHistory<TYPE extends RemoteModel> {
@Override @Override
public void run() { public void run() {
String token = actFmPreferenceService.getToken(); String token = actFmPreferenceService.getToken();
if (TextUtils.isEmpty(token) || TextUtils.isEmpty(uuid)) if (TextUtils.isEmpty(token) || TextUtils.isEmpty(uuid)) {
return; return;
}
ArrayList<Object> params = new ArrayList<Object>(); ArrayList<Object> params = new ArrayList<Object>();
if (NameMaps.TABLE_ID_TASKS.equals(table)) if (NameMaps.TABLE_ID_TASKS.equals(table)) {
params.add("task_id"); params.add("task_id");
else if (NameMaps.TABLE_ID_TAGS.equals(table)) } else if (NameMaps.TABLE_ID_TAGS.equals(table)) {
params.add("tag_id"); params.add("tag_id");
else } else {
return; return;
}
params.add(uuid); params.add(uuid);
@ -111,8 +113,9 @@ public class FetchHistory<TYPE extends RemoteModel> {
history.setValue(History.UUID, historyJson.optString("id") + ":" + uuid); history.setValue(History.UUID, historyJson.optString("id") + ":" + uuid);
String userId = historyJson.optString("user_id"); String userId = historyJson.optString("user_id");
if (userId.equals(ActFmPreferenceService.userId())) if (userId.equals(ActFmPreferenceService.userId())) {
userId = Task.USER_ID_SELF; userId = Task.USER_ID_SELF;
}
history.setValue(History.USER_UUID, historyJson.optString("user_id")); history.setValue(History.USER_UUID, historyJson.optString("user_id"));
history.setValue(History.COLUMN, historyJson.optString("column")); history.setValue(History.COLUMN, historyJson.optString("column"));
history.setValue(History.OLD_VALUE, historyJson.optString("prev")); history.setValue(History.OLD_VALUE, historyJson.optString("prev"));
@ -145,8 +148,9 @@ public class FetchHistory<TYPE extends RemoteModel> {
try { try {
template = dao.getModelClass().newInstance(); template = dao.getModelClass().newInstance();
template.setValue(historyTimeProperty, time); template.setValue(historyTimeProperty, time);
if (modifiedAfter == 0 || hasMore) if (modifiedAfter == 0 || hasMore) {
template.setValue(historyHasMoreProperty, hasMore ? 1 : 0); template.setValue(historyHasMoreProperty, hasMore ? 1 : 0);
}
dao.update(RemoteModel.UUID_PROPERTY.eq(uuid), template); dao.update(RemoteModel.UUID_PROPERTY.eq(uuid), template);
} catch (InstantiationException e) { } catch (InstantiationException e) {
Log.e(ERROR_TAG, "Error instantiating model for recording time", 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); JSONObject userObj = users.optJSONObject(key);
if (userObj != null) { if (userObj != null) {
String userUuid = userObj.optString("id"); String userUuid = userObj.optString("id");
if (RemoteModel.isUuidEmpty(uuid)) if (RemoteModel.isUuidEmpty(uuid)) {
continue; continue;
}
User user = new User(); User user = new User();
user.setValue(User.FIRST_NAME, userObj.optString("first_name")); 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); Log.e(ERROR_TAG, "Error getting model history", e);
} }
if (done != null) if (done != null) {
done.runOnSuccess(); done.runOnSuccess();
}
} }
}).start(); }).start();
} }

@ -87,19 +87,22 @@ public class JSONChangeToPropertyVisitor implements PropertyVisitor<Void, String
public Void visitString(Property<String> property, String key) { public Void visitString(Property<String> property, String key) {
try { try {
String value = data.getString(key); String value = data.getString(key);
if ("null".equals(value)) if ("null".equals(value)) {
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; 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(Task.USER, ""); // Clear this value for migration purposes
}
model.setValue((StringProperty) property, value); model.setValue((StringProperty) property, value);
} catch (JSONException e) { } catch (JSONException e) {
try { try {
JSONObject object = data.getJSONObject(key); JSONObject object = data.getJSONObject(key);
if (object != null) if (object != null) {
model.setValue((StringProperty) property, object.toString()); model.setValue((StringProperty) property, object.toString());
}
} catch (JSONException e2) { } catch (JSONException e2) {
Log.e(ERROR_TAG, "Error reading JSON value with key " + key + " from JSON " + data, e); 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() { public String closeAndReturnString() {
if (messageCount > 0) if (messageCount > 0) {
sb.deleteCharAt(sb.length() - 1); // Remove final comma sb.deleteCharAt(sb.length() - 1); // Remove final comma
}
sb.append("]"); //$NON-NLS-1$ sb.append("]"); //$NON-NLS-1$
return sb.toString(); 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) { private static <T extends RemoteModel> void saveOrUpdateModelAfterChanges(RemoteModelDao<T> dao, T model, String oldUuid, String uuid, String serverTime, Criterion orCriterion) {
Criterion uuidCriterion; Criterion uuidCriterion;
if (oldUuid == null) if (oldUuid == null) {
uuidCriterion = RemoteModel.UUID_PROPERTY.eq(uuid); uuidCriterion = RemoteModel.UUID_PROPERTY.eq(uuid);
else } else {
uuidCriterion = RemoteModel.UUID_PROPERTY.eq(oldUuid); uuidCriterion = RemoteModel.UUID_PROPERTY.eq(oldUuid);
}
if (orCriterion != null) if (orCriterion != null) {
uuidCriterion = Criterion.or(uuidCriterion, orCriterion); uuidCriterion = Criterion.or(uuidCriterion, orCriterion);
}
if (model.getSetValues() != null && model.getSetValues().size() > 0) { if (model.getSetValues() != null && model.getSetValues().size() > 0) {
long pushedAt; long pushedAt;
@ -87,8 +89,9 @@ public class MakeChanges<TYPE extends RemoteModel> extends ServerToClientMessage
pushedAt = 0; pushedAt = 0;
} }
if (pushedAt > 0) if (pushedAt > 0) {
model.setValue(RemoteModel.PUSHED_AT_PROPERTY, pushedAt); model.setValue(RemoteModel.PUSHED_AT_PROPERTY, pushedAt);
}
model.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true); model.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true);
if (dao.update(uuidCriterion, model) <= 0) { // If update doesn't update rows. create a new model 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); 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); model.setValue(uuidProperty, uuid);
}
saveOrUpdateModelAfterChanges(dao, model, oldUuid, uuid, serverTime, getMatchCriterion(model)); saveOrUpdateModelAfterChanges(dao, model, oldUuid, uuid, serverTime, getMatchCriterion(model));
afterSaveChanges(changes, model, uuid, oldUuid); afterSaveChanges(changes, model, uuid, oldUuid);
@ -133,36 +137,41 @@ public class MakeChanges<TYPE extends RemoteModel> extends ServerToClientMessage
private Criterion getMatchCriterion(TYPE model) { private Criterion getMatchCriterion(TYPE model) {
if (NameMaps.TABLE_ID_TASK_LIST_METADATA.equals(table)) { 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)); 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 TaskListMetadata.TAG_UUID.eq(model.getSetValues().getAsString(TaskListMetadata.TAG_UUID.name));
}
} }
return null; return null;
} }
private void beforeSaveChanges(JSONObject changes, TYPE model, String uuid) { private void beforeSaveChanges(JSONObject changes, TYPE model, String uuid) {
ChangeHooks beforeSaveChanges = null; ChangeHooks beforeSaveChanges = null;
if (NameMaps.TABLE_ID_TASKS.equals(table)) if (NameMaps.TABLE_ID_TASKS.equals(table)) {
beforeSaveChanges = new BeforeSaveTaskChanges(model, changes, uuid); 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); beforeSaveChanges = new BeforeSaveTagChanges(model, changes, uuid);
}
if (beforeSaveChanges != null) if (beforeSaveChanges != null) {
beforeSaveChanges.performChanges(); beforeSaveChanges.performChanges();
}
} }
private void afterSaveChanges(JSONObject changes, TYPE model, String uuid, String oldUuid) { private void afterSaveChanges(JSONObject changes, TYPE model, String uuid, String oldUuid) {
ChangeHooks afterSaveChanges = null; ChangeHooks afterSaveChanges = null;
if (NameMaps.TABLE_ID_TASKS.equals(table)) if (NameMaps.TABLE_ID_TASKS.equals(table)) {
afterSaveChanges = new AfterSaveTaskChanges(model, changes, uuid, oldUuid); 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); 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); afterSaveChanges = new AfterSaveUserChanges(model, changes, uuid);
}
if (afterSaveChanges != null) if (afterSaveChanges != null) {
afterSaveChanges.performChanges(); afterSaveChanges.performChanges();
}
} }
private abstract class ChangeHooks { private abstract class ChangeHooks {
@ -213,8 +222,9 @@ public class MakeChanges<TYPE extends RemoteModel> extends ServerToClientMessage
public void performChanges() { public void performChanges() {
JSONArray addMembers = changes.optJSONArray("member_added"); JSONArray addMembers = changes.optJSONArray("member_added");
boolean membersAdded = (addMembers != null && addMembers.length() > 0); boolean membersAdded = (addMembers != null && addMembers.length() > 0);
if (membersAdded) if (membersAdded) {
model.setValue(TagData.MEMBERS, ""); // Clear this value for migration purposes 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))) { changes.has(NameMaps.localPropertyToServerColumnName(NameMaps.TABLE_ID_TASKS, Task.COMPLETION_DATE))) {
Task t = PluginServices.getTaskDao().fetch(uuid, ReminderService.NOTIFICATION_PROPERTIES); Task t = PluginServices.getTaskDao().fetch(uuid, ReminderService.NOTIFICATION_PROPERTIES);
if (t != null) { 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()); Notifications.cancelNotifications(t.getId());
}
ReminderService.getInstance().scheduleAlarm(t); ReminderService.getInstance().scheduleAlarm(t);
} }
} }
@ -248,12 +259,14 @@ public class MakeChanges<TYPE extends RemoteModel> extends ServerToClientMessage
JSONArray removeTags = changes.optJSONArray("tag_removed"); JSONArray removeTags = changes.optJSONArray("tag_removed");
boolean tagsAdded = (addTags != null && addTags.length() > 0); boolean tagsAdded = (addTags != null && addTags.length() > 0);
boolean tagsRemoved = (removeTags != null && removeTags.length() > 0); boolean tagsRemoved = (removeTags != null && removeTags.length() > 0);
if (!tagsAdded && !tagsRemoved) if (!tagsAdded && !tagsRemoved) {
return; return;
}
long localId = AbstractModel.NO_ID; long localId = AbstractModel.NO_ID;
if (tagsAdded || tagsRemoved) if (tagsAdded || tagsRemoved) {
localId = getLocalId(); localId = getLocalId();
}
if (tagsAdded) { if (tagsAdded) {
if (model.isSaved()) { if (model.isSaved()) {
@ -284,8 +297,9 @@ public class MakeChanges<TYPE extends RemoteModel> extends ServerToClientMessage
} }
private void uuidChanged(String fromUuid, String toUuid) { 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); Log.e(ERROR_TAG, "Task UUID collision -- old uuid: " + fromUuid + ", new uuid: " + toUuid);
}
// Update reference from UserActivity to task uuid // Update reference from UserActivity to task uuid
UserActivityDao activityDao = PluginServices.getUserActivityDao(); UserActivityDao activityDao = PluginServices.getUserActivityDao();
@ -359,8 +373,9 @@ public class MakeChanges<TYPE extends RemoteModel> extends ServerToClientMessage
boolean membersRemoved = (removeMembers != null && removeMembers.length() > 0); boolean membersRemoved = (removeMembers != null && removeMembers.length() > 0);
long localId = AbstractModel.NO_ID; long localId = AbstractModel.NO_ID;
if (membersAdded || membersRemoved) if (membersAdded || membersRemoved) {
localId = getLocalId(); localId = getLocalId();
}
if (membersAdded) { if (membersAdded) {
for (int i = 0; i < addMembers.length(); i++) { 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) { 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); Log.e(ERROR_TAG, "Tag UUID collision -- old uuid: " + fromUuid + ", new uuid: " + toUuid);
}
UserActivityDao activityDao = PluginServices.getUserActivityDao(); UserActivityDao activityDao = PluginServices.getUserActivityDao();
UserActivity activityTemplate = new UserActivity(); UserActivity activityTemplate = new UserActivity();

@ -78,31 +78,34 @@ public class NameMaps {
propertyMap.put(property, serverName); propertyMap.put(property, serverName);
localNameMap.put(property.name, property); localNameMap.put(property.name, property);
serverNameMap.put(property.name, serverName); serverNameMap.put(property.name, serverName);
if (!writeable && excludedFromOutstandingSet != null) if (!writeable && excludedFromOutstandingSet != null) {
excludedFromOutstandingSet.add(property.name); excludedFromOutstandingSet.add(property.name);
}
} }
public static Property<?>[] syncableProperties(String table) { 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); 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); 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); 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); 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); 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 computeSyncableProperties(WAITING_ON_ME_PROPERTIES_LOCAL_TO_SERVER.keySet(), WAITING_ON_ME_PROPERTIES_EXCLUDED);
}
return null; return null;
} }
private static Property<?>[] computeSyncableProperties(Set<Property<?>> baseSet, Set<String> excluded) { private static Property<?>[] computeSyncableProperties(Set<Property<?>> baseSet, Set<String> excluded) {
Set<Property<?>> result = new HashSet<Property<?>>(); Set<Property<?>> result = new HashSet<Property<?>>();
for (Property<?> elem : baseSet) { for (Property<?> elem : baseSet) {
if (!excluded.contains(elem.name)) if (!excluded.contains(elem.name)) {
result.add(elem); result.add(elem);
}
} }
return result.toArray(new Property<?>[result.size()]); 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, 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> userActivityMap, Map<A, B> taskAttachmentMap, Map<A, B> taskListMetadataMap, Map<A, B> waitingOnMeMap) {
Map<A, B> map = null; Map<A, B> map = null;
if (TABLE_ID_TASKS.equals(table)) if (TABLE_ID_TASKS.equals(table)) {
map = taskMap; map = taskMap;
else if (TABLE_ID_TAGS.equals(table)) } else if (TABLE_ID_TAGS.equals(table)) {
map = tagMap; map = tagMap;
else if (TABLE_ID_USERS.equals(table)) } else if (TABLE_ID_USERS.equals(table)) {
map = userMap; map = userMap;
else if (TABLE_ID_USER_ACTIVITY.equals(table)) } else if (TABLE_ID_USER_ACTIVITY.equals(table)) {
map = userActivityMap; map = userActivityMap;
else if (TABLE_ID_ATTACHMENTS.equals(table)) } else if (TABLE_ID_ATTACHMENTS.equals(table)) {
map = taskAttachmentMap; map = taskAttachmentMap;
else if (TABLE_ID_TASK_LIST_METADATA.equals(table)) } else if (TABLE_ID_TASK_LIST_METADATA.equals(table)) {
map = taskListMetadataMap; map = taskListMetadataMap;
else if (TABLE_ID_WAITING_ON_ME.equals(table)) } else if (TABLE_ID_WAITING_ON_ME.equals(table)) {
map = waitingOnMeMap; map = waitingOnMeMap;
}
if (map == null) if (map == null) {
return null; return null;
}
return map.get(col); return map.get(col);
} }
public static boolean shouldRecordOutstandingColumnForTable(String table, String column) { public static boolean shouldRecordOutstandingColumnForTable(String table, String column) {
if (TABLE_ID_TASKS.equals(table)) { 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); return !TASK_PROPERTIES_EXCLUDED.contains(column);
}
} else if (TABLE_ID_TAGS.equals(table)) { } 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); return !TAG_PROPERTIES_EXCLUDED.contains(column);
}
} else if (TABLE_ID_USER_ACTIVITY.equals(table)) { } 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); return !USER_ACTIVITY_PROPERTIES_EXCLUDED.contains(column);
}
} else if (TABLE_ID_USERS.equals(table)) { } 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); return !USER_PROPERTIES_EXCLUDED.contains(column);
}
} else if (TABLE_ID_ATTACHMENTS.equals(table)) { } 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); return !TASK_ATTACHMENT_PROPERTIES_EXCLUDED.contains(column);
}
} else if (TABLE_ID_TASK_LIST_METADATA.equals(table)) { } 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); return !TASK_LIST_METADATA_PROPERTIES_EXCLUDED.contains(column);
}
} else if (TABLE_ID_WAITING_ON_ME.equals(table)) { } 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 !WAITING_ON_ME_PROPERTIES_EXCLUDED.contains(column);
}
} }
return false; return false;
} }

@ -50,25 +50,30 @@ public class NowBriefed<TYPE extends RemoteModel> extends ServerToClientMessage
if (TextUtils.isEmpty(uuid)) { if (TextUtils.isEmpty(uuid)) {
if (!TextUtils.isEmpty(taskId)) { if (!TextUtils.isEmpty(taskId)) {
Task template = new Task(); 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); 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); template.setValue(Task.USER_ACTIVITIES_PUSHED_AT, pushedAt);
}
if (template.getSetValues() != null) if (template.getSetValues() != null) {
PluginServices.getTaskDao().update(Task.UUID.eq(taskId), template); PluginServices.getTaskDao().update(Task.UUID.eq(taskId), template);
}
} else if (!TextUtils.isEmpty(tagId)) { } else if (!TextUtils.isEmpty(tagId)) {
TagData template = new TagData(); 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); 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); 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); template.setValue(TagData.USER_ACTIVITIES_PUSHED_AT, pushedAt);
}
if (template.getSetValues() != null) if (template.getSetValues() != null) {
PluginServices.getTagDataDao().update(TagData.UUID.eq(tagId), template); PluginServices.getTagDataDao().update(TagData.UUID.eq(tagId), template);
}
} else if (!TextUtils.isEmpty(userId)) { } else if (!TextUtils.isEmpty(userId)) {
if (NameMaps.TABLE_ID_TASKS.equals(table)) { if (NameMaps.TABLE_ID_TASKS.equals(table)) {
@ -78,21 +83,23 @@ public class NowBriefed<TYPE extends RemoteModel> extends ServerToClientMessage
} }
} else { } else {
String pushedAtKey = null; String pushedAtKey = null;
if (NameMaps.TABLE_ID_TASKS.equals(table)) if (NameMaps.TABLE_ID_TASKS.equals(table)) {
pushedAtKey = NameMaps.PUSHED_AT_TASKS; 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; 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; 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; 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; 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; pushedAtKey = NameMaps.PUSHED_AT_WAITING_ON_ME;
}
if (pushedAtKey != null) if (pushedAtKey != null) {
Preferences.setLong(pushedAtKey, pushedAt); Preferences.setLong(pushedAtKey, pushedAt);
}
} }
} else { } else {

@ -72,14 +72,16 @@ public class ReplayOutstandingEntries<T extends RemoteModel, OE extends Outstand
for (; !outstanding.isAfterLast(); outstanding.moveToNext()) { for (; !outstanding.isAfterLast(); outstanding.moveToNext()) {
instance.clear(); instance.clear();
instance.readPropertiesFromCursor(outstanding); instance.readPropertiesFromCursor(outstanding);
if (instance.getValue(OutstandingEntry.ENTITY_ID_PROPERTY) != id) if (instance.getValue(OutstandingEntry.ENTITY_ID_PROPERTY) != id) {
break; break;
}
count ++; count ++;
String column = instance.getValue(OutstandingEntry.COLUMN_STRING_PROPERTY); String column = instance.getValue(OutstandingEntry.COLUMN_STRING_PROPERTY);
Property<?> property = NameMaps.localColumnNameToProperty(table, column); Property<?> property = NameMaps.localColumnNameToProperty(table, column);
// set values to model // set values to model
if (property != null) if (property != null) {
property.accept(visitor, instance); property.accept(visitor, instance);
}
} }
model.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true); model.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true);
@ -110,24 +112,27 @@ public class ReplayOutstandingEntries<T extends RemoteModel, OE extends Outstand
@Override @Override
public Void visitInteger(Property<Integer> property, OE data) { public Void visitInteger(Property<Integer> property, OE data) {
Integer i = data.getMergedValues().getAsInteger(OutstandingEntry.VALUE_STRING_PROPERTY.name); Integer i = data.getMergedValues().getAsInteger(OutstandingEntry.VALUE_STRING_PROPERTY.name);
if (i != null) if (i != null) {
model.setValue(property, i); model.setValue(property, i);
}
return null; return null;
} }
@Override @Override
public Void visitLong(Property<Long> property, OE data) { public Void visitLong(Property<Long> property, OE data) {
Long l = data.getMergedValues().getAsLong(OutstandingEntry.VALUE_STRING_PROPERTY.name); Long l = data.getMergedValues().getAsLong(OutstandingEntry.VALUE_STRING_PROPERTY.name);
if (l != null) if (l != null) {
model.setValue(property, l); model.setValue(property, l);
}
return null; return null;
} }
@Override @Override
public Void visitDouble(Property<Double> property, OE data) { public Void visitDouble(Property<Double> property, OE data) {
Double d = data.getMergedValues().getAsDouble(OutstandingEntry.VALUE_STRING_PROPERTY.name); Double d = data.getMergedValues().getAsDouble(OutstandingEntry.VALUE_STRING_PROPERTY.name);
if (d != null) if (d != null) {
model.setValue(property, d); model.setValue(property, d);
}
return null; return null;
} }

@ -14,8 +14,9 @@ public class ReplayTaskListMetadataOutstanding extends ReplayOutstandingEntries<
@Override @Override
protected boolean shouldSaveModel(TaskListMetadata model) { protected boolean shouldSaveModel(TaskListMetadata model) {
if (model.containsNonNullValue(TaskListMetadata.TASK_IDS) && if (model.containsNonNullValue(TaskListMetadata.TASK_IDS) &&
TaskListMetadata.taskIdsIsEmpty(model.getValue(TaskListMetadata.TASK_IDS))) TaskListMetadata.taskIdsIsEmpty(model.getValue(TaskListMetadata.TASK_IDS))) {
return false; return false;
}
return true; return true;
} }

@ -32,62 +32,65 @@ public abstract class ServerToClientMessage {
public static ServerToClientMessage instantiateMessage(JSONObject json) { public static ServerToClientMessage instantiateMessage(JSONObject json) {
String type = json.optString("type"); String type = json.optString("type");
if (TYPE_MAKE_CHANGES.equals(type)) if (TYPE_MAKE_CHANGES.equals(type)) {
return instantiateMakeChanges(json); return instantiateMakeChanges(json);
else if (TYPE_NOW_BRIEFED.equals(type)) } else if (TYPE_NOW_BRIEFED.equals(type)) {
return instantiateNowBriefed(json); return instantiateNowBriefed(json);
else if (TYPE_ACKNOWLEDGE_CHANGE.equals(type)) } else if (TYPE_ACKNOWLEDGE_CHANGE.equals(type)) {
return new AcknowledgeChange(json); return new AcknowledgeChange(json);
else if (TYPE_USER_DATA.equals(type)) } else if (TYPE_USER_DATA.equals(type)) {
return new UserData(json); return new UserData(json);
else if (TYPE_DOUBLE_CHECK.equals(type)) } else if (TYPE_DOUBLE_CHECK.equals(type)) {
return new DoubleCheck(json); return new DoubleCheck(json);
else if (TYPE_USER_MIGRATED.equals(type)) } else if (TYPE_USER_MIGRATED.equals(type)) {
return new UserMigrated(json); return new UserMigrated(json);
else if (TYPE_DEBUG.equals(type)) } else if (TYPE_DEBUG.equals(type)) {
return new Debug(json); return new Debug(json);
}
return null; return null;
} }
private static MakeChanges<?> instantiateMakeChanges(JSONObject json) { private static MakeChanges<?> instantiateMakeChanges(JSONObject json) {
String table = json.optString("table"); 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()); 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()); 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()); 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()); 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()); 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()); 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()); return new MakeChanges<WaitingOnMe>(json, PluginServices.getWaitingOnMeDao());
else } else {
return null; return null;
}
} }
private static NowBriefed<?> instantiateNowBriefed(JSONObject json) { private static NowBriefed<?> instantiateNowBriefed(JSONObject json) {
String table = json.optString("table"); 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()); 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()); 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()); 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()); 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()); 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()); 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()); return new NowBriefed<WaitingOnMe>(json, PluginServices.getWaitingOnMeDao());
else } else {
return null; return null;
}
} }
} }

@ -24,8 +24,9 @@ public class UserData extends ServerToClientMessage {
String uuid = json.optString("uuid"); String uuid = json.optString("uuid");
String email = json.optString("email"); String email = json.optString("email");
if (TextUtils.isEmpty(uuid)) if (TextUtils.isEmpty(uuid)) {
return; return;
}
Task taskTemplate = new Task(); Task taskTemplate = new Task();
taskTemplate.setValue(Task.USER_ID, uuid); taskTemplate.setValue(Task.USER_ID, uuid);

@ -48,8 +48,9 @@ public final class AlarmControlSet extends TaskEditControlSet {
alertsContainer.removeAllViews(); alertsContainer.removeAllViews();
TodorooCursor<Metadata> cursor = AlarmService.getInstance().getAlarms(model.getId()); TodorooCursor<Metadata> cursor = AlarmService.getInstance().getAlarms(model.getId());
try { try {
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
addAlarm(new Date(cursor.get(AlarmFields.TIME))); addAlarm(new Date(cursor.get(AlarmFields.TIME)));
}
} finally { } finally {
cursor.close(); cursor.close();
} }
@ -71,8 +72,9 @@ public final class AlarmControlSet extends TaskEditControlSet {
@Override @Override
public String writeToModel(Task task) { public String writeToModel(Task task) {
if (initialized && pickerDialog != null) if (initialized && pickerDialog != null) {
pickerDialog.dismiss(); pickerDialog.dismiss();
}
return super.writeToModel(task); return super.writeToModel(task);
} }
@ -81,13 +83,15 @@ public final class AlarmControlSet extends TaskEditControlSet {
LinkedHashSet<Long> alarms = new LinkedHashSet<Long>(); LinkedHashSet<Long> alarms = new LinkedHashSet<Long>();
for(int i = 0; i < alertsContainer.getChildCount(); i++) { for(int i = 0; i < alertsContainer.getChildCount(); i++) {
Long dateValue = (Long) alertsContainer.getChildAt(i).getTag(); Long dateValue = (Long) alertsContainer.getChildAt(i).getTag();
if(dateValue == null) if(dateValue == null) {
continue; continue;
}
alarms.add(dateValue); alarms.add(dateValue);
} }
if(AlarmService.getInstance().synchronizeAlarms(task.getId(), alarms)) if(AlarmService.getInstance().synchronizeAlarms(task.getId(), alarms)) {
task.setValue(Task.MODIFICATION_DATE, DateUtilities.now()); task.setValue(Task.MODIFICATION_DATE, DateUtilities.now());
}
return null; return null;
} }

@ -31,12 +31,14 @@ public class AlarmDetailExposer extends BroadcastReceiver {
ContextManager.setContext(context); ContextManager.setContext(context);
// get tags associated with this task // get tags associated with this task
long taskId = intent.getLongExtra(AstridApiConstants.EXTRAS_TASK_ID, -1); long taskId = intent.getLongExtra(AstridApiConstants.EXTRAS_TASK_ID, -1);
if(taskId == -1) if(taskId == -1) {
return; return;
}
String taskDetail = getTaskDetails(context, taskId); String taskDetail = getTaskDetails(context, taskId);
if(taskDetail == null) if(taskDetail == null) {
return; return;
}
// transmit // transmit
Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_SEND_DETAILS); 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; return null;
}
int flags = DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_SHOW_TIME; int flags = DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_SHOW_TIME;
Date today = new Date(); Date today = new Date();
Date alarm = new Date(nextTime); Date alarm = new Date(nextTime);
if(today.getYear() == alarm.getYear()) if(today.getYear() == alarm.getYear()) {
flags |= DateUtils.FORMAT_NO_YEAR; 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; flags |= DateUtils.FORMAT_SHOW_DATE;
}
CharSequence durationString = DateUtils.formatDateTime(context, nextTime, CharSequence durationString = DateUtils.formatDateTime(context, nextTime,
flags); flags);
return "<img src='silk_clock'/> " + durationString; //$NON-NLS-1$ return "<img src='silk_clock'/> " + durationString; //$NON-NLS-1$

@ -46,8 +46,9 @@ public class AlarmService {
private static AlarmService instance = null; private static AlarmService instance = null;
public static synchronized AlarmService getInstance() { public static synchronized AlarmService getInstance() {
if(instance == null) if(instance == null) {
instance = new AlarmService(); instance = new AlarmService();
}
return instance; return instance;
} }
@ -96,8 +97,9 @@ public class AlarmService {
} }
}, true); }, true);
if(changed) if(changed) {
scheduleAlarms(taskId); scheduleAlarms(taskId);
}
return changed; return changed;
} }
@ -184,8 +186,9 @@ public class AlarmService {
*/ */
@SuppressWarnings("nls") @SuppressWarnings("nls")
private void scheduleAlarm(Metadata alarm) { private void scheduleAlarm(Metadata alarm) {
if(alarm == null) if(alarm == null) {
return; return;
}
long taskId = alarm.getValue(Metadata.TASK); long taskId = alarm.getValue(Metadata.TASK);
@ -194,12 +197,13 @@ public class AlarmService {
PendingIntent pendingIntent = pendingIntentForAlarm(alarm, taskId); PendingIntent pendingIntent = pendingIntentForAlarm(alarm, taskId);
long time = alarm.getValue(AlarmFields.TIME); long time = alarm.getValue(AlarmFields.TIME);
if(time == 0 || time == NO_ALARM) if(time == 0 || time == NO_ALARM) {
am.cancel(pendingIntent); am.cancel(pendingIntent);
else if(time > DateUtilities.now()) { } else if(time > DateUtilities.now()) {
if(Constants.DEBUG) if(Constants.DEBUG) {
Log.e("Astrid", "Alarm (" + taskId + ", " + ReminderService.TYPE_ALARM + 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); am.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
} }
} }

@ -23,20 +23,24 @@ public class AlarmTaskRepeatListener extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
ContextManager.setContext(context); ContextManager.setContext(context);
long taskId = intent.getLongExtra(AstridApiConstants.EXTRAS_TASK_ID, -1); long taskId = intent.getLongExtra(AstridApiConstants.EXTRAS_TASK_ID, -1);
if(taskId == -1) if(taskId == -1) {
return; return;
}
long oldDueDate = intent.getLongExtra(AstridApiConstants.EXTRAS_OLD_DUE_DATE, 0); long oldDueDate = intent.getLongExtra(AstridApiConstants.EXTRAS_OLD_DUE_DATE, 0);
if(oldDueDate == 0) if(oldDueDate == 0) {
oldDueDate = DateUtilities.now(); oldDueDate = DateUtilities.now();
}
long newDueDate = intent.getLongExtra(AstridApiConstants.EXTRAS_NEW_DUE_DATE, -1); long newDueDate = intent.getLongExtra(AstridApiConstants.EXTRAS_NEW_DUE_DATE, -1);
if(newDueDate <= 0 || newDueDate <= oldDueDate) if(newDueDate <= 0 || newDueDate <= oldDueDate) {
return; return;
}
TodorooCursor<Metadata> cursor = AlarmService.getInstance().getAlarms(taskId); TodorooCursor<Metadata> cursor = AlarmService.getInstance().getAlarms(taskId);
try { try {
if(cursor.getCount() == 0) if(cursor.getCount() == 0) {
return; return;
}
Metadata metadata = new Metadata(); Metadata metadata = new Metadata();
LinkedHashSet<Long> alarms = new LinkedHashSet<Long>(cursor.getCount()); LinkedHashSet<Long> alarms = new LinkedHashSet<Long>(cursor.getCount());

@ -63,8 +63,9 @@ public class BackupPreferences extends TodorooPreferenceActivity {
@Override @Override
public void onChildViewAdded(View parent, View child) { public void onChildViewAdded(View parent, View child) {
View view = findViewById(R.id.status); View view = findViewById(R.id.status);
if(view != null) if(view != null) {
view.setBackgroundColor(statusColor); view.setBackgroundColor(statusColor);
}
} }
}); });
@ -104,10 +105,11 @@ public class BackupPreferences extends TodorooPreferenceActivity {
// auto // auto
if (r.getString(R.string.backup_BPr_auto_key).equals( if (r.getString(R.string.backup_BPr_auto_key).equals(
preference.getKey())) { preference.getKey())) {
if (value != null && !(Boolean)value) if (value != null && !(Boolean)value) {
preference.setSummary(R.string.backup_BPr_auto_disabled); preference.setSummary(R.string.backup_BPr_auto_disabled);
else } else {
preference.setSummary(R.string.backup_BPr_auto_enabled); preference.setSummary(R.string.backup_BPr_auto_enabled);
}
} }
// status // status
@ -143,8 +145,9 @@ public class BackupPreferences extends TodorooPreferenceActivity {
preference.setSummary(subtitle); preference.setSummary(subtitle);
View view = findViewById(R.id.status); View view = findViewById(R.id.status);
if(view != null) if(view != null) {
view.setBackgroundColor(statusColor); view.setBackgroundColor(statusColor);
}
} }
} }

@ -127,13 +127,15 @@ public class BackupService extends Service {
} }
}; };
File astridDir = backupDirectorySetting.getBackupDirectory(); File astridDir = backupDirectorySetting.getBackupDirectory();
if(astridDir == null) if(astridDir == null) {
return; return;
}
// grab all backup files, sort by modified date, delete old ones // grab all backup files, sort by modified date, delete old ones
File[] files = astridDir.listFiles(backupFileFilter); File[] files = astridDir.listFiles(backupFileFilter);
if(files == null) if(files == null) {
return; return;
}
Arrays.sort(files, new Comparator<File>() { Arrays.sort(files, new Comparator<File>() {
@Override @Override
@ -142,8 +144,9 @@ public class BackupService extends Service {
} }
}); });
for(int i = DAYS_TO_KEEP_BACKUP; i < files.length; i++) { 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$ 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); AndroidUtilities.sortFilesByDateDesc(filesAsFile);
files = new String[filesAsFile.length]; 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(); files[i] = filesAsFile[i].getName();
}
setItems(files, this); setItems(files, this);
} else { } else {

@ -107,8 +107,9 @@ public class TasksXmlExporter {
progressDialog.setCancelable(false); progressDialog.setCancelable(false);
progressDialog.setIndeterminate(false); progressDialog.setIndeterminate(false);
progressDialog.show(); progressDialog.show();
if(context instanceof Activity) if(context instanceof Activity) {
progressDialog.setOwnerActivity((Activity)context); progressDialog.setOwnerActivity((Activity) context);
}
} }
new Thread(new Runnable() { new Thread(new Runnable() {
@ -119,15 +120,17 @@ public class TasksXmlExporter {
exportType); exportType);
int tasks = taskService.countTasks(); int tasks = taskService.countTasks();
if(tasks > 0) if(tasks > 0) {
doTasksExport(output); doTasksExport(output);
}
Preferences.setLong(BackupPreferences.PREF_BACKUP_LAST_DATE, Preferences.setLong(BackupPreferences.PREF_BACKUP_LAST_DATE,
DateUtilities.now()); DateUtilities.now());
Preferences.setString(BackupPreferences.PREF_BACKUP_LAST_ERROR, null); Preferences.setString(BackupPreferences.PREF_BACKUP_LAST_ERROR, null);
if (exportType == ExportType.EXPORT_TYPE_MANUAL) if (exportType == ExportType.EXPORT_TYPE_MANUAL) {
onFinishExport(output); onFinishExport(output);
}
} catch (IOException e) { } catch (IOException e) {
switch(exportType) { switch(exportType) {
case EXPORT_TYPE_MANUAL: case EXPORT_TYPE_MANUAL:
@ -144,8 +147,9 @@ public class TasksXmlExporter {
break; break;
} }
} finally { } finally {
if(runAfterExport != null) if(runAfterExport != null) {
runAfterExport.run(); runAfterExport.run();
}
} }
} }
}).start(); }).start();
@ -224,9 +228,11 @@ public class TasksXmlExporter {
*/ */
private void serializeModel(AbstractModel model, Property<?>[] properties, Property<?>... excludes) { private void serializeModel(AbstractModel model, Property<?>[] properties, Property<?>... excludes) {
outer: for(Property<?> property : properties) { outer: for(Property<?> property : properties) {
for(Property<?> exclude : excludes) for(Property<?> exclude : excludes) {
if(property.name.equals(exclude.name)) if (property.name.equals(exclude.name)) {
continue outer; continue outer;
}
}
try { try {
property.accept(xmlWritingVisitor, model); property.accept(xmlWritingVisitor, model);
@ -301,8 +307,9 @@ public class TasksXmlExporter {
public Void visitString(Property<String> property, AbstractModel data) { public Void visitString(Property<String> property, AbstractModel data) {
try { try {
String value = data.getValue(property); String value = data.getValue(property);
if(value == null) if(value == null) {
return null; return null;
}
xml.attribute(null, property.name, value); xml.attribute(null, property.name, value);
} catch (UnsupportedOperationException e) { } catch (UnsupportedOperationException e) {
// didn't read this value, do nothing // didn't read this value, do nothing
@ -322,15 +329,16 @@ public class TasksXmlExporter {
@Override @Override
public void run() { public void run() {
if(exportCount == 0) if(exportCount == 0) {
Toast.makeText(context, context.getString(R.string.export_toast_no_tasks), Toast.LENGTH_LONG).show(); 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), CharSequence text = String.format(context.getString(R.string.export_toast),
context.getResources().getQuantityString(R.plurals.Ntasks, exportCount, context.getResources().getQuantityString(R.plurals.Ntasks, exportCount,
exportCount), outputFile); exportCount), outputFile);
Toast.makeText(context, text, Toast.LENGTH_LONG).show(); 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); DialogUtilities.dismissDialog((Activity) context, progressDialog);
}
} }
} }
}); });

@ -108,8 +108,9 @@ public class TasksXmlImporter {
progressDialog.setIndeterminate(true); progressDialog.setIndeterminate(true);
try { try {
progressDialog.show(); progressDialog.show();
if(context instanceof Activity) if(context instanceof Activity) {
progressDialog.setOwnerActivity((Activity)context); progressDialog.setOwnerActivity((Activity) context);
}
} catch (BadTokenException e) { } catch (BadTokenException e) {
// Running from a unit test or some such thing // Running from a unit test or some such thing
} }
@ -147,14 +148,15 @@ public class TasksXmlImporter {
// Process <astrid ... > // Process <astrid ... >
if (tag.equals(BackupConstants.ASTRID_TAG)) { if (tag.equals(BackupConstants.ASTRID_TAG)) {
String format = xpp.getAttributeValue(null, BackupConstants.ASTRID_ATTR_FORMAT); String format = xpp.getAttributeValue(null, BackupConstants.ASTRID_ATTR_FORMAT);
if(TextUtils.equals(format, FORMAT1)) if(TextUtils.equals(format, FORMAT1)) {
new Format1TaskImporter(xpp); new Format1TaskImporter(xpp);
else if(TextUtils.equals(format, FORMAT2)) } else if(TextUtils.equals(format, FORMAT2)) {
new Format2TaskImporter(xpp); new Format2TaskImporter(xpp);
else } else {
throw new UnsupportedOperationException( throw new UnsupportedOperationException(
"Did not know how to import tasks with xml format '" + "Did not know how to import tasks with xml format '" +
format + "'"); format + "'");
}
} }
} }
} }
@ -164,8 +166,9 @@ public class TasksXmlImporter {
handler.post(new Runnable() { handler.post(new Runnable() {
@Override @Override
public void run() { public void run() {
if(progressDialog.isShowing() && context instanceof Activity) if(progressDialog.isShowing() && context instanceof Activity) {
DialogUtilities.dismissDialog((Activity) context, progressDialog); DialogUtilities.dismissDialog((Activity) context, progressDialog);
}
showSummary(); showSummary();
} }
}); });
@ -220,8 +223,9 @@ public class TasksXmlImporter {
while (xpp.next() != XmlPullParser.END_DOCUMENT) { while (xpp.next() != XmlPullParser.END_DOCUMENT) {
String tag = xpp.getName(); String tag = xpp.getName();
if (tag == null || xpp.getEventType() == XmlPullParser.END_TAG) if (tag == null || xpp.getEventType() == XmlPullParser.END_TAG) {
continue; continue;
}
try { try {
if (tag.equals(BackupConstants.TASK_TAG)) { if (tag.equals(BackupConstants.TASK_TAG)) {
@ -270,12 +274,14 @@ public class TasksXmlImporter {
// fix for failed migration in 4.0.6 // fix for failed migration in 4.0.6
if(version < UpgradeService.V4_0_6) { if(version < UpgradeService.V4_0_6) {
if(!completionDate.equals("0") && 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); existingTask = cursor.get(Task.ID);
}
if(!deletionDate.equals("0") && 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); existingTask = cursor.get(Task.ID);
}
} }
if(existingTask == 0) { if(existingTask == 0) {
@ -289,13 +295,15 @@ public class TasksXmlImporter {
// else, make a new task model and add away. // else, make a new task model and add away.
deserializeModel(currentTask, Task.PROPERTIES); deserializeModel(currentTask, Task.PROPERTIES);
if(version < UpgradeService.V4_0_6) if(version < UpgradeService.V4_0_6) {
adjustDueDateScheme(currentTask); adjustDueDateScheme(currentTask);
}
if(existingTask > 0) if(existingTask > 0) {
currentTask.setId(existingTask); currentTask.setId(existingTask);
else } else {
currentTask.setId(Task.NO_ID); currentTask.setId(Task.NO_ID);
}
// Save the task to the database. // Save the task to the database.
taskService.save(currentTask); taskService.save(currentTask);
@ -319,8 +327,9 @@ public class TasksXmlImporter {
} }
private void parseMetadata() { private void parseMetadata() {
if(!currentTask.isSaved()) if(!currentTask.isSaved()) {
return; return;
}
metadata.clear(); metadata.clear();
deserializeModel(metadata, Metadata.PROPERTIES); deserializeModel(metadata, Metadata.PROPERTIES);
metadata.setId(Metadata.NO_ID); metadata.setId(Metadata.NO_ID);
@ -352,18 +361,20 @@ public class TasksXmlImporter {
public Void visitInteger(Property<Integer> property, public Void visitInteger(Property<Integer> property,
AbstractModel data) { AbstractModel data) {
String value = xpp.getAttributeValue(null, property.name); String value = xpp.getAttributeValue(null, property.name);
if(value != null) if(value != null) {
data.setValue(property, TasksXmlExporter.XML_NULL.equals(value) ? data.setValue(property, TasksXmlExporter.XML_NULL.equals(value) ?
null : Integer.parseInt(value)); null : Integer.parseInt(value));
}
return null; return null;
} }
@Override @Override
public Void visitLong(Property<Long> property, AbstractModel data) { public Void visitLong(Property<Long> property, AbstractModel data) {
String value = xpp.getAttributeValue(null, property.name); String value = xpp.getAttributeValue(null, property.name);
if(value != null) if(value != null) {
data.setValue(property, TasksXmlExporter.XML_NULL.equals(value) ? data.setValue(property, TasksXmlExporter.XML_NULL.equals(value) ?
null : Long.parseLong(value)); null : Long.parseLong(value));
}
return null; return null;
} }
@ -371,9 +382,10 @@ public class TasksXmlImporter {
public Void visitDouble(Property<Double> property, public Void visitDouble(Property<Double> property,
AbstractModel data) { AbstractModel data) {
String value = xpp.getAttributeValue(null, property.name); String value = xpp.getAttributeValue(null, property.name);
if(value != null) if(value != null) {
data.setValue(property, TasksXmlExporter.XML_NULL.equals(value) ? data.setValue(property, TasksXmlExporter.XML_NULL.equals(value) ?
null : Double.parseDouble(value)); null : Double.parseDouble(value));
}
return null; return null;
} }
@ -381,8 +393,9 @@ public class TasksXmlImporter {
public Void visitString(Property<String> property, public Void visitString(Property<String> property,
AbstractModel data) { AbstractModel data) {
String value = xpp.getAttributeValue(null, property.name); String value = xpp.getAttributeValue(null, property.name);
if(value != null) if(value != null) {
data.setValue(property, value); data.setValue(property, value);
}
return null; return null;
} }
@ -408,11 +421,11 @@ public class TasksXmlImporter {
String tag = xpp.getName(); String tag = xpp.getName();
try { try {
if(BackupConstants.TASK_TAG.equals(tag) && xpp.getEventType() == XmlPullParser.END_TAG) if(BackupConstants.TASK_TAG.equals(tag) && xpp.getEventType() == XmlPullParser.END_TAG) {
saveTags(); saveTags();
else if (tag == null || xpp.getEventType() == XmlPullParser.END_TAG) } else if (tag == null || xpp.getEventType() == XmlPullParser.END_TAG) {
continue; continue;
else if (tag.equals(BackupConstants.TASK_TAG)) { } else if (tag.equals(BackupConstants.TASK_TAG)) {
// Parse <task ... > // Parse <task ... >
currentTask = parseTask(); currentTask = parseTask();
} else if (currentTask != null) { } else if (currentTask != null) {
@ -523,10 +536,11 @@ public class TasksXmlImporter {
} }
if(upgradeNotes != null) { 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); task.setValue(Task.NOTES, task.getValue(Task.NOTES) + "\n" + upgradeNotes);
else } else {
task.setValue(Task.NOTES, upgradeNotes); task.setValue(Task.NOTES, upgradeNotes);
}
upgradeNotes = null; upgradeNotes = null;
} }
@ -577,11 +591,12 @@ public class TasksXmlImporter {
} }
else if(field.equals(LegacyTaskModel.PREFERRED_DUE_DATE)) { else if(field.equals(LegacyTaskModel.PREFERRED_DUE_DATE)) {
String definite = xpp.getAttributeValue(null, LegacyTaskModel.DEFINITE_DUE_DATE); String definite = xpp.getAttributeValue(null, LegacyTaskModel.DEFINITE_DUE_DATE);
if(definite != null) if(definite != null) {
; // handled above ; // handled above
else } else {
task.setValue(Task.DUE_DATE, task.setValue(Task.DUE_DATE,
BackupDateUtilities.getTaskDueDateFromIso8601String(value).getTime()); BackupDateUtilities.getTaskDueDateFromIso8601String(value).getTime());
}
} }
else if(field.equals(LegacyTaskModel.HIDDEN_UNTIL)) { else if(field.equals(LegacyTaskModel.HIDDEN_UNTIL)) {
task.setValue(Task.HIDE_UNTIL, task.setValue(Task.HIDE_UNTIL,
@ -628,8 +643,9 @@ public class TasksXmlImporter {
} }
} }
else if(field.equals(LegacyTaskModel.FLAGS)) { 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; syncOnComplete = true;
}
} }
else { else {
return false; return false;

@ -41,8 +41,9 @@ public class PhoneStateChangedReceiver extends BroadcastReceiver {
if (TelephonyManager.EXTRA_STATE_RINGING.equals(state)) { if (TelephonyManager.EXTRA_STATE_RINGING.equals(state)) {
String number = digitsOnly(intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER)); String number = digitsOnly(intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER));
if (TextUtils.isEmpty(number)) if (TextUtils.isEmpty(number)) {
return; return;
}
Preferences.setString(PREF_LAST_INCOMING_NUMBER, number); Preferences.setString(PREF_LAST_INCOMING_NUMBER, number);
} else if (TelephonyManager.EXTRA_STATE_IDLE.equals(state)) { } else if (TelephonyManager.EXTRA_STATE_IDLE.equals(state)) {
@ -81,8 +82,9 @@ public class PhoneStateChangedReceiver extends BroadcastReceiver {
} }
} }
try { try {
if (calls == null) if (calls == null) {
return; return;
}
if (calls.moveToFirst()) { if (calls.moveToFirst()) {
int numberIndex = calls.getColumnIndex(Calls.NUMBER); int numberIndex = calls.getColumnIndex(Calls.NUMBER);
String number = calls.getString(numberIndex); String number = calls.getString(numberIndex);
@ -121,8 +123,9 @@ public class PhoneStateChangedReceiver extends BroadcastReceiver {
} catch (Exception e) { } catch (Exception e) {
Log.e("phone-state", "Unexpected exception in PhoneStateChangedReceiver", e); Log.e("phone-state", "Unexpected exception in PhoneStateChangedReceiver", e);
} finally { } finally {
if (calls != null) if (calls != null) {
calls.close(); calls.close();
}
} }
} }
}.start(); }.start();
@ -130,13 +133,15 @@ public class PhoneStateChangedReceiver extends BroadcastReceiver {
} }
private String digitsOnly(String number) { private String digitsOnly(String number) {
if (number == null) if (number == null) {
return ""; return "";
}
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
for (int i = 0; i < number.length(); i++) { for (int i = 0; i < number.length(); i++) {
char c = number.charAt(i); char c = number.charAt(i);
if (Character.isDigit(c)) if (Character.isDigit(c)) {
builder.append(c); builder.append(c);
}
} }
return builder.toString(); return builder.toString();
} }

@ -64,13 +64,15 @@ public final class CoreFilterExposer extends BroadcastReceiver implements Astrid
List<FilterListItem> filters = new ArrayList<FilterListItem>(3); List<FilterListItem> filters = new ArrayList<FilterListItem>(3);
filters.add(buildInboxFilter(r)); 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)); filters.add(getTodayFilter(r));
}
if (Preferences.getBoolean(R.string.p_show_waiting_on_me_filter, true) && 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), 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)); filters.add(getWaitingOnMeFilter(r));
}
// transmit filter list // transmit filter list
return filters.toArray(new FilterListItem[filters.size()]); return filters.toArray(new FilterListItem[filters.size()]);
@ -140,8 +142,9 @@ public final class CoreFilterExposer extends BroadcastReceiver implements Astrid
@Override @Override
public FilterListItem[] getFilters() { public FilterListItem[] getFilters() {
if (ContextManager.getContext() == null || ContextManager.getContext().getResources() == null) if (ContextManager.getContext() == null || ContextManager.getContext().getResources() == null) {
return null; return null;
}
Resources r = ContextManager.getContext().getResources(); Resources r = ContextManager.getContext().getResources();
return prepareFilters(r); return prepareFilters(r);

@ -110,16 +110,18 @@ public class CustomFilterActivity extends SherlockFragmentActivity {
} }
return criterion.text; return criterion.text;
} else if(criterion instanceof TextInputCriterion) { } else if(criterion instanceof TextInputCriterion) {
if(selectedText == null) if(selectedText == null) {
return criterion.text; return criterion.text;
}
return criterion.text.replace("?", selectedText); return criterion.text.replace("?", selectedText);
} }
throw new UnsupportedOperationException("Unknown criterion type"); //$NON-NLS-1$ throw new UnsupportedOperationException("Unknown criterion type"); //$NON-NLS-1$
} }
public String getValueFromCriterion() { public String getValueFromCriterion() {
if(type == TYPE_UNIVERSE) if(type == TYPE_UNIVERSE) {
return null; return null;
}
if(criterion instanceof MultipleSelectCriterion) { if(criterion instanceof MultipleSelectCriterion) {
if(selectedIndex >= 0 && ((MultipleSelectCriterion)criterion).entryValues != null && if(selectedIndex >= 0 && ((MultipleSelectCriterion)criterion).entryValues != null &&
selectedIndex < ((MultipleSelectCriterion)criterion).entryValues.length) { selectedIndex < ((MultipleSelectCriterion)criterion).entryValues.length) {
@ -154,8 +156,9 @@ public class CustomFilterActivity extends SherlockFragmentActivity {
ContextManager.setContext(this); ContextManager.setContext(this);
ActionBar ab = getSupportActionBar(); ActionBar ab = getSupportActionBar();
if (ab != null) if (ab != null) {
ab.setDisplayHomeAsUpEnabled(true); ab.setDisplayHomeAsUpEnabled(true);
}
setContentView(R.layout.custom_filter_activity); setContentView(R.layout.custom_filter_activity);
setTitle(R.string.FLA_new_filter); setTitle(R.string.FLA_new_filter);
@ -178,10 +181,11 @@ public class CustomFilterActivity extends SherlockFragmentActivity {
private void setupForDialogOrFullscreen() { private void setupForDialogOrFullscreen() {
isDialog = AstridPreferences.useTabletLayout(this); isDialog = AstridPreferences.useTabletLayout(this);
if (isDialog) if (isDialog) {
setTheme(ThemeService.getDialogTheme()); setTheme(ThemeService.getDialogTheme());
else } else {
ThemeService.applyTheme(this); ThemeService.applyTheme(this);
}
} }
/** /**
@ -367,8 +371,9 @@ public class CustomFilterActivity extends SherlockFragmentActivity {
@Override @Override
public void finish() { public void finish() {
super.finish(); super.finish();
if (!AstridPreferences.useTabletLayout(this)) if (!AstridPreferences.useTabletLayout(this)) {
AndroidUtilities.callOverridePendingTransition(this, R.anim.slide_right_in, R.anim.slide_right_out); AndroidUtilities.callOverridePendingTransition(this, R.anim.slide_right_in, R.anim.slide_right_out);
}
} }
@ -376,8 +381,9 @@ public class CustomFilterActivity extends SherlockFragmentActivity {
@Override @Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
if(menu.size() > 0) if(menu.size() > 0) {
menu.clear(); menu.clear();
}
// view holder // view holder
if(v.getTag() != null) { if(v.getTag() != null) {
@ -393,8 +399,9 @@ public class CustomFilterActivity extends SherlockFragmentActivity {
for(int i = 0; i < adapter.getCount(); i++) { for(int i = 0; i < adapter.getCount(); i++) {
CriterionInstance instance = adapter.getItem(i); CriterionInstance instance = adapter.getItem(i);
String value = instance.getValueFromCriterion(); 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 = ""; value = "";
}
String title = instance.getTitleFromCriterion(); String title = instance.getTitleFromCriterion();
@ -418,9 +425,9 @@ public class CustomFilterActivity extends SherlockFragmentActivity {
// special code for all tasks universe // special code for all tasks universe
if(instance.criterion.sql == null) if(instance.criterion.sql == null) {
sql.append(TaskCriteria.activeVisibleMine()).append(' '); sql.append(TaskCriteria.activeVisibleMine()).append(' ');
else { } else {
String subSql = instance.criterion.sql.replace("?", UnaryCriterion.sanitize(value)); String subSql = instance.criterion.sql.replace("?", UnaryCriterion.sanitize(value));
sql.append(Task.ID).append(" IN (").append(subSql).append(") "); 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++) { for(int i = 0; i < adapter.getCount(); i++) {
CriterionInstance instance = adapter.getItem(i); CriterionInstance instance = adapter.getItem(i);
String value = instance.getValueFromCriterion(); 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 = ""; value = "";
}
switch(instance.type) { switch(instance.type) {
case CriterionInstance.TYPE_ADD: case CriterionInstance.TYPE_ADD:
@ -480,9 +488,9 @@ public class CustomFilterActivity extends SherlockFragmentActivity {
} }
// special code for all tasks universe // special code for all tasks universe
if(instance.criterion.sql == null) if(instance.criterion.sql == null) {
sql.append(TaskCriteria.activeVisibleMine()).append(' '); sql.append(TaskCriteria.activeVisibleMine()).append(' ');
else { } else {
String subSql = instance.criterion.sql.replace("?", UnaryCriterion.sanitize(value)); String subSql = instance.criterion.sql.replace("?", UnaryCriterion.sanitize(value));
subSql = PermaSql.replacePlaceholders(subSql); subSql = PermaSql.replacePlaceholders(subSql);
sql.append(Task.ID).append(" IN (").append(subSql).append(") "); 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) { private <V> V getNth(int index, Map<?,V> map) {
int i = 0; int i = 0;
for (V v : map.values()) { for (V v : map.values()) {
if (i == index) return v; if (i == index) {
return v;
}
i++; i++;
} }
throw new IllegalArgumentException("out of bounds"); throw new IllegalArgumentException("out of bounds");

@ -52,10 +52,12 @@ public class CustomFilterAdapter extends ArrayAdapter<CriterionInstance> {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
ViewHolder viewHolder = (ViewHolder) v.getTag(); ViewHolder viewHolder = (ViewHolder) v.getTag();
if(viewHolder == null) if(viewHolder == null) {
return; return;
if(viewHolder.item.type == CriterionInstance.TYPE_UNIVERSE) }
if(viewHolder.item.type == CriterionInstance.TYPE_UNIVERSE) {
return; return;
}
showOptionsFor(viewHolder.item, new Runnable() { showOptionsFor(viewHolder.item, new Runnable() {
@Override @Override
@ -70,14 +72,16 @@ public class CustomFilterAdapter extends ArrayAdapter<CriterionInstance> {
public void onCreateContextMenu(ContextMenu menu, View v) { public void onCreateContextMenu(ContextMenu menu, View v) {
// view holder // view holder
ViewHolder viewHolder = (ViewHolder) v.getTag(); ViewHolder viewHolder = (ViewHolder) v.getTag();
if(viewHolder == null || viewHolder.item.type == CriterionInstance.TYPE_UNIVERSE) if(viewHolder == null || viewHolder.item.type == CriterionInstance.TYPE_UNIVERSE) {
return; return;
}
int index = getPosition(viewHolder.item); int index = getPosition(viewHolder.item);
menu.setHeaderTitle(viewHolder.name.getText()); menu.setHeaderTitle(viewHolder.name.getText());
if(viewHolder.icon.getVisibility() == View.VISIBLE) if(viewHolder.icon.getVisibility() == View.VISIBLE) {
menu.setHeaderIcon(viewHolder.icon.getDrawable()); menu.setHeaderIcon(viewHolder.icon.getDrawable());
}
MenuItem item = menu.add(CustomFilterActivity.MENU_GROUP_CONTEXT_TYPE, CriterionInstance.TYPE_INTERSECT, index, MenuItem item = menu.add(CustomFilterActivity.MENU_GROUP_CONTEXT_TYPE, CriterionInstance.TYPE_INTERSECT, index,
@ -116,8 +120,9 @@ public class CustomFilterAdapter extends ArrayAdapter<CriterionInstance> {
@Override @Override
public void onClick(DialogInterface click, int which) { public void onClick(DialogInterface click, int which) {
item.selectedIndex = which; item.selectedIndex = which;
if(onComplete != null) if(onComplete != null) {
onComplete.run(); onComplete.run();
}
} }
}; };
dialog.setAdapter(adapter, listener); dialog.setAdapter(adapter, listener);
@ -136,8 +141,9 @@ public class CustomFilterAdapter extends ArrayAdapter<CriterionInstance> {
@Override @Override
public void onClick(DialogInterface dialogInterface, int which) { public void onClick(DialogInterface dialogInterface, int which) {
item.selectedText = editText.getText().toString(); item.selectedText = editText.getText().toString();
if(onComplete != null) if(onComplete != null) {
onComplete.run(); onComplete.run();
}
} }
}); });
} }
@ -203,8 +209,9 @@ public class CustomFilterAdapter extends ArrayAdapter<CriterionInstance> {
viewHolder.icon.setVisibility(item.criterion.icon == null ? View.GONE : viewHolder.icon.setVisibility(item.criterion.icon == null ? View.GONE :
View.VISIBLE); View.VISIBLE);
if(item.criterion.icon != null) if(item.criterion.icon != null) {
viewHolder.icon.setImageBitmap(item.criterion.icon); viewHolder.icon.setImageBitmap(item.criterion.icon);
}
viewHolder.name.setText(title); 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); boolean useCustomFilters = Preferences.getBoolean(R.string.p_use_filters, true);
StoreObjectDao dao = PluginServices.getStoreObjectDao(); StoreObjectDao dao = PluginServices.getStoreObjectDao();
TodorooCursor<StoreObject> cursor = null; TodorooCursor<StoreObject> cursor = null;
if (useCustomFilters) if (useCustomFilters) {
cursor = dao.query(Query.select(StoreObject.PROPERTIES).where( 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 { try {
ArrayList<Filter> list = new ArrayList<Filter>(); ArrayList<Filter> list = new ArrayList<Filter>();
@ -99,8 +100,9 @@ public final class CustomFilterExposer extends BroadcastReceiver implements Astr
list.add(recent); 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)); list.add(getAssignedByMeFilter(r));
}
if (useCustomFilters && cursor != null) { if (useCustomFilters && cursor != null) {
StoreObject savedFilter = new StoreObject(); StoreObject savedFilter = new StoreObject();
@ -121,8 +123,9 @@ public final class CustomFilterExposer extends BroadcastReceiver implements Astr
return list.toArray(new Filter[list.size()]); return list.toArray(new Filter[list.size()]);
} finally { } finally {
if (cursor != null) if (cursor != null) {
cursor.close(); cursor.close();
}
} }
} }
@ -183,8 +186,9 @@ public final class CustomFilterExposer extends BroadcastReceiver implements Astr
@Override @Override
public FilterListItem[] getFilters() { public FilterListItem[] getFilters() {
if (ContextManager.getContext() == null) if (ContextManager.getContext() == null) {
return null; return null;
}
return prepareFilters(ContextManager.getContext()); 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); 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())) { } 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); 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)); preference.setSummary(r.getString(R.string.rmd_EPr_defaultRemind_desc_disabled));
else { } else {
String setting = r.getStringArray(R.array.EPr_reminder_random)[index]; String setting = r.getStringArray(R.array.EPr_reminder_random)[index];
preference.setSummary(r.getString(R.string.rmd_EPr_defaultRemind_desc, setting)); preference.setSummary(r.getString(R.string.rmd_EPr_defaultRemind_desc, setting));
} }
} else if(r.getString(R.string.gcal_p_default).equals(preference.getKey())) { } else if(r.getString(R.string.gcal_p_default).equals(preference.getKey())) {
ListPreference listPreference = (ListPreference) preference; ListPreference listPreference = (ListPreference) preference;
int index = AndroidUtilities.indexOf(listPreference.getEntryValues(), (String)value); 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)); preference.setSummary(r.getString(R.string.EPr_default_addtocalendar_desc_disabled));
else { } else {
String setting = listPreference.getEntries()[index].toString(); String setting = listPreference.getEntries()[index].toString();
preference.setSummary(r.getString(R.string.EPr_default_addtocalendar_desc, setting)); preference.setSummary(r.getString(R.string.EPr_default_addtocalendar_desc, setting));
} }
} else if (r.getString(R.string.p_voiceInputCreatesTask).equals(preference.getKey())) { } else if (r.getString(R.string.p_voiceInputCreatesTask).equals(preference.getKey())) {
preference.setEnabled(Preferences.getBoolean(R.string.p_voiceInputEnabled, false)); 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); preference.setSummary(R.string.EPr_voiceInputCreatesTask_desc_disabled);
else } else {
preference.setSummary(R.string.EPr_voiceInputCreatesTask_desc_enabled); preference.setSummary(R.string.EPr_voiceInputCreatesTask_desc_enabled);
}
} }
} }

@ -38,15 +38,18 @@ import com.todoroo.astrid.notes.NotesAction;
public class LinkActionExposer { public class LinkActionExposer {
public static TaskAction getActionsForTask(Context context, Task task, boolean hasAttachments, boolean hasNotes) { 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)); Spannable titleSpan = Spannable.Factory.getInstance().newSpannable(task.getValue(Task.TITLE));
Linkify.addLinks(titleSpan, Linkify.ALL); Linkify.addLinks(titleSpan, Linkify.ALL);
URLSpan[] urlSpans = titleSpan.getSpans(0, titleSpan.length(), URLSpan.class); URLSpan[] urlSpans = titleSpan.getSpans(0, titleSpan.length(), URLSpan.class);
if(urlSpans.length == 0 && !hasNotes && if(urlSpans.length == 0 && !hasNotes &&
!hasAttachments) !hasAttachments) {
return null; return null;
}
PackageManager pm = context.getPackageManager(); PackageManager pm = context.getPackageManager();
@ -56,8 +59,9 @@ public class LinkActionExposer {
int end = titleSpan.getSpanEnd(urlSpan); int end = titleSpan.getSpanEnd(urlSpan);
String text = titleSpan.subSequence(start, end).toString(); String text = titleSpan.subSequence(start, end).toString();
TaskAction taskAction = createLinkAction(context, task.getId(), url, text, pm); TaskAction taskAction = createLinkAction(context, task.getId(), url, text, pm);
if (taskAction != null) if (taskAction != null) {
return taskAction; return taskAction;
}
} }
Resources r = context.getResources(); Resources r = context.getResources();
@ -95,8 +99,9 @@ public class LinkActionExposer {
} }
// no intents -> no item // no intents -> no item
else else {
return null; return null;
}
Resources r = context.getResources(); Resources r = context.getResources();
Drawable icon; Drawable icon;
@ -108,8 +113,9 @@ public class LinkActionExposer {
icon = getBitmapDrawable(R.drawable.action_web, r); icon = getBitmapDrawable(R.drawable.action_web, r);
} }
if(text.length() > 15) if(text.length() > 15) {
text = text.substring(0, 12) + "..."; //$NON-NLS-1$ text = text.substring(0, 12) + "..."; //$NON-NLS-1$
}
TaskAction action = new TaskAction(text, TaskAction action = new TaskAction(text,
PendingIntent.getActivity(context, (int)id, actionIntent, 0), (BitmapDrawable)icon); 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 final HashMap<Integer, BitmapDrawable> IMAGE_CACHE = new HashMap<Integer, BitmapDrawable>();
private static BitmapDrawable getBitmapDrawable(int resId, Resources resources) { private static BitmapDrawable getBitmapDrawable(int resId, Resources resources) {
if (IMAGE_CACHE.containsKey(resId)) if (IMAGE_CACHE.containsKey(resId)) {
return IMAGE_CACHE.get(resId); return IMAGE_CACHE.get(resId);
else { } else {
BitmapDrawable b = (BitmapDrawable) resources.getDrawable(resId); BitmapDrawable b = (BitmapDrawable) resources.getDrawable(resId);
IMAGE_CACHE.put(resId, b); IMAGE_CACHE.put(resId, b);
return b; return b;

@ -246,8 +246,9 @@ public class OldTaskPreferences extends TodorooPreferenceActivity {
for(int i = 0; i < length; i++) { for(int i = 0; i < length; i++) {
cursor.moveToNext(); cursor.moveToNext();
task.readFromCursor(cursor); task.readFromCursor(cursor);
if (GCalHelper.deleteTaskEvent(task)) if (GCalHelper.deleteTaskEvent(task)) {
deletedEventCount++; deletedEventCount++;
}
} }
} finally { } finally {
cursor.close(); cursor.close();
@ -287,8 +288,9 @@ public class OldTaskPreferences extends TodorooPreferenceActivity {
for(int i = 0; i < length; i++) { for(int i = 0; i < length; i++) {
cursor.moveToNext(); cursor.moveToNext();
task.readFromCursor(cursor); task.readFromCursor(cursor);
if (GCalHelper.deleteTaskEvent(task)) if (GCalHelper.deleteTaskEvent(task)) {
deletedEventCount++; deletedEventCount++;
}
} }
} finally { } finally {
cursor.close(); cursor.close();

@ -130,8 +130,9 @@ public final class PluginServices {
private static PluginServices getInstance() { private static PluginServices getInstance() {
if(instance == null) { if(instance == null) {
synchronized (PluginServices.class) { synchronized (PluginServices.class) {
if (instance == null) if (instance == null) {
instance = new PluginServices(); instance = new PluginServices();
}
} }
} }
return instance; return instance;
@ -248,8 +249,9 @@ public final class PluginServices {
if(cursor.getCount() > 0) { if(cursor.getCount() > 0) {
cursor.moveToNext(); cursor.moveToNext();
return new Metadata(cursor); return new Metadata(cursor);
} else } else {
return null; return null;
}
} finally { } finally {
cursor.close(); cursor.close();
} }

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

Loading…
Cancel
Save