Remove unused code

pull/46/head
Alex Baker 11 years ago
parent e8b1eff7d7
commit e7d629e365

@ -334,11 +334,6 @@ abstract public class AbstractDatabase {
*/
public static class SqlConstructorVisitor implements PropertyVisitor<String, Void> {
@Override
public String visitDouble(Property<Double> property, Void data) {
return String.format("%s REAL", property.getColumnName());
}
@Override
public String visitInteger(Property<Integer> property, Void data) {
return String.format("%s INTEGER", property.getColumnName());

@ -9,7 +9,6 @@ import android.content.ContentValues;
import android.os.Parcel;
import android.os.Parcelable;
import com.todoroo.andlib.data.Property.DoubleProperty;
import com.todoroo.andlib.data.Property.IntegerProperty;
import com.todoroo.andlib.data.Property.LongProperty;
import com.todoroo.andlib.data.Property.PropertyVisitor;
@ -22,7 +21,6 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
/**
* <code>AbstractModel</code> represents a row in a database.
@ -172,11 +170,6 @@ public abstract class AbstractModel implements Parcelable, Cloneable {
return clone;
}
/** Check if this model has values that have been changed */
public boolean isModified() {
return setValues.size() > 0;
}
// --- data retrieval
/**
@ -222,8 +215,6 @@ public abstract class AbstractModel implements Parcelable, Cloneable {
return (TYPE) Long.valueOf((String) value);
} else if(value instanceof String && property instanceof IntegerProperty) {
return (TYPE) Integer.valueOf((String) value);
} else if(value instanceof String && property instanceof DoubleProperty) {
return (TYPE) Double.valueOf((String) value);
} else if(value instanceof Integer && property instanceof LongProperty) {
return (TYPE) Long.valueOf(((Number) value).longValue());
}
@ -379,17 +370,6 @@ public abstract class AbstractModel implements Parcelable, Cloneable {
}
}
/**
* Sets the state of the given flag on the given property
*/
public void setFlag(IntegerProperty property, int flag, boolean value) {
if(value) {
setValue(property, getValue(property) | flag);
} else {
setValue(property, getValue(property) & ~flag);
}
}
/**
* Returns the set state of the given flag on the given property
* @param property the property to get the set state of the flag
@ -424,13 +404,6 @@ public abstract class AbstractModel implements Parcelable, Cloneable {
return transitoryData.remove(key);
}
public Set<String> getAllTransitoryKeys() {
if (transitoryData == null) {
return null;
}
return transitoryData.keySet();
}
// --- Convenience wrappers for using transitories as flags
public boolean checkTransitory(String flag) {
Object trans = getTransitory(flag);
@ -498,12 +471,6 @@ public abstract class AbstractModel implements Parcelable, Cloneable {
}
}
@Override
public Void visitDouble(Property<Double> property, Object value) {
store.put(property.getColumnName(), (Double) value);
return null;
}
@Override
public Void visitInteger(Property<Integer> property, Object value) {
store.put(property.getColumnName(), (Integer) value);
@ -542,13 +509,6 @@ public abstract class AbstractModel implements Parcelable, Cloneable {
dest.writeParcelable(values, 0);
}
/**
* In addition to overriding this class, model classes should create
* a static final variable named "CREATOR" in order to satisfy the
* requirements of the Parcelable interface.
*/
abstract protected Parcelable.Creator<? extends AbstractModel> getCreator();
/**
* Parcelable creator helper
*/

@ -1,165 +0,0 @@
/**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.andlib.data;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import com.todoroo.andlib.service.Autowired;
import com.todoroo.andlib.service.DependencyInjectionService;
import com.todoroo.andlib.sql.Criterion;
import com.todoroo.andlib.sql.Query;
import com.todoroo.andlib.utility.AndroidUtilities;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Set;
/**
* DAO for reading and writing values from an Android ContentResolver
*
* @author Tim Su <tim@todoroo.com>
*
* @param <TYPE> model type
*/
public class ContentResolverDao<TYPE extends AbstractModel> {
/** class of model */
private final Class<TYPE> modelClass;
/** base content uri */
private final Uri baseUri;
/** content resolver */
private final ContentResolver cr;
@Autowired
protected Boolean debug;
public ContentResolverDao(Class<TYPE> modelClass, Context context, Uri baseUri) {
DependencyInjectionService.getInstance().inject(this);
this.modelClass = modelClass;
if(debug == null) {
debug = false;
}
this.baseUri = baseUri;
cr = context.getContentResolver();
}
/**
* Returns a URI for a single id
*/
private Uri uriWithId(long id) {
return Uri.withAppendedPath(baseUri, Long.toString(id));
}
/**
* Delete specific item from the given table
* @return number of rows affected
*/
public int delete(long id) {
return cr.delete(uriWithId(id), null, null);
}
/**
* Delete by criteria
* @return number of rows affected
*/
public int deleteWhere(Criterion where) {
return cr.delete(baseUri, where.toString(), null);
}
/**
* Query content provider
*/
public TodorooCursor<TYPE> query(Query query) {
if(debug) {
Log.i("SQL-" + modelClass.getSimpleName(), query.toString()); //$NON-NLS-1$
}
Cursor cursor = query.queryContentResolver(cr, baseUri);
return new TodorooCursor<TYPE>(cursor, query.getFields());
}
/**
* Create new or save existing model
* @return true if data was written to the db, false otherwise
*/
public boolean save(TYPE model) {
writeTransitoriesToModelContentValues(model);
if(model.isSaved()) {
if(model.getSetValues() == null) {
return false;
}
if(cr.update(uriWithId(model.getId()), model.getSetValues(), null, null) != 0) {
return true;
}
}
Uri uri = cr.insert(baseUri, model.getMergedValues());
long id = Long.parseLong(uri.getLastPathSegment());
model.setId(id);
model.markSaved();
return true;
}
private void writeTransitoriesToModelContentValues(AbstractModel model) {
Set<String> keys = model.getAllTransitoryKeys();
if (keys != null) {
ContentValues transitories = new ContentValues();
for (String key : keys) {
String newKey = AbstractModel.RETAIN_TRANSITORY_PREFIX + key;
Object value = model.getTransitory(key);
AndroidUtilities.putInto(transitories, newKey, value, false);
}
model.mergeWith(transitories);
}
}
/**
* Returns object corresponding to the given identifier
*
* @param properties
* properties to read
* @param id
* id of item
* @return null if no item found
*/
public TYPE fetch(long id, Property<?>... properties) {
TodorooCursor<TYPE> cursor = query(
Query.select(properties).where(AbstractModel.ID_PROPERTY.eq(id)));
try {
if (cursor.getCount() == 0) {
return null;
}
cursor.moveToFirst();
Constructor<TYPE> constructor = modelClass.getConstructor(TodorooCursor.class);
return constructor.newInstance(cursor);
} catch (SecurityException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} finally {
try {
cursor.close();
} catch (NullPointerException e) {
// cursor was not open
}
}
}
}

@ -19,20 +19,16 @@ import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* DAO for reading data from an instance of {@link AbstractDatabase}. If you
* are writing an add-on for Astrid, you probably want to be using a subclass
* of {@link ContentResolverDao} instead.
* of ContentResolverDao instead.
*
* @author Tim Su <tim@todoroo.com>
*
*/
public class DatabaseDao<TYPE extends AbstractModel> {
private static final String ERROR_TAG = "database-dao"; //$NON-NLS-1$
private final Class<TYPE> modelClass;
private Table table;
@ -50,20 +46,11 @@ public class DatabaseDao<TYPE extends AbstractModel> {
}
}
public DatabaseDao(Class<TYPE> modelClass, AbstractDatabase database) {
this(modelClass);
setDatabase(database);
}
/** Gets table associated with this DAO */
public Table getTable() {
return table;
}
public Class<TYPE> getModelClass() {
return modelClass;
}
/**
* Sets database accessed by this DAO. Used for dependency-injected
* initialization by child classes and unit tests

@ -132,8 +132,6 @@ public abstract class Property<TYPE> extends Field implements Cloneable {
public RETURN visitLong(Property<Long> property, PARAMETER data);
public RETURN visitDouble(Property<Double> property, PARAMETER data);
public RETURN visitString(Property<String> property, PARAMETER data);
}
@ -192,10 +190,6 @@ public abstract class Property<TYPE> extends Field implements Cloneable {
super(table, name, flags);
}
protected StringProperty(Table table, String name, String expression) {
super(table, name, expression);
}
@Override
public <RETURN, PARAMETER> RETURN accept(
PropertyVisitor<RETURN, PARAMETER> visitor, PARAMETER data) {
@ -228,39 +222,6 @@ public abstract class Property<TYPE> extends Field implements Cloneable {
}
}
/**
* Double property type. See {@link Property}
*
* @author Tim Su <tim@todoroo.com>
*
*/
public static class DoubleProperty extends Property<Double> {
public DoubleProperty(Table table, String name) {
super(table, name);
}
public DoubleProperty(Table table, String name, int flags) {
super(table, name, flags);
}
protected DoubleProperty(Table table, String name, String expression) {
super(table, name, expression);
}
@Override
public <RETURN, PARAMETER> RETURN accept(
PropertyVisitor<RETURN, PARAMETER> visitor, PARAMETER data) {
return visitor.visitDouble(this, data);
}
@Override
public DoubleProperty cloneAs(String tableAlias, String columnAlias) {
return (DoubleProperty) super.cloneAs(tableAlias, columnAlias);
}
}
/**
* Long property type. See {@link Property}
*
@ -277,10 +238,6 @@ public abstract class Property<TYPE> extends Field implements Cloneable {
super(table, name, flags);
}
protected LongProperty(Table table, String name, String expression) {
super(table, name, expression);
}
@Override
public <RETURN, PARAMETER> RETURN accept(
PropertyVisitor<RETURN, PARAMETER> visitor, PARAMETER data) {
@ -311,14 +268,6 @@ public abstract class Property<TYPE> extends Field implements Cloneable {
// --- pseudo-properties
/** Runs a SQL function and returns the result as a string */
public static class StringFunctionProperty extends StringProperty {
public StringFunctionProperty(String function, String columnName) {
super(null, columnName, function);
alias = columnName;
}
}
/** Runs a SQL function and returns the result as a string */
public static class IntegerFunctionProperty extends IntegerProperty {
public IntegerFunctionProperty(String function, String columnName) {

@ -5,7 +5,6 @@
*/
package com.todoroo.andlib.data;
import com.todoroo.andlib.sql.Field;
import com.todoroo.andlib.sql.SqlTable;
/**
@ -58,16 +57,6 @@ public final class Table extends SqlTable {
return new Table(name, modelClass, newAlias);
}
/**
* Create a field object based on the given property
*/
public Field field(Property<?> property) {
if(alias != null) {
return Field.field(alias + "." + property.name);
}
return Field.field(name + "." + property.name);
}
@Override
public String toString() {
if(hasAlias()) {

@ -33,9 +33,6 @@ public class TodorooCursor<TYPE extends AbstractModel> extends CursorWrapper {
/** Property reading visitor */
private static final CursorReadingVisitor reader = new CursorReadingVisitor();
/** Wrapped cursor */
private final Cursor cursor;
/**
* Create an <code>AstridCursor</code> from the supplied {@link Cursor}
* object.
@ -45,7 +42,6 @@ public class TodorooCursor<TYPE extends AbstractModel> extends CursorWrapper {
public TodorooCursor(Cursor cursor, Property<?>[] properties) {
super(cursor);
this.cursor = cursor;
this.properties = properties;
columnIndexCache = new WeakHashMap<String, Integer>();
}
@ -60,13 +56,6 @@ public class TodorooCursor<TYPE extends AbstractModel> extends CursorWrapper {
return (PROPERTY_TYPE)property.accept(reader, this);
}
/**
* @return underlying cursor
*/
public Cursor getCursor() {
return cursor;
}
/**
* Gets entire property list
*/
@ -95,16 +84,6 @@ public class TodorooCursor<TYPE extends AbstractModel> extends CursorWrapper {
*/
public static class CursorReadingVisitor implements PropertyVisitor<Object, TodorooCursor<?>> {
@Override
public Object visitDouble(Property<Double> property,
TodorooCursor<?> cursor) {
int column = columnIndex(property, cursor);
if(property.checkFlag(Property.PROP_FLAG_NULLABLE) && cursor.isNull(column)) {
return null;
}
return cursor.getDouble(column);
}
@Override
public Object visitInteger(Property<Integer> property,
TodorooCursor<?> cursor) {

@ -18,8 +18,6 @@ public interface NotificationManager {
public void cancel(int id);
public void cancelAll();
public void notify(int id, Notification notification);
/**
@ -41,11 +39,6 @@ public interface NotificationManager {
nm.cancel(id);
}
@Override
public void cancelAll() {
nm.cancelAll();
}
@Override
public void notify(int id, Notification notification) {
nm.notify(id, notification);

@ -6,7 +6,6 @@
package com.todoroo.andlib.sql;
import static com.todoroo.andlib.sql.SqlConstants.AND;
import static com.todoroo.andlib.sql.SqlConstants.EXISTS;
import static com.todoroo.andlib.sql.SqlConstants.LEFT_PARENTHESIS;
import static com.todoroo.andlib.sql.SqlConstants.NOT;
import static com.todoroo.andlib.sql.SqlConstants.OR;
@ -60,16 +59,6 @@ public abstract class Criterion {
};
}
public static Criterion exists(final Query query) {
return new Criterion(Operator.exists) {
@Override
protected void populate(StringBuilder sb) {
sb.append(EXISTS).append(SPACE).append(LEFT_PARENTHESIS).append(query).append(RIGHT_PARENTHESIS);
}
};
}
public static Criterion not(final Criterion criterion) {
return new Criterion(Operator.not) {

@ -1,12 +0,0 @@
/**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.andlib.sql;
public class EqCriterion extends UnaryCriterion {
EqCriterion(Field field, Object value) {
super(field, Operator.eq, value);
}
}

@ -5,8 +5,6 @@
*/
package com.todoroo.andlib.sql;
import static com.todoroo.andlib.sql.SqlConstants.AND;
import static com.todoroo.andlib.sql.SqlConstants.BETWEEN;
import static com.todoroo.andlib.sql.SqlConstants.COMMA;
import static com.todoroo.andlib.sql.SqlConstants.LEFT_PARENTHESIS;
import static com.todoroo.andlib.sql.SqlConstants.RIGHT_PARENTHESIS;
@ -56,10 +54,6 @@ public class Field extends DBObject<Field> {
return UnaryCriterion.gt(this, value);
}
public Criterion gte(Object value) {
return UnaryCriterion.gte(this, value);
}
public Criterion lt(final Object value) {
return UnaryCriterion.lt(this, value);
}
@ -76,18 +70,6 @@ public class Field extends DBObject<Field> {
return UnaryCriterion.isNotNull(this);
}
public Criterion between(final Object lower, final Object upper) {
final Field field = this;
return new Criterion(null) {
@Override
protected void populate(StringBuilder sb) {
sb.append(field).append(SPACE).append(BETWEEN).append(SPACE).append(lower).append(SPACE).append(AND)
.append(SPACE).append(upper);
}
};
}
public Criterion like(final String value) {
return UnaryCriterion.like(this, value);
}

@ -5,8 +5,6 @@
*/
package com.todoroo.andlib.sql;
import com.todoroo.andlib.data.Property.IntegerProperty;
import com.todoroo.andlib.data.Property.LongProperty;
import com.todoroo.andlib.data.Property.StringProperty;
@ -35,34 +33,12 @@ public final class Functions {
return new Field("(strftime('%s','now')*1000)");
}
public static Field fromNow(long millis) {
return new Field("(strftime('%s','now')*1000 + " + millis + ")");
}
public static Field strftime(LongProperty field, String format) {
return new Field("(strftime('" + format + "', datetime(" + field.toString() + "/1000, 'unixepoch', 'localtime')))");
}
public static Field cast(Field field, String newType) {
return new Field("CAST(" + field.toString() + " AS " +
newType + ")");
}
public static Field max(Field field) {
return new Field("MAX(" + field.toString() + ")");
}
public static Field count() {
return new Field("COUNT(1)");
}
public static Field length(StringProperty field) {
return new Field("LENGTH(" + field.toString() + ")");
}
public static Field bitwiseAnd(IntegerProperty field, int value) {
return new Field(field.toString() + " & " + value);
}
}

@ -1,19 +0,0 @@
/**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.andlib.sql;
import java.util.ArrayList;
import java.util.List;
public class GroupBy {
private List<Field> fields = new ArrayList<Field>();
public static GroupBy groupBy(Field field) {
GroupBy groupBy = new GroupBy();
groupBy.fields.add(field);
return groupBy;
}
}

@ -29,14 +29,6 @@ public class Join {
return new Join(table, JoinType.LEFT, criterions);
}
public static Join right(SqlTable table, Criterion... criterions) {
return new Join(table, JoinType.RIGHT, criterions);
}
public static Join out(SqlTable table, Criterion... criterions) {
return new Join(table, JoinType.OUT, criterions);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();

@ -6,5 +6,5 @@
package com.todoroo.andlib.sql;
public enum JoinType {
INNER, LEFT, RIGHT, OUT
INNER, LEFT
}

@ -8,8 +8,6 @@ package com.todoroo.andlib.sql;
import java.util.HashMap;
import java.util.Map;
import static com.todoroo.andlib.sql.SqlConstants.SPACE;
public final class Operator {
private final String operator;
@ -45,15 +43,6 @@ public final class Operator {
this.operator = operator;
}
public Operator getContrary() {
if(!contraryRegistry.containsKey(this)){
Operator opposite = new Operator(not.toString() + SPACE + this.toString());
contraryRegistry.put(this, opposite);
contraryRegistry.put(opposite, this);
}
return contraryRegistry.get(this);
}
@Override
public String toString() {
return this.operator.toString();

@ -37,10 +37,6 @@ public class Order {
secondaryExpressions.add(secondary);
}
public void removeSecondaryExpression(Order secondary) {
secondaryExpressions.remove(secondary);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();

@ -5,12 +5,7 @@
*/
package com.todoroo.andlib.sql;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import com.todoroo.andlib.data.Property;
import com.todoroo.astrid.api.AstridApiConstants;
import java.util.ArrayList;
import java.util.regex.Matcher;
@ -21,15 +16,12 @@ import static com.todoroo.andlib.sql.SqlConstants.COMMA;
import static com.todoroo.andlib.sql.SqlConstants.DISTINCT;
import static com.todoroo.andlib.sql.SqlConstants.FROM;
import static com.todoroo.andlib.sql.SqlConstants.GROUP_BY;
import static com.todoroo.andlib.sql.SqlConstants.LEFT_PARENTHESIS;
import static com.todoroo.andlib.sql.SqlConstants.LIMIT;
import static com.todoroo.andlib.sql.SqlConstants.ORDER_BY;
import static com.todoroo.andlib.sql.SqlConstants.RIGHT_PARENTHESIS;
import static com.todoroo.andlib.sql.SqlConstants.SELECT;
import static com.todoroo.andlib.sql.SqlConstants.SPACE;
import static com.todoroo.andlib.sql.SqlConstants.UNION;
import static com.todoroo.andlib.sql.SqlConstants.WHERE;
import static com.todoroo.andlib.sql.SqlTable.table;
import static java.util.Arrays.asList;
public final class Query {
@ -80,11 +72,6 @@ public final class Query {
return this;
}
public Query union(Query query) {
unions.add(query);
return this;
}
public Query orderBy(Order... order) {
orders.addAll(asList(order));
return this;
@ -95,11 +82,6 @@ public final class Query {
return this;
}
public Query appendSelectFields(Property<?>... selectFields) {
this.fields.addAll(asList(selectFields));
return this;
}
@Override
public boolean equals(Object o) {
return this == o || !(o == null || getClass() != o.getClass()) && this.toString().equals(o.toString());
@ -217,15 +199,6 @@ public final class Query {
}
}
public SqlTable as(String alias) {
return table(LEFT_PARENTHESIS + this.toString() + RIGHT_PARENTHESIS).as(alias);
}
public Query having(Criterion criterion) {
this.havings.add(criterion);
return this;
}
/**
* Gets a list of fields returned by this query
*/
@ -242,57 +215,6 @@ public final class Query {
return this;
}
/**
* Parse out properties and run query
*/
public Cursor queryContentResolver(ContentResolver cr, Uri baseUri) {
Uri uri = baseUri;
if(joins.size() != 0) {
throw new UnsupportedOperationException("can't perform join in content resolver query"); //$NON-NLS-1$
}
String[] projection = new String[fields.size()];
for(int i = 0; i < projection.length; i++) {
projection[i] = fields.get(i).toString();
}
StringBuilder groupByClause = new StringBuilder();
StringBuilder selectionClause = new StringBuilder();
StringBuilder orderClause = new StringBuilder();
if(queryTemplate != null) {
QueryTemplateHelper.queryForContentResolver(queryTemplate,
selectionClause, orderClause, groupByClause);
} else {
if(groupBies.size() > 0) {
for (Field groupBy : groupBies) {
groupByClause.append(SPACE).append(groupBy).append(COMMA);
}
if(groupByClause.length() > 0) {
groupByClause.deleteCharAt(groupByClause.length() - 1);
}
}
for (Criterion criterion : criterions) {
selectionClause.append(criterion).append(SPACE);
}
for (Order order : orders) {
orderClause.append(SPACE).append(order).append(COMMA);
}
if(orderClause.length() > 0) {
orderClause.deleteCharAt(orderClause.length() - 1);
}
}
if(groupByClause.length() > 0) {
uri = Uri.withAppendedPath(baseUri, AstridApiConstants.GROUP_BY_URI +
groupByClause.toString().trim());
}
return cr.query(uri, projection, selectionClause.toString(), null,
orderClause.toString());
}
/** query template helper */
public static class QueryTemplateHelper {

@ -110,11 +110,6 @@ public final class QueryTemplate {
}
}
public QueryTemplate having(Criterion criterion) {
this.havings.add(criterion);
return this;
}
public QueryTemplate limit(int limitValue) {
this.limit = limitValue;
return this;

@ -18,14 +18,11 @@ public final class SqlConstants {
public static final String LEFT_PARENTHESIS = "(";
public static final String RIGHT_PARENTHESIS = ")";
public static final String AND = "AND";
public static final String BETWEEN = "BETWEEN";
public static final String LIKE = "LIKE";
public static final String OR = "OR";
public static final String ORDER_BY = "ORDER BY";
public static final String GROUP_BY = "GROUP BY";
public static final String UNION = "UNION";
public static final String WHERE = "WHERE";
public static final String EXISTS = "EXISTS";
public static final String NOT = "NOT";
public static final String LIMIT = "LIMIT";
}

@ -10,15 +10,4 @@ public class SqlTable extends DBObject<SqlTable> {
protected SqlTable(String expression) {
super(expression);
}
public static SqlTable table(String table) {
return new SqlTable(table);
}
protected String fieldExpression(String fieldName) {
if (hasAlias()) {
return alias + "." + fieldName;
}
return expression+"."+fieldName;
}
}

@ -61,10 +61,6 @@ public class UnaryCriterion extends Criterion {
return new UnaryCriterion(field, Operator.gt, value);
}
public static Criterion gte(Field field, Object value) {
return new UnaryCriterion(field, Operator.gte, value);
}
public static Criterion lt(Field field, Object value) {
return new UnaryCriterion(field, Operator.lt, value);
}

@ -10,14 +10,9 @@ import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.text.InputType;
import android.util.DisplayMetrics;
@ -25,39 +20,23 @@ import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import com.todoroo.andlib.service.ExceptionService;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Android Utility Classes
@ -86,43 +65,6 @@ public class AndroidUtilities {
});
}
/**
* @return true if we're connected to the internet
*/
public static boolean isConnected(Context context) {
ConnectivityManager manager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info == null) {
return false;
}
if (info.getState() != State.CONNECTED) {
return false;
}
return true;
}
/** Fetch the image specified by the given url */
public static Bitmap fetchImage(URL url) throws IOException {
InputStream is = null;
try {
URLConnection conn = url.openConnection();
conn.connect();
is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is, 16384);
try {
Bitmap bitmap = BitmapFactory.decodeStream(bis);
return bitmap;
} finally {
bis.close();
}
} finally {
if(is != null) {
is.close();
}
}
}
/** Read a bitmap from the specified file, scaling if necessary
* Returns null if scaling failed after several tries */
private static final int[] SAMPLE_SIZES = { 1, 2, 4, 6, 8, 10 };
@ -163,20 +105,6 @@ public class AndroidUtilities {
}
}
/**
* Start the given intent, handling security exceptions if they arise
*/
public static void startExternalIntentForResult(
Activity activity, Intent intent, int requestCode) {
try {
activity.startActivityForResult(intent, requestCode);
} catch (SecurityException e) {
getExceptionService().displayAndReportError(activity,
"start-external-intent-" + intent.toString(), //$NON-NLS-1$
e);
}
}
/**
* Put an arbitrary object into a {@link ContentValues}
*/
@ -231,19 +159,6 @@ public class AndroidUtilities {
// --- serialization
/**
* Rips apart a content value into two string arrays, keys and value
*/
public static String[][] contentValuesToStringArrays(ContentValues source) {
String[][] result = new String[2][source.size()];
int i = 0;
for(Entry<String, Object> entry : source.valueSet()) {
result[0][i] = entry.getKey();
result[1][i++] = entry.getValue().toString();
}
return result;
}
/**
* Return index of value in array
* @param array array to search
@ -495,29 +410,6 @@ public class AndroidUtilities {
}
}
/**
* Find a child view of a certain type
* @return first view (by DFS) if found, or null if none
*/
public static <TYPE> TYPE findViewByType(View view, Class<TYPE> type) {
if(view == null) {
return null;
}
if(type.isInstance(view)) {
return (TYPE) view;
}
if(view instanceof ViewGroup) {
ViewGroup group = (ViewGroup) view;
for(int i = 0; i < group.getChildCount(); i++) {
TYPE v = findViewByType(group.getChildAt(i), type);
if(v != null) {
return v;
}
}
}
return null;
}
/**
* @return Android SDK version as an integer. Works on all versions
*/
@ -525,25 +417,6 @@ public class AndroidUtilities {
return Integer.parseInt(android.os.Build.VERSION.SDK);
}
/**
* Copy databases to a given folder. Useful for debugging
*/
public static void copyDatabases(Context context, String folder) {
File folderFile = new File(folder);
if(!folderFile.exists()) {
folderFile.mkdir();
}
for(String db : context.databaseList()) {
File dbFile = context.getDatabasePath(db);
try {
copyFile(dbFile, new File(folderFile.getAbsolutePath() +
File.separator + db));
} catch (Exception e) {
Log.e("ERROR", "ERROR COPYING DB " + db, e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
/**
* Sort files by date so the newest file is on top
*/
@ -556,19 +429,6 @@ public class AndroidUtilities {
});
}
/**
* Search for the given value in the map, returning key if found
* @return null if not found, otherwise key
*/
public static <KEY, VALUE> KEY findKeyInMap(Map<KEY, VALUE> map, VALUE value){
for (Entry<KEY, VALUE> entry: map.entrySet()) {
if(entry.getValue().equals(value)) {
return entry.getKey();
}
}
return null;
}
/**
* Sleep, ignoring interruption. Before using this method, think carefully
* about why you are ignoring interruptions.
@ -615,30 +475,6 @@ public class AndroidUtilities {
receiver, methodName, params, args);
}
/**
* Call a static method via reflection if API level is at least minSdk
* @param minSdk minimum sdk number (i.e. 8)
* @param className fully qualified class to call method on
* @param methodName method name to call
* @param params method parameter types
* @param args arguments
* @return method return value, or null if nothing was called or exception
*/
public static Object callApiStaticMethod(int minSdk, String className,
String methodName, Class<?>[] params, Object... args) {
if(getSdkVersion() < minSdk) {
return null;
}
try {
return AndroidUtilities.callMethod(Class.forName(className),
null, methodName, params, args);
} catch (ClassNotFoundException e) {
getExceptionService().reportError("call-method", e);
return null;
}
}
/**
* Call a method via reflection
* @param receiver object to call method on (can be null)
@ -647,12 +483,11 @@ public class AndroidUtilities {
* @param args arguments
* @return method return value, or null if nothing was called or exception
*/
public static Object callMethod(Class<?> cls, Object receiver,
public static void callMethod(Class<?> cls, Object receiver,
String methodName, Class<?>[] params, Object... args) {
try {
Method method = cls.getMethod(methodName, params);
Object result = method.invoke(receiver, args);
return result;
method.invoke(receiver, args);
} catch (SecurityException e) {
getExceptionService().reportError("call-method", e);
} catch (NoSuchMethodException e) {
@ -664,101 +499,6 @@ public class AndroidUtilities {
} catch (InvocationTargetException e) {
getExceptionService().reportError("call-method", e);
}
return null;
}
/**
* From Android MyTracks project (http://mytracks.googlecode.com/).
* Licensed under the Apache Public License v2
*/
public static CharSequence readFile(Context activity, int id) {
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(
activity.getResources().openRawResource(id)));
String line;
StringBuilder buffer = new StringBuilder();
while ((line = in.readLine()) != null) {
buffer.append(line).append('\n');
}
return buffer;
} catch (IOException e) {
return ""; //$NON-NLS-1$
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// Ignore
}
}
}
}
public static String readInputStream(InputStream input) {
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(input), 1 << 14);
String line;
StringBuilder buffer = new StringBuilder();
while ((line = in.readLine()) != null) {
buffer.append(line).append('\n');
}
return buffer.toString();
} catch (IOException e) {
return ""; //$NON-NLS-1$
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
// Ignore
}
}
}
}
/**
* Performs an md5 hash on the input string
*/
public static String md5(String input) {
try {
byte[] bytesOfMessage = input.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(bytesOfMessage);
BigInteger bigInt = new BigInteger(1,digest);
String hashtext = bigInt.toString(16);
while(hashtext.length() < 32 ){
hashtext = "0" + hashtext;
}
return hashtext;
} catch (Exception e) {
return "";
}
}
/**
* Create an intent to a remote activity
*/
public static Intent remoteIntent(String appPackage, String activityClass) {
Intent intent = new Intent();
intent.setClassName(appPackage, activityClass);
return intent;
}
/**
* Gets application signature
* @return application signature, or null if an error was encountered
*/
public static String getSignature(Context context, String packageName) {
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName,
PackageManager.GET_SIGNATURES);
return packageInfo.signatures[0].toCharsString();
} catch (Exception e) {
return null;
}
}
/**
@ -804,36 +544,6 @@ public class AndroidUtilities {
return exceptionService;
}
/**
* Concatenate additional stuff to the end of the array
*/
public static <TYPE> TYPE[] concat(TYPE[] dest, TYPE[] source, TYPE... additional) {
int i = 0;
for(; i < Math.min(dest.length, source.length); i++) {
dest[i] = source[i];
}
int base = i;
for(; i < dest.length; i++) {
dest[i] = additional[i - base];
}
return dest;
}
/**
* Returns a map where the keys are the values of the map argument
* and the values are the corresponding keys. Use at your own
* risk if your map is not 1-to-1!
*/
public static <K, V> Map<V, K> reverseMap(Map<K, V> map) {
HashMap<V, K> reversed = new HashMap<V, K>();
Set<Entry<K, V>> entries = map.entrySet();
for (Entry<K, V> entry : entries) {
reversed.put(entry.getValue(), entry.getKey());
}
return reversed;
}
/**
* Capitalize the first character
*/
@ -894,28 +604,6 @@ public class AndroidUtilities {
}
}
/**
* Tries to parse an int from a string, returning the default value on failure
*/
public static int tryParseInt(String str, int defaultValue) {
try {
return Integer.parseInt(str);
} catch (NumberFormatException e) {
return defaultValue;
}
}
/**
* Tries to parse an int from a string, returning the default value on failure
*/
public static long tryParseLong(String str, long defaultValue) {
try {
return Long.parseLong(str);
} catch (NumberFormatException e) {
return defaultValue;
}
}
/**
* Returns the final word characters after the last '.'
*/
@ -930,37 +618,4 @@ public class AndroidUtilities {
}
return extension;
}
/**
* Logs a JSONObject using in a readable way
*/
public static void logJSONObject(String tag, JSONObject object) {
if (object == null) {
Log.e(tag, "JSONOBject: null");
return;
} else {
Log.e(tag, "Logging JSONObject");
}
Iterator<String> keys = object.keys();
while (keys.hasNext()) {
String key = keys.next();
JSONArray array = object.optJSONArray(key);
if (array != null) {
Log.e(tag, " " + key + ": Array");
for (int i = 0; i < array.length(); i++) {
try {
Object elem = array.get(i);
Log.e(tag, " Index " + i + ": " + elem);
} catch (JSONException e) {/**/}
}
} else {
try {
Object value = object.get(key);
Log.e(tag, " " + key + ": " + value);
} catch (JSONException e) {/**/}
}
}
}
}

@ -25,14 +25,6 @@ public class DateUtilities {
* ============================================================ long time
* ====================================================================== */
/** Convert unixtime into date */
public static final Date unixtimeToDate(long millis) {
if(millis == 0) {
return null;
}
return new Date(millis);
}
/** Convert date into unixtime */
public static final long dateToUnixtime(Date date) {
if(date == null) {
@ -208,13 +200,6 @@ public class DateUtilities {
DateUtils.LENGTH_MEDIUM);
}
/**
* @return date format as getDateFormat with weekday
*/
public static String getDateStringWithTimeAndWeekday(Context context, Date date) {
return getDateStringWithWeekday(date) + " " + getTimeString(context, date);
}
/**
* @return date with time at the end
*/
@ -317,17 +302,4 @@ public class DateUtilities {
Date result = new SimpleDateFormat(formatString).parse(iso8601String);
return result.getTime();
}
public static String timeToIso8601(long time, boolean includeTime) {
if (time == 0) {
return null;
}
Date date = new Date(time);
String formatString = "yyyy-MM-dd'T'HH:mm:ssZ"; //$NON-NLS-1$
if (!includeTime) {
formatString = "yyyy-MM-dd"; //$NON-NLS-1$
}
return new SimpleDateFormat(formatString).format(date);
}
}

@ -31,10 +31,6 @@ public class Pair<L, R> {
this.right = right;
}
public static <A, B> Pair<A, B> create(A left, B right) {
return new Pair<A, B>(left, right);
}
@Override
public final boolean equals(Object o) {
if (!(o instanceof Pair<?, ?>)) {

@ -126,31 +126,6 @@ public class Preferences {
}
}
/** Gets an float value from a string preference. Returns null
* if the value is not set or not an flat.
*
* @param keyResource resource from string.xml
*/
public static Float getFloatFromString(int keyResource) {
Context context = ContextManager.getContext();
Resources r = context.getResources();
String value = getPrefs(context).getString(r.getString(keyResource), ""); //$NON-NLS-1$
try {
return Float.parseFloat(value);
} catch (Exception e) {
return null;
}
}
/**
* Sets string preference
*/
public static void setString(int keyResource, String newValue) {
Context context = ContextManager.getContext();
setString(context.getString(keyResource), newValue);
}
/**
* Sets string preference
*/

@ -6,7 +6,6 @@
package com.todoroo.astrid.api;
import android.content.Intent;
import android.widget.RemoteViews;
/**
* Constants for interfacing with Astrid.
@ -76,18 +75,8 @@ public class AstridApiConstants {
*/
public static final String EXTRAS_NEW_DUE_DATE = "newDueDate";
/**
* Extras name for sync provider name
*/
public static final String EXTRAS_NAME = "name";
// --- Add-ons API
/**
* Action name for broadcast intent requesting add-ons
*/
public static final String BROADCAST_REQUEST_ADDONS = API_PACKAGE + ".REQUEST_ADDONS";
/**
* Action name for broadcast intent sending add-ons back to Astrid
* <li> EXTRAS_RESPONSE an {@link Addon} object
@ -123,21 +112,6 @@ public class AstridApiConstants {
*/
public static final String BROADCAST_SEND_CUSTOM_FILTER_CRITERIA = API_PACKAGE + ".SEND_CUSTOM_FILTER_CRITERIA";
// --- Edit Controls API
/**
* Action name for broadcast intent requesting task edit controls
* <li> EXTRAS_TASK_ID id of the task user is editing
*/
public static final String BROADCAST_REQUEST_EDIT_CONTROLS = API_PACKAGE + ".REQUEST_EDIT_CONTROLS";
/**
* Action name for broadcast intent sending task edit controls back to Astrid
* <li> EXTRAS_ADDON your add-on identifier
* <li> EXTRAS_RESPONSE a {@link RemoteViews} with your edit controls
*/
public static final String BROADCAST_SEND_EDIT_CONTROLS = API_PACKAGE + ".SEND_EDIT_CONTROLS";
// --- Task Details API
/**
@ -175,12 +149,6 @@ public class AstridApiConstants {
// --- Task Decorations API
/**
* Action name for broadcast intent requesting task list decorations for a task
* <li> EXTRAS_TASK_ID id of the task
*/
public static final String BROADCAST_REQUEST_DECORATIONS = API_PACKAGE + ".REQUEST_DECORATIONS";
/**
* Action name for broadcast intent sending decorations back to Astrid
* <li> EXTRAS_ADDON your add-on identifier
@ -213,11 +181,6 @@ public class AstridApiConstants {
// --- Events API
/**
* Action name for broadcast intent notifying add-ons that Astrid started up
*/
public static final String BROADCAST_EVENT_STARTUP = API_PACKAGE + ".STARTUP";
/**
* Action name for broadcast intent notifying Astrid task list to refresh
*/

@ -1,55 +0,0 @@
/**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.astrid.api;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Section Header for Filter List
*
* @author Tim Su <tim@todoroo.com>
*
*/
public class FilterListHeader extends FilterListItem {
/**
* Constructor for creating a new FilterListHeader
*/
public FilterListHeader(String listingTitle) {
this.listingTitle = listingTitle;
}
/**
* Constructor for creating a new FilterListHeader
*/
protected FilterListHeader() {
//
}
// --- parcelable
@Override
public int describeContents() {
return 0;
}
public static final Parcelable.Creator<FilterListHeader> CREATOR = new Parcelable.Creator<FilterListHeader>() {
@Override
public FilterListHeader createFromParcel(Parcel source) {
FilterListHeader item = new FilterListHeader();
item.readFromParcel(source);
return item;
}
@Override
public FilterListHeader[] newArray(int size) {
return new FilterListHeader[size];
}
};
}

@ -1,91 +0,0 @@
/**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.astrid.api;
import android.app.PendingIntent;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Special filter that launches a PendingIntent when accessed.
*
* @author Tim Su <tim@todoroo.com>
*
*/
public final class IntentFilter extends FilterListItem implements Parcelable {
/**
* PendingIntent to trigger when pressed
*/
public PendingIntent intent;
/**
* Constructor for creating a new IntentFilter
*
* @param listingTitle
* Title of this item as displayed on the lists page, e.g. Inbox
* @param intent
* intent to load
*/
public IntentFilter(String listingTitle, PendingIntent intent) {
this.listingTitle = listingTitle;
this.intent = intent;
}
/**
* Constructor for creating a new IntentFilter used internally
*/
protected IntentFilter(PendingIntent intent) {
this.intent = intent;
}
// --- parcelable
/**
* {@inheritDoc}
*/
@Override
public int describeContents() {
return 0;
}
/**
* {@inheritDoc}
*/
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelable(intent, 0);
super.writeToParcel(dest, flags);
}
/**
* Parcelable creator
*/
public static final Parcelable.Creator<IntentFilter> CREATOR = new Parcelable.Creator<IntentFilter>() {
/**
* {@inheritDoc}
*/
@Override
public IntentFilter createFromParcel(Parcel source) {
IntentFilter item = new IntentFilter((PendingIntent) source.readParcelable(
PendingIntent.class.getClassLoader()));
item.readFromParcel(source);
return item;
}
/**
* {@inheritDoc}
*/
@Override
public IntentFilter[] newArray(int size) {
return new IntentFilter[size];
}
};
}

@ -16,11 +16,6 @@ import android.graphics.drawable.BitmapDrawable;
*/
public class TaskAction {
/**
* Label
*/
public String text = null;
/**
* Intent to call when invoking this operation
*/
@ -31,64 +26,12 @@ public class TaskAction {
*/
public BitmapDrawable icon = null;
/**
* Quick action drawable resource
*/
public int drawable = 0;
/**
* Create an EditOperation object
*
* @param text
* label to display
*/
public TaskAction(String text, PendingIntent intent, BitmapDrawable icon) {
public TaskAction(PendingIntent intent, BitmapDrawable icon) {
super();
this.text = text;
this.intent = intent;
this.icon = icon;
}
// --- parcelable helpers
/**
* {@inheritDoc}
*/
public int describeContents() {
return 0;
}
//
// /**
// * {@inheritDoc}
// */
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(text);
// dest.writeParcelable(intent, 0);
// dest.writeParcelable(icon, 0);
// dest.writeInt(drawable);
// }
//
// /**
// * Parcelable creator
// */
// public static final Parcelable.Creator<TaskAction> CREATOR = new Parcelable.Creator<TaskAction>() {
// /**
// * {@inheritDoc}
// */
// public TaskAction createFromParcel(Parcel source) {
// TaskAction action = new TaskAction(source.readString(),
// (PendingIntent)source.readParcelable(PendingIntent.class.getClassLoader()),
// (Bitmap)source.readParcelable(Bitmap.class.getClassLoader()));
// action.drawable = source.readInt();
// return action;
// }
//
// /**
// * {@inheritDoc}
// */
// public TaskAction[] newArray(int size) {
// return new TaskAction[size];
// };
// };
}

@ -1,70 +0,0 @@
/**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.astrid.core;
import android.os.Parcel;
import android.os.Parcelable;
import com.todoroo.astrid.api.FilterListItem;
/**
* Special filter that triggers the search functionality when accessed.
*
* @author Tim Su <tim@todoroo.com>
*
*/
public class SearchFilter extends FilterListItem {
/**
* Constructor for creating a new SearchFilter
*
* @param listingTitle
* Title of this item as displayed on the lists page, e.g. Inbox
*/
public SearchFilter(String listingTitle) {
this.listingTitle = listingTitle;
}
protected SearchFilter() {
//
}
// --- parcelable
/**
* {@inheritDoc}
*/
@Override
public int describeContents() {
return 0;
}
/**
* Parcelable creator
*/
public static final Parcelable.Creator<SearchFilter> CREATOR = new Parcelable.Creator<SearchFilter>() {
/**
* {@inheritDoc}
*/
@Override
public SearchFilter createFromParcel(Parcel source) {
SearchFilter item = new SearchFilter();
item.readFromParcel(source);
return item;
}
/**
* {@inheritDoc}
*/
@Override
public SearchFilter[] newArray(int size) {
return new SearchFilter[size];
}
};
}

@ -122,10 +122,4 @@ public class Metadata extends AbstractModel {
// --- parcelable helpers
private static final Creator<Metadata> CREATOR = new ModelCreator<Metadata>(Metadata.class);
@Override
protected Creator<? extends AbstractModel> getCreator() {
return CREATOR;
}
}

@ -1,49 +0,0 @@
/**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.astrid.data;
import android.content.Context;
import com.todoroo.andlib.data.ContentResolverDao;
import com.todoroo.andlib.sql.Criterion;
/**
* Data access object for accessing Astrid's {@link Metadata} table. A
* piece of Metadata is information about a task, for example a tag or a
* note. It operates in a one-to-many relation with tasks.
*
* @author Tim Su <tim@todoroo.com>
*
*/
public class MetadataApiDao extends ContentResolverDao<Metadata> {
public MetadataApiDao(Context context) {
super(Metadata.class, context, Metadata.CONTENT_URI);
}
/**
* Generates SQL clauses
*/
public static class MetadataCriteria {
/** Returns all metadata associated with a given task */
public static Criterion byTask(long taskId) {
return Metadata.TASK.eq(taskId);
}
/** Returns all metadata associated with a given key */
public static Criterion withKey(String key) {
return Metadata.KEY.eq(key);
}
/** Returns all metadata associated with a given key */
public static Criterion byTaskAndwithKey(long taskId, String key) {
return Criterion.and(withKey(key), byTask(taskId));
}
}
}

@ -12,9 +12,7 @@ import android.graphics.BitmapFactory;
import android.text.TextUtils;
import com.todoroo.andlib.data.AbstractModel;
import com.todoroo.andlib.data.Property.LongProperty;
import com.todoroo.andlib.data.Property.StringProperty;
import com.todoroo.andlib.data.TodorooCursor;
import com.todoroo.andlib.utility.DateUtilities;
import org.json.JSONException;
@ -43,21 +41,12 @@ abstract public class RemoteModel extends AbstractModel {
/** user id property common to all remote models */
protected static final String USER_ID_PROPERTY_NAME = "userId"; //$NON-NLS-1$
/** user id property */
public static final StringProperty USER_ID_PROPERTY = new StringProperty(null, USER_ID_PROPERTY_NAME);
/** user json property common to all remote models */
protected static final String USER_JSON_PROPERTY_NAME = "user"; //$NON-NLS-1$
/** user json property */
@Deprecated public static final StringProperty USER_JSON_PROPERTY = new StringProperty(null, USER_JSON_PROPERTY_NAME);
/** pushed at date property name */
public static final String PUSHED_AT_PROPERTY_NAME = "pushedAt"; //$NON-NLS-1$
/** pushed at date property name */
public static final LongProperty PUSHED_AT_PROPERTY = new LongProperty(null, PUSHED_AT_PROPERTY_NAME);
/** constant value for no uuid */
public static final String NO_UUID = "0"; //$NON-NLS-1$
@ -70,13 +59,6 @@ abstract public class RemoteModel extends AbstractModel {
}
}
/**
* Utility method to get the identifier of the model, if it exists.
*
* @return {@value #NO_UUID} if this model was not added to the database
*/
abstract public String getUuid();
protected String getUuidHelper(StringProperty uuid) {
if(setValues != null && setValues.containsKey(uuid.name)) {
return setValues.getAsString(uuid.name);
@ -105,7 +87,6 @@ abstract public class RemoteModel extends AbstractModel {
public static final String PICTURE_THUMB = "thumb"; //$NON-NLS-1$
public static final String PICTURE_MEDIUM = "medium"; //$NON-NLS-1$
public static final String PICTURE_LARGE = "large"; //$NON-NLS-1$
public String getPictureUrl(StringProperty pictureProperty, String size) {
String value = getValue(pictureProperty);
@ -121,11 +102,6 @@ abstract public class RemoteModel extends AbstractModel {
public static final String PICTURES_DIRECTORY = "pictures"; //$NON-NLS-1$
public static String getPictureHash(UserActivity update) {
return String.format("cached::%s%s", update.getValue(UserActivity.TARGET_ID), update.getValue(UserActivity.CREATED_AT));
}
public static String getPictureHash(TagData tagData) {
long tag_date = 0;
if (tagData.containsValue(TagData.CREATION_DATE)) {
@ -206,10 +182,5 @@ abstract public class RemoteModel extends AbstractModel {
}
}
public static String getPictureUrlFromCursor(TodorooCursor<?> cursor, StringProperty pictureProperty, String size) {
String value = cursor.get(pictureProperty);
return getPictureUrl(value, size);
}
}
}

@ -60,14 +60,6 @@ public class StoreObject extends AbstractModel {
public static final StringProperty VALUE3 = new StringProperty(
TABLE, "value3");
/** Store Value Column 4 */
public static final StringProperty VALUE4 = new StringProperty(
TABLE, "value4");
/** Store Value Column 5 */
public static final StringProperty VALUE5 = new StringProperty(
TABLE, "value5");
/** List of all properties for this model */
public static final Property<?>[] PROPERTIES = generateProperties(StoreObject.class);
@ -104,10 +96,4 @@ public class StoreObject extends AbstractModel {
// --- parcelable helpers
private static final Creator<StoreObject> CREATOR = new ModelCreator<StoreObject>(StoreObject.class);
@Override
protected Creator<? extends AbstractModel> getCreator() {
return CREATOR;
}
}

@ -1,45 +0,0 @@
/**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.astrid.data;
import android.content.Context;
import com.todoroo.andlib.data.ContentResolverDao;
import com.todoroo.andlib.sql.Criterion;
/**
* Data access object for accessing Astrid's {@link StoreObject} table. A
* StoreObject is an arbitrary piece of data stored inside of Astrid.
*
* @author Tim Su <tim@todoroo.com>
*
*/
public class StoreObjectApiDao extends ContentResolverDao<StoreObject> {
public StoreObjectApiDao(Context context) {
super(StoreObject.class, context, StoreObject.CONTENT_URI);
}
// --- SQL clause generators
/**
* Generates SQL clauses
*/
public static class StoreObjectCriteria {
/** Returns all store objects with given type */
public static Criterion byType(String type) {
return StoreObject.TYPE.eq(type);
}
/** Returns store object with type and key */
public static Criterion byTypeAndItem(String type, String item) {
return Criterion.and(byType(type), StoreObject.ITEM.eq(item));
}
}
}

@ -7,16 +7,13 @@ package com.todoroo.astrid.data;
import android.content.ContentValues;
import android.net.Uri;
import com.todoroo.andlib.data.AbstractModel;
import com.todoroo.andlib.data.Property;
import com.todoroo.andlib.data.Property.IntegerProperty;
import com.todoroo.andlib.data.Property.LongProperty;
import com.todoroo.andlib.data.Property.StringProperty;
import com.todoroo.andlib.data.Table;
import com.todoroo.andlib.data.TodorooCursor;
import com.todoroo.astrid.api.AstridApiConstants;
/**
* Data Model which represents a collaboration space for users / tasks.
@ -31,10 +28,6 @@ public final class TagData extends RemoteModel {
/** table for this model */
public static final Table TABLE = new Table("tagdata", TagData.class);
/** content uri for this model */
public static final Uri CONTENT_URI = Uri.parse("content://" + AstridApiConstants.API_PACKAGE + "/" +
TABLE.name);
// --- properties
/** ID */
@ -77,10 +70,6 @@ public final class TagData extends RemoteModel {
public static final LongProperty CREATION_DATE = new LongProperty(
TABLE, "created", Property.PROP_FLAG_DATE);
/** Unixtime Project was last touched */
public static final LongProperty MODIFICATION_DATE = new LongProperty(
TABLE, "modified", Property.PROP_FLAG_DATE);
/** Unixtime Project was completed. 0 means active */
public static final LongProperty COMPLETION_DATE = new LongProperty(
TABLE, "completed", Property.PROP_FLAG_DATE);
@ -145,18 +134,6 @@ public final class TagData extends RemoteModel {
/** List of all properties for this model */
public static final Property<?>[] PROPERTIES = generateProperties(TagData.class);
// --- flags
/** whether user should not be notified of tag activity */
public static final int FLAG_SILENT = 1 << 1;
/** whether tag is emergent */
@Deprecated
public static final int FLAG_EMERGENT = 1 << 2;
/** whether tag represents a featured list */
public static final int FLAG_FEATURED = 1 << 3;
// --- defaults
/** Default values container */
@ -214,7 +191,6 @@ public final class TagData extends RemoteModel {
return getIdHelper(ID);
}
@Override
public String getUuid() {
return getUuidHelper(UUID);
}
@ -223,18 +199,8 @@ public final class TagData extends RemoteModel {
public static final Creator<TagData> CREATOR = new ModelCreator<TagData>(TagData.class);
@Override
protected Creator<? extends AbstractModel> getCreator() {
return CREATOR;
}
// --- data access methods
/** Checks whether task is done. Requires COMPLETION_DATE */
public boolean isCompleted() {
return getValue(COMPLETION_DATE) > 0;
}
/** Checks whether task is deleted. Will return false if DELETION_DATE not read */
public boolean isDeleted() {
// assume false if we didn't load deletion date

@ -1,7 +1,6 @@
package com.todoroo.astrid.data;
import android.content.ContentValues;
import android.net.Uri;
import com.todoroo.andlib.data.AbstractModel;
import com.todoroo.andlib.data.Property;
@ -9,16 +8,11 @@ import com.todoroo.andlib.data.Property.LongProperty;
import com.todoroo.andlib.data.Property.StringProperty;
import com.todoroo.andlib.data.Table;
import com.todoroo.andlib.data.TodorooCursor;
import com.todoroo.astrid.api.AstridApiConstants;
public class TagMetadata extends AbstractModel {
public static final Table TABLE = new Table("tag_metadata", TagMetadata.class);
/** content uri for this model */
public static final Uri CONTENT_URI = Uri.parse("content://" + AstridApiConstants.API_PACKAGE + "/" +
TABLE.name);
// --- properties
/** ID */
@ -41,18 +35,6 @@ public class TagMetadata extends AbstractModel {
public static final StringProperty VALUE1 = new StringProperty(
TABLE, "value");
/** Metadata Text Value Column 2 */
public static final StringProperty VALUE2 = new StringProperty(
TABLE, "value2");
/** Metadata Text Value Column 3 */
public static final StringProperty VALUE3 = new StringProperty(
TABLE, "value3");
/** Unixtime Metadata was created */
public static final LongProperty CREATION_DATE = new LongProperty(
TABLE, "created");
/** Unixtime metadata was deleted/tombstoned */
public static final LongProperty DELETION_DATE = new LongProperty(
TABLE, "deleted");
@ -94,9 +76,4 @@ public class TagMetadata extends AbstractModel {
// --- parcelable helpers
private static final Creator<TagMetadata> CREATOR = new ModelCreator<TagMetadata>(TagMetadata.class);
@Override
protected Creator<? extends AbstractModel> getCreator() {
return CREATOR;
}
}

@ -10,7 +10,6 @@ import android.content.ContentValues;
import android.content.res.Resources;
import android.net.Uri;
import com.todoroo.andlib.data.AbstractModel;
import com.todoroo.andlib.data.Property;
import com.todoroo.andlib.data.Property.IntegerProperty;
import com.todoroo.andlib.data.Property.LongProperty;
@ -303,7 +302,6 @@ public final class Task extends RemoteModel {
return getIdHelper(ID);
}
@Override
public String getUuid() {
return getUuidHelper(UUID);
}
@ -312,11 +310,6 @@ public final class Task extends RemoteModel {
public static final Creator<Task> CREATOR = new ModelCreator<Task>(Task.class);
@Override
protected Creator<? extends AbstractModel> getCreator() {
return CREATOR;
}
// --- data access methods
/** Checks whether task is done. Requires COMPLETION_DATE */

@ -6,152 +6,29 @@
package com.todoroo.astrid.data;
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import com.todoroo.andlib.data.ContentResolverDao;
import com.todoroo.andlib.data.TodorooCursor;
import com.todoroo.andlib.sql.Criterion;
import com.todoroo.andlib.sql.Functions;
import com.todoroo.andlib.sql.Query;
import com.todoroo.astrid.api.PermaSql;
/**
* Data access object for accessing Astrid's {@link Task} table. If you
* are looking to store extended information about a Task, you probably
* want to use the {@link MetadataApiDao} object.
* want to use the MetadataApiDao object.
*
* @author Tim Su <tim@todoroo.com>
*
*/
public class TaskApiDao extends ContentResolverDao<Task> {
public TaskApiDao(Context context) {
super(Task.class, context, Task.CONTENT_URI);
}
public class TaskApiDao {
/**
* Generates SQL clauses
*/
public static class TaskCriteria {
/** @return tasks by id */
public static Criterion byId(long id) {
return Task.ID.eq(id);
}
/** @return tasks that were deleted */
public static Criterion isDeleted() {
return Task.DELETION_DATE.neq(0);
}
/** @return tasks that were not deleted */
public static Criterion notDeleted() {
return Task.DELETION_DATE.eq(0);
}
/** @return tasks that have not yet been completed or deleted */
public static Criterion activeAndVisible() {
return Criterion.and(Task.COMPLETION_DATE.eq(0),
Task.DELETION_DATE.eq(0),
Task.HIDE_UNTIL.lt(Functions.now()));
}
/** @return tasks that have not yet been completed or deleted */
public static Criterion isActive() {
return Criterion.and(Task.COMPLETION_DATE.eq(0),
Task.DELETION_DATE.eq(0));
}
/** @return tasks that are not hidden at current time */
public static Criterion isVisible() {
return Task.HIDE_UNTIL.lt(Functions.now());
}
/** @return tasks that have a due date */
public static Criterion hasDeadlines() {
return Task.DUE_DATE.neq(0);
}
/** @return tasks that are due before a certain unixtime */
public static Criterion dueBeforeNow() {
return Criterion.and(Task.DUE_DATE.gt(0), Task.DUE_DATE.lt(Functions.now()));
}
/** @return tasks that are due after a certain unixtime */
public static Criterion dueAfterNow() {
return Task.DUE_DATE.gt(Functions.now());
}
/** @return tasks completed before a given unixtime */
public static Criterion completed() {
return Criterion.and(Task.COMPLETION_DATE.gt(0), Task.COMPLETION_DATE.lt(Functions.now()));
}
/** @return tasks that have a blank or null title */
public static Criterion hasNoTitle() {
return Criterion.or(Task.TITLE.isNull(), Task.TITLE.eq(""));
}
/** @return tasks that have not yet been completed or deleted */
public static Criterion activeVisibleMine() {
return Criterion.and(Task.COMPLETION_DATE.eq(0),
Task.DELETION_DATE.eq(0),
Task.HIDE_UNTIL.lt(Functions.now()),
Task.IS_READONLY.eq(0),
Task.USER_ID.eq(0));
}
/** Check if a given task belongs to someone else & is read-only */
public static Criterion ownedByMe() {
return Criterion.and(Task.IS_READONLY.eq(0),
Task.USER_ID.eq(0));
}
}
/**
* Count tasks matching criterion
* @return # of tasks matching
*/
public int countTasks(Criterion criterion) {
TodorooCursor<Task> cursor = query(Query.select(Task.ID).where(criterion));
try {
return cursor.getCount();
} finally {
cursor.close();
}
}
/**
* Count tasks matching query tepmlate
* @return # of tasks matching
*/
public int countTasks(String queryTemplate) {
queryTemplate = PermaSql.replacePlaceholders(queryTemplate);
TodorooCursor<Task> cursor = query(Query.select(Task.ID).withQueryTemplate(queryTemplate));
try {
return cursor.getCount();
} finally {
cursor.close();
}
}
@Override
public boolean save(Task model) {
try {
return super.save(model);
} catch (SQLException e) {
if (model.containsNonNullValue(Task.UUID)) {
TodorooCursor<Task> cursor = query(Query.select(Task.ID).where(Task.UUID.eq(model.getValue(Task.UUID))));
if (cursor.getCount() > 0) {
cursor.moveToFirst();
model.setId(cursor.get(Task.ID));
return super.save(model);
}
}
}
return false;
}
/** @return true if task change shouldn't be broadcast */

@ -7,9 +7,7 @@ package com.todoroo.astrid.data;
import android.content.ContentValues;
import android.net.Uri;
import com.todoroo.andlib.data.AbstractModel;
import com.todoroo.andlib.data.Property;
import com.todoroo.andlib.data.Property.IntegerProperty;
import com.todoroo.andlib.data.Property.LongProperty;
@ -17,7 +15,6 @@ import com.todoroo.andlib.data.Property.StringProperty;
import com.todoroo.andlib.data.Table;
import com.todoroo.andlib.data.TodorooCursor;
import com.todoroo.andlib.utility.DateUtilities;
import com.todoroo.astrid.api.AstridApiConstants;
/**
* Data Model which represents a user.
@ -32,10 +29,6 @@ public final class TaskAttachment extends RemoteModel {
/** table for this model */
public static final Table TABLE = new Table("task_attachments", TaskAttachment.class);
/** content uri for this model */
public static final Uri CONTENT_URI = Uri.parse("content://" + AstridApiConstants.API_PACKAGE + "/" +
TABLE.name);
// --- properties
/** ID */
@ -172,18 +165,7 @@ public final class TaskAttachment extends RemoteModel {
return getIdHelper(ID);
}
@Override
public String getUuid() {
return getUuidHelper(UUID);
}
// --- parcelable helpers
public static final Creator<TaskAttachment> CREATOR = new ModelCreator<TaskAttachment>(TaskAttachment.class);
@Override
protected Creator<? extends AbstractModel> getCreator() {
return CREATOR;
}
}

@ -7,17 +7,13 @@ package com.todoroo.astrid.data;
import android.content.ContentValues;
import android.net.Uri;
import android.text.TextUtils;
import com.todoroo.andlib.data.AbstractModel;
import com.todoroo.andlib.data.Property;
import com.todoroo.andlib.data.Property.IntegerProperty;
import com.todoroo.andlib.data.Property.LongProperty;
import com.todoroo.andlib.data.Property.StringProperty;
import com.todoroo.andlib.data.Table;
import com.todoroo.andlib.data.TodorooCursor;
import com.todoroo.astrid.api.AstridApiConstants;
/**
* Data Model which represents a user.
@ -32,10 +28,6 @@ public final class TaskListMetadata extends RemoteModel {
/** table for this model */
public static final Table TABLE = new Table("task_list_metadata", TaskListMetadata.class);
/** content uri for this model */
public static final Uri CONTENT_URI = Uri.parse("content://" + AstridApiConstants.API_PACKAGE + "/" +
TABLE.name);
// --- properties
/** ID */
@ -85,16 +77,6 @@ public final class TaskListMetadata extends RemoteModel {
public static final String FILTER_ID_ALL = "all";
public static final String FILTER_ID_TODAY = "today";
public static final String FILTER_ID_NO_LIST = "nolist";
public static final String FILTER_ID_ASSIGNED_BY_ME = "assigned";
public static final String SORT_AUTO = "auto";
public static final String SORT_MANUAL = "manual";
public static final String SORT_DUE = "due";
public static final String SORT_CREATED = "created";
public static final String SORT_COMPLETED = "completed";
public static final String SORT_UPDATED = "updated";
public static final String SORT_TITLE = "title";
// --- defaults
@ -129,31 +111,12 @@ public final class TaskListMetadata extends RemoteModel {
readPropertiesFromCursor(cursor);
}
public void readFromCursor(TodorooCursor<TaskListMetadata> cursor) {
super.readPropertiesFromCursor(cursor);
}
@Override
public long getId() {
return getIdHelper(ID);
}
@Override
public String getUuid() {
return getUuidHelper(UUID);
}
public static boolean taskIdsIsEmpty(String taskIds) {
return TextUtils.isEmpty(taskIds) || "[]".equals(taskIds) || "[\"-1\"]".equals(taskIds) || "[-1]".equals(taskIds);
}
// --- parcelable helpers
public static final Creator<TaskListMetadata> CREATOR = new ModelCreator<TaskListMetadata>(TaskListMetadata.class);
@Override
protected Creator<? extends AbstractModel> getCreator() {
return CREATOR;
}
}

@ -6,15 +6,12 @@
package com.todoroo.astrid.data;
import android.content.ContentValues;
import android.net.Uri;
import com.todoroo.andlib.data.AbstractModel;
import com.todoroo.andlib.data.Property;
import com.todoroo.andlib.data.Property.LongProperty;
import com.todoroo.andlib.data.Property.StringProperty;
import com.todoroo.andlib.data.Table;
import com.todoroo.andlib.data.TodorooCursor;
import com.todoroo.astrid.api.AstridApiConstants;
@ -32,10 +29,6 @@ public class Update extends RemoteModel {
/** table for this model */
public static final Table TABLE = new Table("updates", Update.class);
/** content uri for this model */
public static final Uri CONTENT_URI = Uri.parse("content://" + AstridApiConstants.API_PACKAGE + "/" +
TABLE.name);
// --- properties
/** ID */
@ -98,17 +91,9 @@ public class Update extends RemoteModel {
public static final StringProperty PICTURE = new StringProperty(
TABLE, "picture");
/** Unixtime Metadata was created */
public static final LongProperty CREATION_DATE = new LongProperty(
TABLE, "created");
/** List of all properties for this model */
public static final Property<?>[] PROPERTIES = generateProperties(Update.class);
// --- constants
public static final String PICTURE_LOADING = "<loading>";
// --- defaults
/** Default values container */
@ -147,27 +132,12 @@ public class Update extends RemoteModel {
readPropertiesFromCursor(cursor);
}
public void readFromCursor(TodorooCursor<Update> cursor) {
super.readPropertiesFromCursor(cursor);
}
@Override
public long getId() {
return getIdHelper(ID);
};
@Override
public String getUuid() {
return null;
}
// --- parcelable helpers
private static final Creator<Update> CREATOR = new ModelCreator<Update>(Update.class);
@Override
protected Creator<? extends AbstractModel> getCreator() {
return CREATOR;
}
}

@ -3,7 +3,6 @@ package com.todoroo.astrid.data;
import android.content.ContentValues;
import android.net.Uri;
import com.todoroo.andlib.data.AbstractModel;
import com.todoroo.andlib.data.Property;
import com.todoroo.andlib.data.Property.LongProperty;
import com.todoroo.andlib.data.Property.StringProperty;
@ -32,10 +31,6 @@ public class UserActivity extends RemoteModel {
public static final StringProperty UUID = new StringProperty(
TABLE, UUID_PROPERTY_NAME);
/** Pushed at */
public static final LongProperty PUSHED_AT = new LongProperty(
TABLE, PUSHED_AT_PROPERTY_NAME, Property.PROP_FLAG_DATE);
/** User ID (activity initiator) */
public static final StringProperty USER_UUID = new StringProperty(
TABLE, "user_uuid", Property.PROP_FLAG_USER_ID);
@ -75,26 +70,14 @@ public class UserActivity extends RemoteModel {
// --- Action codes
public static final String ACTION_TASK_COMMENT = "task_comment";
public static final String ACTION_TAG_COMMENT = "tag_comment";
public static final String ACTION_REQUEST_FRIENDSHIP = "request_friendship";
public static final String ACTION_CONFIRM_FRIENDSHIP = "confirm_friendship";
public static final String ACTION_ACHIEVEMENT_REACHED = "achievement_reached";
public UserActivity(TodorooCursor<UserActivity> cursor) {
this();
readPropertiesFromCursor(cursor);
}
public void readFromCursor(TodorooCursor<UserActivity> cursor) {
super.readPropertiesFromCursor(cursor);
}
// --- helpers
@Override
public String getUuid() {
return getUuidHelper(UUID);
}
/** Default values container */
private static final ContentValues defaultValues = new ContentValues();
@ -124,10 +107,4 @@ public class UserActivity extends RemoteModel {
}
private static final Creator<UserActivity> CREATOR = new ModelCreator<UserActivity>(UserActivity.class);
@Override
protected Creator<? extends AbstractModel> getCreator() {
return CREATOR;
}
}

@ -1,167 +0,0 @@
/**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.astrid.sync;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import com.todoroo.andlib.service.Autowired;
import com.todoroo.andlib.service.ContextManager;
import com.todoroo.andlib.service.DependencyInjectionService;
import com.todoroo.andlib.service.ExceptionService;
import com.todoroo.andlib.utility.DateUtilities;
import com.todoroo.andlib.utility.Preferences;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Performs synchronization service logic in background service to avoid
* ANR (application not responding) messages.
* <p>
* Starting this service
* schedules a repeating alarm which handles
* synchronization with your serv
*
* @author Tim Su
*
*/
abstract public class SyncBackgroundService extends Service {
/** Minimum time before an auto-sync */
private static final long AUTO_SYNC_MIN_OFFSET = 5*60*1000L;
@Autowired private ExceptionService exceptionService;
// --- abstract methods
abstract protected SyncProvider<?> getSyncProvider();
abstract protected SyncProviderUtilities getSyncUtilities();
// --- implementation
public SyncBackgroundService() {
DependencyInjectionService.getInstance().inject(this);
}
private final AtomicBoolean started = new AtomicBoolean(false);
/** Receive the alarm - start the synchronize service! */
@Override
public void onStart(Intent intent, int startId) {
try {
if(intent != null && !started.getAndSet(true)) {
startSynchronization(this);
}
} catch (Exception e) {
exceptionService.reportError(getSyncUtilities().getIdentifier() + "-bg-sync", e); //$NON-NLS-1$
}
}
/** Start the actual synchronization */
private void startSynchronization(Context context) {
if(context == null || context.getResources() == null) {
return;
}
ContextManager.setContext(context);
if(!getSyncUtilities().isLoggedIn()) {
return;
}
getSyncProvider().synchronize(context);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public synchronized void stop() {
started.set(false);
stopSelf();
}
// --- alarm management
/**
* Schedules repeating alarm for auto-synchronization
*/
public void scheduleService() {
int syncFrequencySeconds = 0;
try {
syncFrequencySeconds = Preferences.getIntegerFromString(
getSyncUtilities().getSyncIntervalKey(), -1);
} catch(ClassCastException e) {
Preferences.setStringFromInteger(getSyncUtilities().getSyncIntervalKey(), 0);
}
Context context = ContextManager.getContext();
if(syncFrequencySeconds <= 0) {
unscheduleService(context);
return;
}
// figure out synchronization frequency
long interval = 1000L * syncFrequencySeconds;
long offset = computeNextSyncOffset(interval);
// give a little padding
offset = Math.max(offset, AUTO_SYNC_MIN_OFFSET);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(context, getSyncUtilities().getSyncIntervalKey(),
createAlarmIntent(context), PendingIntent.FLAG_UPDATE_CURRENT);
Log.i("Astrid", "Autosync set for " + offset / 1000 //$NON-NLS-1$ //$NON-NLS-2$
+ " seconds repeating every " + syncFrequencySeconds); //$NON-NLS-1$
// cancel all existing
am.cancel(pendingIntent);
// schedule new
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + offset,
interval, pendingIntent);
}
/**
* Removes repeating alarm for auto-synchronization
*/
private void unscheduleService(Context context) {
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(context, getSyncUtilities().getSyncIntervalKey(),
createAlarmIntent(context), PendingIntent.FLAG_UPDATE_CURRENT);
am.cancel(pendingIntent);
}
/** Create the alarm intent */
private Intent createAlarmIntent(Context context) {
Intent intent = new Intent(context, getClass());
return intent;
}
// --- utility methods
private long computeNextSyncOffset(long interval) {
// figure out last synchronize time
long lastSyncDate = getSyncUtilities().getLastSyncDate();
// if user never synchronized, give them a full offset period before bg sync
if(lastSyncDate != 0) {
return Math.max(0, lastSyncDate + interval - DateUtilities.now());
} else {
return interval;
}
}
}

@ -5,7 +5,6 @@
*/
package com.todoroo.astrid.sync;
import com.todoroo.andlib.utility.AndroidUtilities;
import com.todoroo.astrid.data.Metadata;
import com.todoroo.astrid.data.Task;
@ -15,7 +14,6 @@ import java.util.ArrayList;
* Container class for transmitting tasks and including local and remote
* metadata. Synchronization Providers can subclass this class if desired.
*
* @see SyncProvider
* @author Tim Su <tim@todoroo.com>
*
*/
@ -23,19 +21,6 @@ public class SyncContainer {
public Task task;
public ArrayList<Metadata> metadata;
/**
* Check if the metadata contains anything with the given key
* @return first match. or null
*/
public Metadata findMetadata(String key) {
for(Metadata item : metadata) {
if(AndroidUtilities.equals(key, item.getValue(Metadata.KEY))) {
return item;
}
}
return null;
}
/**
* Method called when sync container is about to be saved into the database.
*/

@ -1,428 +0,0 @@
/**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.astrid.sync;
import android.app.Activity;
import android.app.Notification;
import android.content.Context;
import android.widget.Toast;
import com.todoroo.andlib.data.Property.LongProperty;
import com.todoroo.andlib.data.TodorooCursor;
import com.todoroo.andlib.service.Autowired;
import com.todoroo.andlib.service.ContextManager;
import com.todoroo.andlib.service.DependencyInjectionService;
import com.todoroo.andlib.service.ExceptionService;
import com.todoroo.andlib.service.NotificationManager;
import com.todoroo.andlib.utility.DialogUtilities;
import com.todoroo.astrid.data.Task;
import org.tasks.api.R;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
/**
* A helper class for writing synchronization services for Astrid. This class
* contains logic for merging incoming changes and writing outgoing changes.
* <p>
* Use {@link #initiateManual} as the entry point for your synchronization
* service, which should check if a user is logged in. If not, you should
* handle that in the UI, otherwise, you should launch your background
* service to perform synchronization in the background.
* <p>
* Your background service should {@link #synchronize}, which in turn
* invokes {@link #initiateBackground} to initiate synchronization.
*
* @author Tim Su <tim@todoroo.com>
*
*/
public abstract class SyncProvider<TYPE extends SyncContainer> {
// --- abstract methods - your services should implement these
/**
* @return sync utility instance
*/
abstract protected SyncProviderUtilities getUtilities();
/**
* Perform log in (launching activity if necessary) and sync. This is
* invoked when users manually request synchronization
*
* @param activity
* context
*/
abstract protected void initiateManual(Activity activity);
/**
* Perform synchronize. Since this can be called from background services,
* you should not open up new activities. Instead, if the user is not signed
* in, your service should do nothing.
*/
abstract protected void initiateBackground();
/**
* Updates the text of a notification and the intent to open when tapped
* @return notification id (in Android, there is at most one notification
* in the tray for a given id)
*/
abstract protected int updateNotification(Context context, Notification n);
/**
* Create a task on the remote server.
*
* @param task
* task to create
*/
abstract protected void create(TYPE task);
/**
* Push variables from given task to the remote server, and read the newly
* updated task.
*
* @param task
* task proxy to push
* @param remote
* remote task that we merged with. may be null
* @return task pulled on remote server
*/
abstract protected TYPE push(TYPE task, TYPE remote);
/**
* Fetch remote task. Used to re-read merged tasks
*
* @param task
* task with id's to re-read
* @return new Task
*/
abstract protected TYPE pull(TYPE task);
/**
* Reads a task container from a task in the database
*/
abstract protected TYPE read(TodorooCursor<Task> task);
/**
* Save task. Used to save local tasks that have been updated and remote
* tasks that need to be created locally
*/
abstract protected void write(TYPE task);
/**
* Finds a task in the list with the same remote identifier(s) as
* the task passed in
*
* @return task from list if matches, null otherwise
*/
abstract protected int matchTask(ArrayList<TYPE> tasks, TYPE target);
/**
* Transfer remote identifier(s) from one task to another
*/
abstract protected void transferIdentifiers(TYPE source,
TYPE destination);
// --- implementation
private final Notification notification;
@Autowired protected ExceptionService exceptionService;
public SyncProvider() {
DependencyInjectionService.getInstance().inject(this);
// initialize notification
int icon = android.R.drawable.stat_notify_sync;
long when = System.currentTimeMillis();
notification = new Notification(icon, null, when);
notification.flags |= Notification.FLAG_ONGOING_EVENT;
}
/**
* Synchronize this provider with sync toast
*/
public void synchronize(final Context context) {
synchronize(context, true);
}
/**
* Synchronize this provider
* @param showSyncToast should we toast to indicate synchronizing?
*/
public void synchronize(final Context context, final boolean showSyncToast) {
// display toast
if(context instanceof Activity) {
if(getUtilities().isLoggedIn()) {
((Activity) context).runOnUiThread(new Runnable() {
@Override
public void run() {
if(showSyncToast) {
makeSyncToast(context);
}
}
});
}
initiateManual((Activity)context);
} else if(context instanceof SyncBackgroundService) {
// display notification
final int notificationId = updateNotification(context, notification);
final NotificationManager nm = new NotificationManager.AndroidNotificationManager(context);
nm.notify(notificationId, notification);
// start next step in background thread
new Thread(new Runnable() {
@Override
public void run() {
try {
initiateBackground();
} finally {
nm.cancel(notificationId);
((SyncBackgroundService)context).stop();
}
}
}).start();
} else {
// unit test
initiateBackground();
}
}
protected void makeSyncToast(Context context) {
Toast.makeText(context, R.string.SyP_progress_toast,
Toast.LENGTH_LONG).show();
}
// --- synchronization logic
/**
* Helper to synchronize remote tasks with our local database.
*
* This initiates the following process: 1. local changes are read 2. remote
* changes are read 3. local tasks are merged with remote changes and pushed
* across 4. remote changes are then read in
*
* @param data synchronization data structure
*/
protected void synchronizeTasks(SyncData<TYPE> data) {
int length;
// create internal data structures
HashMap<String, Integer> remoteNewTaskNameMap = new HashMap<String, Integer>();
length = data.remoteUpdated.size();
for(int i = 0; i < length; i++) {
TYPE remote = data.remoteUpdated.get(i);
if(remote.task.getId() != Task.NO_ID) {
continue;
}
remoteNewTaskNameMap.put(remote.task.getValue(Task.TITLE), i);
}
// 1. CREATE: grab newly created tasks and create them remotely
sendLocallyCreated(data, remoteNewTaskNameMap);
// 2. UPDATE: for each updated local task
sendLocallyUpdated(data);
// 3. REMOTE: load remote information
readRemotelyUpdated(data);
}
protected String getFinalSyncStatus() {
if (getUtilities().getLastError() != null || getUtilities().getLastAttemptedSyncDate() != 0) {
if (getUtilities().getLastAttemptedSyncDate() == 0) {
return "errors";
} else {
return "failed";
}
} else {
return "success";
}
}
protected void readRemotelyUpdated(SyncData<TYPE> data) {
int length;
// Rearrange remoteTasks so completed tasks get synchronized first.
// This prevents bugs where a repeated task has two copies come down
// the wire, the new version and the completed old version. The new
// version would get merged, then completed, if done in the wrong order.
Collections.sort(data.remoteUpdated, new Comparator<TYPE>() {
private static final int SENTINEL = -2;
private final int check(TYPE o1, TYPE o2, LongProperty property) {
long o1Property = o1.task.getValue(property);
long o2Property = o2.task.getValue(property);
if(o1Property != 0 && o2Property != 0) {
return 0;
} else if(o1Property != 0) {
return -1;
} else if(o2Property != 0) {
return 1;
}
return SENTINEL;
}
@Override
public int compare(TYPE o1, TYPE o2) {
int comparison = check(o1, o2, Task.DELETION_DATE);
if(comparison != SENTINEL) {
return comparison;
}
comparison = check(o1, o2, Task.COMPLETION_DATE);
if(comparison != SENTINEL) {
return comparison;
}
return 0;
}
});
length = data.remoteUpdated.size();
for(int i = 0; i < length; i++) {
TYPE remote = data.remoteUpdated.get(i);
// don't synchronize new & deleted tasks
if(!remote.task.isSaved() && (remote.task.isDeleted())) {
continue;
}
try {
write(remote);
} catch (Exception e) {
handleException("sync-remote-updated", e, false); //$NON-NLS-1$
}
}
}
protected void sendLocallyUpdated(SyncData<TYPE> data) {
int length;
length = data.localUpdated.getCount();
for(int i = 0; i < length; i++) {
data.localUpdated.moveToNext();
TYPE local = read(data.localUpdated);
try {
if(local.task == null) {
continue;
}
// if there is a conflict, merge
int remoteIndex = matchTask((ArrayList<TYPE>)data.remoteUpdated, local);
if(remoteIndex != -1) {
TYPE remote = data.remoteUpdated.get(remoteIndex);
remote = push(local, remote);
// re-read remote task after merge (with local's title)
remote.task.setId(local.task.getId());
data.remoteUpdated.set(remoteIndex, remote);
} else {
push(local, null);
}
} catch (Exception e) {
handleException("sync-local-updated", e, false); //$NON-NLS-1$
}
write(local);
}
}
protected void sendLocallyCreated(SyncData<TYPE> data,
HashMap<String, Integer> remoteNewTaskNameMap) {
int length;
length = data.localCreated.getCount();
for(int i = 0; i < length; i++) {
data.localCreated.moveToNext();
TYPE local = read(data.localCreated);
try {
String taskTitle = local.task.getValue(Task.TITLE);
/* If there exists an incoming remote task with the same name and no
* mapping, we don't want to create this on the remote server,
* because user could have synchronized this before. Instead,
* we create a mapping and do an update.
*/
if (remoteNewTaskNameMap.containsKey(taskTitle)) {
int remoteIndex = remoteNewTaskNameMap.remove(taskTitle);
TYPE remote = data.remoteUpdated.get(remoteIndex);
transferIdentifiers(remote, local);
remote = push(local, remote);
// re-read remote task after merge, update remote task list
remote.task.setId(local.task.getId());
data.remoteUpdated.set(remoteIndex, remote);
} else {
create(local);
}
} catch (Exception e) {
handleException("sync-local-created", e, false); //$NON-NLS-1$
}
write(local);
}
}
// --- exception handling
/**
* Deal with a synchronization exception. If requested, will show an error
* to the user (unless synchronization is happening in background)
*
* @param tag
* error tag
* @param e
* exception
*/
protected void handleException(String tag, Exception e, boolean displayError) {
final Context context = ContextManager.getContext();
getUtilities().setLastError(e.toString(), "");
String message = null;
// occurs when application was closed
if(e instanceof IllegalStateException) {
exceptionService.reportError(tag + "-caught", e); //$NON-NLS-1$
}
// occurs when network error
else if(e instanceof IOException) {
exceptionService.reportError(tag + "-io", e); //$NON-NLS-1$
message = context.getString(R.string.SyP_ioerror);
}
// unhandled error
else {
message = context.getString(R.string.DLG_error, e.toString());
exceptionService.reportError(tag + "-unhandled", e); //$NON-NLS-1$
}
if(displayError && context instanceof Activity && message != null) {
DialogUtilities.okDialog((Activity)context,
message, null);
}
}
// --- helper classes
/** data structure builder */
protected static class SyncData<TYPE extends SyncContainer> {
public ArrayList<TYPE> remoteUpdated;
public TodorooCursor<Task> localCreated;
public TodorooCursor<Task> localUpdated;
public SyncData(ArrayList<TYPE> remoteUpdated,
TodorooCursor<Task> localCreated,
TodorooCursor<Task> localUpdated) {
super();
this.remoteUpdated = remoteUpdated;
this.localCreated = localCreated;
this.localUpdated = localUpdated;
}
}
}

@ -59,9 +59,6 @@ abstract public class SyncProviderUtilities {
return getPrefs().getString(getIdentifier() + PREF_TOKEN, null);
}
/** Returns something like "Logged in as: user@gmail.com" */
abstract public String getLoggedInUserName();
/** Sets the authentication token. Set to null to clear. */
public void setToken(String setting) {
Editor editor = getPrefs().edit();
@ -142,23 +139,4 @@ abstract public class SyncProviderUtilities {
editor.putBoolean(getIdentifier() + PREF_ONGOING, true);
editor.commit();
}
/**
* Reads the frequency, in seconds, auto-sync should occur.
*
* @return seconds duration, or 0 if not desired
*/
public int getSyncAutoSyncFrequency() {
String value = getPrefs().getString(
ContextManager.getContext().getString(
getSyncIntervalKey()), null);
if (value == null) {
return 0;
}
try {
return Integer.parseInt(value);
} catch (Exception e) {
return 0;
}
}
}

@ -49,6 +49,7 @@ abstract public class SyncV2BackgroundService extends Service {
// --- implementation
@SuppressWarnings("unused")
public SyncV2BackgroundService() {
DependencyInjectionService.getInstance().inject(this);
}
@ -96,11 +97,6 @@ abstract public class SyncV2BackgroundService extends Service {
return null;
}
public synchronized void stop() {
started.set(false);
stopSelf();
}
// --- alarm management
/**

@ -70,11 +70,6 @@ abstract public class SyncV2Provider {
*/
abstract public void synchronizeList(Object list, boolean manual, SyncResultCallback callback);
/**
* Sign out of service, deleting all synchronization metadata
*/
abstract public void signOut();
/**
* @return sync utility instance
*/

@ -52,9 +52,6 @@
<string name="DLG_error">¡Ui, sembla que hi ha hagut un problema! Això es el que ha passat:\n\n%s</string>
<string name="DLG_error_generic">¡Ui, sembla que hi ha hagut un problema!</string>
<string name="DLG_wait">Si us plau, espera...</string>
<string name="SyP_progress">Sincronitzant les seves tasques...</string>
<string name="SyP_progress_toast">S\'està sincronitzant...</string>
<string name="SyP_ioerror">Error de conexió! Verifiqui la conexió d\'internet.</string>
<string name="sync_SPr_group_status">Estat</string>
<string name="sync_status_ongoing">Sincronització en curs...</string>
<string name="sync_status_success">Última sincronització:\n%s</string>

@ -70,11 +70,8 @@
<string name="DLG_error">Jejda, vypadá to, že se vyskytla chyba! Tady je co se stalo:\n\n%s</string>
<string name="DLG_error_generic">Jejda, vypadá to, že se vyskytla chyba!</string>
<string name="DLG_wait">Čekejte prosím...</string>
<string name="SyP_progress">Probíhá synchronizace Vašich úkolů...</string>
<string name="SyP_progress_toast">Sychronizuji...</string>
<string name="SyP_label">Synchronizace</string>
<string name="SyP_summary">Google Tasks, uložená data, lokální záloha</string>
<string name="SyP_ioerror">Chyba připojení! Zkontrolujte vaše internetové připojení.</string>
<string name="sync_SPr_group_status">Stav</string>
<string name="sync_SPr_status_subtitle">Stav: %s</string>
<string name="sync_status_loggedout">Nepřihlášen</string>

@ -56,9 +56,7 @@
<string name="DLG_question_title">Spørsmål:</string>
<string name="DLG_close">Luk</string>
<string name="DLG_wait">Vent venligst...</string>
<string name="SyP_progress_toast">Synkroniserer...</string>
<string name="SyP_label">Synkronisering</string>
<string name="SyP_ioerror">Forbindelsesfejl! Tjek din internetforbindelse.</string>
<string name="sync_SPr_group_options">Indstillinger</string>
<string name="sync_SPr_interval_title">Baggrunds Synk</string>
<string name="sync_SPr_interval_desc_disabled">Baggrunds synkronisering er slået fra</string>

@ -70,12 +70,9 @@
<string name="DLG_error">Ups, sieht aus, als ob ein Fehler aufgetreten ist! Folgendes ist passiert:\n\n%s</string>
<string name="DLG_error_generic">Ups, sieht aus, als ob ein Fehler aufgetreten ist!</string>
<string name="DLG_wait">Bitte warten...</string>
<string name="SyP_progress">Synchronisiere deine Aufgaben</string>
<string name="SyP_progress_toast">Synchronisiere…</string>
<string name="SyP_label">Synchronisation</string>
<string name="Sync_now_label">Jetzt synchronisieren</string>
<string name="SyP_summary">Google Tasks, gespeicherte Daten, lokale Backups</string>
<string name="SyP_ioerror">Verbindungsfehler! Überprüfe Deine Internetverbindung.</string>
<string name="sync_status_loggedout">Nicht angemeldet</string>
<string name="sync_status_ongoing">Synchronisierung läuft...</string>
<string name="sync_status_success">Letzte Synchronisierung:\n%s</string>

@ -70,12 +70,9 @@
<string name="DLG_error">¡Uy, parece que ocurró un error! Esto es lo que pasó:\n\n%s</string>
<string name="DLG_error_generic">¡Uy, parece que ocurrió un error!</string>
<string name="DLG_wait">Espere un momento...</string>
<string name="SyP_progress">Sincronizando sus tareas...</string>
<string name="SyP_progress_toast">Sincronizando...</string>
<string name="SyP_label">Sincronización &amp; copia de seguridad</string>
<string name="Sync_now_label">Sincronizar ahora</string>
<string name="SyP_summary">Google Tasks, información guardada, copia de seguridad local</string>
<string name="SyP_ioerror">¡Error en la conexión! Compruebe su conexión de Internet.</string>
<string name="sync_SPr_group_status">Estado</string>
<string name="sync_SPr_status_subtitle">Estado: %s</string>
<string name="sync_status_loggedout">Sesión no iniciada</string>

@ -70,12 +70,9 @@
<string name="DLG_error">Oups, une erreur est survenue ! Voici ce qu\'il s\'est passé :\n\n%s</string>
<string name="DLG_error_generic">Oups, une erreur est survenue !</string>
<string name="DLG_wait">Veuillez patienter...</string>
<string name="SyP_progress">Synchronisation de vos tâches...</string>
<string name="SyP_progress_toast">Synchronisation...</string>
<string name="SyP_label">Synchronisation</string>
<string name="Sync_now_label">Synchroniser maintenant</string>
<string name="SyP_summary">Tâches Google, données enregistrées, sauvegarde locale</string>
<string name="SyP_ioerror">Erreur de connexion ! Veuillez vérifier votre connexion Internet.</string>
<string name="sync_SPr_group_status">Statut</string>
<string name="sync_SPr_status_subtitle">État : %s</string>
<string name="sync_status_loggedout">Non connecté</string>

@ -70,11 +70,8 @@
<string name="DLG_error">Oops, sembra che ci sia stato un errore! E\' successo questo:\n\n%s</string>
<string name="DLG_error_generic">Oops, sembra che ci sia stato un errore!</string>
<string name="DLG_wait">Attendi...</string>
<string name="SyP_progress">Sincronizzando le tue attività...</string>
<string name="SyP_progress_toast">Sincronizzando...</string>
<string name="SyP_label">Sincronizza &amp; archivia</string>
<string name="SyP_summary">Attività Google, dati salvati, backup locale </string>
<string name="SyP_ioerror">Errore di Connessione! Controlla la tua connessione Internet.</string>
<string name="sync_SPr_group_status">Stato</string>
<string name="sync_SPr_status_subtitle">Stato: %s</string>
<string name="sync_status_loggedout">Non connesso</string>

@ -70,12 +70,9 @@
<string name="DLG_error">אוּפְּס, נראה שארעה שגיאה! הנה מה שקה:\n\n%s</string>
<string name="DLG_error_generic">אוּפְּס, נראה שארעה שגיאה!</string>
<string name="DLG_wait">אנא המתן...</string>
<string name="SyP_progress">מסנכרן את המשימות שלך...</string>
<string name="SyP_progress_toast">מסנכרנת...</string>
<string name="SyP_label">סינכרון וגיבוי</string>
<string name="Sync_now_label">סנכרני כעת</string>
<string name="SyP_summary">אתר אסטריד, ״משימות גוגל״, מידע שמור, גיבוי מקומי</string>
<string name="SyP_ioerror">שגיאה בחיבור! בדוק את חיבור הרשת שלך</string>
<string name="sync_SPr_group_status">מצב</string>
<string name="sync_SPr_status_subtitle">מצב: %s</string>
<string name="sync_status_loggedout">לא מחובר</string>

@ -62,10 +62,7 @@
<string name="DLG_error_title">エラー</string>
<string name="DLG_close">閉じる</string>
<string name="DLG_wait">お待ちください</string>
<string name="SyP_progress">タスクの同期中...</string>
<string name="SyP_progress_toast">同期中...</string>
<string name="SyP_label">同期</string>
<string name="SyP_ioerror">接続エラー!インターネットに接続できるか確認してください。</string>
<string name="sync_SPr_group_status">状況</string>
<string name="sync_status_ongoing">同期中</string>
<string name="sync_status_success">前回の同期:\n%s</string>

@ -70,12 +70,9 @@
<string name="DLG_error">에러가 발생한 것 같습니다! 발생한 에러는 다음과 같습니다:\n\n%s</string>
<string name="DLG_error_generic">에러가 발생한 것 같습니다!</string>
<string name="DLG_wait">잠시 기다리세요...</string>
<string name="SyP_progress">일정을 동기화 중입니다...</string>
<string name="SyP_progress_toast">동기화하는 중...</string>
<string name="SyP_label">동기화 &amp; 백업</string>
<string name="Sync_now_label">지금 동기화하기</string>
<string name="SyP_summary">구글 일정, 저장한 자료, 로컬 백업</string>
<string name="SyP_ioerror">연결 오류! 인터넷 연결을 확인하세요.</string>
<string name="sync_SPr_group_status">상태</string>
<string name="sync_SPr_status_subtitle">상태: %s</string>
<string name="sync_status_loggedout">로그인 안 됨</string>

@ -64,9 +64,6 @@
<string name="DLG_error">Oi, det oppstod en feil! Dette skjedde:\n\n%s</string>
<string name="DLG_error_generic">Oi, det oppstod en feil!</string>
<string name="DLG_wait">Vennligst vent...</string>
<string name="SyP_progress">Synkroniserer oppgavene dine...</string>
<string name="SyP_progress_toast">Synkroniserer...</string>
<string name="SyP_ioerror">Tilkoblingsfeil! Kontroller tilkoblingen til Internett</string>
<string name="sync_status_ongoing">Synkronisering pågår...</string>
<string name="sync_status_success">Siste synkronisering:\n%s</string>
<string name="sync_status_failed">Mislykket: %s</string>

@ -70,12 +70,9 @@
<string name="DLG_error">Er is een fout opgetreden:\n\n%s</string>
<string name="DLG_error_generic">Er is een fout opgetreden!</string>
<string name="DLG_wait">Even geduld a.u.b.</string>
<string name="SyP_progress">Taken synchroniseren...</string>
<string name="SyP_progress_toast">Synchroniseren…</string>
<string name="SyP_label">Synchronisatie</string>
<string name="Sync_now_label">Nu synchroniseren</string>
<string name="SyP_summary">Google Taken, opgeslagen data, lokale back-up</string>
<string name="SyP_ioerror">Verbindingsfout! Controleer de internetverbinding</string>
<string name="sync_status_loggedout">Niet aangemeld</string>
<string name="sync_status_ongoing">Synchronisatie bezig...</string>
<string name="sync_status_success">Vorige:\n%s</string>

@ -70,12 +70,9 @@
<string name="DLG_error">Ups! Wygląda na to, że wystąpił jakiś błąd! Oto, co się stało:\n\n%s</string>
<string name="DLG_error_generic">Ups! Wygląda na to, że wystąpił jakiś błąd!</string>
<string name="DLG_wait">Proszę czekać...</string>
<string name="SyP_progress">Synchronizowanie Twoich zadań...</string>
<string name="SyP_progress_toast">Synchronizacja...</string>
<string name="SyP_label">Synchronizacja</string>
<string name="Sync_now_label">Zsynchronizuj</string>
<string name="SyP_summary">Zadania Google, zapisane dane, lokalna kopia zapasowa</string>
<string name="SyP_ioerror">Błąd połączenia! Sprawdź swoje połączenie z Internetem!</string>
<string name="sync_SPr_group_status">Stan</string>
<string name="sync_status_loggedout">Niezalogowany</string>
<string name="sync_status_ongoing">Synchronizacja trwa...</string>

@ -70,11 +70,8 @@
<string name="DLG_error">Opa, parece que ocorreu um erro! Aqui está o que aconteceu:\n\n%s</string>
<string name="DLG_error_generic">Opa, parece que ocorreu um erro!</string>
<string name="DLG_wait">Por favor, aguarde...</string>
<string name="SyP_progress">Sincronizando suas tarefas...</string>
<string name="SyP_progress_toast">Sincronizando...</string>
<string name="SyP_label">Sincronização</string>
<string name="SyP_summary">Google Tasks, dados salvos, backup local</string>
<string name="SyP_ioerror">Erro na Conexão! Verifique sua conexão com a internet.</string>
<string name="sync_SPr_group_status">Estado</string>
<string name="sync_status_loggedout">Não Registrado</string>
<string name="sync_status_ongoing">Sincronizando...</string>

@ -57,7 +57,6 @@
<string name="DLG_information_title">Informação</string>
<string name="DLG_close">Fechar</string>
<string name="DLG_wait">Por favor aguarde...</string>
<string name="SyP_progress_toast">A Sincronizar...</string>
<string name="SyP_label">Sincronização</string>
<string name="sync_SPr_group_status">Estado</string>
<string name="sync_SPr_group_options">Opções</string>

@ -70,12 +70,9 @@
<string name="DLG_error">Ой, похоже произошла ошибка! Подробности ниже:\n\n%s</string>
<string name="DLG_error_generic">Ой, похоже произошла ошибка!</string>
<string name="DLG_wait">Пожалуйста, подождите…</string>
<string name="SyP_progress">Синхронизация задач…</string>
<string name="SyP_progress_toast">Синхронизация…</string>
<string name="SyP_label">Синхронизация</string>
<string name="Sync_now_label">Синхронизировать</string>
<string name="SyP_summary">Задачи Google, сохраненные данные, локальная резервная копия</string>
<string name="SyP_ioerror">Ошибка соединения! Проверьте подключение к интернету.</string>
<string name="sync_SPr_group_status">Состояние</string>
<string name="sync_SPr_status_subtitle">Состояние: %s</string>
<string name="sync_status_loggedout">Вход не выполнен</string>

@ -67,11 +67,8 @@
<string name="DLG_error">Oj, det uppstod ett fel! Detta hände:\n\n%s</string>
<string name="DLG_error_generic">Oj, det uppstod ett fel!</string>
<string name="DLG_wait">Var god vänta...</string>
<string name="SyP_progress">Synkroniserar dina uppgifter...</string>
<string name="SyP_progress_toast">Synkroniserar...</string>
<string name="SyP_label">Synkronisering</string>
<string name="SyP_summary">Google Aktiviteter, sparad data, lokal backup</string>
<string name="SyP_ioerror">Tillkopplingsfel! Kontrollera din tillkoppling till internet.</string>
<string name="sync_status_loggedout">Ej inloggad</string>
<string name="sync_status_ongoing">Synkronisering pågår...</string>
<string name="sync_status_success">Synkroniserades senast:\n%s</string>

@ -37,7 +37,6 @@
<string name="tomorrow">พรุ่งนี้</string>
<string name="yesterday">เมื่อวาน</string>
<string name="DLG_information_title">ข้อมูล</string>
<string name="SyP_ioerror">ข้อผิดพลาดในการเชื่อมต่อ! ตรวจดูการเชื่อมต่ออินเตอร์เน็ท</string>
<string name="sync_SPr_group_status">สถานะ</string>
<string name="sync_SPr_group_options">ตัวเลือก</string>
</resources>

@ -70,9 +70,6 @@
<string name="DLG_error">Oops, bir sorun meydana geldi! Olan şu:\n\n%s</string>
<string name="DLG_error_generic">Oops, bir sorun meydana geldi!</string>
<string name="DLG_wait">Lütfen bekleyin...</string>
<string name="SyP_progress">Görevleriniz eşleniyor...</string>
<string name="SyP_progress_toast">Eşleniyor...</string>
<string name="SyP_ioerror">Bağlantı Hatası! Internet bağlantınızı kontrol edin.</string>
<string name="sync_SPr_group_status">Durum</string>
<string name="sync_SPr_status_subtitle">Durum: %s</string>
<string name="sync_status_loggedout">Oturum açılmadı</string>

@ -54,12 +54,9 @@
<string name="DLG_error">На жаль, схоже, сталася помилка! Ось що вийшло:\n\n%s</string>
<string name="DLG_error_generic">На жаль, схоже, сталася помилка!</string>
<string name="DLG_wait">Будь ласка, зачекайте...</string>
<string name="SyP_progress">Синхронізація завдань...</string>
<string name="SyP_progress_toast">Синхронізація…</string>
<string name="SyP_label">Синхронізація і резерв. копіювання</string>
<string name="Sync_now_label">Синхронізувати</string>
<string name="SyP_summary">Google Tasks, збережені дані, локальне резервне копіювання</string>
<string name="SyP_ioerror">Помилка з\'єднання! Перевірте підключення до Інтернету.</string>
<string name="sync_SPr_group_status">Статус</string>
<string name="sync_SPr_status_subtitle">Статус: %s</string>
<string name="sync_status_loggedout">Не залогований</string>

@ -70,11 +70,8 @@
<string name="DLG_error">糟糕,发生错误!状况是:\n\n%s</string>
<string name="DLG_error_generic">糟糕,发生错误!</string>
<string name="DLG_wait">请稍候...</string>
<string name="SyP_progress">任务同步中...</string>
<string name="SyP_progress_toast">正在同步中...</string>
<string name="SyP_label">同步和备份</string>
<string name="SyP_summary">谷歌任务,已存数据,本地备份</string>
<string name="SyP_ioerror">连接错误!请检查您的因特网连接。</string>
<string name="sync_SPr_group_status">状态</string>
<string name="sync_SPr_status_subtitle">状态:%s</string>
<string name="sync_status_loggedout">未登陆</string>

@ -70,11 +70,8 @@
<string name="DLG_error">糟糕,發生錯誤!狀況是:\n\n%s</string>
<string name="DLG_error_generic">糟糕,發生錯誤!</string>
<string name="DLG_wait">請稍候...</string>
<string name="SyP_progress">工作同步中...</string>
<string name="SyP_progress_toast">正在同步中...</string>
<string name="SyP_label">同步和備份</string>
<string name="SyP_summary">谷歌任務,已存數據,本地備份</string>
<string name="SyP_ioerror">連結錯誤! 檢查您的網際網路連線.</string>
<string name="sync_SPr_group_status">狀態</string>
<string name="sync_SPr_status_subtitle">狀態:%s</string>
<string name="sync_status_loggedout">未登陸</string>

@ -125,12 +125,6 @@
<!-- ====================================================== SyncProvider == -->
<!-- Sync Notification: message when sync service active -->
<string name="SyP_progress">Synchronizing your tasks...</string>
<!-- Sync Notification: toast when sync activated from activity -->
<string name="SyP_progress_toast">Synchronizing...</string>
<!-- Sync Label: used in menu to denote synchronization -->
<string name="SyP_label">Sync &amp; backup</string>
@ -140,9 +134,6 @@
<!-- Sync label subtitle -->
<string name="SyP_summary">Google Tasks, saved data, local backup</string>
<!-- Error msg when io exception -->
<string name="SyP_ioerror">Connection Error! Check your Internet connection.</string>
<!-- ================================================== SyncPreferences == -->
<!-- Status Group Label -->

@ -18,11 +18,6 @@ public class TestDependencyInjector extends AbstractDependencyInjector {
injectables.put(field, injection);
}
@Override
protected void addInjectables() {
// do nothing, we populate injectables via the addInjectable method
}
@Override
public String toString() {
return "TestDI:" + name;

@ -43,18 +43,6 @@ public class TodorooTestCase extends AndroidTestCase {
setLocale(Locale.getDefault());
}
/**
* Loop through each locale and call runnable
*/
public void forEachLocale(Runnable r) {
Locale[] locales = Locale.getAvailableLocales();
for(Locale locale : locales) {
setLocale(locale);
r.run();
}
}
/**
* Sets locale
*/

@ -109,14 +109,14 @@ public class GtasksDetailExposerTest extends DatabaseTestCase {
gtasksListService.updateLists(lists);
}
private Task givenTaskWithList(String list) {
private void givenTaskWithList(String list) {
Task newTask = new Task();
PluginServices.getTaskService().save(newTask);
Metadata metadata = GtasksMetadata.createEmptyMetadata(newTask.getId());
if(list != null)
metadata.setValue(GtasksMetadata.LIST_ID, list);
PluginServices.getMetadataService().save(metadata);
return task = newTask;
task = newTask;
}
@Override

@ -260,17 +260,14 @@ public class GtasksTaskMovingTest extends DatabaseTestCase {
* E
* F
*/
private Task[] givenTasksABCDEF() {
Task[] tasks = new Task[] {
A = createTask("A", 0, 0),
B = createTask("B", 1, 1),
C = createTask("C", 2, 1),
D = createTask("D", 3, 2),
E = createTask("E", 4, 0),
F = createTask("F", 5, 0),
};
private void givenTasksABCDEF() {
A = createTask("A", 0, 0);
B = createTask("B", 1, 1);
C = createTask("C", 2, 1);
D = createTask("D", 3, 2);
E = createTask("E", 4, 0);
F = createTask("F", 5, 0);
gtasksTaskListUpdater.correctMetadataForList("1");
return tasks;
}
private Task createTask(String title, long order, int indent) {

@ -39,7 +39,7 @@ public class TaskTests extends DatabaseTestCase {
}
/** Check defaults */
public void checkDefaults() {
public void testDefaults() {
AstridPreferences.setPreferenceDefaults();
ContentValues defaults = new Task().getDefaultValues();
assertTrue(defaults.containsKey(Task.TITLE.name));
@ -50,7 +50,7 @@ public class TaskTests extends DatabaseTestCase {
}
/** Check task gets a creation date at some point */
public void checkCreationDate() {
public void testCreationDate() {
Task task = new Task();
taskService.save(task);
assertTrue(task.getValue(Task.CREATION_DATE) > 0);
@ -59,7 +59,7 @@ public class TaskTests extends DatabaseTestCase {
/**
* Check various getters
*/
public void checkGetters() {
public void testGetters() {
Task task = new Task();
assertFalse(task.isCompleted());
task.setValue(Task.COMPLETION_DATE, DateUtilities.now());

@ -77,10 +77,6 @@ public class NotificationTests extends DatabaseTestCase {
// allowed
}
public void cancelAll() {
fail("wtf cancel all?");
}
public void notify(int id, Notification notification) {
fail("sent a notification, you shouldn't have...");
}
@ -106,10 +102,6 @@ public class NotificationTests extends DatabaseTestCase {
// allowed
}
public void cancelAll() {
fail("wtf cancel all?");
}
public void notify(int id, Notification notification) {
fail("sent a notification, you shouldn't have...");
}
@ -189,9 +181,6 @@ public class NotificationTests extends DatabaseTestCase {
public void cancel(int id) {
fail("wtf cance?");
}
public void cancelAll() {
fail("wtf cancel all?");
}
}
}

@ -59,13 +59,7 @@ public class NewRepeatTests<REMOTE_MODEL> extends DatabaseTestCase {
AndroidUtilities.sleepDeep(200L); // Delay to make sure changes persist
}
protected REMOTE_MODEL assertTaskExistsRemotely(Task t, long expectedDueDate) {
// Subclasses can override this to check the existence of remote objects
return null;
}
protected long setCompletionDate(boolean completeBefore, Task t,
REMOTE_MODEL remoteModel, long dueDate) {
protected long setCompletionDate(boolean completeBefore, Task t, long dueDate) {
long completionDate;
if (completeBefore)
completionDate = dueDate - DateUtilities.ONE_DAY;
@ -133,9 +127,8 @@ public class NewRepeatTests<REMOTE_MODEL> extends DatabaseTestCase {
waitAndSync();
t = taskDao.fetch(t.getId(), Task.PROPERTIES); // Refetch
REMOTE_MODEL remoteModel = assertTaskExistsRemotely(t, dueDate);
long completionDate = setCompletionDate(completeBefore, t, remoteModel, dueDate);
long completionDate = setCompletionDate(completeBefore, t, dueDate);
System.err.println("Completion date: " + new Date(completionDate));
waitAndSync();
@ -158,7 +151,6 @@ public class NewRepeatTests<REMOTE_MODEL> extends DatabaseTestCase {
long fromDate = (fromCompletion? completionDate : dueDate);
long expectedTime = computeNextDueDateFromDate(fromDate, rrule, fromCompletion);
assertTaskExistsRemotely(t, expectedTime);
if (frequency == Frequency.WEEKLY) // We do this because DST was making the results be off by an hour
assertTimesWithinOneHour(expectedTime, newDueDate);
else

@ -61,7 +61,7 @@ public class TitleParserTest extends DatabaseTestCase {
};
for (int i = 0; i < 23; i++) {
String testTitle = "Jog on " + titleMonthStrings[i] + " 12.";
insertTitleAddTask(testTitle, task, taskService);
insertTitleAddTask(testTitle, task);
Date date = new Date(task.getValue(Task.DUE_DATE));
assertEquals(date.getMonth(), i/2);
assertEquals(date.getDate(), 12);
@ -73,7 +73,7 @@ public class TitleParserTest extends DatabaseTestCase {
Task task = new Task();
for (int i = 1; i < 13; i++) {
String testTitle = "Jog on " + i + "/12/13";
insertTitleAddTask(testTitle, task, taskService);
insertTitleAddTask(testTitle, task);
Date date = new Date(task.getValue(Task.DUE_DATE));
assertEquals(date.getMonth(), i-1);
assertEquals(date.getDate(), 12);
@ -85,7 +85,7 @@ public class TitleParserTest extends DatabaseTestCase {
TaskService taskService = new TaskService();
Task task = new Task();
String testTitle = "Jog on 23:21.";
insertTitleAddTask(testTitle, task, taskService);
insertTitleAddTask(testTitle, task);
Date date = new Date(task.getValue(Task.DUE_DATE));
assertEquals(date.getMinutes(), 21);
assertEquals(date.getHours(), 23);
@ -95,7 +95,7 @@ public class TitleParserTest extends DatabaseTestCase {
TaskService taskService = new TaskService();
Task task = new Task();
String testTitle = "Jog at 8:33 PM.";
insertTitleAddTask(testTitle, task, taskService);
insertTitleAddTask(testTitle, task);
Date date = new Date(task.getValue(Task.DUE_DATE));
assertEquals(date.getMinutes(), 33);
assertEquals(date.getHours(), 20);
@ -105,7 +105,7 @@ public class TitleParserTest extends DatabaseTestCase {
TaskService taskService = new TaskService();
Task task = new Task();
String testTitle = "Jog at 8 PM.";
insertTitleAddTask(testTitle, task, taskService);
insertTitleAddTask(testTitle, task);
Date date = new Date(task.getValue(Task.DUE_DATE));
assertEquals(date.getMinutes(), 0);
assertEquals(date.getHours(), 20);
@ -115,7 +115,7 @@ public class TitleParserTest extends DatabaseTestCase {
TaskService taskService = new TaskService();
Task task = new Task();
String testTitle = "Jog at 8 o'clock AM.";
insertTitleAddTask(testTitle, task, taskService);
insertTitleAddTask(testTitle, task);
Date date = new Date(task.getValue(Task.DUE_DATE));
assertEquals(date.getMinutes(), 0);
assertEquals(date.getHours(), 8);
@ -130,7 +130,7 @@ public class TitleParserTest extends DatabaseTestCase {
"at 8:00 AM"
};
for (String testTitle: testTitles) {
insertTitleAddTask(testTitle, task, taskService);
insertTitleAddTask(testTitle, task);
Date date = new Date(task.getValue(Task.DUE_DATE));
assertEquals(date.getMinutes(), 0);
assertEquals(date.getHours(), 8);
@ -148,14 +148,14 @@ public class TitleParserTest extends DatabaseTestCase {
};
for (String testTitle: testTitles) {
insertTitleAddTask(testTitle, task, taskService);
insertTitleAddTask(testTitle, task);
Date date = new Date(task.getValue(Task.DUE_DATE));
assertEquals(date.getMinutes(), 30);
assertEquals(date.getHours(), 12);
}
}
private void insertTitleAddTask(String title, Task task, TaskService taskService) {
private void insertTitleAddTask(String title, Task task) {
task.clear();
task.setValue(Task.TITLE, title);
TaskService.createWithValues(task, null, title);

@ -6,8 +6,6 @@ import com.todoroo.astrid.data.TaskListMetadata;
public class SubtasksHelperTest extends SubtasksTestCase {
private Task A, B, C, D, E, F;
@Override
protected void setUp() throws Exception {
super.setUp();
@ -17,21 +15,20 @@ public class SubtasksHelperTest extends SubtasksTestCase {
updater.initializeFromSerializedTree(m, filter, SubtasksHelper.convertTreeToRemoteIds(DEFAULT_SERIALIZED_TREE));
}
private Task createTask(String title, String uuid) {
private void createTask(String title, String uuid) {
Task t = new Task();
t.setValue(Task.TITLE, title);
t.setValue(Task.UUID, uuid);
PluginServices.getTaskService().save(t);
return t;
}
private void createTasks() {
A = createTask("A", "6"); // Local id 1
B = createTask("B", "4"); // Local id 2
C = createTask("C", "3"); // Local id 3
D = createTask("D", "1"); // Local id 4
E = createTask("E", "2"); // Local id 5
F = createTask("F", "5"); // Local id 6
createTask("A", "6"); // Local id 1
createTask("B", "4"); // Local id 2
createTask("C", "3"); // Local id 3
createTask("D", "1"); // Local id 4
createTask("E", "2"); // Local id 5
createTask("F", "5"); // Local id 6
}
private static final String[] EXPECTED_ORDER = { "-1", "1", "2", "3", "4", "5", "6" };

@ -28,7 +28,6 @@ public class SubtasksTestCase extends DatabaseTestCase {
* F
*/
public static final String DEFAULT_SERIALIZED_TREE = "[-1, [1, 2, [3, 4]], 5, 6]".replaceAll("\\s", "");
public static final String DEFAULT_SERIALIZED_TREE_STRING = "[\"-1\", [\"1\", \"2\", [\"3\", \"4\"]], \"5\", \"6\"]".replaceAll("\\s", "");
@Override
protected void setUp() throws Exception {

@ -1,7 +1,6 @@
package com.todoroo.astrid.sync;
import com.todoroo.andlib.service.Autowired;
import com.todoroo.astrid.dao.RemoteModelDao;
import com.todoroo.astrid.dao.TagDataDao;
import com.todoroo.astrid.dao.TaskDao;
import com.todoroo.astrid.data.SyncFlags;
@ -18,7 +17,6 @@ public class NewSyncTestCase extends DatabaseTestCase {
@Override
protected void setUp() throws Exception {
super.setUp();
RemoteModelDao.setOutstandingEntryFlags(RemoteModelDao.OUTSTANDING_ENTRY_FLAG_RECORD_OUTSTANDING);
}
protected Task createTask(String title, boolean suppress) {
@ -43,7 +41,7 @@ public class NewSyncTestCase extends DatabaseTestCase {
return createTask(SYNC_TASK_TITLE, suppress);
}
protected TagData createTagData(String name, boolean suppress) {
protected TagData createTagData(String name) {
TagData tag = new TagData();
tag.setValue(TagData.NAME, name);
@ -52,10 +50,6 @@ public class NewSyncTestCase extends DatabaseTestCase {
}
protected TagData createTagData() {
return createTagData(false);
}
protected TagData createTagData(boolean suppress) {
return createTagData("new tag", suppress);
return createTagData("new tag");
}
}

@ -11,8 +11,6 @@ import com.todoroo.astrid.dao.Database;
import com.todoroo.astrid.provider.ProviderTestUtilities;
import com.todoroo.astrid.service.AstridDependencyInjector;
import java.io.File;
/**
* Test case that automatically sets up and tears down a test database
*
@ -45,15 +43,6 @@ public class DatabaseTestCase extends TodorooTestCaseWithInjector {
ProviderTestUtilities.setDatabaseOverride(database);
}
/**
* Helper to delete a database by name
*/
protected void deleteDatabase(String toDelete) {
File db = getContext().getDatabasePath(toDelete);
if(db.exists())
db.delete();
}
@Override
protected void tearDown() throws Exception {
database.close();

@ -111,7 +111,6 @@ public class JUnitReportListener implements TestListener {
/**
* Creates a new listener.
*
* @param context context of the test application
* @param targetContext context of the application under test
* @param reportFile name of the report file(s) to create
* @param reportDir path of the directory under which to write files
@ -121,7 +120,7 @@ public class JUnitReportListener implements TestListener {
* framework methods) omitted for clarity
* @param multiFile if true, use a separate file for each test suite
*/
public JUnitReportListener(Context context, Context targetContext, String reportFile, String reportDir, boolean filterTraces, boolean multiFile) {
public JUnitReportListener(Context targetContext, String reportFile, String reportDir, boolean filterTraces, boolean multiFile) {
Log.i(LOG_TAG, "Listener created with arguments:\n" +
" report file : '" + reportFile + "'\n" +
" report dir : '" + reportDir + "'\n" +

@ -23,7 +23,6 @@ import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
@ -33,31 +32,23 @@ import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import com.todoroo.andlib.utility.AndroidUtilities;
import com.todoroo.astrid.ui.ErrorCatchingListView;
import org.tasks.R;
public class TouchListView extends ErrorCatchingListView {
private ImageView mDragView;
private View mOriginalView;
private WindowManager mWindowManager;
private WindowManager.LayoutParams mWindowParams;
private int mDragPos; // which item is being dragged
private int mFirstDragPos; // where was the dragged item originally
private int mDragPoint; // at what offset inside the item did the user grab it
private int mCoordOffset; // the difference between screen coordinates and coordinates in this view
private float mDragStartX, mDragCurrentX;
private long mDragStartTime;
private DragListener mDragListener;
private float mDragStartX;
private DropListener mDropListener;
private SwipeListener mSwipeListener;
private GrabberClickListener mClickListener;
private int mUpperBound;
private int mLowerBound;
private int mHeight;
private GestureDetector mGestureDetector;
public static final int FLING = 0;
public static final int SLIDE_RIGHT = 1;
public static final int SLIDE_LEFT = 2;
private int mRemoveMode = -1;
@ -123,7 +114,7 @@ public class TouchListView extends ErrorCatchingListView {
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (mDragListener != null || mDropListener != null) {
if (mDropListener != null) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
int x = (int) ev.getX();
@ -163,8 +154,6 @@ public class TouchListView extends ErrorCatchingListView {
mFirstDragPos = mDragPos;
mHeight = getHeight();
mDragStartX = ev.getX();
mDragStartTime = System.currentTimeMillis();
mOriginalView = item;
int touchSlop = mTouchSlop;
mUpperBound = Math.min(y - touchSlop, mHeight / 3);
@ -312,26 +301,17 @@ public class TouchListView extends ErrorCatchingListView {
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (mGestureDetector != null) {
mGestureDetector.onTouchEvent(ev);
}
if ((mDragListener != null || mDropListener != null) && mDragView != null) {
if ((mDropListener != null) && mDragView != null) {
int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
Rect r = mTempRect;
mDragView.getDrawingRect(r);
stopDragging(ev);
stopDragging();
if (mDragPos == mFirstDragPos && ev.getX() > mDragStartX + 20) {
if (mSwipeListener!= null) {
mSwipeListener.swipeRight(mFirstDragPos);
}
unExpandViews(true);
} else if (mDragPos == mFirstDragPos && ev.getX() < mDragStartX - 20) {
if (mSwipeListener!= null) {
mSwipeListener.swipeLeft(mFirstDragPos);
}
unExpandViews(true);
} else {
if (mDropListener != null && mDragPos >= 0 && mDragPos < getCount()) {
@ -349,9 +329,6 @@ public class TouchListView extends ErrorCatchingListView {
int itemnum = getItemForPosition(y);
if (itemnum >= 0) {
if (action == MotionEvent.ACTION_DOWN || itemnum != mDragPos) {
if (mDragListener != null) {
mDragListener.drag(mDragPos, itemnum);
}
mDragPos = itemnum;
doExpansion();
}
@ -385,7 +362,7 @@ public class TouchListView extends ErrorCatchingListView {
}
private void startDragging(Bitmap bm, int x, int y) {
stopDragging(null);
stopDragging();
mWindowParams = new WindowManager.LayoutParams();
mWindowParams.gravity = Gravity.TOP|Gravity.LEFT;
@ -409,35 +386,8 @@ public class TouchListView extends ErrorCatchingListView {
mWindowManager = (WindowManager)getContext().getSystemService(Context.WINDOW_SERVICE);
mWindowManager.addView(v, mWindowParams);
mDragView = v;
if(mClickListener != null) {
longPressThread = new Thread(longPressRunnable);
longPressThread.start();
}
}
private final Runnable longPressRunnable = new Runnable() {
@Override
public void run() {
AndroidUtilities.sleepDeep(1000L);
if(Thread.currentThread().isInterrupted()) {
return;
}
if(mDragView != null && mDragPos == mFirstDragPos &&
Math.abs(mDragCurrentX - mDragStartX) < 10) {
post(new Runnable() {
@Override
public void run() {
stopDragging(null);
mClickListener.onLongClick(mOriginalView);
invalidate();
}
});
}
}
};
private void dragView(int x, int y) {
float alpha = 1.0f;
int width = mDragView.getWidth();
@ -456,10 +406,9 @@ public class TouchListView extends ErrorCatchingListView {
}
mWindowParams.y = y - mDragPoint + mCoordOffset;
mWindowManager.updateViewLayout(mDragView, mWindowParams);
mDragCurrentX = x;
}
private void stopDragging(MotionEvent ev) {
private void stopDragging() {
if (mDragBitmap != null) {
mDragBitmap.recycle();
mDragBitmap = null;
@ -471,19 +420,6 @@ public class TouchListView extends ErrorCatchingListView {
wm.removeView(mDragView);
mDragView.setImageDrawable(null);
mDragView = null;
if (ev != null && mClickListener != null) {
// detect press & long press case
if(mDragPos == mFirstDragPos &&
Math.abs(mDragCurrentX - mDragStartX) < 10) {
long pressTime = System.currentTimeMillis() - mDragStartTime;
if(pressTime < 1000) {
mClickListener.onClick(mOriginalView);
} else {
mClickListener.onLongClick(mOriginalView);
}
}
}
}
if(longPressThread != null) {
@ -492,34 +428,15 @@ public class TouchListView extends ErrorCatchingListView {
}
}
public void setDragListener(DragListener l) {
mDragListener = l;
}
public void setDropListener(DropListener l) {
mDropListener = l;
}
public void setSwipeListener(SwipeListener l) {
mSwipeListener = l;
}
public void setClickListener(GrabberClickListener listener) {
this.mClickListener = listener;
}
public void setDragndropBackgroundColor(int color) {
this.dragndropBackgroundColor = color;
}
public interface GrabberClickListener {
public void onClick(View v);
public void onLongClick(View v);
}
public interface DragListener {
void drag(int from, int to);
}
public interface DropListener {
void drop(int from, int to);
}

@ -6,7 +6,6 @@
package com.mdimension.jchronic;
import com.mdimension.jchronic.handlers.Handler;
import com.mdimension.jchronic.numerizer.Numerizer;
import com.mdimension.jchronic.repeaters.Repeater;
import com.mdimension.jchronic.tags.Grabber;
import com.mdimension.jchronic.tags.Ordinal;
@ -21,7 +20,6 @@ import java.util.LinkedList;
import java.util.List;
public class AstridChronic {
public static final String VERSION = "0.2.3";
private AstridChronic() {
// DO NOTHING
@ -145,13 +143,6 @@ public class AstridChronic {
return normalizedText;
}
/**
* Convert number words to numbers (three => 3)
*/
protected static String numericizeNumbers(String text) {
return Numerizer.numerize(text);
}
/**
* Convert ordinal words to numeric ordinals (third => 3rd)
*/

@ -38,55 +38,6 @@ public class ActFmCameraModule {
public void clearImage();
}
public static void showPictureLauncher(final Activity activity, final ClearImageCallback clearImageOption) {
ArrayList<String> options = new ArrayList<String>();
final Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
PackageManager pm = activity.getPackageManager();
final boolean cameraAvailable = pm.queryIntentActivities(cameraIntent, 0).size() > 0;
if(cameraAvailable) {
options.add(activity.getString(R.string.actfm_picture_camera));
}
options.add(activity.getString(R.string.actfm_picture_gallery));
if (clearImageOption != null) {
options.add(activity.getString(R.string.actfm_picture_clear));
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity,
android.R.layout.simple_spinner_dropdown_item, options.toArray(new String[options.size()]));
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface d, int which) {
if(which == 0 && cameraAvailable) {
lastTempFile = getTempFile(activity);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (lastTempFile != null) {
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(lastTempFile));
}
activity.startActivityForResult(intent, REQUEST_CODE_CAMERA);
} else if ((which == 1 && cameraAvailable) || (which == 0 && !cameraAvailable)) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
activity.startActivityForResult(Intent.createChooser(intent,
activity.getString(R.string.actfm_TVA_tag_picture)), REQUEST_CODE_PICTURE);
} else {
if (clearImageOption != null) {
clearImageOption.clearImage();
}
}
}
};
// show a menu of available options
new AlertDialog.Builder(activity)
.setAdapter(adapter, listener)
.show().setOwnerActivity(activity);
}
public static void showPictureLauncher(final Fragment fragment, final ClearImageCallback clearImageOption) {
ArrayList<String> options = new ArrayList<String>();

@ -7,7 +7,6 @@ package com.todoroo.astrid.actfm;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Bundle;
@ -67,8 +66,6 @@ public abstract class CommentsFragment extends SherlockListFragment {
protected static final int MENU_REFRESH_ID = Menu.FIRST;
protected Resources resources;
@Autowired UserActivityDao userActivityDao;
public CommentsFragment() {
@ -95,8 +92,6 @@ public abstract class CommentsFragment extends SherlockListFragment {
protected abstract Cursor getCursor();
protected abstract String getSourceIdentifier();
protected abstract void addHeaderToListView(ListView listView);
protected abstract UserActivity createUpdate();
@ -125,8 +120,6 @@ public abstract class CommentsFragment extends SherlockListFragment {
addCommentField.setOnTouchListener(onTouch);
setUpUpdateList();
resources = getResources();
}
protected void setUpUpdateList() {
@ -211,10 +204,9 @@ public abstract class CommentsFragment extends SherlockListFragment {
if(updateAdapter == null) {
cursor = getCursor();
activity.startManagingCursor(cursor);
String source = getSourceIdentifier();
updateAdapter = new UpdateAdapter(this, R.layout.update_adapter_row,
cursor, false, source);
cursor, false);
addHeaderToListView(listView);
addFooterToListView(listView);
listView.setAdapter(updateAdapter);

@ -14,7 +14,6 @@ import android.widget.ListView;
import com.todoroo.andlib.service.Autowired;
import com.todoroo.andlib.utility.DateUtilities;
import com.todoroo.andlib.utility.Preferences;
import com.todoroo.astrid.adapter.UpdateAdapter;
import com.todoroo.astrid.data.RemoteModel;
import com.todoroo.astrid.data.TagData;
import com.todoroo.astrid.data.Task;
@ -70,11 +69,6 @@ public class TagCommentsFragment extends CommentsFragment {
return tagDataService.getActivityForTagData(tagData, null);
}
@Override
protected String getSourceIdentifier() {
return (tagData == null) ? UpdateAdapter.FROM_RECENT_ACTIVITY_VIEW : UpdateAdapter.FROM_TAG_VIEW;
}
@Override
protected void addHeaderToListView(ListView listView) {
if (AstridPreferences.useTabletLayout(getActivity()) && tagData != null) {

@ -55,8 +55,6 @@ public class TagSettingsActivity extends SherlockFragmentActivity {
public static final String TOKEN_AUTOPOPULATE_NAME = "autopopulateName"; //$NON-NLS-1$
private static final String MEMBERS_IN_PROGRESS = "members"; //$NON-NLS-1$
private TagData tagData;
@Autowired TagService tagService;

@ -189,10 +189,6 @@ public class TagViewFragment extends TaskListFragment {
}
}
@Override
public void requestCommentCountUpdate() {
}
// --------------------------------------------------------- refresh data
@ -307,7 +303,7 @@ public class TagViewFragment extends TaskListFragment {
@Override
protected boolean hasDraggableOption() {
return tagData != null && !tagData.getFlag(TagData.FLAGS, TagData.FLAG_FEATURED);
return tagData != null;
}
@Override

@ -6,7 +6,6 @@ import android.widget.ListView;
import com.todoroo.andlib.service.Autowired;
import com.todoroo.andlib.utility.DateUtilities;
import com.todoroo.astrid.adapter.UpdateAdapter;
import com.todoroo.astrid.dao.TaskDao;
import com.todoroo.astrid.data.Task;
import com.todoroo.astrid.data.UserActivity;
@ -58,11 +57,6 @@ public class TaskCommentsFragment extends CommentsFragment {
return taskService.getActivityForTask(task);
}
@Override
protected String getSourceIdentifier() {
return (task == null) ? UpdateAdapter.FROM_RECENT_ACTIVITY_VIEW : UpdateAdapter.FROM_TASK_VIEW;
}
@Override
protected void addHeaderToListView(ListView listView) {
// Do nothing

@ -5,7 +5,6 @@
*/
package com.todoroo.astrid.activity;
import android.app.PendingIntent.CanceledException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
@ -34,10 +33,8 @@ import com.todoroo.astrid.api.AstridApiConstants;
import com.todoroo.astrid.api.Filter;
import com.todoroo.astrid.api.FilterListItem;
import com.todoroo.astrid.api.FilterWithCustomIntent;
import com.todoroo.astrid.api.IntentFilter;
import com.todoroo.astrid.core.CoreFilterExposer;
import com.todoroo.astrid.core.PluginServices;
import com.todoroo.astrid.core.SearchFilter;
import com.todoroo.astrid.dao.TaskDao;
import com.todoroo.astrid.data.TagData;
import com.todoroo.astrid.data.Task;
@ -141,34 +138,23 @@ public class AstridActivity extends SherlockFragmentActivity
if (this instanceof TaskListActivity && (item instanceof Filter) ) {
((TaskListActivity) this).setSelectedItem((Filter) item);
}
if (item instanceof SearchFilter) {
onSearchRequested();
return false;
} else {
// If showing both fragments, directly update the tasklist-fragment
Intent intent = getIntent();
if(item instanceof Filter) {
Filter filter = (Filter)item;
// If showing both fragments, directly update the tasklist-fragment
Intent intent = getIntent();
Bundle extras = configureIntentAndExtrasWithFilter(intent, filter);
if (fragmentLayout == LAYOUT_TRIPLE && getTaskEditFragment() != null) {
onBackPressed(); // remove the task edit fragment when switching between lists
}
setupTasklistFragmentWithFilter(filter, extras);
if(item instanceof Filter) {
Filter filter = (Filter)item;
// no animation for dualpane-layout
AndroidUtilities.callOverridePendingTransition(this, 0, 0);
return true;
} else if(item instanceof IntentFilter) {
try {
((IntentFilter)item).intent.send();
} catch (CanceledException e) {
// ignore
}
Bundle extras = configureIntentAndExtrasWithFilter(intent, filter);
if (fragmentLayout == LAYOUT_TRIPLE && getTaskEditFragment() != null) {
onBackPressed(); // remove the task edit fragment when switching between lists
}
return false;
setupTasklistFragmentWithFilter(filter, extras);
// no animation for dualpane-layout
AndroidUtilities.callOverridePendingTransition(this, 0, 0);
return true;
}
return false;
}
protected Bundle configureIntentAndExtrasWithFilter(Intent intent, Filter filter) {
@ -244,13 +230,6 @@ public class AstridActivity extends SherlockFragmentActivity
}
}
public void onTaskListItemClicked(String uuid) {
Task task = taskDao.fetch(uuid, Task.ID, Task.IS_READONLY, Task.IS_PUBLIC, Task.USER_ID);
if (task != null) {
onTaskListItemClicked(task.getId(), task.isEditable());
}
}
@Override
public void onTaskListItemClicked(long taskId, boolean editable) {
if (editable) {

@ -80,33 +80,6 @@ public class BeastModePreferences extends ListActivity {
Preferences.setBoolean(BEAST_MODE_ASSERTED_HIDE_ALWAYS, true);
}
public static void setDefaultLiteModeOrder(Context context, boolean force) {
if (Preferences.getStringValue(BEAST_MODE_ORDER_PREF) != null && !force) {
return;
}
if (force) {
Preferences.clear(BEAST_MODE_ORDER_PREF);
}
ArrayList<String> list = constructOrderedControlList(context);
String hideSeparator = context.getResources().getString(R.string.TEA_ctrl_hide_section_pref);
String importancePref = context.getResources().getString(R.string.TEA_ctrl_importance_pref);
String listsPref = context.getResources().getString(R.string.TEA_ctrl_lists_pref);
list.remove(importancePref);
list.remove(listsPref);
list.remove(hideSeparator);
list.add(hideSeparator);
StringBuilder newSetting = new StringBuilder(30);
for (String item : list) {
newSetting.append(item);
newSetting.append(BEAST_MODE_PREF_ITEM_SEPARATOR);
}
Preferences.setString(BEAST_MODE_ORDER_PREF, newSetting.toString());
}
public static void setDefaultOrder(Context context, boolean force) {
if (Preferences.getStringValue(BEAST_MODE_ORDER_PREF) != null && !force) {
return;

@ -66,7 +66,6 @@ public class FilterListFragment extends SherlockListFragment {
private static final int CONTEXT_MENU_INTENT = Menu.FIRST + 4;
public static final int REQUEST_CUSTOM_INTENT = 10;
static final int REQUEST_VIEW_TASKS = 2;
public static final int REQUEST_NEW_BUTTON = 3;
public static final int REQUEST_NEW_LIST = 4;

@ -31,19 +31,6 @@ public class TaskEditViewPager extends PagerAdapter {
titles = titleList.toArray(new String[titleList.size()]);
}
public static int getPageForPosition(int position, int tabStyle) {
int numOnesEncountered = 0;
for (int i = 0; i <= 2; i++) {
if ((tabStyle & (1 << i)) > 0) {
numOnesEncountered++;
}
if (numOnesEncountered == position + 1) {
return 1 << i;
}
}
return -1;
}
@Override
public int getCount() {
return titles.length;

@ -53,10 +53,7 @@ import com.todoroo.andlib.sql.Criterion;
import com.todoroo.andlib.sql.Field;
import com.todoroo.andlib.sql.Join;
import com.todoroo.andlib.utility.AndroidUtilities;
import com.todoroo.andlib.utility.DateUtilities;
import com.todoroo.andlib.utility.Preferences;
import com.todoroo.astrid.actfm.CommentsActivity;
import com.todoroo.astrid.actfm.TagViewFragment;
import com.todoroo.astrid.activity.SortSelectionActivity.OnSortSelectedListener;
import com.todoroo.astrid.adapter.TaskAdapter;
import com.todoroo.astrid.adapter.TaskAdapter.OnCompletedTaskListener;
@ -78,7 +75,8 @@ import com.todoroo.astrid.data.TaskListMetadata;
import com.todoroo.astrid.helper.SyncActionHelper;
import com.todoroo.astrid.helper.TaskListContextMenuExtensionLoader;
import com.todoroo.astrid.helper.TaskListContextMenuExtensionLoader.ContextMenuItem;
import com.todoroo.astrid.reminders.ReminderDebugContextActions;
import com.todoroo.astrid.reminders.MakeNotification;
import com.todoroo.astrid.reminders.WhenReminder;
import com.todoroo.astrid.service.AstridDependencyInjector;
import com.todoroo.astrid.service.TaskService;
import com.todoroo.astrid.service.UpgradeService;
@ -111,9 +109,6 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele
public static final String TAG_TASKLIST_FRAGMENT = "tasklist_fragment"; //$NON-NLS-1$
public static final String PREF_LAST_FEEDBACK_TIME = "pref_last_feedback_time"; //$NON-NLS-1$
private static final long FEEDBACK_TIME_INTERVAL = DateUtilities.ONE_WEEK * 12;
// --- activities
public static final long AUTOSYNC_INTERVAL = 90000L;
@ -121,14 +116,11 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele
private static final long WAIT_BEFORE_AUTOSYNC = 2000L;
public static final int ACTIVITY_EDIT_TASK = 0;
public static final int ACTIVITY_SETTINGS = 1;
public static final int ACTIVITY_SORT = 2;
public static final int ACTIVITY_ADDONS = 3;
public static final int ACTIVITY_MENU_EXTERNAL = 4;
public static final int ACTIVITY_REQUEST_NEW_FILTER = 5;
// --- menu codes
protected static final int MENU_SUPPORT_ID = R.string.TLA_menu_support;
protected static final int MENU_ADDON_INTENT_ID = Menu.FIRST + 199;
protected static final int CONTEXT_MENU_EDIT_TASK_ID = R.string.TAd_contextEditTask;
@ -159,8 +151,8 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele
@Autowired TaskListMetadataDao taskListMetadataDao;
private final TaskContextActionExposer[] contextItemExposers = new TaskContextActionExposer[] {
new ReminderDebugContextActions.MakeNotification(),
new ReminderDebugContextActions.WhenReminder(),
new MakeNotification(),
new WhenReminder(),
};
protected Resources resources;
@ -235,14 +227,6 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele
return newFragment;
}
/**
* Convenience method for calling instantiateWithFilterAndExtras(Filter, Bundle, Class<?>) with
* TaskListFragment as the default component
*/
public static TaskListFragment instantiateWithFilterAndExtras(Filter filter, Bundle extras) {
return instantiateWithFilterAndExtras(filter, extras, null);
}
/**
* Container Activity must implement this interface and we ensure that it
* does during the onAttach() callback
@ -354,10 +338,6 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele
return null;
}
public TaskListMetadata getTaskListMetadata() {
return taskListMetadata;
}
protected void initializeData() {
if (extras != null && extras.containsKey(TOKEN_FILTER)) {
filter = extras.getParcelable(TOKEN_FILTER);
@ -653,11 +633,6 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele
}
}
// Subclasses should override this
public void requestCommentCountUpdate() {
TaskListActivity activity = (TaskListActivity) getActivity();
}
@Override
public void onPause() {
super.onPause();
@ -821,8 +796,6 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele
public static final String TAGS_METADATA_JOIN = "for_tags"; //$NON-NLS-1$
public static final String USER_IMAGE_JOIN = "for_images"; // //$NON-NLS-1$
public static final String FILE_METADATA_JOIN = "for_actions"; //$NON-NLS-1$
@ -944,24 +917,6 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele
}
}
/**
* Comments button in action bar was clicked
*/
protected void handleCommentsButtonClicked() {
Activity activity = getActivity();
if (activity != null) {
Intent intent = new Intent(activity, CommentsActivity.class);
long id = 0;
TagData td = getActiveTagData();
if (td != null) {
id = td.getId();
}
intent.putExtra(TagViewFragment.EXTRA_TAG_DATA, id);
startActivity(intent);
AndroidUtilities.callOverridePendingTransition(activity, R.anim.slide_left_in, R.anim.slide_left_out);
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
@ -1000,10 +955,6 @@ public class TaskListFragment extends SherlockListFragment implements OnSortSele
}
}
public boolean isInbox() {
return isInbox;
}
/** Show a dialog box and delete the task specified */
private void deleteTask(final Task task) {
new AlertDialog.Builder(getActivity()).setTitle(

@ -14,7 +14,6 @@ import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Parcelable;
@ -43,13 +42,10 @@ import com.todoroo.astrid.api.AstridFilterExposer;
import com.todoroo.astrid.api.Filter;
import com.todoroo.astrid.api.FilterCategory;
import com.todoroo.astrid.api.FilterCategoryWithNewButton;
import com.todoroo.astrid.api.FilterListHeader;
import com.todoroo.astrid.api.FilterListItem;
import com.todoroo.astrid.api.FilterWithCustomIntent;
import com.todoroo.astrid.api.FilterWithUpdate;
import com.todoroo.astrid.service.MarketStrategy.NookMarketStrategy;
import com.todoroo.astrid.service.TaskService;
import com.todoroo.astrid.utility.Constants;
import org.tasks.R;
@ -63,10 +59,6 @@ import java.util.regex.Pattern;
public class FilterAdapter extends ArrayAdapter<Filter> {
public static interface FilterDataSourceChangedListener {
public void filterDataSourceChanged();
}
// --- style constants
public int filterStyle = R.style.TextAppearance_FLA_Filter;
@ -80,8 +72,6 @@ public class FilterAdapter extends ArrayAdapter<Filter> {
/** parent activity */
protected final Activity activity;
protected final Resources resources;
/** owner listview */
protected ListView listView;
@ -108,11 +98,6 @@ public class FilterAdapter extends ArrayAdapter<Filter> {
private final HashMap<Filter, Integer> filterCounts;
private FilterDataSourceChangedListener listener;
private final boolean nook;
// Previous solution involved a queue of filters and a filterSizeLoadingThread. The filterSizeLoadingThread had
// a few problems: how to make sure that the thread is resumed when the controlling activity is resumed, and
// how to make sure that the the filterQueue does not accumulate filters without being processed. I am replacing
@ -134,15 +119,12 @@ public class FilterAdapter extends ArrayAdapter<Filter> {
DependencyInjectionService.getInstance().inject(this);
this.activity = activity;
this.resources = activity.getResources();
this.listView = listView;
this.layout = rowLayout;
this.skipIntentFilters = skipIntentFilters;
this.selectable = selectable;
this.filterCounts = new HashMap<Filter, Integer>();
this.nook = (Constants.MARKET_STRATEGY instanceof NookMarketStrategy);
inflater = (LayoutInflater) activity.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
@ -257,10 +239,6 @@ public class FilterAdapter extends ArrayAdapter<Filter> {
});
}
public void setDataSourceChangedListener(FilterDataSourceChangedListener listener) {
this.listener = listener;
}
public void setListView(ListView listView) {
this.listView = listView;
}
@ -392,7 +370,6 @@ public class FilterAdapter extends ArrayAdapter<Filter> {
for (Parcelable item : filters) {
FilterListItem filter = (FilterListItem) item;
if(skipIntentFilters && !(filter instanceof Filter ||
filter instanceof FilterListHeader ||
filter instanceof FilterCategory)) {
continue;
}
@ -411,14 +388,6 @@ public class FilterAdapter extends ArrayAdapter<Filter> {
}
}
@Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
if (listener != null) {
listener.filterDataSourceChanged();
}
}
/**
* Broadcast a request for lists. The request is sent to every
* application registered to listen for this broadcast. Each application
@ -462,7 +431,7 @@ public class FilterAdapter extends ArrayAdapter<Filter> {
viewHolder.decoration = null;
}
if(viewHolder.item instanceof FilterListHeader || viewHolder.item instanceof FilterCategory) {
if(viewHolder.item instanceof FilterCategory) {
viewHolder.name.setTextAppearance(activity, headerStyle);
viewHolder.name.setShadowLayer(1, 1, 1, Color.BLACK);
} else {
@ -510,11 +479,6 @@ public class FilterAdapter extends ArrayAdapter<Filter> {
viewHolder.name.getLayoutParams().height = (int) (58 * metrics.density);
if (nook) {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewHolder.name.getLayoutParams();
params.setMargins((int) (8 * metrics.density), 0, 0, 0);
}
if (filter.color != 0) {
viewHolder.name.setTextColor(filter.color);
}

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

Loading…
Cancel
Save