pull/437/head
Alex Baker 8 years ago
parent 173e0ac8ad
commit d46ef1b901

@ -187,27 +187,25 @@ abstract public class TranslationTests extends AndroidTestCase {
}
forEachLocale(new Runnable() {
public void run() {
Locale locale = r.getConfiguration().locale;
for(int i = 0; i < strings.length; i++) {
try {
switch(strings[i]) {
case R.string.abc_shareactionprovider_share_with_application:
continue;
}
String string = r.getString(strings[i]);
FormatStringData newFS = new FormatStringData(string);
if(!newFS.matches(formatStrings[i])) {
String name = r.getResourceName(strings[i]);
failures.append(String.format("%s (%s): %s != %s\n",
name, locale.toString(), newFS, formatStrings[i]));
}
} catch (Exception e) {
forEachLocale(() -> {
Locale locale = r.getConfiguration().locale;
for(int i = 0; i < strings.length; i++) {
try {
switch(strings[i]) {
case R.string.abc_shareactionprovider_share_with_application:
continue;
}
String string = r.getString(strings[i]);
FormatStringData newFS = new FormatStringData(string);
if(!newFS.matches(formatStrings[i])) {
String name = r.getResourceName(strings[i]);
failures.append(String.format("%s: error opening %s: %s\n",
locale.toString(), name, e.getMessage()));
failures.append(String.format("%s (%s): %s != %s\n",
name, locale.toString(), newFS, formatStrings[i]));
}
} catch (Exception e) {
String name = r.getResourceName(strings[i]);
failures.append(String.format("%s: error opening %s: %s\n",
locale.toString(), name, e.getMessage()));
}
}
});
@ -225,24 +223,22 @@ abstract public class TranslationTests extends AndroidTestCase {
final int[] dateStrings = getDateFormatStrings();
final DateTime date = newDateTime();
forEachLocale(new Runnable() {
public void run() {
Locale locale = r.getConfiguration().locale;
for (int dateString : dateStrings) {
forEachLocale(() -> {
Locale locale = r.getConfiguration().locale;
for (int dateString : dateStrings) {
try {
String string = r.getString(dateString);
try {
String string = r.getString(dateString);
try {
date.toString(string);
} catch (Exception e) {
String name = r.getResourceName(dateString);
failures.append(String.format("%s: invalid format string '%s': %s\n",
locale.toString(), name, e.getMessage()));
}
date.toString(string);
} catch (Exception e) {
String name = r.getResourceName(dateString);
failures.append(String.format("%s: error opening %s: %s\n",
failures.append(String.format("%s: invalid format string '%s': %s\n",
locale.toString(), name, e.getMessage()));
}
} catch (Exception e) {
String name = r.getResourceName(dateString);
failures.append(String.format("%s: error opening %s: %s\n",
locale.toString(), name, e.getMessage()));
}
}
});
@ -271,28 +267,26 @@ abstract public class TranslationTests extends AndroidTestCase {
}
}
forEachLocale(new Runnable() {
public void run() {
for(int i = 0; i < arrays.length; i++) {
if(sizes[i] == -1)
continue;
int size;
try {
size = r.getStringArray(arrays[i]).length;
} catch (Resources.NotFoundException e) {
String name = r.getResourceName(arrays[i]);
Locale locale = r.getConfiguration().locale;
failures.append(String.format("%s: error opening %s: %s\n",
locale, name, e.getMessage()));
continue;
}
forEachLocale(() -> {
for(int i = 0; i < arrays.length; i++) {
if(sizes[i] == -1)
continue;
int size;
try {
size = r.getStringArray(arrays[i]).length;
} catch (Resources.NotFoundException e) {
String name = r.getResourceName(arrays[i]);
Locale locale = r.getConfiguration().locale;
failures.append(String.format("%s: error opening %s: %s\n",
locale, name, e.getMessage()));
continue;
}
if(size != sizes[i]) {
String name = r.getResourceName(arrays[i]);
Locale locale = r.getConfiguration().locale;
failures.append(String.format("%s (%s): size %d != %d\n",
name, locale.toString(), size, sizes[i]));
}
if(size != sizes[i]) {
String name = r.getResourceName(arrays[i]);
Locale locale = r.getConfiguration().locale;
failures.append(String.format("%s (%s): size %d != %d\n",
name, locale.toString(), size, sizes[i]));
}
}
});

@ -59,34 +59,30 @@ public class DateUtilitiesTest extends AndroidTestCase {
}
public void testTimeString() {
forEachLocale(new Runnable() {
public void run() {
DateTime d = newDateTime();
DateUtilities.is24HourOverride = false;
for (int i = 0; i < 24; i++) {
d = d.withHourOfDay(i);
getTimeString(getContext(), d);
}
DateUtilities.is24HourOverride = true;
for (int i = 0; i < 24; i++) {
d = d.withHourOfDay(i);
getTimeString(getContext(), d);
}
forEachLocale(() -> {
DateTime d = newDateTime();
DateUtilities.is24HourOverride = false;
for (int i = 0; i < 24; i++) {
d = d.withHourOfDay(i);
getTimeString(getContext(), d);
}
DateUtilities.is24HourOverride = true;
for (int i = 0; i < 24; i++) {
d = d.withHourOfDay(i);
getTimeString(getContext(), d);
}
});
}
public void testDateString() {
forEachLocale(new Runnable() {
public void run() {
DateTime d = newDateTime();
for (int i = 0; i < 12; i++) {
d = d.withMonthOfYear(i);
getDateString(d);
}
forEachLocale(() -> {
DateTime d = newDateTime();
for (int i = 0; i < 12; i++) {
d = d.withMonthOfYear(i);
getDateString(d);
}
});
}

@ -53,12 +53,10 @@ public class AstridTranslationTest extends TranslationTests {
final Resources r = getContext().getResources();
final StringBuilder failures = new StringBuilder();
forEachLocale(new Runnable() {
public void run() {
contains(r, R.string.CFC_tag_text, failures, "?");
contains(r, R.string.CFC_title_contains_text, failures, "?");
contains(r, R.string.CFC_dueBefore_text, failures, "?");
}
forEachLocale(() -> {
contains(r, R.string.CFC_tag_text, failures, "?");
contains(r, R.string.CFC_title_contains_text, failures, "?");
contains(r, R.string.CFC_dueBefore_text, failures, "?");
});
assertEquals(failures.toString(), 0,

@ -22,17 +22,12 @@ public class GtaskListMaker {
return make(instantiator, properties);
}
private static final Instantiator<GtasksList> instantiator = new Instantiator<GtasksList>() {
@Override
public GtasksList instantiate(final PropertyLookup<GtasksList> lookup) {
return new GtasksList(new StoreObject() {{
setType(GtasksList.TYPE);
setValue(StoreObject.ID, lookup.valueOf(GtaskListMaker.ID, 1L));
setValue(StoreObject.ITEM, lookup.valueOf(REMOTE_ID, "1"));
setValue(StoreObject.VALUE1, lookup.valueOf(NAME, "Default"));
setValue(StoreObject.VALUE2, String.valueOf(lookup.valueOf(ORDER, 0)));
setValue(StoreObject.VALUE3, String.valueOf(lookup.valueOf(LAST_SYNC, 0L)));
}});
}
};
private static final Instantiator<GtasksList> instantiator = lookup -> new GtasksList(new StoreObject() {{
setType(GtasksList.TYPE);
setValue(StoreObject.ID, lookup.valueOf(GtaskListMaker.ID, 1L));
setValue(StoreObject.ITEM, lookup.valueOf(REMOTE_ID, "1"));
setValue(StoreObject.VALUE1, lookup.valueOf(NAME, "Default"));
setValue(StoreObject.VALUE2, String.valueOf(lookup.valueOf(ORDER, 0)));
setValue(StoreObject.VALUE3, String.valueOf(lookup.valueOf(LAST_SYNC, 0L)));
}});
}

@ -24,37 +24,34 @@ public class TaskMaker {
return make(instantiator, properties);
}
private static final Instantiator<Task> instantiator = new Instantiator<Task>() {
@Override
public Task instantiate(PropertyLookup<Task> lookup) {
Task task = new Task();
DateTime dueDate = lookup.valueOf(DUE_DATE, (DateTime) null);
if (dueDate != null) {
task.setDueDate(Task.createDueDate(Task.URGENCY_SPECIFIC_DAY, dueDate.getMillis()));
}
DateTime dueTime = lookup.valueOf(DUE_TIME, (DateTime) null);
if (dueTime != null) {
task.setDueDate(Task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, dueTime.getMillis()));
}
int hideType = lookup.valueOf(HIDE_TYPE, -1);
if (hideType >= 0) {
task.setHideUntil(task.createHideUntil(hideType, 0));
}
int reminderFlags = lookup.valueOf(REMINDERS, -1);
if (reminderFlags >= 0) {
task.setReminderFlags(reminderFlags);
}
DateTime reminderLast = lookup.valueOf(REMINDER_LAST, (DateTime) null);
if (reminderLast != null) {
task.setReminderLast(reminderLast.getMillis());
}
return task;
private static final Instantiator<Task> instantiator = lookup -> {
Task task = new Task();
DateTime dueDate = lookup.valueOf(DUE_DATE, (DateTime) null);
if (dueDate != null) {
task.setDueDate(Task.createDueDate(Task.URGENCY_SPECIFIC_DAY, dueDate.getMillis()));
}
DateTime dueTime = lookup.valueOf(DUE_TIME, (DateTime) null);
if (dueTime != null) {
task.setDueDate(Task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, dueTime.getMillis()));
}
int hideType = lookup.valueOf(HIDE_TYPE, -1);
if (hideType >= 0) {
task.setHideUntil(task.createHideUntil(hideType, 0));
}
int reminderFlags = lookup.valueOf(REMINDERS, -1);
if (reminderFlags >= 0) {
task.setReminderFlags(reminderFlags);
}
DateTime reminderLast = lookup.valueOf(REMINDER_LAST, (DateTime) null);
if (reminderLast != null) {
task.setReminderLast(reminderLast.getMillis());
}
return task;
};
}

@ -19,13 +19,8 @@ public class RemoteGtaskListMaker {
return make(instantiator, properties);
}
private static final Instantiator<TaskList> instantiator = new Instantiator<TaskList>() {
@Override
public TaskList instantiate(final PropertyLookup<TaskList> lookup) {
return new TaskList()
.setId(lookup.valueOf(REMOTE_ID, "1"))
.setTitle(lookup.valueOf(NAME, "Default"))
.setUpdated(new DateTime(currentTimeMillis()));
}
};
private static final Instantiator<TaskList> instantiator = lookup -> new TaskList()
.setId(lookup.valueOf(REMOTE_ID, "1"))
.setTitle(lookup.valueOf(NAME, "Default"))
.setUpdated(new DateTime(currentTimeMillis()));
}

@ -654,28 +654,22 @@ public class IabHelper {
checkNotDisposed();
checkSetupDone("queryInventory");
flagStartAsync("refresh inventory");
executor.execute(new Runnable() {
public void run() {
IabResult result = new IabResult(BILLING_RESPONSE_RESULT_OK, "Inventory refresh successful.");
Inventory inv = null;
try {
inv = queryInventory(querySkuDetails, moreSkus);
}
catch (IabException ex) {
result = ex.getResult();
}
executor.execute(() -> {
IabResult result = new IabResult(BILLING_RESPONSE_RESULT_OK, "Inventory refresh successful.");
Inventory inv = null;
try {
inv = queryInventory(querySkuDetails, moreSkus);
}
catch (IabException ex) {
result = ex.getResult();
}
flagEndAsync();
flagEndAsync();
final IabResult result_f = result;
final Inventory inv_f = inv;
if (!mDisposed && listener != null) {
handler.post(new Runnable() {
public void run() {
listener.onQueryInventoryFinished(result_f, inv_f);
}
});
}
final IabResult result_f = result;
final Inventory inv_f = inv;
if (!mDisposed && listener != null) {
handler.post(() -> listener.onQueryInventoryFinished(result_f, inv_f));
}
});
}
@ -1011,35 +1005,25 @@ public class IabHelper {
final OnConsumeMultiFinishedListener multiListener) {
final Handler handler = new Handler();
flagStartAsync("consume");
executor.execute(new Runnable() {
public void run() {
final List<IabResult> results = new ArrayList<IabResult>();
for (Purchase purchase : purchases) {
try {
consume(purchase);
results.add(new IabResult(BILLING_RESPONSE_RESULT_OK, "Successful consume of sku " + purchase.getSku()));
}
catch (IabException ex) {
results.add(ex.getResult());
}
}
flagEndAsync();
if (!mDisposed && singleListener != null) {
handler.post(new Runnable() {
public void run() {
singleListener.onConsumeFinished(purchases.get(0), results.get(0));
}
});
executor.execute(() -> {
final List<IabResult> results = new ArrayList<IabResult>();
for (Purchase purchase : purchases) {
try {
consume(purchase);
results.add(new IabResult(BILLING_RESPONSE_RESULT_OK, "Successful consume of sku " + purchase.getSku()));
}
if (!mDisposed && multiListener != null) {
handler.post(new Runnable() {
public void run() {
multiListener.onConsumeMultiFinished(purchases, results);
}
});
catch (IabException ex) {
results.add(ex.getResult());
}
}
flagEndAsync();
if (!mDisposed && singleListener != null) {
handler.post(() -> singleListener.onConsumeFinished(purchases.get(0), results.get(0)));
}
if (!mDisposed && multiListener != null) {
handler.post(() -> multiListener.onConsumeMultiFinished(purchases, results));
}
});
}

@ -46,12 +46,7 @@ public class GtasksFilterExposer {
for (GtasksList list : gtasksListService.getLists()) {
listFilters.add(filterFromList(list));
}
Collections.sort(listFilters, new Comparator<Filter>() {
@Override
public int compare(Filter filter, Filter t1) {
return filter.listingTitle.compareTo(t1.listingTitle);
}
});
Collections.sort(listFilters, (filter, t1) -> filter.listingTitle.compareTo(t1.listingTitle));
return listFilters;
}

@ -55,22 +55,19 @@ public class GtasksPreferences extends InjectingPreferenceActivity implements Go
final CheckBoxPreference gtaskPreference = (CheckBoxPreference) findPreference(getString(R.string.sync_gtasks));
gtaskPreference.setChecked(syncAdapterHelper.isEnabled());
gtaskPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if ((boolean) newValue) {
if (!playServicesAvailability.refreshAndCheck()) {
playServicesAvailability.resolve(GtasksPreferences.this);
} else if (permissionRequestor.requestAccountPermissions()) {
requestLogin();
}
return false;
} else {
syncAdapterHelper.enableSynchronization(false);
tracker.reportEvent(Tracking.Events.GTASK_DISABLED);
gtasksPreferenceService.stopOngoing();
return true;
gtaskPreference.setOnPreferenceChangeListener((preference, newValue) -> {
if ((boolean) newValue) {
if (!playServicesAvailability.refreshAndCheck()) {
playServicesAvailability.resolve(GtasksPreferences.this);
} else if (permissionRequestor.requestAccountPermissions()) {
requestLogin();
}
return false;
} else {
syncAdapterHelper.enableSynchronization(false);
tracker.reportEvent(Tracking.Events.GTASK_DISABLED);
gtasksPreferenceService.stopOngoing();
return true;
}
});
if (gtasksPreferenceService.getLastSyncDate() > 0) {
@ -78,40 +75,28 @@ public class GtasksPreferences extends InjectingPreferenceActivity implements Go
DateUtilities.getDateStringWithTime(GtasksPreferences.this,
gtasksPreferenceService.getLastSyncDate())));
}
findPreference(getString(R.string.gtasks_GPr_interval_key)).setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
syncAdapterHelper.setSynchronizationInterval(Integer.parseInt((String) o));
return true;
}
findPreference(getString(R.string.gtasks_GPr_interval_key)).setOnPreferenceChangeListener((preference, o) -> {
syncAdapterHelper.setSynchronizationInterval(Integer.parseInt((String) o));
return true;
});
findPreference(getString(R.string.sync_SPr_forget_key)).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
dialogBuilder.newMessageDialog(R.string.sync_forget_confirm)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
gtasksPreferenceService.clearLastSyncDate();
gtasksPreferenceService.setUserName(null);
metadataDao.deleteWhere(Metadata.KEY.eq(GtasksMetadata.METADATA_KEY));
syncAdapterHelper.enableSynchronization(false);
tracker.reportEvent(Tracking.Events.GTASK_LOGOUT);
gtaskPreference.setChecked(false);
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
return true;
}
findPreference(getString(R.string.sync_SPr_forget_key)).setOnPreferenceClickListener(preference -> {
dialogBuilder.newMessageDialog(R.string.sync_forget_confirm)
.setPositiveButton(android.R.string.ok, (dialog, which) -> {
gtasksPreferenceService.clearLastSyncDate();
gtasksPreferenceService.setUserName(null);
metadataDao.deleteWhere(Metadata.KEY.eq(GtasksMetadata.METADATA_KEY));
syncAdapterHelper.enableSynchronization(false);
tracker.reportEvent(Tracking.Events.GTASK_LOGOUT);
gtaskPreference.setChecked(false);
})
.setNegativeButton(android.R.string.cancel, null)
.show();
return true;
});
getPref(R.string.p_gtasks_default_list).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
new NativeGoogleTaskListPicker()
.show(getFragmentManager(), FRAG_TAG_GOOGLE_TASK_LIST_SELECTION);
return false;
}
getPref(R.string.p_gtasks_default_list).setOnPreferenceClickListener(preference -> {
new NativeGoogleTaskListPicker()
.show(getFragmentManager(), FRAG_TAG_GOOGLE_TASK_LIST_SELECTION);
return false;
});
updateDefaultGoogleTaskList();
}

@ -110,19 +110,16 @@ public class GtasksTaskListUpdater extends OrderedMetadataListUpdater<GtasksList
GtasksMetadata.LIST_ID.eq(listId),
GtasksMetadata.PARENT_TASK.eq(parent)))
.orderBy(Order.asc(Functions.cast(GtasksMetadata.GTASKS_ORDER, "INTEGER")));
metadataDao.query(query, new Callback<Metadata>() {
@Override
public void apply(Metadata curr) {
if (!alreadyChecked.contains(curr.getTask())) {
curr.setValue(GtasksMetadata.INDENT, indentLevel);
curr.setValue(GtasksMetadata.ORDER, order.getAndIncrement());
metadataDao.saveExisting(curr);
alreadyChecked.add(curr.getTask());
orderAndIndentHelper(listId, order, curr.getTask(), indentLevel + 1, alreadyChecked);
}
}
}
metadataDao.query(query, curr -> {
if (!alreadyChecked.contains(curr.getTask())) {
curr.setValue(GtasksMetadata.INDENT, indentLevel);
curr.setValue(GtasksMetadata.ORDER, order.getAndIncrement());
metadataDao.saveExisting(curr);
alreadyChecked.add(curr.getTask());
orderAndIndentHelper(listId, order, curr.getTask(), indentLevel + 1, alreadyChecked);
}
}
);
}
@ -130,42 +127,39 @@ public class GtasksTaskListUpdater extends OrderedMetadataListUpdater<GtasksList
final AtomicLong previousTask = new AtomicLong(Task.NO_ID);
final AtomicInteger previousIndent = new AtomicInteger(-1);
iterateThroughList(list, new OrderedListIterator() {
@Override
public void processTask(long taskId, Metadata metadata) {
int indent = metadata.getValue(GtasksMetadata.INDENT);
try {
long parent, sibling;
if(indent > previousIndent.get()) {
parent = previousTask.get();
sibling = Task.NO_ID;
} else if(indent == previousIndent.get()) {
sibling = previousTask.get();
iterateThroughList(list, (taskId, metadata) -> {
int indent = metadata.getValue(GtasksMetadata.INDENT);
try {
long parent, sibling;
if(indent > previousIndent.get()) {
parent = previousTask.get();
sibling = Task.NO_ID;
} else if(indent == previousIndent.get()) {
sibling = previousTask.get();
parent = parents.get(sibling);
} else {
// move up once for each indent
sibling = previousTask.get();
for(int i = indent; i < previousIndent.get(); i++) {
sibling = parents.get(sibling);
}
if(parents.containsKey(sibling)) {
parent = parents.get(sibling);
} else {
// move up once for each indent
sibling = previousTask.get();
for(int i = indent; i < previousIndent.get(); i++) {
sibling = parents.get(sibling);
}
if(parents.containsKey(sibling)) {
parent = parents.get(sibling);
} else {
parent = Task.NO_ID;
}
parent = Task.NO_ID;
}
parents.put(taskId, parent);
siblings.put(taskId, sibling);
} catch (Exception e) {
Timber.e(e, e.getMessage());
}
parents.put(taskId, parent);
siblings.put(taskId, sibling);
} catch (Exception e) {
Timber.e(e, e.getMessage());
}
previousTask.set(taskId);
previousIndent.set(indent);
if(!TextUtils.isEmpty(metadata.getValue(GtasksMetadata.ID))) {
localToRemoteIdMap.put(taskId, metadata.getValue(GtasksMetadata.ID));
}
previousTask.set(taskId);
previousIndent.set(indent);
if(!TextUtils.isEmpty(metadata.getValue(GtasksMetadata.ID))) {
localToRemoteIdMap.put(taskId, metadata.getValue(GtasksMetadata.ID));
}
});
}

@ -199,12 +199,7 @@ public class OrderedMetadataListFragmentHelper<LIST> implements OrderedListFragm
taskAdapter = new DraggableTaskAdapter(context, preferences, fragment, cursor,
sqlQueryTemplate, dialogBuilder, checkBoxes, tagService, themeCache);
taskAdapter.addOnCompletedTaskListener(new OnCompletedTaskListener() {
@Override
public void onCompletedTask(Task item, boolean newState) {
setCompletedForItemAndSubtasks(item, newState);
}
});
taskAdapter.addOnCompletedTaskListener(this::setCompletedForItemAndSubtasks);
return taskAdapter;
}
@ -253,23 +248,20 @@ public class OrderedMetadataListFragmentHelper<LIST> implements OrderedListFragm
final ArrayList<Long> chained = new ArrayList<>();
final int parentIndent = item.getValue(updater.indentProperty());
updater.applyToChildren(list, itemId, new OrderedMetadataListUpdater.OrderedListNodeVisitor() {
@Override
public void visitNode(OrderedMetadataListUpdater.Node node) {
Task childTask = taskService.fetchById(node.taskId, Task.RECURRENCE);
if(!TextUtils.isEmpty(childTask.getRecurrence())) {
Metadata metadata = updater.getTaskMetadata(node.taskId);
metadata.setValue(updater.indentProperty(), parentIndent);
metadataDao.persist(metadata);
}
updater.applyToChildren(list, itemId, node -> {
Task childTask = taskService.fetchById(node.taskId, Task.RECURRENCE);
if(!TextUtils.isEmpty(childTask.getRecurrence())) {
Metadata metadata = updater.getTaskMetadata(node.taskId);
metadata.setValue(updater.indentProperty(), parentIndent);
metadataDao.persist(metadata);
}
model.setId(node.taskId);
model.setCompletionDate(completionDate);
taskService.save(model);
model.clear();
model.setId(node.taskId);
model.setCompletionDate(completionDate);
taskService.save(model);
model.clear();
chained.add(node.taskId);
}
chained.add(node.taskId);
});
if(chained.size() > 0) {

@ -68,53 +68,49 @@ abstract public class OrderedMetadataListUpdater<LIST> {
final AtomicLong previousTask = new AtomicLong(Task.NO_ID);
final AtomicLong globalOrder = new AtomicLong(-1);
iterateThroughList(list, new OrderedListIterator() {
@Override
public void processTask(long taskId, Metadata metadata) {
if(!metadata.isSaved()) {
metadata = createEmptyMetadata(list, taskId);
}
int indent = metadata.containsNonNullValue(indentProperty()) ?
metadata.getValue(indentProperty()) : 0;
long order = globalOrder.incrementAndGet();
metadata.setValue(orderProperty(), order);
if(targetTaskId == taskId) {
// if indenting is warranted, indent me and my children
if(indent + delta <= previousIndent.get() + 1 && indent + delta >= 0) {
targetTaskIndent.set(indent);
metadata.setValue(indentProperty(), indent + delta);
if(parentProperty() != null) {
long newParent = computeNewParent(list,
taskId, indent + delta - 1);
if (newParent == taskId) {
metadata.setValue(parentProperty(), Task.NO_ID);
} else {
metadata.setValue(parentProperty(), newParent);
}
iterateThroughList(list, (taskId, metadata) -> {
if(!metadata.isSaved()) {
metadata = createEmptyMetadata(list, taskId);
}
int indent = metadata.containsNonNullValue(indentProperty()) ?
metadata.getValue(indentProperty()) : 0;
long order = globalOrder.incrementAndGet();
metadata.setValue(orderProperty(), order);
if(targetTaskId == taskId) {
// if indenting is warranted, indent me and my children
if(indent + delta <= previousIndent.get() + 1 && indent + delta >= 0) {
targetTaskIndent.set(indent);
metadata.setValue(indentProperty(), indent + delta);
if(parentProperty() != null) {
long newParent = computeNewParent(list,
taskId, indent + delta - 1);
if (newParent == taskId) {
metadata.setValue(parentProperty(), Task.NO_ID);
} else {
metadata.setValue(parentProperty(), newParent);
}
saveAndUpdateModifiedDate(metadata);
}
} else if(targetTaskIndent.get() > -1) {
// found first task that is not beneath target
if(indent <= targetTaskIndent.get()) {
targetTaskIndent.set(-1);
} else {
metadata.setValue(indentProperty(), indent + delta);
saveAndUpdateModifiedDate(metadata);
}
} else {
previousIndent.set(indent);
previousTask.set(taskId);
saveAndUpdateModifiedDate(metadata);
}
if(!metadata.isSaved()) {
} else if(targetTaskIndent.get() > -1) {
// found first task that is not beneath target
if(indent <= targetTaskIndent.get()) {
targetTaskIndent.set(-1);
} else {
metadata.setValue(indentProperty(), indent + delta);
saveAndUpdateModifiedDate(metadata);
}
} else {
previousIndent.set(indent);
previousTask.set(taskId);
}
if(!metadata.isSaved()) {
saveAndUpdateModifiedDate(metadata);
}
});
onMovedOrIndented(getTaskMetadata(targetTaskId));
}
@ -129,17 +125,14 @@ abstract public class OrderedMetadataListUpdater<LIST> {
final AtomicLong lastPotentialParent = new AtomicLong(Task.NO_ID);
final AtomicBoolean computedParent = new AtomicBoolean(false);
iterateThroughList(list, new OrderedListIterator() {
@Override
public void processTask(long taskId, Metadata metadata) {
if (targetTask.get() == taskId) {
computedParent.set(true);
}
iterateThroughList(list, (taskId, metadata) -> {
if (targetTask.get() == taskId) {
computedParent.set(true);
}
int indent = metadata.getValue(indentProperty());
if (!computedParent.get() && indent == desiredParentIndent.get()) {
lastPotentialParent.set(taskId);
}
int indent = metadata.getValue(indentProperty());
if (!computedParent.get() && indent == desiredParentIndent.get()) {
lastPotentialParent.set(taskId);
}
});
@ -254,35 +247,32 @@ abstract public class OrderedMetadataListUpdater<LIST> {
final AtomicInteger previoustIndent = new AtomicInteger(-1);
final AtomicReference<Node> currentNode = new AtomicReference<>(root);
iterateThroughList(list, new OrderedListIterator() {
@Override
public void processTask(long taskId, Metadata metadata) {
int indent = metadata.getValue(indentProperty());
int previousIndentValue = previoustIndent.get();
if(indent == previousIndentValue) { // sibling
Node parent = currentNode.get().parent;
currentNode.set(new Node(taskId, parent));
parent.children.add(currentNode.get());
} else if(indent > previousIndentValue) { // child
Node parent = currentNode.get();
currentNode.set(new Node(taskId, parent));
parent.children.add(currentNode.get());
} else { // in a different tree
Node node = currentNode.get().parent;
for(int i = indent; i < previousIndentValue; i++) {
node = node.parent;
if(node == null) {
node = root;
break;
}
iterateThroughList(list, (taskId, metadata) -> {
int indent = metadata.getValue(indentProperty());
int previousIndentValue = previoustIndent.get();
if(indent == previousIndentValue) { // sibling
Node parent = currentNode.get().parent;
currentNode.set(new Node(taskId, parent));
parent.children.add(currentNode.get());
} else if(indent > previousIndentValue) { // child
Node parent = currentNode.get();
currentNode.set(new Node(taskId, parent));
parent.children.add(currentNode.get());
} else { // in a different tree
Node node = currentNode.get().parent;
for(int i = indent; i < previousIndentValue; i++) {
node = node.parent;
if(node == null) {
node = root;
break;
}
currentNode.set(new Node(taskId, node));
node.children.add(currentNode.get());
}
previoustIndent.set(indent);
currentNode.set(new Node(taskId, node));
node.children.add(currentNode.get());
}
previoustIndent.set(indent);
});
return root;
}

@ -88,12 +88,7 @@ public class GtasksLoginActivity extends InjectingAppCompatActivity implements A
@Override
public void authenticationFailed(final String message) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(GtasksLoginActivity.this, message, Toast.LENGTH_LONG).show();
}
});
runOnUiThread(() -> Toast.makeText(GtasksLoginActivity.this, message, Toast.LENGTH_LONG).show());
DialogUtilities.dismissDialog(GtasksLoginActivity.this, pd);
}
});

@ -173,14 +173,11 @@ public class GtasksSyncService {
startAtCriterion)).
orderBy(order);
metadataDao.query(query, new Callback<Metadata>() {
@Override
public void apply(Metadata entry) {
long taskId = entry.getValue(Metadata.TASK);
Metadata metadata = metadataDao.getFirstActiveByTaskAndKey(taskId, GtasksMetadata.METADATA_KEY);
if(metadata != null) {
iterator.processTask(taskId, metadata);
}
metadataDao.query(query, entry -> {
long taskId = entry.getValue(Metadata.TASK);
Metadata metadata = metadataDao.getFirstActiveByTaskAndKey(taskId, GtasksMetadata.METADATA_KEY);
if(metadata != null) {
iterator.processTask(taskId, metadata);
}
});
}
@ -210,20 +207,17 @@ public class GtasksSyncService {
final AtomicInteger indentToMatch = new AtomicInteger(gtasksMetadata.getValue(GtasksMetadata.INDENT));
final AtomicLong parentToMatch = new AtomicLong(gtasksMetadata.getValue(GtasksMetadata.PARENT_TASK));
final AtomicReference<String> sibling = new AtomicReference<>();
OrderedMetadataListUpdater.OrderedListIterator iterator = new OrderedMetadataListUpdater.OrderedListIterator() {
@Override
public void processTask(long taskId, Metadata metadata) {
Task t = taskDao.fetch(taskId, Task.TITLE, Task.DELETION_DATE);
if (t == null || t.isDeleted()) {
return;
}
int currIndent = metadata.getValue(GtasksMetadata.INDENT);
long currParent = metadata.getValue(GtasksMetadata.PARENT_TASK);
OrderedMetadataListUpdater.OrderedListIterator iterator = (taskId, metadata) -> {
Task t = taskDao.fetch(taskId, Task.TITLE, Task.DELETION_DATE);
if (t == null || t.isDeleted()) {
return;
}
int currIndent = metadata.getValue(GtasksMetadata.INDENT);
long currParent = metadata.getValue(GtasksMetadata.PARENT_TASK);
if (currIndent == indentToMatch.get() && currParent == parentToMatch.get()) {
if (sibling.get() == null) {
sibling.set(metadata.getValue(GtasksMetadata.ID));
}
if (currIndent == indentToMatch.get() && currParent == parentToMatch.get()) {
if (sibling.get() == null) {
sibling.set(metadata.getValue(GtasksMetadata.ID));
}
}
};

@ -40,15 +40,12 @@ public class SyncV2Service {
public void clearCompleted(final GtasksList list, final SyncResultCallback callback) {
if (syncAdapterHelper.isEnabled()) {
syncExecutor.execute(callback, new Runnable() {
@Override
public void run() {
callback.started();
try {
gtasksSyncService.clearCompleted(list.getRemoteId());
} finally {
callback.finished();
}
syncExecutor.execute(callback, () -> {
callback.started();
try {
gtasksSyncService.clearCompleted(list.getRemoteId());
} finally {
callback.finished();
}
});
}

@ -50,12 +50,7 @@ public class AccountManager {
}
public List<String> getAccounts() {
return transform(getAccountList(), new Function<Account, String>() {
@Override
public String apply(Account account) {
return account.name;
}
});
return transform(getAccountList(), account -> account.name);
}
public boolean hasAccount(final String name) {
@ -71,19 +66,16 @@ public class AccountManager {
if (account == null) {
handler.authenticationFailed(activity.getString(R.string.gtasks_error_accountNotFound, accountName));
} else {
new Thread(new Runnable() {
@Override
public void run() {
try {
GoogleAuthUtil.getToken(activity, account, "oauth2:" + TasksScopes.TASKS, null);
handler.authenticationSuccessful(accountName);
} catch(UserRecoverableAuthException e) {
Timber.e(e, e.getMessage());
activity.startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch(GoogleAuthException | IOException e) {
Timber.e(e, e.getMessage());
handler.authenticationFailed(context.getString(R.string.gtasks_GLA_errorIOAuth));
}
new Thread(() -> {
try {
GoogleAuthUtil.getToken(activity, account, "oauth2:" + TasksScopes.TASKS, null);
handler.authenticationSuccessful(accountName);
} catch(UserRecoverableAuthException e) {
Timber.e(e, e.getMessage());
activity.startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch(GoogleAuthException | IOException e) {
Timber.e(e, e.getMessage());
handler.authenticationFailed(context.getString(R.string.gtasks_GLA_errorIOAuth));
}
}).start();
}
@ -100,11 +92,6 @@ public class AccountManager {
return null;
}
return tryFind(getAccountList(), new Predicate<Account>() {
@Override
public boolean apply(Account account) {
return name.equalsIgnoreCase(account.name);
}
}).orNull();
return tryFind(getAccountList(), account -> name.equalsIgnoreCase(account.name)).orNull();
}
}

@ -25,12 +25,7 @@ public class NativeGoogleTaskListPicker extends InjectingNativeDialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return createDialog(dialogBuilder, gtasksListService, new GoogleTaskListSelectionHandler() {
@Override
public void selectedList(GtasksList list) {
handler.selectedList(list);
}
});
return createDialog(dialogBuilder, gtasksListService, list -> handler.selectedList(list));
}
@Override

@ -30,12 +30,7 @@ public class SupportGoogleTaskListPicker extends InjectingDialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return createDialog(dialogBuilder, gtasksListService, new GoogleTaskListSelectionHandler() {
@Override
public void selectedList(GtasksList list) {
handler.selectedList(list);
}
});
return createDialog(dialogBuilder, gtasksListService, list -> handler.selectedList(list));
}
@Override
@ -47,26 +42,13 @@ public class SupportGoogleTaskListPicker extends InjectingDialogFragment {
public static AlertDialog createDialog(DialogBuilder dialogBuilder, GtasksListService gtasksListService, final GoogleTaskListSelectionHandler handler) {
final List<GtasksList> lists = gtasksListService.getLists();
List<String> listNames = transform(lists, new Function<GtasksList, String>() {
@Override
public String apply(GtasksList gtasksList) {
return gtasksList.getName();
}
});
List<String> listNames = transform(lists, GtasksList::getName);
return dialogBuilder.newDialog()
.setItems(listNames, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
handler.selectedList(lists.get(which));
dialog.dismiss();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
.setItems(listNames, (dialog, which) -> {
handler.selectedList(lists.get(which));
dialog.dismiss();
})
.setNegativeButton(android.R.string.cancel, (dialog, which) -> dialog.dismiss())
.show();
}

@ -34,20 +34,17 @@ public class Tracker {
tracker = analytics.newTracker(R.xml.google_analytics);
tracker.setAppVersion(Integer.toString(BuildConfig.VERSION_CODE));
final StandardExceptionParser standardExceptionParser = new StandardExceptionParser(context, null);
exceptionParser = new ExceptionParser() {
@Override
public String getDescription(String thread, Throwable throwable) {
StringBuilder stack = new StringBuilder()
.append(standardExceptionParser.getDescription(thread, throwable))
.append("\n")
.append(throwable.getClass().getName())
exceptionParser = (thread, throwable) -> {
StringBuilder stack = new StringBuilder()
.append(standardExceptionParser.getDescription(thread, throwable))
.append("\n")
.append(throwable.getClass().getName())
.append("\n");
for (StackTraceElement element : throwable.getStackTrace()) {
stack.append(element.toString())
.append("\n");
for (StackTraceElement element : throwable.getStackTrace()) {
stack.append(element.toString())
.append("\n");
}
return stack.toString();
}
return stack.toString();
};
ExceptionReporter reporter = new ExceptionReporter(
tracker,

@ -52,35 +52,29 @@ public class InventoryHelper implements IabBroadcastReceiver.IabBroadcastListene
}
private IabHelper.OnIabSetupFinishedListener getSetupListener(final IabHelper helper) {
return new IabHelper.OnIabSetupFinishedListener() {
@Override
public void onIabSetupFinished(IabResult result) {
if (result.isSuccess()) {
helper.queryInventoryAsync(getQueryListener(helper));
} else {
Timber.e("setup failed: %s", result.getMessage());
helper.dispose();
}
return result -> {
if (result.isSuccess()) {
helper.queryInventoryAsync(getQueryListener(helper));
} else {
Timber.e("setup failed: %s", result.getMessage());
helper.dispose();
}
};
}
private IabHelper.QueryInventoryFinishedListener getQueryListener(final IabHelper helper) {
return new IabHelper.QueryInventoryFinishedListener() {
@Override
public void onQueryInventoryFinished(IabResult result, Inventory inv) {
if (result.isSuccess()) {
inventory = inv;
checkPurchase(R.string.sku_tasker, R.string.p_purchased_tasker);
checkPurchase(R.string.sku_tesla_unread, R.string.p_purchased_tesla_unread);
checkPurchase(R.string.sku_dashclock, R.string.p_purchased_dashclock);
checkPurchase(R.string.sku_themes, R.string.p_purchased_themes);
broadcaster.refresh();
} else {
Timber.e("query inventory failed: %s", result.getMessage());
}
helper.dispose();
return (result, inv) -> {
if (result.isSuccess()) {
inventory = inv;
checkPurchase(R.string.sku_tasker, R.string.p_purchased_tasker);
checkPurchase(R.string.sku_tesla_unread, R.string.p_purchased_tesla_unread);
checkPurchase(R.string.sku_dashclock, R.string.p_purchased_dashclock);
checkPurchase(R.string.sku_themes, R.string.p_purchased_themes);
broadcaster.refresh();
} else {
Timber.e("query inventory failed: %s", result.getMessage());
}
helper.dispose();
};
}

@ -66,18 +66,8 @@ public class PurchaseHelper implements IabHelper.OnIabSetupFinishedListener {
if (activity.getString(R.string.sku_tasker).equals(sku) && isAppInstalled(activity, "org.tasks.locale")) {
dialogBuilder.newMessageDialog(R.string.tasker_message)
.setCancelable(false)
.setPositiveButton(R.string.buy, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
launchPurchaseFlow(activity, sku, pref, requestCode, callback);
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
callback.purchaseCompleted(false, sku);
}
})
.setPositiveButton(R.string.buy, (dialog, which) -> launchPurchaseFlow(activity, sku, pref, requestCode, callback))
.setNegativeButton(android.R.string.cancel, (dialog, which) -> callback.purchaseCompleted(false, sku))
.show();
return false;
} else {
@ -107,42 +97,36 @@ public class PurchaseHelper implements IabHelper.OnIabSetupFinishedListener {
}
final IabHelper iabHelper = new IabHelper(context, context.getString(R.string.gp_key), executor);
iabHelper.enableDebugLogging(true);
iabHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
@Override
public void onIabSetupFinished(IabResult result) {
if (result.isSuccess()) {
iabHelper.consumeAsync(purchases, new IabHelper.OnConsumeMultiFinishedListener() {
@Override
public void onConsumeMultiFinished(List<Purchase> purchases, List<IabResult> results) {
for (int i = 0 ; i < purchases.size() ; i++) {
Purchase purchase = purchases.get(i);
IabResult iabResult = results.get(i);
if (iabResult.isSuccess()) {
if (purchase.equals(tasker)) {
preferences.setBoolean(R.string.p_purchased_tasker, false);
} else if (purchase.equals(dashclock)) {
preferences.setBoolean(R.string.p_purchased_dashclock, false);
} else if (purchase.equals(teslaUnread)) {
preferences.setBoolean(R.string.p_purchased_tesla_unread, false);
preferences.setBoolean(R.string.p_tesla_unread_enabled, false);
} else if (purchase.equals(themes)) {
preferences.setBoolean(R.string.p_purchased_themes, false);
} else {
Timber.e("Unhandled consumption for purchase: %s", purchase);
}
inventory.erasePurchase(purchase.getSku());
Timber.d("Consumed %s", purchase);
} else {
Timber.e("Consume failed: %s, %s", purchase, iabResult);
}
iabHelper.startSetup(result -> {
if (result.isSuccess()) {
iabHelper.consumeAsync(purchases, (purchases1, results) -> {
for (int i = 0; i < purchases1.size() ; i++) {
Purchase purchase = purchases1.get(i);
IabResult iabResult = results.get(i);
if (iabResult.isSuccess()) {
if (purchase.equals(tasker)) {
preferences.setBoolean(R.string.p_purchased_tasker, false);
} else if (purchase.equals(dashclock)) {
preferences.setBoolean(R.string.p_purchased_dashclock, false);
} else if (purchase.equals(teslaUnread)) {
preferences.setBoolean(R.string.p_purchased_tesla_unread, false);
preferences.setBoolean(R.string.p_tesla_unread_enabled, false);
} else if (purchase.equals(themes)) {
preferences.setBoolean(R.string.p_purchased_themes, false);
} else {
Timber.e("Unhandled consumption for purchase: %s", purchase);
}
iabHelper.dispose();
inventory.erasePurchase(purchase.getSku());
Timber.d("Consumed %s", purchase);
} else {
Timber.e("Consume failed: %s, %s", purchase, iabResult);
}
});
} else {
Timber.e("setup failed: %s", result.getMessage());
}
iabHelper.dispose();
}
});
} else {
Timber.e("setup failed: %s", result.getMessage());
iabHelper.dispose();
}
});
}
@ -157,45 +141,39 @@ public class PurchaseHelper implements IabHelper.OnIabSetupFinishedListener {
iabHelper = new IabHelper(context, context.getString(R.string.gp_key), executor);
iabHelper.enableDebugLogging(BuildConfig.DEBUG);
Timber.d("%s: startSetup", iabHelper);
iabHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
@Override
public void onIabSetupFinished(IabResult result) {
if (result.isSuccess()) {
try {
Timber.d("%s: launchPurchaseFlow for %s", iabHelper, sku);
iabHelper.launchPurchaseFlow(activity, sku, requestCode, new IabHelper.OnIabPurchaseFinishedListener() {
@Override
public void onIabPurchaseFinished(IabResult result, Purchase info) {
Timber.d(result.toString());
tracker.reportIabResult(result, sku);
if (result.isSuccess()) {
if (!Strings.isNullOrEmpty(pref)) {
preferences.setBoolean(pref, true);
broadcaster.refresh();
}
inventory.refreshInventory();
} else if (result.getResponse() != IabHelper.BILLING_RESPONSE_RESULT_USER_CANCELED &&
result.getResponse() != IabHelper.IABHELPER_USER_CANCELLED) {
Toast.makeText(activity, result.getMessage(), Toast.LENGTH_LONG).show();
}
if (activityResultCallback != null) {
activityResultCallback.purchaseCompleted(result.isSuccess(), sku);
}
disposeIabHelper();
iabHelper.startSetup(result -> {
if (result.isSuccess()) {
try {
Timber.d("%s: launchPurchaseFlow for %s", iabHelper, sku);
iabHelper.launchPurchaseFlow(activity, sku, requestCode, (result1, info) -> {
Timber.d(result1.toString());
tracker.reportIabResult(result1, sku);
if (result1.isSuccess()) {
if (!Strings.isNullOrEmpty(pref)) {
preferences.setBoolean(pref, true);
broadcaster.refresh();
}
});
} catch (IllegalStateException e) {
tracker.reportException(e);
Toast.makeText(activity, R.string.billing_service_busy, Toast.LENGTH_LONG).show();
callback.purchaseCompleted(false, sku);
inventory.refreshInventory();
} else if (result1.getResponse() != IabHelper.BILLING_RESPONSE_RESULT_USER_CANCELED &&
result1.getResponse() != IabHelper.IABHELPER_USER_CANCELLED) {
Toast.makeText(activity, result1.getMessage(), Toast.LENGTH_LONG).show();
}
if (activityResultCallback != null) {
activityResultCallback.purchaseCompleted(result1.isSuccess(), sku);
}
disposeIabHelper();
}
} else {
Timber.e(result.toString());
Toast.makeText(activity, result.getMessage(), Toast.LENGTH_LONG).show();
});
} catch (IllegalStateException e) {
tracker.reportException(e);
Toast.makeText(activity, R.string.billing_service_busy, Toast.LENGTH_LONG).show();
callback.purchaseCompleted(false, sku);
disposeIabHelper();
}
} else {
Timber.e(result.toString());
Toast.makeText(activity, result.getMessage(), Toast.LENGTH_LONG).show();
callback.purchaseCompleted(false, sku);
disposeIabHelper();
}
});
}

@ -44,14 +44,11 @@ public class DashClockSettings extends InjectingPreferenceActivity implements Pu
addPreferencesFromResource(R.xml.preferences_dashclock);
findPreference(getString(R.string.p_dashclock_filter)).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
startActivityForResult(new Intent(DashClockSettings.this, FilterSelectionActivity.class) {{
putExtra(FilterSelectionActivity.EXTRA_RETURN_FILTER, true);
}}, REQUEST_SELECT_FILTER);
return false;
}
findPreference(getString(R.string.p_dashclock_filter)).setOnPreferenceClickListener(preference -> {
startActivityForResult(new Intent(DashClockSettings.this, FilterSelectionActivity.class) {{
putExtra(FilterSelectionActivity.EXTRA_RETURN_FILTER, true);
}}, REQUEST_SELECT_FILTER);
return false;
});
refreshPreferences();

@ -39,19 +39,13 @@ public class AccountSelectionDialog extends InjectingDialogFragment {
return dialogBuilder.newDialog()
.setTitle(R.string.choose_google_account)
.setItems(accounts, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
handler.accountSelected(accounts.get(which));
dialog.dismiss();
}
.setItems(accounts, (dialog, which) -> {
handler.accountSelected(accounts.get(which));
dialog.dismiss();
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (handler != null) {
handler.onCancel();
}
.setNegativeButton(android.R.string.cancel, (dialog, which) -> {
if (handler != null) {
handler.onCancel();
}
})
.show();

@ -409,20 +409,17 @@ public class GoogleTaskSyncAdapter extends InjectingAbstractThreadedSyncAdapter
newMetadataValues.add(metadatum.getMergedValues());
}
metadataDao.byTaskAndKey(taskId, metadataKey, new Callback<Metadata>() {
@Override
public void apply(Metadata item) {
long id = item.getId();
// clear item id when matching with incoming values
item.clearValue(Metadata.ID);
ContentValues itemMergedValues = item.getMergedValues();
if(newMetadataValues.contains(itemMergedValues)) {
newMetadataValues.remove(itemMergedValues);
} else {
// not matched. cut it
metadataDao.delete(id);
}
metadataDao.byTaskAndKey(taskId, metadataKey, item -> {
long id = item.getId();
// clear item id when matching with incoming values
item.clearValue(Metadata.ID);
ContentValues itemMergedValues = item.getMergedValues();
if(newMetadataValues.contains(itemMergedValues)) {
newMetadataValues.remove(itemMergedValues);
} else {
// not matched. cut it
metadataDao.delete(id);
}
});

@ -66,27 +66,16 @@ public final class TaskerSettingsActivity extends AbstractFragmentPluginAppCompa
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_close_24dp));
toolbar.setOnMenuItemClickListener(this);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (equalBundles(getResultBundle(), previousBundle)) {
cancel();
} else {
dialogBuilder.newMessageDialog(R.string.discard_changes)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
cancel();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
}
toolbar.setNavigationOnClickListener(view -> {
if (equalBundles(getResultBundle(), previousBundle)) {
cancel();
} else {
dialogBuilder.newMessageDialog(R.string.discard_changes)
.setPositiveButton(android.R.string.ok, (dialog, which) -> cancel())
.setNegativeButton(android.R.string.cancel, (dialog, which) -> {
})
.show();
}
});
toolbar.inflateMenu(R.menu.tasker_menu);

@ -48,28 +48,22 @@ public class GeofenceApi {
return;
}
newClient(new GoogleApi.GoogleApiClientConnectionHandler() {
@Override
public void onConnect(final GoogleApiClient client) {
@SuppressWarnings("ResourceType")
@SuppressLint("MissingPermission")
PendingResult<Status> result = LocationServices.GeofencingApi.addGeofences(
client,
getRequests(geofences),
PendingIntent.getService(context, 0, new Intent(context, GeofenceTransitionsIntentService.class), PendingIntent.FLAG_UPDATE_CURRENT));
result.setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
if (status.isSuccess()) {
Timber.i("Registered %s", geofences);
} else {
Timber.e("Failed to register %s", geofences);
}
client.disconnect();
}
});
}
newClient(client -> {
@SuppressWarnings("ResourceType")
@SuppressLint("MissingPermission")
PendingResult<Status> result = LocationServices.GeofencingApi.addGeofences(
client,
getRequests(geofences),
PendingIntent.getService(context, 0, new Intent(context, GeofenceTransitionsIntentService.class), PendingIntent.FLAG_UPDATE_CURRENT));
result.setResultCallback(status -> {
if (status.isSuccess()) {
Timber.i("Registered %s", geofences);
} else {
Timber.e("Failed to register %s", geofences);
}
client.disconnect();
});
});
}
@ -82,31 +76,18 @@ public class GeofenceApi {
return;
}
final List<String> ids = newArrayList(transform(geofences, new Function<Geofence, String>() {
@Override
public String apply(Geofence geofence) {
return Long.toString(geofence.getMetadataId());
}
}));
newClient(new GoogleApi.GoogleApiClientConnectionHandler() {
@Override
public void onConnect(final GoogleApiClient client) {
LocationServices.GeofencingApi.removeGeofences(client, ids)
.setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
if (status.isSuccess()) {
Timber.i("Removed %s", geofences);
} else {
Timber.e("Failed to remove %s", geofences);
}
client.disconnect();
}
});
}
});
final List<String> ids = newArrayList(transform(geofences, geofence -> Long.toString(geofence.getMetadataId())));
newClient(client -> LocationServices.GeofencingApi.removeGeofences(client, ids)
.setResultCallback(status -> {
if (status.isSuccess()) {
Timber.i("Removed %s", geofences);
} else {
Timber.e("Failed to remove %s", geofences);
}
client.disconnect();
}));
}
private void newClient(final GoogleApi.GoogleApiClientConnectionHandler handler) {
@ -114,12 +95,7 @@ public class GeofenceApi {
}
private List<com.google.android.gms.location.Geofence> getRequests(List<Geofence> geofences) {
return newArrayList(transform(geofences, new Function<Geofence, com.google.android.gms.location.Geofence>() {
@Override
public com.google.android.gms.location.Geofence apply(Geofence geofence) {
return toGoogleGeofence(geofence);
}
}));
return newArrayList(transform(geofences, this::toGoogleGeofence));
}
private com.google.android.gms.location.Geofence toGoogleGeofence(Geofence geofence) {

@ -33,12 +33,7 @@ public class GoogleApi implements GoogleApiClient.ConnectionCallbacks {
}
public void connect(final GoogleApiClientConnectionHandler googleApiClientConnectionHandler) {
connect(googleApiClientConnectionHandler, new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Timber.e("onConnectionFailed(%s)", connectionResult);
}
});
connect(googleApiClientConnectionHandler, connectionResult -> Timber.e("onConnectionFailed(%s)", connectionResult));
}
private void connect(final GoogleApiClientConnectionHandler googleApiClientConnectionHandler, GoogleApiClient.OnConnectionFailedListener onConnectionFailedListener) {

@ -54,12 +54,7 @@ public class DatabaseDao<TYPE extends AbstractModel> {
public List<TYPE> toList(Query query) {
final List<TYPE> result = new ArrayList<>();
query(new Callback<TYPE>() {
@Override
public void apply(TYPE entry) {
result.add(entry);
}
}, query);
query(result::add, query);
return result;
}

@ -47,13 +47,10 @@ public class AndroidUtilities {
public static void suppressVirtualKeyboard(final TextView editor) {
final int inputType = editor.getInputType();
editor.setInputType(InputType.TYPE_NULL);
editor.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
editor.setInputType(inputType);
editor.setOnTouchListener(null);
return false;
}
editor.setOnTouchListener((v, event) -> {
editor.setInputType(inputType);
editor.setOnTouchListener(null);
return false;
});
}
@ -178,26 +175,23 @@ public class AndroidUtilities {
}
ContentValues result = new ContentValues();
fromSerialized(string, result, new SerializedPut<ContentValues>() {
@Override
public void put(ContentValues object, String key, char type, String value) throws NumberFormatException {
switch(type) {
case 'i':
object.put(key, Integer.parseInt(value));
break;
case 'd':
object.put(key, Double.parseDouble(value));
break;
case 'l':
object.put(key, Long.parseLong(value));
break;
case 's':
object.put(key, value.replace(SEPARATOR_ESCAPE, SERIALIZATION_SEPARATOR));
break;
case 'b':
object.put(key, Boolean.parseBoolean(value));
break;
}
fromSerialized(string, result, (object, key, type, value) -> {
switch(type) {
case 'i':
object.put(key, Integer.parseInt(value));
break;
case 'd':
object.put(key, Double.parseDouble(value));
break;
case 'l':
object.put(key, Long.parseLong(value));
break;
case 's':
object.put(key, value.replace(SEPARATOR_ESCAPE, SERIALIZATION_SEPARATOR));
break;
case 'b':
object.put(key, Boolean.parseBoolean(value));
break;
}
});
return result;
@ -212,26 +206,23 @@ public class AndroidUtilities {
}
Bundle result = new Bundle();
fromSerialized(string, result, new SerializedPut<Bundle>() {
@Override
public void put(Bundle object, String key, char type, String value) throws NumberFormatException {
switch(type) {
case 'i':
object.putInt(key, Integer.parseInt(value));
break;
case 'd':
object.putDouble(key, Double.parseDouble(value));
break;
case 'l':
object.putLong(key, Long.parseLong(value));
break;
case 's':
object.putString(key, value.replace(SEPARATOR_ESCAPE, SERIALIZATION_SEPARATOR));
break;
case 'b':
object.putBoolean(key, Boolean.parseBoolean(value));
break;
}
fromSerialized(string, result, (object, key, type, value) -> {
switch(type) {
case 'i':
object.putInt(key, Integer.parseInt(value));
break;
case 'd':
object.putDouble(key, Double.parseDouble(value));
break;
case 'l':
object.putLong(key, Long.parseLong(value));
break;
case 's':
object.putString(key, value.replace(SEPARATOR_ESCAPE, SERIALIZATION_SEPARATOR));
break;
case 'b':
object.putBoolean(key, Boolean.parseBoolean(value));
break;
}
});
return result;
@ -328,12 +319,7 @@ public class AndroidUtilities {
* Sort files by date so the newest file is on top
*/
public static void sortFilesByDateDesc(File[] files) {
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
return Long.valueOf(o2.lastModified()).compareTo(o1.lastModified());
}
});
Arrays.sort(files, (o1, o2) -> Long.valueOf(o2.lastModified()).compareTo(o1.lastModified()));
}
/**

@ -21,14 +21,11 @@ public class DialogUtilities {
if(dialog == null) {
return;
}
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
dialog.dismiss();
} catch(Exception e) {
Timber.e(e, e.getMessage());
}
activity.runOnUiThread(() -> {
try {
dialog.dismiss();
} catch(Exception e) {
Timber.e(e, e.getMessage());
}
});
}

@ -61,14 +61,11 @@ public class FilterSettingsActivity extends ThemedInjectingAppCompatActivity imp
toolbar.setNavigationIcon(getResources().getDrawable(
backButtonSavesTask ? R.drawable.ic_close_24dp : R.drawable.ic_save_24dp));
toolbar.setTitle(filter.listingTitle);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (backButtonSavesTask) {
discard();
} else {
save();
}
toolbar.setNavigationOnClickListener(v -> {
if (backButtonSavesTask) {
discard();
} else {
save();
}
});
toolbar.inflateMenu(R.menu.tag_settings_activity);
@ -120,13 +117,10 @@ public class FilterSettingsActivity extends ThemedInjectingAppCompatActivity imp
private void deleteTag() {
dialogBuilder.newMessageDialog(R.string.delete_tag_confirmation, filter.listingTitle)
.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
storeObjectDao.delete(filter.getId());
setResult(RESULT_OK, new Intent(AstridApiConstants.BROADCAST_EVENT_FILTER_DELETED).putExtra(TOKEN_FILTER, filter));
finish();
}
.setPositiveButton(R.string.delete, (dialog, which) -> {
storeObjectDao.delete(filter.getId());
setResult(RESULT_OK, new Intent(AstridApiConstants.BROADCAST_EVENT_FILTER_DELETED).putExtra(TOKEN_FILTER, filter));
finish();
})
.setNegativeButton(android.R.string.cancel, null)
.show();
@ -138,12 +132,7 @@ public class FilterSettingsActivity extends ThemedInjectingAppCompatActivity imp
finish();
} else {
dialogBuilder.newMessageDialog(R.string.discard_changes)
.setPositiveButton(R.string.discard, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setPositiveButton(R.string.discard, (dialog, which) -> finish())
.setNegativeButton(android.R.string.cancel, null)
.show();
}

@ -100,14 +100,11 @@ public class TagSettingsActivity extends ThemedInjectingAppCompatActivity implem
toolbar.setTitle(isNewTag ? getString(R.string.new_tag) : tagData.getName());
toolbar.setNavigationIcon(getResources().getDrawable(
backButtonSavesTask ? R.drawable.ic_close_24dp : R.drawable.ic_save_24dp));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (backButtonSavesTask) {
discard();
} else {
save();
}
toolbar.setNavigationOnClickListener(v -> {
if (backButtonSavesTask) {
discard();
} else {
save();
}
});
toolbar.inflateMenu(R.menu.tag_settings_activity);
@ -237,17 +234,14 @@ public class TagSettingsActivity extends ThemedInjectingAppCompatActivity implem
private void deleteTag() {
dialogBuilder.newMessageDialog(R.string.delete_tag_confirmation, tagData.getName())
.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (tagData != null) {
String uuid = tagData.getUuid();
metadataDao.deleteWhere(Criterion.and(MetadataDao.MetadataCriteria.withKey(TaskToTagMetadata.KEY), TaskToTagMetadata.TAG_UUID.eq(uuid)));
tagDataDao.delete(tagData.getId());
setResult(RESULT_OK, new Intent(AstridApiConstants.BROADCAST_EVENT_TAG_DELETED).putExtra(EXTRA_TAG_UUID, uuid));
}
finish();
.setPositiveButton(R.string.delete, (dialog, which) -> {
if (tagData != null) {
String uuid = tagData.getUuid();
metadataDao.deleteWhere(Criterion.and(MetadataDao.MetadataCriteria.withKey(TaskToTagMetadata.KEY), TaskToTagMetadata.TAG_UUID.eq(uuid)));
tagDataDao.delete(tagData.getId());
setResult(RESULT_OK, new Intent(AstridApiConstants.BROADCAST_EVENT_TAG_DELETED).putExtra(EXTRA_TAG_UUID, uuid));
}
finish();
})
.setNegativeButton(android.R.string.cancel, null)
.show();
@ -258,12 +252,7 @@ public class TagSettingsActivity extends ThemedInjectingAppCompatActivity implem
finish();
} else {
dialogBuilder.newMessageDialog(R.string.discard_changes)
.setPositiveButton(R.string.discard, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setPositiveButton(R.string.discard, (dialog, which) -> finish())
.setNegativeButton(android.R.string.cancel, null)
.show();
}

@ -65,12 +65,7 @@ public class BeastModePreferences extends ThemedInjectingAppCompatActivity imple
ButterKnife.bind(this);
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_back_24dp));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
toolbar.setNavigationOnClickListener(v -> finish());
toolbar.inflateMenu(R.menu.beast_mode);
toolbar.setOnMenuItemClickListener(this);
MenuColorizer.colorToolbar(this, toolbar);
@ -90,19 +85,11 @@ public class BeastModePreferences extends ThemedInjectingAppCompatActivity imple
}
};
touchList.setAdapter(adapter);
touchList.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
});
touchList.setDropListener(new DropListener() {
@Override
public void drop(int from, int to) {
String s = items.remove(from);
items.add(to, s);
adapter.notifyDataSetChanged();
}
touchList.setOnTouchListener((v, event) -> false);
touchList.setDropListener((from, to) -> {
String s = items.remove(from);
items.add(to, s);
adapter.notifyDataSetChanged();
});
}

@ -127,14 +127,11 @@ public final class TaskEditFragment extends InjectingFragment implements Toolbar
final boolean backButtonSavesTask = preferences.backButtonSavesTask();
toolbar.setNavigationIcon(getResources().getDrawable(
backButtonSavesTask ? R.drawable.ic_close_24dp : R.drawable.ic_save_24dp));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (backButtonSavesTask) {
discardButtonClick();
} else {
save();
}
toolbar.setNavigationOnClickListener(v -> {
if (backButtonSavesTask) {
discardButtonClick();
} else {
save();
}
});
toolbar.inflateMenu(R.menu.task_edit_fragment);
@ -274,12 +271,7 @@ public final class TaskEditFragment extends InjectingFragment implements Toolbar
if (hasChanges(taskEditControlSetFragmentManager.getFragmentsInPersistOrder(getChildFragmentManager()))) {
dialogBuilder.newMessageDialog(R.string.discard_confirmation)
.setPositiveButton(R.string.keep_editing, null)
.setNegativeButton(R.string.discard, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
discard();
}
})
.setNegativeButton(R.string.discard, (dialog, which) -> discard())
.show();
} else {
discard();
@ -297,13 +289,10 @@ public final class TaskEditFragment extends InjectingFragment implements Toolbar
protected void deleteButtonClick() {
dialogBuilder.newMessageDialog(R.string.DLG_delete_this_task_question)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
TimerPlugin.stopTimer(notificationManager, taskService, getActivity(), model);
taskDeleter.delete(model);
callback.taskEditFinished();
}
.setPositiveButton(android.R.string.ok, (dialog, which) -> {
TimerPlugin.stopTimer(notificationManager, taskService, getActivity(), model);
taskDeleter.delete(model);
callback.taskEditFinished();
})
.setNegativeButton(android.R.string.cancel, null)
.show();

@ -225,14 +225,9 @@ public class TaskListActivity extends InjectingAppCompatActivity implements
if (syncAdapterHelper.shouldShowBackgroundSyncWarning() && !preferences.getBoolean(R.string.p_sync_warning_shown, false)) {
if (taskListFragment != null) {
taskListFragment.makeSnackbar(R.string.master_sync_warning)
.setAction(R.string.TLA_menu_settings, new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(Settings.ACTION_SYNC_SETTINGS) {{
setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}});
}
})
.setAction(R.string.TLA_menu_settings, view -> startActivity(new Intent(Settings.ACTION_SYNC_SETTINGS) {{
setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}}))
.setCallback(new Snackbar.Callback() {
@Override
public void onShown(Snackbar snackbar) {

@ -175,12 +175,9 @@ public class TaskListFragment extends InjectingListFragment implements
public void setSyncOngoing(final boolean ongoing) {
Activity activity = getActivity();
if (activity != null) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
swipeRefreshLayout.setRefreshing(ongoing);
emptyView.setRefreshing(ongoing);
}
activity.runOnUiThread(() -> {
swipeRefreshLayout.setRefreshing(ongoing);
emptyView.setRefreshing(ongoing);
});
}
}
@ -252,12 +249,7 @@ public class TaskListFragment extends InjectingListFragment implements
toolbar.setTitle(filter.listingTitle);
toolbar.setNavigationIcon(R.drawable.ic_menu_24dp);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
callbacks.onNavigationIconClicked();
}
});
toolbar.setNavigationOnClickListener(v -> callbacks.onNavigationIconClicked());
inflateMenu(toolbar);
setupMenu(toolbar.getMenu());
toolbar.setOnMenuItemClickListener(this);
@ -390,39 +382,36 @@ public class TaskListFragment extends InjectingListFragment implements
registerForContextMenu(listView);
// set listener for quick-changing task priority
listView.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View view, int keyCode, KeyEvent event) {
if (event.getAction() != KeyEvent.ACTION_UP || view == null) {
return false;
}
boolean filterOn = listView.isTextFilterEnabled();
View selected = listView.getSelectedView();
// hot-key to set task priority - 1-4 or ALT + Q-R
if (!filterOn && event.getUnicodeChar() >= '1'
&& event.getUnicodeChar() <= '4' && selected != null) {
int importance = event.getNumber() - '1';
Task task = ((ViewHolder) selected.getTag()).task;
task.setImportance(importance);
taskService.save(task);
taskAdapter.setFieldContentsAndVisibility(selected);
}
// filter
else if (!filterOn && event.getUnicodeChar() != 0) {
listView.setTextFilterEnabled(true);
listView.setFilterText(
Character.toString((char) event.getUnicodeChar()));
}
// turn off filter if nothing is selected
else if (filterOn
&& TextUtils.isEmpty(listView.getTextFilter())) {
listView.setTextFilterEnabled(false);
}
listView.setOnKeyListener((view, keyCode, event) -> {
if (event.getAction() != KeyEvent.ACTION_UP || view == null) {
return false;
}
boolean filterOn = listView.isTextFilterEnabled();
View selected = listView.getSelectedView();
// hot-key to set task priority - 1-4 or ALT + Q-R
if (!filterOn && event.getUnicodeChar() >= '1'
&& event.getUnicodeChar() <= '4' && selected != null) {
int importance = event.getNumber() - '1';
Task task = ((ViewHolder) selected.getTag()).task;
task.setImportance(importance);
taskService.save(task);
taskAdapter.setFieldContentsAndVisibility(selected);
}
// filter
else if (!filterOn && event.getUnicodeChar() != 0) {
listView.setTextFilterEnabled(true);
listView.setFilterText(
Character.toString((char) event.getUnicodeChar()));
}
// turn off filter if nothing is selected
else if (filterOn
&& TextUtils.isEmpty(listView.getTextFilter())) {
listView.setTextFilterEnabled(false);
}
return false;
});
filter.setFilterQueryOverride(null);
@ -440,19 +429,15 @@ public class TaskListFragment extends InjectingListFragment implements
return;
}
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (taskAdapter != null) {
TodorooCursor<Task> cursor = (TodorooCursor<Task>) taskAdapter.getItem(position);
Task task = new Task(cursor);
if (task.isDeleted()) {
return;
}
onTaskListItemClicked(id);
listView.setOnItemClickListener((parent, view, position, id) -> {
if (taskAdapter != null) {
TodorooCursor<Task> cursor = (TodorooCursor<Task>) taskAdapter.getItem(position);
Task task = new Task(cursor);
if (task.isDeleted()) {
return;
}
onTaskListItemClicked(id);
}
});
}
@ -541,10 +526,7 @@ public class TaskListFragment extends InjectingListFragment implements
protected TaskAdapter createTaskAdapter(TodorooCursor<Task> cursor) {
return new TaskAdapter(context, preferences, taskAttachmentDao, taskService, this, cursor, sqlQueryTemplate,
new OnCompletedTaskListener() {
@Override
public void onCompletedTask(Task item, boolean newState) {
}
(item, newState) -> {
}, dialogBuilder, checkBoxes, tagService, themeCache);
}
@ -657,13 +639,10 @@ public class TaskListFragment extends InjectingListFragment implements
/** Show a dialog box and delete the task specified */
private void deleteTask(final Task task) {
dialogBuilder.newMessageDialog(R.string.delete_tag_confirmation, task.getTitle())
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
onTaskDelete(task);
taskDeleter.delete(task);
loadTaskListContent();
}
.setPositiveButton(android.R.string.ok, (dialog, which) -> {
onTaskDelete(task);
taskDeleter.delete(task);
loadTaskListContent();
})
.setNegativeButton(android.R.string.cancel, null)
.show();
@ -695,15 +674,12 @@ public class TaskListFragment extends InjectingListFragment implements
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
Callback<String> quickAddTask = new Callback<String>() {
@Override
public void apply(String title) {
Task task = addTask(title);
taskCreator.addToCalendar(task);
onTaskListItemClicked(task.getId());
loadTaskListContent();
onTaskCreated(task.getId(), task.getUUID());
}
Callback<String> quickAddTask = title -> {
Task task = addTask(title);
taskCreator.addToCalendar(task);
onTaskListItemClicked(task.getId());
loadTaskListContent();
onTaskCreated(task.getId(), task.getUUID());
};
voiceInputAssistant.handleActivityResult(data, quickAddTask);
}

@ -95,21 +95,11 @@ public class FilterAdapter extends ArrayAdapter<FilterListItem> {
@Override
public void notifyDataSetChanged() {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
FilterAdapter.super.notifyDataSetChanged();
}
});
activity.runOnUiThread(FilterAdapter.super::notifyDataSetChanged);
}
public void refreshFilterCount() {
filterCounter.refreshFilterCounts(new Runnable() {
@Override
public void run() {
notifyDataSetChanged();
}
});
filterCounter.refreshFilterCounts(this::notifyDataSetChanged);
}
/**
@ -286,12 +276,7 @@ public class FilterAdapter extends ArrayAdapter<FilterListItem> {
notifyDataSetChanged();
filterCounter.refreshFilterCounts(new Runnable() {
@Override
public void run() {
notifyDataSetChanged();
}
});
filterCounter.refreshFilterCounts(this::notifyDataSetChanged);
}
/**

@ -369,32 +369,26 @@ public class TaskAdapter extends CursorAdapter implements Filterable {
final ViewHolder viewHolder = (ViewHolder)container.getTag();
// check box listener
OnTouchListener otl = new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
lastTouchYRawY = new Pair<>(event.getY(), event.getRawY());
return false;
}
OnTouchListener otl = (v, event) -> {
lastTouchYRawY = new Pair<>(event.getY(), event.getRawY());
return false;
};
viewHolder.completeBox.setOnTouchListener(otl);
viewHolder.completeBox.setOnClickListener(completeBoxListener);
if (viewHolder.taskActionContainer != null) {
viewHolder.taskActionContainer.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
TaskAction action = (TaskAction) viewHolder.taskActionIcon.getTag();
if (action instanceof NotesAction) {
showEditNotesDialog(viewHolder.task);
} else if (action instanceof FilesAction) {
showFilesDialog(viewHolder.task);
} else if (action != null) {
try {
action.intent.send();
} catch (CanceledException e) {
// Oh well
Timber.e(e, e.getMessage());
}
viewHolder.taskActionContainer.setOnClickListener(v -> {
TaskAction action = (TaskAction) viewHolder.taskActionIcon.getTag();
if (action instanceof NotesAction) {
showEditNotesDialog(viewHolder.task);
} else if (action instanceof FilesAction) {
showFilesDialog(viewHolder.task);
} else if (action != null) {
try {
action.intent.send();
} catch (CanceledException e) {
// Oh well
Timber.e(e, e.getMessage());
}
}
});
@ -443,25 +437,22 @@ public class TaskAdapter extends CursorAdapter implements Filterable {
}
}
protected final View.OnClickListener completeBoxListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
int[] location = new int[2];
v.getLocationOnScreen(location);
ViewHolder viewHolder = getTagFromCheckBox(v);
if(Math.abs(location[1] + lastTouchYRawY.getLeft() - lastTouchYRawY.getRight()) > 10) {
viewHolder.completeBox.setChecked(!viewHolder.completeBox.isChecked());
return;
}
protected final View.OnClickListener completeBoxListener = v -> {
int[] location = new int[2];
v.getLocationOnScreen(location);
ViewHolder viewHolder = getTagFromCheckBox(v);
if(Math.abs(location[1] + lastTouchYRawY.getLeft() - lastTouchYRawY.getRight()) > 10) {
viewHolder.completeBox.setChecked(!viewHolder.completeBox.isChecked());
return;
}
Task task = viewHolder.task;
Task task = viewHolder.task;
completeTask(task, viewHolder.completeBox.isChecked());
completeTask(task, viewHolder.completeBox.isChecked());
// set check box to actual action item state
setTaskAppearance(viewHolder, task);
}
// set check box to actual action item state
setTaskAppearance(viewHolder, task);
};
private ViewHolder getTagFromCheckBox(View v) {
@ -512,12 +503,7 @@ public class TaskAdapter extends CursorAdapter implements Filterable {
checkBoxView.invalidate();
}
private final Function<String, TagData> uuidToTag = new Function<String, TagData>() {
@Override
public TagData apply(String input) {
return tagMap.get(input);
}
};
private final Function<String, TagData> uuidToTag = tagMap::get;
private final Ordering<TagData> orderByName = new Ordering<TagData>() {
@Override
@ -542,18 +528,15 @@ public class TaskAdapter extends CursorAdapter implements Filterable {
};
private Function<TagData, SpannableString> tagToString(final float maxLength) {
return new Function<TagData, SpannableString>() {
@Override
public SpannableString apply(TagData tagData) {
String tagName = tagData.getName();
tagName = tagName.substring(0, Math.min(tagName.length(), (int) maxLength));
SpannableString string = new SpannableString(SPACE + tagName + SPACE);
int themeIndex = tagData.getColor();
ThemeColor color = themeIndex >= 0 ? themeCache.getThemeColor(themeIndex) : themeCache.getUntaggedColor();
string.setSpan(new BackgroundColorSpan(color.getPrimaryColor()), 0, string.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
string.setSpan(new ForegroundColorSpan(color.getActionBarTint()), 0, string.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
return string;
}
return tagData -> {
String tagName = tagData.getName();
tagName = tagName.substring(0, Math.min(tagName.length(), (int) maxLength));
SpannableString string = new SpannableString(SPACE + tagName + SPACE);
int themeIndex = tagData.getColor();
ThemeColor color = themeIndex >= 0 ? themeCache.getThemeColor(themeIndex) : themeCache.getUntaggedColor();
string.setSpan(new BackgroundColorSpan(color.getPrimaryColor()), 0, string.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
string.setSpan(new ForegroundColorSpan(color.getActionBarTint()), 0, string.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
return string;
};
}
@ -648,12 +631,9 @@ public class TaskAdapter extends CursorAdapter implements Filterable {
this.onCompletedTaskListener = newListener;
} else {
final OnCompletedTaskListener old = this.onCompletedTaskListener;
this.onCompletedTaskListener = new OnCompletedTaskListener() {
@Override
public void onCompletedTask(Task item, boolean newState) {
old.onCompletedTask(item, newState);
newListener.onCompletedTask(item, newState);
}
this.onCompletedTaskListener = (item, newState) -> {
old.onCompletedTask(item, newState);
newListener.onCompletedTask(item, newState);
};
}
}

@ -79,13 +79,10 @@ public class AlarmService {
metadata.add(item);
}
boolean changed = synchronizeMetadata(taskId, metadata, new SynchronizeMetadataCallback() {
@Override
public void beforeDeleteMetadata(Metadata m) {
// Cancel the alarm before the metadata is deleted
PendingIntent pendingIntent = pendingIntentForAlarm(m, taskId);
alarmManager.cancel(pendingIntent);
}
boolean changed = synchronizeMetadata(taskId, metadata, m -> {
// Cancel the alarm before the metadata is deleted
PendingIntent pendingIntent = pendingIntentForAlarm(m, taskId);
alarmManager.cancel(pendingIntent);
});
if(changed) {
@ -113,24 +110,14 @@ public class AlarmService {
* Schedules all alarms
*/
public void scheduleAllAlarms() {
getActiveAlarms(new Callback<Metadata>() {
@Override
public void apply(Metadata alarm) {
scheduleAlarm(alarm);
}
});
getActiveAlarms(this::scheduleAlarm);
}
/**
* Schedules alarms for a single task
*/
private void scheduleAlarms(long taskId) {
getActiveAlarmsForTask(taskId, new Callback<Metadata>() {
@Override
public void apply(Metadata alarm) {
scheduleAlarm(alarm);
}
});
getActiveAlarmsForTask(taskId, this::scheduleAlarm);
}
private PendingIntent pendingIntentForAlarm(Metadata alarm, long taskId) {
@ -181,27 +168,24 @@ public class AlarmService {
newMetadataValues.add(values);
}
metadataDao.byTaskAndKey(taskId, AlarmFields.METADATA_KEY, new Callback<Metadata>() {
@Override
public void apply(Metadata item) {
long id = item.getId();
// clear item id when matching with incoming values
item.clearValue(Metadata.ID);
item.clearValue(Metadata.CREATION_DATE);
ContentValues itemMergedValues = item.getMergedValues();
if(newMetadataValues.contains(itemMergedValues)) {
newMetadataValues.remove(itemMergedValues);
} else {
// not matched. cut it
item.setId(id);
if (callback != null) {
callback.beforeDeleteMetadata(item);
}
metadataDao.delete(id);
dirty[0] = true;
metadataDao.byTaskAndKey(taskId, AlarmFields.METADATA_KEY, item -> {
long id = item.getId();
// clear item id when matching with incoming values
item.clearValue(Metadata.ID);
item.clearValue(Metadata.CREATION_DATE);
ContentValues itemMergedValues = item.getMergedValues();
if(newMetadataValues.contains(itemMergedValues)) {
newMetadataValues.remove(itemMergedValues);
} else {
// not matched. cut it
item.setId(id);
if (callback != null) {
callback.beforeDeleteMetadata(item);
}
metadataDao.delete(id);
dirty[0] = true;
}
});

@ -43,12 +43,7 @@ public class AlarmTaskRepeatListener extends InjectingBroadcastReceiver {
}
final Set<Long> alarms = new LinkedHashSet<>();
alarmService.getAlarms(taskId, new Callback<Metadata>() {
@Override
public void apply(Metadata metadata) {
alarms.add(metadata.getValue(AlarmFields.TIME) + (newDueDate - oldDueDate));
}
});
alarmService.getAlarms(taskId, metadata -> alarms.add(metadata.getValue(AlarmFields.TIME) + (newDueDate - oldDueDate)));
if (!alarms.isEmpty()) {
alarmService.synchronizeAlarms(taskId, alarms);
}

@ -79,12 +79,9 @@ public class TasksXmlExporter {
}
private void setProgress(final int taskNumber, final int total) {
post(new Runnable() {
@Override
public void run() {
progressDialog.setMax(total);
progressDialog.setProgress(taskNumber);
}
post(() -> {
progressDialog.setMax(total);
progressDialog.setProgress(taskNumber);
});
}
@ -109,35 +106,29 @@ public class TasksXmlExporter {
this.progressDialog = new ProgressDialog(context);
}
new Thread(new Runnable() {
@Override
public void run() {
try {
String output = setupFile(backupDirectory,
exportType);
int tasks = taskService.countTasks();
new Thread(() -> {
try {
String output = setupFile(backupDirectory,
exportType);
int tasks = taskService.countTasks();
if(tasks > 0) {
doTasksExport(output);
}
if(tasks > 0) {
doTasksExport(output);
}
preferences.setLong(PREF_BACKUP_LAST_DATE, DateUtilities.now());
preferences.setLong(PREF_BACKUP_LAST_DATE, DateUtilities.now());
if (exportType == ExportType.EXPORT_TYPE_MANUAL) {
onFinishExport(output);
}
} catch (IOException e) {
Timber.e(e, e.getMessage());
} finally {
post(new Runnable() {
@Override
public void run() {
if(progressDialog.isShowing() && context instanceof Activity) {
DialogUtilities.dismissDialog((Activity) context, progressDialog);
}
}
});
if (exportType == ExportType.EXPORT_TYPE_MANUAL) {
onFinishExport(output);
}
} catch (IOException e) {
Timber.e(e, e.getMessage());
} finally {
post(() -> {
if(progressDialog.isShowing() && context instanceof Activity) {
DialogUtilities.dismissDialog((Activity) context, progressDialog);
}
});
}
}).start();
}
@ -169,16 +160,13 @@ public class TasksXmlExporter {
}
private void serializeTagDatas() {
tagDataDao.allTags(new Callback<TagData>() {
@Override
public void apply(TagData tag) {
try {
xml.startTag(null, BackupConstants.TAGDATA_TAG);
serializeModel(tag, TagData.PROPERTIES, TagData.ID);
xml.endTag(null, BackupConstants.TAGDATA_TAG);
} catch(IOException e) {
throw new RuntimeException(e);
}
tagDataDao.allTags(tag -> {
try {
xml.startTag(null, BackupConstants.TAGDATA_TAG);
serializeModel(tag, TagData.PROPERTIES, TagData.ID);
xml.endTag(null, BackupConstants.TAGDATA_TAG);
} catch(IOException e) {
throw new RuntimeException(e);
}
});
}
@ -207,16 +195,13 @@ public class TasksXmlExporter {
}
private synchronized void serializeMetadata(Task task) {
metadataDao.byTask(task.getId(), new Callback<Metadata>() {
@Override
public void apply(Metadata metadata) {
try {
xml.startTag(null, BackupConstants.METADATA_TAG);
serializeModel(metadata, Metadata.PROPERTIES, Metadata.ID, Metadata.TASK);
xml.endTag(null, BackupConstants.METADATA_TAG);
} catch (IOException e) {
throw new RuntimeException(e);
}
metadataDao.byTask(task.getId(), metadata -> {
try {
xml.startTag(null, BackupConstants.METADATA_TAG);
serializeModel(metadata, Metadata.PROPERTIES, Metadata.ID, Metadata.TASK);
xml.endTag(null, BackupConstants.METADATA_TAG);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
@ -308,17 +293,14 @@ public class TasksXmlExporter {
}
private void onFinishExport(final String outputFile) {
post(new Runnable() {
@Override
public void run() {
if(exportCount == 0) {
Toast.makeText(context, context.getString(R.string.export_toast_no_tasks), Toast.LENGTH_LONG).show();
} else {
CharSequence text = String.format(context.getString(R.string.export_toast),
context.getResources().getQuantityString(R.plurals.Ntasks, exportCount,
exportCount), outputFile);
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}
post(() -> {
if(exportCount == 0) {
Toast.makeText(context, context.getString(R.string.export_toast_no_tasks), Toast.LENGTH_LONG).show();
} else {
CharSequence text = String.format(context.getString(R.string.export_toast),
context.getResources().getQuantityString(R.plurals.Ntasks, exportCount,
exportCount), outputFile);
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}
});
}

@ -59,12 +59,7 @@ public class TasksXmlImporter {
private String input;
private void setProgressMessage(final String message) {
handler.post(new Runnable() {
@Override
public void run() {
progressDialog.setMessage(message);
}
});
handler.post(() -> progressDialog.setMessage(message));
}
@Inject
@ -83,14 +78,11 @@ public class TasksXmlImporter {
handler = new Handler();
new Thread(new Runnable() {
@Override
public void run() {
try {
performImport();
} catch (IOException | XmlPullParserException e) {
Timber.e(e, e.getMessage());
}
new Thread(() -> {
try {
performImport();
} catch (IOException | XmlPullParserException e) {
Timber.e(e, e.getMessage());
}
}).start();
}
@ -126,13 +118,10 @@ public class TasksXmlImporter {
} finally {
Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_EVENT_REFRESH);
activity.sendBroadcast(broadcastIntent, AstridApiConstants.PERMISSION_READ);
handler.post(new Runnable() {
@Override
public void run() {
if(progressDialog.isShowing()) {
DialogUtilities.dismissDialog(activity, progressDialog);
showSummary();
}
handler.post(() -> {
if(progressDialog.isShowing()) {
DialogUtilities.dismissDialog(activity, progressDialog);
showSummary();
}
});
}
@ -148,12 +137,7 @@ public class TasksXmlImporter {
r.getQuantityString(R.plurals.Ntasks, importCount, importCount),
r.getQuantityString(R.plurals.Ntasks, skipCount, skipCount),
r.getQuantityString(R.plurals.Ntasks, errorCount, errorCount)))
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
})
.setPositiveButton(android.R.string.ok, (dialog, id) -> dialog.dismiss())
.show();
}

@ -151,12 +151,7 @@ public class CustomFilterActivity extends ThemedInjectingAppCompatActivity imple
toolbar.setTitle(R.string.FLA_new_filter);
toolbar.inflateMenu(R.menu.menu_custom_filter_activity);
toolbar.setOnMenuItemClickListener(this);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
discard();
}
});
toolbar.setNavigationOnClickListener(view -> discard());
MenuColorizer.colorToolbar(this, toolbar);
listView = (ListView) findViewById(android.R.id.list);
@ -186,30 +181,21 @@ public class CustomFilterActivity extends ThemedInjectingAppCompatActivity imple
}
private void setUpListeners() {
findViewById(R.id.add).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listView.showContextMenu();
findViewById(R.id.add).setOnClickListener(v -> listView.showContextMenu());
listView.setOnCreateContextMenuListener((menu, v, menuInfo) -> {
if(menu.hasVisibleItems()) {
/* If it has items already, then the user did not click on the "Add Criteria" button, but instead
long held on a row in the list view, which caused CustomFilterAdapter.onCreateContextMenu
to be invoked before this onCreateContextMenu method was invoked.
*/
return;
}
});
listView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if(menu.hasVisibleItems()) {
/* If it has items already, then the user did not click on the "Add Criteria" button, but instead
long held on a row in the list view, which caused CustomFilterAdapter.onCreateContextMenu
to be invoked before this onCreateContextMenu method was invoked.
*/
return;
}
int i = 0;
for (CustomFilterCriterion item : filterCriteriaProvider.getAll()) {
menu.add(CustomFilterActivity.MENU_GROUP_FILTER, i, 0, item.name);
i++;
}
int i = 0;
for (CustomFilterCriterion item : filterCriteriaProvider.getAll()) {
menu.add(CustomFilterActivity.MENU_GROUP_FILTER, i, 0, item.name);
i++;
}
});
}
@ -367,12 +353,7 @@ public class CustomFilterActivity extends ThemedInjectingAppCompatActivity imple
finish();
} else {
dialogBuilder.newMessageDialog(R.string.discard_changes)
.setPositiveButton(R.string.discard, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setPositiveButton(R.string.discard, (dialog, which) -> finish())
.setNegativeButton(android.R.string.cancel, null)
.show();
}
@ -385,12 +366,9 @@ public class CustomFilterActivity extends ThemedInjectingAppCompatActivity imple
CustomFilterCriterion criterion = filterCriteriaProvider.getAll().get(item.getItemId());
final CriterionInstance instance = new CriterionInstance();
instance.criterion = criterion;
adapter.showOptionsFor(instance, new Runnable() {
@Override
public void run() {
adapter.add(instance);
updateList();
}
adapter.showOptionsFor(instance, () -> {
adapter.add(instance);
updateList();
});
return true;
}

@ -60,12 +60,9 @@ public class CustomFilterAdapter extends ArrayAdapter<CriterionInstance> {
return;
}
showOptionsFor(viewHolder.item, new Runnable() {
@Override
public void run() {
activity.updateList();
notifyDataSetInvalidated();
}
showOptionsFor(viewHolder.item, () -> {
activity.updateList();
notifyDataSetInvalidated();
});
}
};
@ -110,13 +107,10 @@ public class CustomFilterAdapter extends ArrayAdapter<CriterionInstance> {
if(item.criterion instanceof MultipleSelectCriterion) {
MultipleSelectCriterion multiSelectCriterion = (MultipleSelectCriterion) item.criterion;
final String[] titles = multiSelectCriterion.entryTitles;
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface click, int which) {
item.selectedIndex = which;
if(onComplete != null) {
onComplete.run();
}
DialogInterface.OnClickListener listener = (click, which) -> {
item.selectedIndex = which;
if(onComplete != null) {
onComplete.run();
}
};
dialog.setItems(titles, listener);
@ -131,13 +125,10 @@ public class CustomFilterAdapter extends ArrayAdapter<CriterionInstance> {
FrameLayout.LayoutParams.FILL_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT));
dialog.setView(frameLayout).
setPositiveButton(android.R.string.ok, new OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int which) {
item.selectedText = editText.getText().toString();
if(onComplete != null) {
onComplete.run();
}
setPositiveButton(android.R.string.ok, (dialogInterface, which) -> {
item.selectedText = editText.getText().toString();
if(onComplete != null) {
onComplete.run();
}
});
}

@ -36,12 +36,7 @@ public final class CustomFilterExposer {
}
public List<Filter> getFilters() {
return newArrayList(transform(storeObjectDao.getSavedFilters(), new Function<StoreObject, Filter>() {
@Override
public Filter apply(StoreObject input) {
return load(input);
}
}));
return newArrayList(transform(storeObjectDao.getSavedFilters(), this::load));
}
public Filter getFilter(long id) {

@ -46,14 +46,11 @@ public class DefaultsPreferences extends InjectingPreferenceActivity {
addPreferencesFromResource(R.xml.preferences_defaults);
defaultCalendarPref = findPreference(getString(R.string.gcal_p_default));
defaultCalendarPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
if (permissionRequester.requestCalendarPermissions()) {
startCalendarSelectionActivity();
}
return false;
defaultCalendarPref.setOnPreferenceClickListener(preference -> {
if (permissionRequester.requestCalendarPermissions()) {
startCalendarSelectionActivity();
}
return false;
});
setCalendarSummary(preferences.getStringValue(R.string.gcal_p_default));
}

@ -5,9 +5,7 @@
*/
package com.todoroo.astrid.core;
import android.content.DialogInterface;
import android.os.Bundle;
import android.preference.Preference;
import com.todoroo.andlib.data.TodorooCursor;
import com.todoroo.andlib.sql.Criterion;
@ -45,222 +43,181 @@ public class OldTaskPreferences extends InjectingPreferenceActivity {
addPreferencesFromResource(R.xml.preferences_oldtasks);
findPreference(getString(R.string.EPr_manage_purge_deleted)).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
purgeDeletedTasks();
return false;
}
findPreference(getString(R.string.EPr_manage_purge_deleted)).setOnPreferenceClickListener(preference -> {
purgeDeletedTasks();
return false;
});
findPreference(getString(R.string.EPr_manage_delete_completed)).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
deleteCompletedTasks();
return false;
}
findPreference(getString(R.string.EPr_manage_delete_completed)).setOnPreferenceClickListener(preference -> {
deleteCompletedTasks();
return false;
});
findPreference(getString(R.string.EPr_manage_delete_completed_gcal)).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
deleteCompletedEvents();
return false;
}
findPreference(getString(R.string.EPr_manage_delete_completed_gcal)).setOnPreferenceClickListener(preference -> {
deleteCompletedEvents();
return false;
});
findPreference(getString(R.string.EPr_manage_delete_all_gcal)).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
deleteAllCalendarEvents();
return false;
}
findPreference(getString(R.string.EPr_manage_delete_all_gcal)).setOnPreferenceClickListener(preference -> {
deleteAllCalendarEvents();
return false;
});
findPreference(getString(R.string.EPr_reset_preferences)).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
resetPreferences();
return false;
}
findPreference(getString(R.string.EPr_reset_preferences)).setOnPreferenceClickListener(preference -> {
resetPreferences();
return false;
});
findPreference(getString(R.string.EPr_delete_task_data)).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
deleteTaskData();
return false;
}
findPreference(getString(R.string.EPr_delete_task_data)).setOnPreferenceClickListener(preference -> {
deleteTaskData();
return false;
});
}
private void deleteCompletedTasks() {
dialogBuilder.newMessageDialog(R.string.EPr_manage_delete_completed_message)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
.setPositiveButton(android.R.string.ok, (dialog, which) -> new ProgressDialogAsyncTask(OldTaskPreferences.this, dialogBuilder) {
@Override
public void onClick(DialogInterface dialog, int which) {
new ProgressDialogAsyncTask(OldTaskPreferences.this, dialogBuilder) {
@Override
protected Integer doInBackground(Void... params) {
TodorooCursor<Task> cursor = taskService.query(Query.select(Task.ID, Task.CALENDAR_URI).where(
Criterion.and(Task.COMPLETION_DATE.gt(0), Task.CALENDAR_URI.isNotNull())));
try {
int length = cursor.getCount();
for (int i = 0; i < length; i++) {
cursor.moveToNext();
Task task = new Task(cursor);
gcalHelper.deleteTaskEvent(task);
}
} finally {
cursor.close();
}
Task template = new Task();
template.setDeletionDate(DateUtilities.now());
return taskService.update(Task.COMPLETION_DATE.gt(0), template);
protected Integer doInBackground(Void... params) {
TodorooCursor<Task> cursor = taskService.query(Query.select(Task.ID, Task.CALENDAR_URI).where(
Criterion.and(Task.COMPLETION_DATE.gt(0), Task.CALENDAR_URI.isNotNull())));
try {
int length = cursor.getCount();
for (int i = 0; i < length; i++) {
cursor.moveToNext();
Task task = new Task(cursor);
gcalHelper.deleteTaskEvent(task);
}
} finally {
cursor.close();
}
Task template = new Task();
template.setDeletionDate(DateUtilities.now());
return taskService.update(Task.COMPLETION_DATE.gt(0), template);
}
@Override
protected int getResultResource() {
return R.string.EPr_manage_delete_completed_status;
}
}.execute();
@Override
protected int getResultResource() {
return R.string.EPr_manage_delete_completed_status;
}
})
}.execute())
.setNegativeButton(android.R.string.cancel, null)
.show();
}
private void purgeDeletedTasks() {
dialogBuilder.newMessageDialog(R.string.EPr_manage_purge_deleted_message)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
.setPositiveButton(android.R.string.ok, (dialog, which) -> new ProgressDialogAsyncTask(OldTaskPreferences.this, dialogBuilder) {
@Override
public void onClick(DialogInterface dialog, int which) {
new ProgressDialogAsyncTask(OldTaskPreferences.this, dialogBuilder) {
@Override
protected Integer doInBackground(Void... params) {
TodorooCursor<Task> cursor = taskService.query(Query.select(Task.ID, Task.TITLE, Task.CALENDAR_URI).where(
Criterion.and(Task.DELETION_DATE.gt(0), Task.CALENDAR_URI.isNotNull())));
try {
int length = cursor.getCount();
for (int i = 0; i < length; i++) {
cursor.moveToNext();
Task task = new Task(cursor);
gcalHelper.deleteTaskEvent(task);
}
} finally {
cursor.close();
}
int result = taskDeleter.purgeDeletedTasks();
metadataDao.removeDanglingMetadata();
return result;
protected Integer doInBackground(Void... params) {
TodorooCursor<Task> cursor = taskService.query(Query.select(Task.ID, Task.TITLE, Task.CALENDAR_URI).where(
Criterion.and(Task.DELETION_DATE.gt(0), Task.CALENDAR_URI.isNotNull())));
try {
int length = cursor.getCount();
for (int i = 0; i < length; i++) {
cursor.moveToNext();
Task task = new Task(cursor);
gcalHelper.deleteTaskEvent(task);
}
} finally {
cursor.close();
}
int result = taskDeleter.purgeDeletedTasks();
metadataDao.removeDanglingMetadata();
return result;
}
@Override
protected int getResultResource() {
return R.string.EPr_manage_purge_deleted_status;
}
}.execute();
@Override
protected int getResultResource() {
return R.string.EPr_manage_purge_deleted_status;
}
})
}.execute())
.setNegativeButton(android.R.string.cancel, null)
.show();
}
private void deleteCompletedEvents() {
dialogBuilder.newMessageDialog(R.string.EPr_manage_delete_completed_gcal_message)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
new ProgressDialogAsyncTask(OldTaskPreferences.this, dialogBuilder) {
.setPositiveButton(android.R.string.ok, (dialog, which) -> new ProgressDialogAsyncTask(OldTaskPreferences.this, dialogBuilder) {
@Override
protected Integer doInBackground(Void... params) {
int deletedEventCount = 0;
TodorooCursor<Task> cursor = taskService.query(Query.select(Task.ID, Task.CALENDAR_URI).where(
Criterion.and(Task.COMPLETION_DATE.gt(0), Task.CALENDAR_URI.isNotNull())));
try {
int length = cursor.getCount();
for (int i = 0; i < length; i++) {
cursor.moveToNext();
Task task = new Task(cursor);
if (gcalHelper.deleteTaskEvent(task)) {
deletedEventCount++;
}
}
} finally {
cursor.close();
@Override
protected Integer doInBackground(Void... params) {
int deletedEventCount = 0;
TodorooCursor<Task> cursor = taskService.query(Query.select(Task.ID, Task.CALENDAR_URI).where(
Criterion.and(Task.COMPLETION_DATE.gt(0), Task.CALENDAR_URI.isNotNull())));
try {
int length = cursor.getCount();
for (int i = 0; i < length; i++) {
cursor.moveToNext();
Task task = new Task(cursor);
if (gcalHelper.deleteTaskEvent(task)) {
deletedEventCount++;
}
// mass update the CALENDAR_URI here,
// since the GCalHelper doesnt save it due to performance-reasons
Task template = new Task();
template.setCalendarUri(""); //$NON-NLS-1$
taskService.update(
Criterion.and(Task.COMPLETION_DATE.gt(0), Task.CALENDAR_URI.isNotNull()),
template);
return deletedEventCount;
}
} finally {
cursor.close();
}
// mass update the CALENDAR_URI here,
// since the GCalHelper doesnt save it due to performance-reasons
Task template = new Task();
template.setCalendarUri(""); //$NON-NLS-1$
taskService.update(
Criterion.and(Task.COMPLETION_DATE.gt(0), Task.CALENDAR_URI.isNotNull()),
template);
return deletedEventCount;
}
@Override
protected int getResultResource() {
return R.string.EPr_manage_delete_completed_gcal_status;
}
}.execute();
@Override
protected int getResultResource() {
return R.string.EPr_manage_delete_completed_gcal_status;
}
})
}.execute())
.setNegativeButton(android.R.string.cancel, null)
.show();
}
private void deleteAllCalendarEvents() {
dialogBuilder.newMessageDialog(R.string.EPr_manage_delete_all_gcal_message)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
.setPositiveButton(android.R.string.ok, (dialog, which) -> new ProgressDialogAsyncTask(OldTaskPreferences.this, dialogBuilder) {
@Override
public void onClick(DialogInterface dialog, int which) {
new ProgressDialogAsyncTask(OldTaskPreferences.this, dialogBuilder) {
@Override
protected Integer doInBackground(Void... params) {
int deletedEventCount = 0;
TodorooCursor<Task> cursor = taskService.query(Query.select(Task.ID, Task.CALENDAR_URI).where(
Task.CALENDAR_URI.isNotNull()));
try {
int length = cursor.getCount();
for (int i = 0; i < length; i++) {
cursor.moveToNext();
Task task = new Task(cursor);
if (gcalHelper.deleteTaskEvent(task)) {
deletedEventCount++;
}
}
} finally {
cursor.close();
protected Integer doInBackground(Void... params) {
int deletedEventCount = 0;
TodorooCursor<Task> cursor = taskService.query(Query.select(Task.ID, Task.CALENDAR_URI).where(
Task.CALENDAR_URI.isNotNull()));
try {
int length = cursor.getCount();
for (int i = 0; i < length; i++) {
cursor.moveToNext();
Task task = new Task(cursor);
if (gcalHelper.deleteTaskEvent(task)) {
deletedEventCount++;
}
// mass update the CALENDAR_URI here,
// since the GCalHelper doesnt save it due to performance-reasons
Task template = new Task();
template.setCalendarUri(""); //$NON-NLS-1$
taskService.update(Task.CALENDAR_URI.isNotNull(), template);
return deletedEventCount;
}
} finally {
cursor.close();
}
// mass update the CALENDAR_URI here,
// since the GCalHelper doesnt save it due to performance-reasons
Task template = new Task();
template.setCalendarUri(""); //$NON-NLS-1$
taskService.update(Task.CALENDAR_URI.isNotNull(), template);
return deletedEventCount;
}
@Override
protected int getResultResource() {
return R.string.EPr_manage_delete_all_gcal_status;
}
}.execute();
@Override
protected int getResultResource() {
return R.string.EPr_manage_delete_all_gcal_status;
}
})
}.execute())
.setNegativeButton(android.R.string.cancel, null)
.show();
}
private void resetPreferences() {
dialogBuilder.newMessageDialog(R.string.EPr_reset_preferences_warning)
.setPositiveButton(R.string.EPr_reset_preferences, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
preferences.reset();
System.exit(0);
}
.setPositiveButton(R.string.EPr_reset_preferences, (dialog, which) -> {
preferences.reset();
System.exit(0);
})
.setNegativeButton(android.R.string.cancel, null)
.show();
@ -268,12 +225,9 @@ public class OldTaskPreferences extends InjectingPreferenceActivity {
private void deleteTaskData() {
dialogBuilder.newMessageDialog(R.string.EPr_delete_task_data_warning)
.setPositiveButton(R.string.EPr_delete_task_data, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
deleteDatabase(database.getName());
System.exit(0);
}
.setPositiveButton(R.string.EPr_delete_task_data, (dialog, which) -> {
deleteDatabase(database.getName());
System.exit(0);
})
.setNegativeButton(android.R.string.cancel, null)
.show();

@ -55,12 +55,7 @@ public class StoreObjectDao {
}
public List<GtasksList> getGtasksLists() {
return newArrayList(transform(getByType(GtasksList.TYPE), new Function<StoreObject, GtasksList>() {
@Override
public GtasksList apply(StoreObject input) {
return new GtasksList(input);
}
}));
return newArrayList(transform(getByType(GtasksList.TYPE), GtasksList::new));
}
public boolean persist(StoreObject storeObject) {

@ -78,12 +78,9 @@ public class FilesControlSet extends TaskEditControlFragment {
}
final List<TaskAttachment> files = new ArrayList<>();
taskAttachmentDao.getAttachments(taskUuid, new Callback<TaskAttachment>() {
@Override
public void apply(TaskAttachment attachment) {
files.add(attachment);
addAttachment(attachment);
}
taskAttachmentDao.getAttachments(taskUuid, attachment -> {
files.add(attachment);
addAttachment(attachment);
});
validateFiles(files);
return view;
@ -151,32 +148,19 @@ public class FilesControlSet extends TaskEditControlFragment {
TextView nameView = (TextView) fileRow.findViewById(R.id.file_text);
String name = LEFT_TO_RIGHT_MARK + taskAttachment.getName();
nameView.setText(name);
nameView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showFile(taskAttachment);
}
});
nameView.setOnClickListener(v -> showFile(taskAttachment));
View clearFile = fileRow.findViewById(R.id.clear);
clearFile.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialogBuilder.newMessageDialog(R.string.premium_remove_file_confirm)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
taskAttachmentDao.delete(taskAttachment.getId());
if (taskAttachment.containsNonNullValue(TaskAttachment.FILE_PATH)) {
File f = new File(taskAttachment.getFilePath());
f.delete();
}
attachmentContainer.removeView(fileRow);
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
}
});
clearFile.setOnClickListener(v -> dialogBuilder.newMessageDialog(R.string.premium_remove_file_confirm)
.setPositiveButton(android.R.string.ok, (dialog, which) -> {
taskAttachmentDao.delete(taskAttachment.getId());
if (taskAttachment.containsNonNullValue(TaskAttachment.FILE_PATH)) {
File f = new File(taskAttachment.getFilePath());
f.delete();
}
attachmentContainer.removeView(fileRow);
})
.setNegativeButton(android.R.string.cancel, null)
.show());
}
private void validateFiles(List<TaskAttachment> files) {
@ -226,12 +210,7 @@ public class FilesControlSet extends TaskEditControlFragment {
final String filePath = m.getFilePath();
if (fileType.startsWith(TaskAttachment.FILE_TYPE_AUDIO)) {
play(m.getFilePath(), new PlaybackExceptionHandler() {
@Override
public void playbackFailed() {
showFromIntent(filePath, fileType);
}
});
play(m.getFilePath(), () -> showFromIntent(filePath, fileType));
} else if (fileType.startsWith(TaskAttachment.FILE_TYPE_IMAGE)) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);

@ -4,7 +4,6 @@ import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import com.google.common.base.Predicate;
import com.todoroo.andlib.utility.DateUtilities;
import com.todoroo.astrid.utility.Constants;
@ -104,11 +103,6 @@ public class CalendarAlarmReceiver extends InjectingBroadcastReceiver {
return false;
}
final List<String> myAccounts = accountManager.getAccounts();
return any(attendees, new Predicate<AndroidCalendarEventAttendee>() {
@Override
public boolean apply(AndroidCalendarEventAttendee attendee) {
return myAccounts.contains(attendee.getEmail());
}
});
return any(attendees, attendee -> myAccounts.contains(attendee.getEmail()));
}
}

@ -54,12 +54,7 @@ public class CalendarReminderActivity extends ThemedInjectingAppCompatActivity {
private View dismissButton;
private View ignoreSettingsButton;
private final OnClickListener dismissListener = new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
};
private final OnClickListener dismissListener = v -> finish();
private final OnClickListener ignoreListener = new OnClickListener() {
@Override
@ -69,19 +64,11 @@ public class CalendarReminderActivity extends ThemedInjectingAppCompatActivity {
ignorePresses++;
if (ignorePresses == IGNORE_PROMPT_COUNT) {
dialogBuilder.newMessageDialog(R.string.CRA_ignore_body)
.setPositiveButton(R.string.CRA_ignore_all, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
preferences.setBoolean(R.string.p_calendar_reminders, false);
dismissListener.onClick(v);
}
})
.setNegativeButton(R.string.CRA_ignore_this, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dismissListener.onClick(v);
}
.setPositiveButton(R.string.CRA_ignore_all, (dialog, which) -> {
preferences.setBoolean(R.string.p_calendar_reminders, false);
dismissListener.onClick(v);
})
.setNegativeButton(R.string.CRA_ignore_this, (dialog, which) -> dismissListener.onClick(v))
.show();
} else {
dismissListener.onClick(v);
@ -143,30 +130,17 @@ public class CalendarReminderActivity extends ThemedInjectingAppCompatActivity {
ignoreButton.setOnClickListener(ignoreListener);
dismissButton.setOnClickListener(dismissListener);
ignoreSettingsButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent editPreferences = new Intent(CalendarReminderActivity.this, BasicPreferences.class);
startActivity(editPreferences);
dismissListener.onClick(v);
}
ignoreSettingsButton.setOnClickListener(v -> {
Intent editPreferences = new Intent(CalendarReminderActivity.this, BasicPreferences.class);
startActivity(editPreferences);
dismissListener.onClick(v);
});
if (!fromPostpone) {
postponeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
postpone();
}
});
postponeButton.setOnClickListener(v -> postpone());
}
createListButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
createNewList(getString(R.string.CRA_default_list_name, eventName));
}
});
createListButton.setOnClickListener(v -> createNewList(getString(R.string.CRA_default_list_name, eventName)));
}
private void createNewList(final String name) {

@ -72,30 +72,17 @@ public class CommentsController {
items.clear();
commentsContainer.removeAllViews();
metadataDao.byTaskAndKey(task.getId(), NoteMetadata.METADATA_KEY, new Callback<Metadata>() {
@Override
public void apply(Metadata metadata) {
items.add(NoteOrUpdate.fromMetadata(metadata));
}
});
metadataDao.byTaskAndKey(task.getId(), NoteMetadata.METADATA_KEY, metadata -> items.add(NoteOrUpdate.fromMetadata(metadata)));
userActivityDao.getCommentsForTask(task.getUuid(), new Callback<UserActivity>() {
@Override
public void apply(UserActivity update) {
items.add(NoteOrUpdate.fromUpdate(update));
}
});
userActivityDao.getCommentsForTask(task.getUuid(), update -> items.add(NoteOrUpdate.fromUpdate(update)));
Collections.sort(items, new Comparator<NoteOrUpdate>() {
@Override
public int compare(NoteOrUpdate a, NoteOrUpdate b) {
if (a.createdAt < b.createdAt) {
return 1;
} else if (a.createdAt == b.createdAt) {
return 0;
} else {
return -1;
}
Collections.sort(items, (a, b) -> {
if (a.createdAt < b.createdAt) {
return 1;
} else if (a.createdAt == b.createdAt) {
return 0;
} else {
return -1;
}
});
@ -109,13 +96,10 @@ public class CommentsController {
loadMore.setText(R.string.TEA_load_more);
loadMore.setTextColor(activity.getResources().getColor(R.color.task_edit_deadline_gray));
loadMore.setBackgroundColor(Color.alpha(0));
loadMore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Perform action on click
commentItems += 10;
reloadView();
}
loadMore.setOnClickListener(v -> {
// Perform action on click
commentItems += 10;
reloadView();
});
commentsContainer.addView(loadMore);
}
@ -155,14 +139,9 @@ public class CommentsController {
String path = getPathFromUri(activity, updateBitmap);
commentPictureView.setImageBitmap(sampleBitmap(path, commentPictureView.getLayoutParams().width, commentPictureView.getLayoutParams().height));
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
activity.startActivity(new Intent(Intent.ACTION_VIEW) {{
setDataAndType(updateBitmap, "image/*");
}});
}
});
view.setOnClickListener(v -> activity.startActivity(new Intent(Intent.ACTION_VIEW) {{
setDataAndType(updateBitmap, "image/*");
}}));
} else {
commentPictureView.setVisibility(View.GONE);
}

@ -72,12 +72,7 @@ public class ReminderPreferences extends InjectingPreferenceActivity {
R.string.p_geofence_responsiveness);
fieldMissedCalls = (CheckBoxPreference) findPreference(getString(R.string.p_field_missed_calls));
fieldMissedCalls.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
return newValue != null && (!(boolean) newValue || permissionRequestor.requestMissedCallPermissions());
}
});
fieldMissedCalls.setOnPreferenceChangeListener((preference, newValue) -> newValue != null && (!(boolean) newValue || permissionRequestor.requestMissedCallPermissions()));
fieldMissedCalls.setChecked(fieldMissedCalls.isChecked() && permissionChecker.canAccessMissedCallPermissions());
initializeRingtonePreference();
@ -85,14 +80,11 @@ public class ReminderPreferences extends InjectingPreferenceActivity {
initializeTimePreference(getQuietStartPreference(), REQUEST_QUIET_START);
initializeTimePreference(getQuietEndPreference(), REQUEST_QUIET_END);
findPreference(getString(R.string.p_led_color)).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
startActivityForResult(new Intent(ReminderPreferences.this, ColorPickerActivity.class) {{
putExtra(ColorPickerActivity.EXTRA_PALETTE, ColorPickerDialog.ColorPalette.LED);
}}, REQUEST_LED_PICKER);
return false;
}
findPreference(getString(R.string.p_led_color)).setOnPreferenceClickListener(preference -> {
startActivityForResult(new Intent(ReminderPreferences.this, ColorPickerActivity.class) {{
putExtra(ColorPickerActivity.EXTRA_PALETTE, ColorPickerDialog.ColorPalette.LED);
}}, REQUEST_LED_PICKER);
return false;
});
requires(atLeastJellybean(), R.string.p_rmd_notif_actions_enabled, R.string.p_notification_priority);
@ -104,24 +96,18 @@ public class ReminderPreferences extends InjectingPreferenceActivity {
private void rescheduleNotificationsOnChange(int... resIds) {
for (int resId : resIds) {
findPreference(getString(resId)).setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
startService(new Intent(ReminderPreferences.this, ReminderSchedulerIntentService.class));
return true;
}
findPreference(getString(resId)).setOnPreferenceChangeListener((preference, newValue) -> {
startService(new Intent(ReminderPreferences.this, ReminderSchedulerIntentService.class));
return true;
});
}
}
private void resetGeofencesOnChange(int... resIds) {
for (int resId : resIds) {
findPreference(getString(resId)).setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
startService(new Intent(ReminderPreferences.this, GeofenceSchedulingIntentService.class));
return true;
}
findPreference(getString(resId)).setOnPreferenceChangeListener((preference, newValue) -> {
startService(new Intent(ReminderPreferences.this, GeofenceSchedulingIntentService.class));
return true;
});
}
}
@ -141,32 +127,26 @@ public class ReminderPreferences extends InjectingPreferenceActivity {
}
private void initializeTimePreference(final TimePreference preference, final int requestCode) {
preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference ignored) {
final DateTime current = new DateTime().withMillisOfDay(preference.getMillisOfDay());
startActivityForResult(new Intent(ReminderPreferences.this, TimePickerActivity.class) {{
putExtra(TimePickerActivity.EXTRA_TIMESTAMP, current.getMillis());
}}, requestCode);
return true;
}
preference.setOnPreferenceClickListener(ignored -> {
final DateTime current = new DateTime().withMillisOfDay(preference.getMillisOfDay());
startActivityForResult(new Intent(ReminderPreferences.this, TimePickerActivity.class) {{
putExtra(TimePickerActivity.EXTRA_TIMESTAMP, current.getMillis());
}}, requestCode);
return true;
});
}
private void initializeRingtonePreference() {
Preference.OnPreferenceChangeListener ringtoneChangedListener = new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
if ("".equals(value)) {
preference.setSummary(R.string.silent);
} else {
Ringtone ringtone = RingtoneManager.getRingtone(ReminderPreferences.this, value == null
? RingtoneManager.getActualDefaultRingtoneUri(getApplicationContext(), RingtoneManager.TYPE_NOTIFICATION)
: Uri.parse((String) value));
preference.setSummary(ringtone == null ? "" : ringtone.getTitle(ReminderPreferences.this));
}
return true;
Preference.OnPreferenceChangeListener ringtoneChangedListener = (preference, value) -> {
if ("".equals(value)) {
preference.setSummary(R.string.silent);
} else {
Ringtone ringtone = RingtoneManager.getRingtone(ReminderPreferences.this, value == null
? RingtoneManager.getActualDefaultRingtoneUri(getApplicationContext(), RingtoneManager.TYPE_NOTIFICATION)
: Uri.parse((String) value));
preference.setSummary(ringtone == null ? "" : ringtone.getTitle(ReminderPreferences.this));
}
return true;
};
String ringtoneKey = getString(R.string.p_rmd_ringtone);

@ -165,12 +165,7 @@ public class RepeatControlSet extends TaskEditControlFragment {
for(int i = 0; i < 7; i++) {
final int index = i;
CheckBox checkBox = (CheckBox) daysOfWeekContainer.getChildAt(i);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
RepeatControlSet.this.isChecked[index] = isChecked;
}
});
checkBox.setOnCheckedChangeListener((buttonView, isChecked1) -> RepeatControlSet.this.isChecked[index] = isChecked1);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
checkBox.setText(dfs.getShortWeekdays()[dayOfWeek].substring(0, 1));
daysOfWeek[i] = checkBox;
@ -179,12 +174,7 @@ public class RepeatControlSet extends TaskEditControlFragment {
}
// set up listeners
value.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
repeatValueClick();
}
});
value.setOnClickListener(v -> repeatValueClick());
setRepeatValue(1);
interval.setOnItemSelectedListener(new OnItemSelectedListener() {
@ -316,22 +306,14 @@ public class RepeatControlSet extends TaskEditControlFragment {
private AlertDialog buildDialog() {
return dialogBuilder.newDialog()
.setView(dialogView)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
doRepeat = true;
.setPositiveButton(android.R.string.ok, (dialog12, which) -> {
doRepeat = true;
callback.repeatChanged(doRepeat);
callback.repeatChanged(doRepeat);
refreshDisplayView();
}
})
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
refreshDisplayView();
}
refreshDisplayView();
})
.setOnCancelListener(dialog1 -> refreshDisplayView())
.create();
}
@ -438,12 +420,7 @@ public class RepeatControlSet extends TaskEditControlFragment {
dialogValue = 1;
}
NumberPickerDialog dialog = new NumberPickerDialog(theme.getThemedDialog(getActivity()), new OnNumberPickedListener() {
@Override
public void onNumberPicked(int number) {
setRepeatValue(number);
}
}, getResources().getString(R.string.repeat_interval_prompt),
NumberPickerDialog dialog = new NumberPickerDialog(theme.getThemedDialog(getActivity()), this::setRepeatValue, getResources().getString(R.string.repeat_interval_prompt),
dialogValue, 1, 1, 365);
theme.applyToContext(dialog.getContext());
dialog.show();

@ -169,13 +169,7 @@ public class RepeatTaskCompleteListener extends InjectingBroadcastReceiver {
}
}
private static Comparator<WeekdayNum> weekdayCompare = new Comparator<WeekdayNum>() {
@Override
public int compare(WeekdayNum object1, WeekdayNum object2) {
return object1.wday.javaDayNum - object2.wday.javaDayNum;
}
};
private static Comparator<WeekdayNum> weekdayCompare = (object1, object2) -> object1.wday.javaDayNum - object2.wday.javaDayNum;
private static WeekdayNum findNextWeekday(List<WeekdayNum> byDay, DateTime date) {
WeekdayNum next = byDay.get(0);

@ -76,11 +76,8 @@ public class StartupService {
}
// perform startup activities in a background thread
new Thread(new Runnable() {
@Override
public void run() {
taskDeleter.deleteTasksWithEmptyTitles(null);
}
new Thread(() -> {
taskDeleter.deleteTasksWithEmptyTitles(null);
}).start();
if (lastVersion == 0) {

@ -187,12 +187,7 @@ public class AstridOrderedListFragmentHelper<LIST> implements OrderedListFragmen
taskAdapter = new DraggableTaskAdapter(context, preferences, fragment, cursor,
sqlQueryTemplate, dialogBuilder, checkBoxes, tagService, themeCache);
taskAdapter.addOnCompletedTaskListener(new OnCompletedTaskListener() {
@Override
public void onCompletedTask(Task item, boolean newState) {
setCompletedForItemAndSubtasks(item, newState);
}
});
taskAdapter.addOnCompletedTaskListener(this::setCompletedForItemAndSubtasks);
return taskAdapter;
}
@ -238,15 +233,12 @@ public class AstridOrderedListFragmentHelper<LIST> implements OrderedListFragmen
}
final ArrayList<String> chained = new ArrayList<>();
updater.applyToDescendants(itemId, new AstridOrderedListUpdater.OrderedListNodeVisitor() {
@Override
public void visitNode(AstridOrderedListUpdater.Node node) {
String uuid = node.uuid;
model.setCompletionDate(completionDate);
taskService.update(Task.UUID.eq(uuid), model);
model.clear();
chained.add(node.uuid);
}
updater.applyToDescendants(itemId, node -> {
String uuid = node.uuid;
model.setCompletionDate(completionDate);
taskService.update(Task.UUID.eq(uuid), model);
model.clear();
chained.add(node.uuid);
});
if(chained.size() > 0) {

@ -65,12 +65,7 @@ public abstract class AstridOrderedListUpdater<LIST> {
public void initializeFromSerializedTree(LIST list, Filter filter, String serializedTree) {
idToNode.clear();
treeRoot = buildTreeModel(serializedTree, new JSONTreeModelBuilder() {
@Override
public void afterAddNode(Node node) {
idToNode.put(node.uuid, node);
}
});
treeRoot = buildTreeModel(serializedTree, node -> idToNode.put(node.uuid, node));
verifyTreeModel(list, filter);
}

@ -156,17 +156,14 @@ public class SubtasksHelper {
}
private static void remapLocalTreeToRemote(Node root, HashMap<Long, String> idMap) {
remapTree(root, idMap, new TreeRemapHelper<Long>() {
@Override
public Long getKeyFromOldUuid(String uuid) {
Long localId = -1L;
try {
localId = Long.parseLong(uuid);
} catch (NumberFormatException e) {
Timber.e(e, e.getMessage());
}
return localId;
remapTree(root, idMap, uuid -> {
Long localId = -1L;
try {
localId = Long.parseLong(uuid);
} catch (NumberFormatException e) {
Timber.e(e, e.getMessage());
}
return localId;
});
}

@ -72,13 +72,10 @@ public final class TagService {
MetadataCriteria.withKey(TaskToTagMetadata.KEY))).
orderBy(order).groupBy(TaskToTagMetadata.TAG_NAME);
final List<TagData> array = new ArrayList<>();
metadataDao.query(query, new Callback<Metadata>() {
@Override
public void apply(Metadata metadata) {
TagData tag = tagFromUUID(metadata.getValue(TaskToTagMetadata.TAG_UUID));
if (tag != null) {
array.add(tag);
}
metadataDao.query(query, metadata -> {
TagData tag = tagFromUUID(metadata.getValue(TaskToTagMetadata.TAG_UUID));
if (tag != null) {
array.add(tag);
}
});
return array.toArray(new TagData[array.size()]);
@ -94,12 +91,7 @@ public final class TagService {
MetadataCriteria.withKey(TaskToTagMetadata.KEY),
Metadata.DELETION_DATE.eq(0),
TaskToTagMetadata.TASK_UUID.eq(uuid))));
return newArrayList(Iterables.transform(tags, new Function<Metadata, TagData>() {
@Override
public TagData apply(Metadata metadata) {
return tagFromUUID(metadata.getValue(TaskToTagMetadata.TAG_UUID));
}
}));
return newArrayList(Iterables.transform(tags, metadata -> tagFromUUID(metadata.getValue(TaskToTagMetadata.TAG_UUID))));
}
public ArrayList<TagData> getTagDataForTask(long taskId) {
@ -108,12 +100,7 @@ public final class TagService {
MetadataCriteria.withKey(TaskToTagMetadata.KEY),
Metadata.DELETION_DATE.eq(0),
MetadataCriteria.byTask(taskId))));
return newArrayList(transform(tags, new Function<Metadata, TagData>() {
@Override
public TagData apply(Metadata metadata) {
return tagFromUUID(metadata.getValue(TaskToTagMetadata.TAG_UUID));
}
}));
return newArrayList(transform(tags, metadata -> tagFromUUID(metadata.getValue(TaskToTagMetadata.TAG_UUID))));
}
public ArrayList<String> getTagNames(long taskId) {
@ -124,11 +111,8 @@ public final class TagService {
MetadataCriteria.byTask(taskId)))
.orderBy(Order.asc(Functions.upper(TaskToTagMetadata.TAG_NAME)));
final ArrayList<String> tagNames = new ArrayList<>();
metadataDao.query(query, new Callback<Metadata>() {
@Override
public void apply(Metadata entry) {
tagNames.add(entry.getValue(TaskToTagMetadata.TAG_NAME));
}
metadataDao.query(query, entry -> {
tagNames.add(entry.getValue(TaskToTagMetadata.TAG_NAME));
});
return tagNames;
}
@ -138,12 +122,9 @@ public final class TagService {
*/
public List<TagData> getTagList() {
final List<TagData> tagList = new ArrayList<>();
tagDataDao.tagDataOrderedByName(new Callback<TagData>() {
@Override
public void apply(TagData tagData) {
if (!TextUtils.isEmpty(tagData.getName())) {
tagList.add(tagData);
}
tagDataDao.tagDataOrderedByName(tagData -> {
if (!TextUtils.isEmpty(tagData.getName())) {
tagList.add(tagData);
}
});
return tagList;

@ -111,20 +111,17 @@ public final class TagsControlSet extends TaskEditControlFragment {
};
private Function<TagData, SpannableString> tagToString(final float maxLength) {
return new Function<TagData, SpannableString>() {
@Override
public SpannableString apply(TagData tagData) {
String tagName = tagData.getName();
tagName = tagName
.substring(0, Math.min(tagName.length(), (int) maxLength))
.replace(' ', NO_BREAK_SPACE);
SpannableString string = new SpannableString(NO_BREAK_SPACE + tagName + NO_BREAK_SPACE);
int themeIndex = tagData.getColor();
ThemeColor color = themeIndex >= 0 ? themeCache.getThemeColor(themeIndex) : themeCache.getUntaggedColor();
string.setSpan(new BackgroundColorSpan(color.getPrimaryColor()), 0, string.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
string.setSpan(new ForegroundColorSpan(color.getActionBarTint()), 0, string.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
return string;
}
return tagData -> {
String tagName = tagData.getName();
tagName = tagName
.substring(0, Math.min(tagName.length(), (int) maxLength))
.replace(' ', NO_BREAK_SPACE);
SpannableString string = new SpannableString(NO_BREAK_SPACE + tagName + NO_BREAK_SPACE);
int themeIndex = tagData.getColor();
ThemeColor color = themeIndex >= 0 ? themeCache.getThemeColor(themeIndex) : themeCache.getUntaggedColor();
string.setSpan(new BackgroundColorSpan(color.getPrimaryColor()), 0, string.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
string.setSpan(new ForegroundColorSpan(color.getActionBarTint()), 0, string.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
return string;
};
}
@ -223,12 +220,7 @@ public final class TagsControlSet extends TaskEditControlFragment {
private AlertDialog buildDialog() {
return dialogBuilder.newDialog()
.setView(dialogView)
.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialogInterface) {
refreshDisplayView();
}
})
.setOnDismissListener(dialogInterface -> refreshDisplayView())
.create();
}
@ -240,12 +232,7 @@ public final class TagsControlSet extends TaskEditControlFragment {
}
private boolean isSelected(List<TagData> selected, final String name) {
return Iterables.any(selected, new Predicate<TagData>() {
@Override
public boolean apply(TagData input) {
return name.equalsIgnoreCase(input.getName());
}
});
return Iterables.any(selected, input -> name.equalsIgnoreCase(input.getName()));
}
private ArrayList<TagData> getSelectedTags() {
@ -335,32 +322,26 @@ public final class TagsControlSet extends TaskEditControlFragment {
}
});
textView.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView arg0, int actionId, KeyEvent arg2) {
if(actionId != EditorInfo.IME_NULL) {
return false;
}
if(getLastTextView().getText().length() != 0) {
addTag(""); //$NON-NLS-1$
}
return true;
textView.setOnEditorActionListener((arg0, actionId, arg2) -> {
if(actionId != EditorInfo.IME_NULL) {
return false;
}
if(getLastTextView().getText().length() != 0) {
addTag(""); //$NON-NLS-1$
}
return true;
});
tagItem.findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView lastView = getLastTextView();
if(lastView == textView && textView.getText().length() == 0) {
return;
}
tagItem.findViewById(R.id.button1).setOnClickListener(v -> {
TextView lastView = getLastTextView();
if(lastView == textView && textView.getText().length() == 0) {
return;
}
if(newTagLayout.getChildCount() > 1) {
newTagLayout.removeView(tagItem);
} else {
textView.setText(""); //$NON-NLS-1$
}
if(newTagLayout.getChildCount() > 1) {
newTagLayout.removeView(tagItem);
} else {
textView.setText(""); //$NON-NLS-1$
}
});
}

@ -125,18 +125,8 @@ public class TimerControlSet extends TaskEditControlFragment {
private AlertDialog buildDialog() {
return dialogBuilder.newDialog()
.setView(dialogView)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
refreshDisplayView();
}
})
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
refreshDisplayView();
}
})
.setPositiveButton(android.R.string.ok, (dialog12, which) -> refreshDisplayView())
.setOnCancelListener(dialog1 -> refreshDisplayView())
.create();
}
@ -239,12 +229,9 @@ public class TimerControlSet extends TaskEditControlFragment {
elapsed += DateUtilities.now() - timerStarted;
chronometer.setBase(SystemClock.elapsedRealtime() - elapsed);
if (elapsed > DateUtilities.ONE_DAY) {
chronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
@Override
public void onChronometerTick(Chronometer cArg) {
long t = SystemClock.elapsedRealtime() - cArg.getBase();
cArg.setText(DateFormat.format("d'd' h:mm", t)); //$NON-NLS-1$
}
chronometer.setOnChronometerTickListener(cArg -> {
long t = SystemClock.elapsedRealtime() - cArg.getBase();
cArg.setText(DateFormat.format("d'd' h:mm", t)); //$NON-NLS-1$
});
}

@ -317,25 +317,17 @@ public class DraggableListView extends ListView {
try {
Thread.sleep(300L);
post(new Runnable() {
@Override
public void run() {
initiateDrag(ev);
}
});
post(() -> initiateDrag(ev));
Thread.sleep(1000L);
post(new Runnable() {
@Override
public void run() {
stopDragging();
dragThread = null;
Vibrator v = (Vibrator) getContext().getSystemService(
Context.VIBRATOR_SERVICE);
v.vibrate(50);
mClickListener.onLongClick(viewAtPosition());
}
post(() -> {
stopDragging();
dragThread = null;
Vibrator v = (Vibrator) getContext().getSystemService(
Context.VIBRATOR_SERVICE);
v.vibrate(50);
mClickListener.onLongClick(viewAtPosition());
});
} catch (InterruptedException e) {

@ -141,12 +141,7 @@ public class ReminderControlSet extends TaskEditControlFragment {
private List<Long> currentAlarms() {
final List<Long> alarms = new ArrayList<>();
alarmService.getAlarms(taskId, new Callback<Metadata>() {
@Override
public void apply(Metadata entry) {
alarms.add(entry.getValue(AlarmFields.TIME));
}
});
alarmService.getAlarms(taskId, entry -> alarms.add(entry.getValue(AlarmFields.TIME)));
return alarms;
}
@ -284,12 +279,7 @@ public class ReminderControlSet extends TaskEditControlFragment {
}
public void addAlarmRow(final Long timestamp) {
addAlarmRow(getLongDateStringWithTime(context, timestamp), new OnClickListener() {
@Override
public void onClick(View v) {
alarms.remove(timestamp);
}
});
addAlarmRow(getLongDateStringWithTime(context, timestamp), v -> alarms.remove(timestamp));
alarms.add(timestamp);
}
@ -301,12 +291,7 @@ public class ReminderControlSet extends TaskEditControlFragment {
}
public void addGeolocationReminder(final Geofence geofence) {
addAlarmRow(geofence.getName(), new OnClickListener() {
@Override
public void onClick(View v) {
geofences.remove(geofence);
}
});
addAlarmRow(geofence.getName(), v -> geofences.remove(geofence));
geofences.add(geofence);
}
@ -349,15 +334,12 @@ public class ReminderControlSet extends TaskEditControlFragment {
private void addAlarmRow(final View alertItem, String text, final View.OnClickListener onRemove) {
TextView display = (TextView) alertItem.findViewById(R.id.alarm_string);
display.setText(text);
alertItem.findViewById(R.id.clear).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
alertContainer.removeView(alertItem);
if (onRemove != null) {
onRemove.onClick(v);
}
updateSpinner();
alertItem.findViewById(R.id.clear).setOnClickListener(v -> {
alertContainer.removeView(alertItem);
if (onRemove != null) {
onRemove.onClick(v);
}
updateSpinner();
});
updateSpinner();
}
@ -384,31 +366,16 @@ public class ReminderControlSet extends TaskEditControlFragment {
private void addDue() {
whenDue = true;
addAlarmRow(getString(R.string.when_due), new OnClickListener() {
@Override
public void onClick(View v) {
whenDue = false;
}
});
addAlarmRow(getString(R.string.when_due), v -> whenDue = false);
}
private void addOverdue() {
whenOverdue = true;
addAlarmRow(getString(R.string.when_overdue), new OnClickListener() {
@Override
public void onClick(View v) {
whenOverdue = false;
}
});
addAlarmRow(getString(R.string.when_overdue), v -> whenOverdue = false);
}
private void addRandomReminder(long reminderPeriod) {
View alarmRow = addAlarmRow(getString(R.string.randomly_once) + " ", new OnClickListener() {
@Override
public void onClick(View v) {
randomControlSet = null;
}
});
View alarmRow = addAlarmRow(getString(R.string.randomly_once) + " ", v -> randomControlSet = null);
randomControlSet = new RandomReminderControlSet(context, alarmRow, reminderPeriod);
}

@ -74,27 +74,19 @@ public class TimeDurationControlSet implements OnNNumberPickedListener, View.OnC
new int[] {999, 59}, new String[] {":", null});
final NumberPicker hourPicker = dialog.getPicker(0);
final NumberPicker minutePicker = dialog.getPicker(1);
minutePicker.setFormatter(new NumberPicker.Formatter() {
@Override
public String toString(int value) {
return String.format("%02d", value);
}
});
minutePicker.setOnChangeListener(new NumberPicker.OnChangedListener() {
@Override
public int onChanged(int newVal) {
if(newVal < 0) {
if(hourPicker.getCurrent() == 0) {
return 0;
}
hourPicker.setCurrent(hourPicker.getCurrent() - 1);
return 60 + newVal;
} else if(newVal > 59) {
hourPicker.setCurrent(hourPicker.getCurrent() + 1);
return newVal % 60;
minutePicker.setFormatter(value -> String.format("%02d", value));
minutePicker.setOnChangeListener(newVal -> {
if(newVal < 0) {
if(hourPicker.getCurrent() == 0) {
return 0;
}
return newVal;
hourPicker.setCurrent(hourPicker.getCurrent() - 1);
return 60 + newVal;
} else if(newVal > 59) {
hourPicker.setCurrent(hourPicker.getCurrent() + 1);
return newVal % 60;
}
return newVal;
});
}

@ -30,18 +30,8 @@ public class AACRecorder {
setOutputFormat(OutputFormat.MPEG_4);
setAudioEncoder(AudioEncoder.AAC);
setOutputFile(tempFile);
setOnErrorListener(new OnErrorListener() {
@Override
public void onError(MediaRecorder mr, int what, int extra) {
Timber.e("mediaRecorder.onError(mr, %s, %s)", what, extra);
}
});
setOnInfoListener(new OnInfoListener() {
@Override
public void onInfo(MediaRecorder mr, int what, int extra) {
Timber.i("mediaRecorder.onInfo(mr, %s, %s)", what, extra);
}
});
setOnErrorListener((mr, what, extra) -> Timber.e("mediaRecorder.onError(mr, %s, %s)", what, extra));
setOnInfoListener((mr, what, extra) -> Timber.i("mediaRecorder.onInfo(mr, %s, %s)", what, extra));
}};
try {

@ -50,13 +50,10 @@ public class VoiceOutputAssistant implements OnInitListener {
if (mTts != null && isTTSInitialized) {
final String id = UUID.randomUUID().toString();
Timber.d("%s: %s (%s)", mTts, textToSpeak, id);
mTts.setOnUtteranceCompletedListener(new TextToSpeech.OnUtteranceCompletedListener() {
@Override
public void onUtteranceCompleted(String utteranceId) {
Timber.d("%s: onUtteranceCompleted", utteranceId);
if(utteranceId.equals(id)) {
shutdown();
}
mTts.setOnUtteranceCompletedListener(utteranceId -> {
Timber.d("%s: onUtteranceCompleted", utteranceId);
if(utteranceId.equals(id)) {
shutdown();
}
});
mTts.speak(textToSpeak, TextToSpeech.QUEUE_ADD, new HashMap<String, String>() {{

@ -72,25 +72,10 @@ public class CalendarSelectionDialog extends InjectingDialogFragment {
adapter = new ArrayAdapter<>(getActivity(), R.layout.simple_list_item_single_choice_themed, calendarNames);
AlertDialogBuilder builder = dialogBuilder.newDialog()
.setAdapter(adapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
handler.selectedCalendar(calendars.get(which));
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
handler.cancel();
}
});
.setAdapter(adapter, (dialog, which) -> handler.selectedCalendar(calendars.get(which)))
.setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> handler.cancel());
if (enableNone) {
builder.setNeutralButton(R.string.none, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
handler.selectedCalendar(AndroidCalendar.NONE);
}
});
builder.setNeutralButton(R.string.none, (dialog, which) -> handler.selectedCalendar(AndroidCalendar.NONE));
}
return builder.show();
@ -104,12 +89,7 @@ public class CalendarSelectionDialog extends InjectingDialogFragment {
calendars.clear();
calendars.addAll(calendarProvider.getCalendars());
calendarNames.clear();
calendarNames.addAll(transform(calendars, new Function<AndroidCalendar, String>() {
@Override
public String apply(AndroidCalendar androidCalendar) {
return androidCalendar.getName();
}
}));
calendarNames.addAll(transform(calendars, AndroidCalendar::getName));
if (calendarNames.isEmpty()) {
Toast.makeText(getActivity(), R.string.no_calendars_found, Toast.LENGTH_LONG).show();
handler.cancel();

@ -66,7 +66,7 @@ public class ColorPickerActivity extends InjectingAppCompatActivity implements C
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_PURCHASE) {
purchaseHelper.handleActivityResult(PurchaseHelperCallback.NO_OP, requestCode, resultCode, data);
purchaseHelper.handleActivityResult(null, requestCode, resultCode, data);
} else {
super.onActivityResult(requestCode, resultCode, data);
}

@ -52,12 +52,7 @@ public class DatePickerActivity extends InjectingAppCompatActivity implements Da
dialog.setAccentColor(themeAccent.getAccentColor());
dialog.show(fragmentManager, FRAG_TAG_DATE_PICKER);
}
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface) {
finish();
}
});
dialog.setOnCancelListener(dialogInterface -> finish());
dialog.setOnDateSetListener(this);
}
}

@ -43,29 +43,21 @@ public class FilterSelectionActivity extends InjectingAppCompatActivity {
filterAdapter.populateList();
dialogBuilder.newDialog()
.setSingleChoiceItems(filterAdapter, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final Filter selectedFilter = (Filter) filterAdapter.getItem(which);
setResult(RESULT_OK, new Intent() {{
if (returnFilter) {
putExtra(EXTRA_FILTER, selectedFilter);
}
putExtra(EXTRA_FILTER_NAME, selectedFilter.listingTitle);
putExtra(EXTRA_FILTER_SQL, selectedFilter.getSqlQuery());
if (selectedFilter.valuesForNewTasks != null) {
putExtra(EXTRA_FILTER_VALUES, AndroidUtilities.contentValuesToSerializedString(selectedFilter.valuesForNewTasks));
}
}});
dialog.dismiss();
}
})
.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
finish();
}
.setSingleChoiceItems(filterAdapter, -1, (dialog, which) -> {
final Filter selectedFilter = (Filter) filterAdapter.getItem(which);
setResult(RESULT_OK, new Intent() {{
if (returnFilter) {
putExtra(EXTRA_FILTER, selectedFilter);
}
putExtra(EXTRA_FILTER_NAME, selectedFilter.listingTitle);
putExtra(EXTRA_FILTER_SQL, selectedFilter.getSqlQuery());
if (selectedFilter.valuesForNewTasks != null) {
putExtra(EXTRA_FILTER_VALUES, AndroidUtilities.contentValuesToSerializedString(selectedFilter.valuesForNewTasks));
}
}});
dialog.dismiss();
})
.setOnDismissListener(dialog -> finish())
.show();
}

@ -56,12 +56,7 @@ public class TimePickerActivity extends InjectingAppCompatActivity implements Ti
dialog.setAccentColor(themeAccent.getAccentColor());
dialog.show(fragmentManager, FRAG_TAG_TIME_PICKER);
}
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface) {
finish();
}
});
dialog.setOnCancelListener(dialogInterface -> finish());
dialog.setOnTimeSetListener(this);
}
}

@ -1,13 +1,5 @@
package org.tasks.billing;
public interface PurchaseHelperCallback {
PurchaseHelperCallback NO_OP = new PurchaseHelperCallback() {
@Override
public void purchaseCompleted(boolean success, String sku) {
}
};
void purchaseCompleted(boolean success, String sku);
}

@ -44,42 +44,19 @@ public class AddAttachmentDialog extends InjectingDialogFragment {
final List<Runnable> actions = newArrayList();
if (device.hasCamera()) {
entries.add(getString(R.string.take_a_picture));
actions.add(new Runnable() {
@Override
public void run() {
callback.takePicture();
}
});
actions.add(() -> callback.takePicture());
}
entries.add(getString(R.string.premium_record_audio));
actions.add(new Runnable() {
@Override
public void run() {
callback.recordNote();
}
});
actions.add(() -> callback.recordNote());
if (device.hasGallery()) {
entries.add(getString(R.string.pick_from_gallery));
actions.add(new Runnable() {
@Override
public void run() {
callback.pickFromGallery();
}
});
actions.add(() -> callback.pickFromGallery());
}
entries.add(getString(R.string.pick_from_storage));
actions.add(new Runnable() {
@Override
public void run() {
callback.pickFromStorage();
}
});
actions.add(() -> callback.pickFromStorage());
return dialogBuilder.newDialog()
.setItems(entries, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
actions.get(which).run();
}
.setItems(entries, (dialog, which) -> {
actions.get(which).run();
})
.show();
}

@ -89,22 +89,14 @@ public class ColorPickerDialog extends InjectingDialogFragment {
};
return dialogBuilder.newDialog(theme)
.setAdapter(adapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (preferences.hasPurchase(R.string.p_purchased_themes) || which < getNumFree()) {
callback.themePicked(palette, which);
} else {
callback.initiateThemePurchase();
}
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
callback.dismissed();
.setAdapter(adapter, (dialog, which) -> {
if (preferences.hasPurchase(R.string.p_purchased_themes) || which < getNumFree()) {
callback.themePicked(palette, which);
} else {
callback.initiateThemePurchase();
}
})
.setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> callback.dismissed())
.show();
}

@ -31,17 +31,14 @@ public class DonationDialog extends InjectingNativeDialogFragment {
final List<String> donationValues = getDonationValues();
return dialogBuilder.newDialog()
.setTitle(R.string.select_amount)
.setItems(donationValues, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = donationValues.get(which);
Pattern pattern = Pattern.compile("\\$(\\d+) USD");
Matcher matcher = pattern.matcher(value);
//noinspection ResultOfMethodCallIgnored
matcher.matches();
String sku = String.format(java.util.Locale.ENGLISH, "%03d", Integer.parseInt(matcher.group(1)));
purchaseHelper.purchase(dialogBuilder, getActivity(), sku, null, BasicPreferences.REQUEST_PURCHASE, (BasicPreferences) getActivity());
}
.setItems(donationValues, (dialog, which) -> {
String value = donationValues.get(which);
Pattern pattern = Pattern.compile("\\$(\\d+) USD");
Matcher matcher = pattern.matcher(value);
//noinspection ResultOfMethodCallIgnored
matcher.matches();
String sku = String.format(java.util.Locale.ENGLISH, "%03d", Integer.parseInt(matcher.group(1)));
purchaseHelper.purchase(dialogBuilder, getActivity(), sku, null, BasicPreferences.REQUEST_PURCHASE, (BasicPreferences) getActivity());
})
.setNegativeButton(android.R.string.cancel, null)
.show();

@ -40,11 +40,8 @@ public class NativeTimePickerDialog extends InjectingNativeDialogFragment implem
public Dialog onCreateDialog(Bundle savedInstanceState) {
Context context = theme.wrap(getActivity());
TimePickerDialog timePickerDialog = new TimePickerDialog(context, this, 0, 0, DateUtilities.is24HourFormat(context));
timePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
callback.cancel();
}
timePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(android.R.string.cancel), (dialogInterface, i) -> {
callback.cancel();
});
if (initial != null) {
timePickerDialog.updateTime(initial.getHourOfDay(), initial.getMinuteOfHour());

@ -66,12 +66,7 @@ public class SeekBarDialog extends InjectingNativeDialogFragment {
slider.setValue(initial, true);
return dialogBuilder.newDialog()
.setView(view)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
callback.valueSelected(slider.getValue(), requestCode);
}
})
.setPositiveButton(android.R.string.ok, (dialogInterface, i) -> callback.valueSelected(slider.getValue(), requestCode))
.setNegativeButton(android.R.string.cancel, null)
.show();
}

@ -79,25 +79,12 @@ public class SortDialog extends InjectingDialogFragment {
}
alertDialog = dialogBuilder.newDialog()
.setSingleChoiceItems(items, selectedIndex, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
selectedIndex = which;
enableReverse();
}
})
.setPositiveButton(R.string.TLA_menu_sort, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
setSelection(false);
}
})
.setNeutralButton(R.string.reverse, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
setSelection(true);
}
.setSingleChoiceItems(items, selectedIndex, (dialog, which) -> {
selectedIndex = which;
enableReverse();
})
.setPositiveButton(R.string.TLA_menu_sort, (dialog, which) -> setSelection(false))
.setNeutralButton(R.string.reverse, (dialog, which) -> setSelection(true))
.setNegativeButton(android.R.string.cancel, null)
.showThemedListView();

@ -42,16 +42,13 @@ public class FilterCounter {
}
public void refreshFilterCounts(final Runnable onComplete) {
executorService.submit(new Runnable() {
@Override
public void run() {
for (Filter filter : filterCounts.keySet()) {
int size = countTasks(filter);
filterCounts.put(filter, size);
}
if (onComplete != null) {
onComplete.run();
}
executorService.submit(() -> {
for (Filter filter : filterCounts.keySet()) {
int size = countTasks(filter);
filterCounts.put(filter, size);
}
if (onComplete != null) {
onComplete.run();
}
});
}

@ -83,12 +83,7 @@ public class FilterCriteriaProvider {
private CustomFilterCriterion getTagFilter() {
// TODO: adding to hash set because duplicate tag name bug hasn't been fixed yet
List<String> tags = newArrayList(newLinkedHashSet(transform(tagService.getTagList(), new Function<TagData, String>() {
@Override
public String apply(TagData tagData) {
return tagData.getName();
}
})));
List<String> tags = newArrayList(newLinkedHashSet(transform(tagService.getTagList(), TagData::getName)));
String[] tagNames = tags.toArray(new String[tags.size()]);
ContentValues values = new ContentValues();
values.put(Metadata.KEY.name, TaskToTagMetadata.KEY);

@ -182,12 +182,9 @@ public class CommentBarFragment extends TaskEditControlFragment {
if (pendingCommentPicture == null) {
showPictureLauncher(null);
} else {
showPictureLauncher(new ClearImageCallback() {
@Override
public void clearImage() {
pendingCommentPicture = null;
resetPictureButton();
}
showPictureLauncher(() -> {
pendingCommentPicture = null;
resetPictureButton();
});
}
}
@ -254,34 +251,21 @@ public class CommentBarFragment extends TaskEditControlFragment {
final boolean cameraAvailable = device.hasCamera();
if (cameraAvailable) {
runnables.add(new Runnable() {
@Override
public void run() {
startActivityForResult(new Intent(activity, CameraActivity.class), REQUEST_CODE_CAMERA);
}
});
runnables.add(() -> startActivityForResult(new Intent(activity, CameraActivity.class), REQUEST_CODE_CAMERA));
options.add(getString(R.string.take_a_picture));
}
if (clearImageOption != null) {
runnables.add(new Runnable() {
@Override
public void run() {
clearImageOption.clearImage();
}
});
runnables.add(clearImageOption::clearImage);
options.add(getString(R.string.actfm_picture_clear));
}
if (runnables.size() == 1) {
runnables.get(0).run();
} else {
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface d, int which) {
runnables.get(which).run();
d.dismiss();
}
DialogInterface.OnClickListener listener = (d, which) -> {
runnables.get(which).run();
d.dismiss();
};
// show a menu of available options

@ -60,12 +60,7 @@ public abstract class InjectingPreferenceActivity extends AppCompatPreferenceAct
toolbar.setTitle(getTitle());
}
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_back_24dp));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
toolbar.setNavigationOnClickListener(v -> finish());
MenuColorizer.colorToolbar(this, toolbar);
}

@ -42,19 +42,11 @@ public class LocalePickerDialog extends InjectingNativeDialogFragment {
for (String override : getResources().getStringArray(R.array.localization)) {
locales.add(locale.withLanguage(override));
}
final List<String> display = transform(locales, new Function<Locale, String>() {
@Override
public String apply(Locale input) {
return input.getDisplayName();
}
});
final List<String> display = transform(locales, Locale::getDisplayName);
return dialogBuilder.newDialog()
.setItems(display, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
callback.onLocaleSelected(locales.get(i));
}
.setItems(display, (dialogInterface, i) -> {
dialogInterface.dismiss();
callback.onLocaleSelected(locales.get(i));
})
.setNegativeButton(android.R.string.cancel, null)
.show();

@ -62,25 +62,15 @@ public class GeofenceService {
}
public boolean synchronizeGeofences(final long taskId, Set<Geofence> geofences) {
List<Metadata> metadata = newArrayList(transform(geofences, new Function<Geofence, Metadata>() {
@Override
public Metadata apply(final Geofence geofence) {
return new Metadata() {{
setKey(GeofenceFields.METADATA_KEY);
setValue(GeofenceFields.PLACE, geofence.getName());
setValue(GeofenceFields.LATITUDE, geofence.getLatitude());
setValue(GeofenceFields.LONGITUDE, geofence.getLongitude());
setValue(GeofenceFields.RADIUS, geofence.getRadius());
}};
}
}));
List<Metadata> metadata = newArrayList(transform(geofences, (Function<Geofence, Metadata>) geofence -> new Metadata() {{
setKey(GeofenceFields.METADATA_KEY);
setValue(GeofenceFields.PLACE, geofence.getName());
setValue(GeofenceFields.LATITUDE, geofence.getLatitude());
setValue(GeofenceFields.LONGITUDE, geofence.getLongitude());
setValue(GeofenceFields.RADIUS, geofence.getRadius());
}}));
boolean changed = synchronizeMetadata(taskId, metadata, new SynchronizeMetadataCallback() {
@Override
public void beforeDeleteMetadata(Metadata m) {
geofenceApi.cancel(new Geofence(m));
}
});
boolean changed = synchronizeMetadata(taskId, metadata, m -> geofenceApi.cancel(new Geofence(m)));
if(changed) {
setupGeofences(taskId);
@ -89,12 +79,7 @@ public class GeofenceService {
}
private List<Geofence> toGeofences(List<Metadata> geofences) {
return newArrayList(transform(geofences, new Function<Metadata, Geofence>() {
@Override
public Geofence apply(Metadata metadata) {
return new Geofence(metadata);
}
}));
return newArrayList(transform(geofences, Geofence::new));
}
private List<Geofence> getActiveGeofences() {
@ -128,27 +113,24 @@ public class GeofenceService {
newMetadataValues.add(values);
}
metadataDao.byTaskAndKey(taskId, GeofenceFields.METADATA_KEY, new Callback<Metadata>() {
@Override
public void apply(Metadata item) {
long id = item.getId();
// clear item id when matching with incoming values
item.clearValue(Metadata.ID);
item.clearValue(Metadata.CREATION_DATE);
ContentValues itemMergedValues = item.getMergedValues();
if(newMetadataValues.contains(itemMergedValues)) {
newMetadataValues.remove(itemMergedValues);
} else {
// not matched. cut it
item.setId(id);
if (callback != null) {
callback.beforeDeleteMetadata(item);
}
metadataDao.delete(id);
dirty[0] = true;
metadataDao.byTaskAndKey(taskId, GeofenceFields.METADATA_KEY, item -> {
long id = item.getId();
// clear item id when matching with incoming values
item.clearValue(Metadata.ID);
item.clearValue(Metadata.CREATION_DATE);
ContentValues itemMergedValues = item.getMergedValues();
if(newMetadataValues.contains(itemMergedValues)) {
newMetadataValues.remove(itemMergedValues);
} else {
// not matched. cut it
item.setId(id);
if (callback != null) {
callback.beforeDeleteMetadata(item);
}
metadataDao.delete(id);
dirty[0] = true;
}
});

@ -46,24 +46,18 @@ public class AppearancePreferences extends InjectingPreferenceActivity {
setExtraOnChange(R.string.p_show_today_filter, EXTRA_FILTERS_CHANGED);
setExtraOnChange(R.string.p_show_recently_modified_filter, EXTRA_FILTERS_CHANGED);
setExtraOnChange(R.string.p_show_not_in_list_filter, EXTRA_FILTERS_CHANGED);
findPreference(getString(R.string.customize_edit_screen)).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
startActivityForResult(new Intent(AppearancePreferences.this, BeastModePreferences.class), REQUEST_CUSTOMIZE);
return true;
}
findPreference(getString(R.string.customize_edit_screen)).setOnPreferenceClickListener(preference -> {
startActivityForResult(new Intent(AppearancePreferences.this, BeastModePreferences.class), REQUEST_CUSTOMIZE);
return true;
});
Preference defaultList = findPreference(getString(R.string.p_default_list));
Filter filter = defaultFilterProvider.getDefaultFilter();
defaultList.setSummary(filter.listingTitle);
defaultList.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
startActivityForResult(new Intent(AppearancePreferences.this, FilterSelectionActivity.class) {{
putExtra(FilterSelectionActivity.EXTRA_RETURN_FILTER, true);
}}, REQUEST_DEFAULT_LIST);
return true;
}
defaultList.setOnPreferenceClickListener(preference -> {
startActivityForResult(new Intent(AppearancePreferences.this, FilterSelectionActivity.class) {{
putExtra(FilterSelectionActivity.EXTRA_RETURN_FILTER, true);
}}, REQUEST_DEFAULT_LIST);
return true;
});
}
@ -100,13 +94,10 @@ public class AppearancePreferences extends InjectingPreferenceActivity {
}
private void setExtraOnChange(final int resId, final String extra) {
findPreference(getString(resId)).setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
tracker.reportEvent(Tracking.Events.SET_PREFERENCE, resId, newValue.toString());
result.putBoolean(extra, true);
return true;
}
findPreference(getString(resId)).setOnPreferenceChangeListener((preference, newValue) -> {
tracker.reportEvent(Tracking.Events.SET_PREFERENCE, resId, newValue.toString());
result.putBoolean(extra, true);
return true;
});
}

@ -31,22 +31,16 @@ public class BackupPreferences extends InjectingPreferenceActivity {
addPreferencesFromResource(R.xml.preferences_backup);
getPref(R.string.backup_BAc_import).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
startActivityForResult(new Intent(BackupPreferences.this, FileExplore.class) {{
putExtra(FileExplore.EXTRA_START_PATH, preferences.getBackupDirectory().getAbsolutePath());
}}, REQUEST_PICKER);
return false;
}
getPref(R.string.backup_BAc_import).setOnPreferenceClickListener(preference -> {
startActivityForResult(new Intent(BackupPreferences.this, FileExplore.class) {{
putExtra(FileExplore.EXTRA_START_PATH, preferences.getBackupDirectory().getAbsolutePath());
}}, REQUEST_PICKER);
return false;
});
getPref(R.string.backup_BAc_export).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
newExportTasksDialog().show(getFragmentManager(), FRAG_TAG_EXPORT_TASKS);
return false;
}
getPref(R.string.backup_BAc_export).setOnPreferenceClickListener(preference -> {
newExportTasksDialog().show(getFragmentManager(), FRAG_TAG_EXPORT_TASKS);
return false;
});
initializeBackupDirectory();
@ -71,15 +65,12 @@ public class BackupPreferences extends InjectingPreferenceActivity {
}
private void initializeBackupDirectory() {
findPreference(getString(R.string.p_backup_dir)).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference p) {
Intent filesDir = new Intent(BackupPreferences.this, FileExplore.class);
filesDir.putExtra(FileExplore.EXTRA_DIRECTORY_MODE, true);
filesDir.putExtra(FileExplore.EXTRA_START_PATH, getBackupDirectory());
startActivityForResult(filesDir, REQUEST_CODE_BACKUP_DIR);
return true;
}
findPreference(getString(R.string.p_backup_dir)).setOnPreferenceClickListener(p -> {
Intent filesDir = new Intent(BackupPreferences.this, FileExplore.class);
filesDir.putExtra(FileExplore.EXTRA_DIRECTORY_MODE, true);
filesDir.putExtra(FileExplore.EXTRA_START_PATH, getBackupDirectory());
startActivityForResult(filesDir, REQUEST_CODE_BACKUP_DIR);
return true;
});
updateBackupDirectory();
}

@ -83,148 +83,109 @@ public class BasicPreferences extends InjectingPreferenceActivity implements
Preference themePreference = findPreference(getString(R.string.p_theme));
themePreference.setSummary(themeBase.getName());
themePreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
startActivityForResult(new Intent(BasicPreferences.this, ColorPickerActivity.class) {{
putExtra(ColorPickerActivity.EXTRA_PALETTE, ColorPickerDialog.ColorPalette.THEMES);
}}, REQUEST_THEME_PICKER);
return false;
}
themePreference.setOnPreferenceClickListener(preference -> {
startActivityForResult(new Intent(BasicPreferences.this, ColorPickerActivity.class) {{
putExtra(ColorPickerActivity.EXTRA_PALETTE, ColorPickerDialog.ColorPalette.THEMES);
}}, REQUEST_THEME_PICKER);
return false;
});
Preference colorPreference = findPreference(getString(R.string.p_theme_color));
colorPreference.setSummary(themeColor.getName());
colorPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
startActivityForResult(new Intent(BasicPreferences.this, ColorPickerActivity.class) {{
putExtra(ColorPickerActivity.EXTRA_PALETTE, ColorPickerDialog.ColorPalette.COLORS);
}}, REQUEST_COLOR_PICKER);
return false;
}
colorPreference.setOnPreferenceClickListener(preference -> {
startActivityForResult(new Intent(BasicPreferences.this, ColorPickerActivity.class) {{
putExtra(ColorPickerActivity.EXTRA_PALETTE, ColorPickerDialog.ColorPalette.COLORS);
}}, REQUEST_COLOR_PICKER);
return false;
});
Preference accentPreference = findPreference(getString(R.string.p_theme_accent));
accentPreference.setSummary(themeAccent.getName());
accentPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
startActivityForResult(new Intent(BasicPreferences.this, ColorPickerActivity.class) {{
putExtra(ColorPickerActivity.EXTRA_PALETTE, ColorPickerDialog.ColorPalette.ACCENTS);
}}, REQUEST_ACCENT_PICKER);
return false;
}
accentPreference.setOnPreferenceClickListener(preference -> {
startActivityForResult(new Intent(BasicPreferences.this, ColorPickerActivity.class) {{
putExtra(ColorPickerActivity.EXTRA_PALETTE, ColorPickerDialog.ColorPalette.ACCENTS);
}}, REQUEST_ACCENT_PICKER);
return false;
});
Preference languagePreference = findPreference(getString(R.string.p_language));
updateLocale();
languagePreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
newLocalePickerDialog()
.show(getFragmentManager(), FRAG_TAG_LOCALE_PICKER);
return false;
}
languagePreference.setOnPreferenceClickListener(preference -> {
newLocalePickerDialog()
.show(getFragmentManager(), FRAG_TAG_LOCALE_PICKER);
return false;
});
findPreference(getString(R.string.p_layout_direction)).setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
tracker.reportEvent(Tracking.Events.SET_PREFERENCE, R.string.p_layout_direction, o.toString());
int newValue = Integer.parseInt((String) o);
if (locale.getDirectionality() != locale.withDirectionality(newValue).getDirectionality()) {
showRestartDialog();
}
return true;
findPreference(getString(R.string.p_layout_direction)).setOnPreferenceChangeListener((preference, o) -> {
tracker.reportEvent(Tracking.Events.SET_PREFERENCE, R.string.p_layout_direction, o.toString());
int newValue = Integer.parseInt((String) o);
if (locale.getDirectionality() != locale.withDirectionality(newValue).getDirectionality()) {
showRestartDialog();
}
return true;
});
findPreference(getString(R.string.p_collect_statistics)).setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (newValue != null) {
tracker.setTrackingEnabled((boolean) newValue);
return true;
}
return false;
findPreference(getString(R.string.p_collect_statistics)).setOnPreferenceChangeListener((preference, newValue) -> {
if (newValue != null) {
tracker.setTrackingEnabled((boolean) newValue);
return true;
}
return false;
});
getPref(R.string.TLA_menu_donate).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
if (BuildConfig.FLAVOR_store.equals("googleplay")) {
newDonationDialog().show(getFragmentManager(), FRAG_TAG_DONATION);
} else {
startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://tasks.org/donate")));
}
return false;
getPref(R.string.TLA_menu_donate).setOnPreferenceClickListener(preference -> {
if (BuildConfig.FLAVOR_store.equals("googleplay")) {
newDonationDialog().show(getFragmentManager(), FRAG_TAG_DONATION);
} else {
startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://tasks.org/donate")));
}
return false;
});
getPref(R.string.p_purchased_themes).setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (newValue != null && (boolean) newValue && !preferences.hasPurchase(R.string.p_purchased_themes)) {
purchaseHelper.purchase(dialogBuilder, BasicPreferences.this, getString(R.string.sku_themes), getString(R.string.p_purchased_themes), REQUEST_PURCHASE, BasicPreferences.this);
}
return false;
getPref(R.string.p_purchased_themes).setOnPreferenceChangeListener((preference, newValue) -> {
if (newValue != null && (boolean) newValue && !preferences.hasPurchase(R.string.p_purchased_themes)) {
purchaseHelper.purchase(dialogBuilder, BasicPreferences.this, getString(R.string.sku_themes), getString(R.string.p_purchased_themes), REQUEST_PURCHASE, BasicPreferences.this);
}
return false;
});
getPref(R.string.p_tesla_unread_enabled).setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (newValue != null) {
if ((boolean) newValue && !preferences.hasPurchase(R.string.p_purchased_tesla_unread)) {
purchaseHelper.purchase(dialogBuilder, BasicPreferences.this, getString(R.string.sku_tesla_unread), getString(R.string.p_purchased_tesla_unread), REQUEST_PURCHASE, BasicPreferences.this);
} else {
teslaUnreadReceiver.setEnabled((boolean) newValue);
return true;
}
getPref(R.string.p_tesla_unread_enabled).setOnPreferenceChangeListener((preference, newValue) -> {
if (newValue != null) {
if ((boolean) newValue && !preferences.hasPurchase(R.string.p_purchased_tesla_unread)) {
purchaseHelper.purchase(dialogBuilder, BasicPreferences.this, getString(R.string.sku_tesla_unread), getString(R.string.p_purchased_tesla_unread), REQUEST_PURCHASE, BasicPreferences.this);
} else {
teslaUnreadReceiver.setEnabled((boolean) newValue);
return true;
}
return false;
}
return false;
});
getPref(R.string.p_purchased_tasker).setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (newValue != null && (boolean) newValue && !preferences.hasPurchase(R.string.p_purchased_tasker)) {
purchaseHelper.purchase(dialogBuilder, BasicPreferences.this, getString(R.string.sku_tasker), getString(R.string.p_purchased_tasker), REQUEST_PURCHASE, BasicPreferences.this);
}
return false;
getPref(R.string.p_purchased_tasker).setOnPreferenceChangeListener((preference, newValue) -> {
if (newValue != null && (boolean) newValue && !preferences.hasPurchase(R.string.p_purchased_tasker)) {
purchaseHelper.purchase(dialogBuilder, BasicPreferences.this, getString(R.string.sku_tasker), getString(R.string.p_purchased_tasker), REQUEST_PURCHASE, BasicPreferences.this);
}
return false;
});
getPref(R.string.p_purchased_dashclock).setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (newValue != null && (boolean) newValue && !preferences.hasPurchase(R.string.p_purchased_dashclock)) {
purchaseHelper.purchase(dialogBuilder, BasicPreferences.this, getString(R.string.sku_dashclock), getString(R.string.p_purchased_dashclock), REQUEST_PURCHASE, BasicPreferences.this);
}
return false;
getPref(R.string.p_purchased_dashclock).setOnPreferenceChangeListener((preference, newValue) -> {
if (newValue != null && (boolean) newValue && !preferences.hasPurchase(R.string.p_purchased_dashclock)) {
purchaseHelper.purchase(dialogBuilder, BasicPreferences.this, getString(R.string.sku_dashclock), getString(R.string.p_purchased_dashclock), REQUEST_PURCHASE, BasicPreferences.this);
}
return false;
});
if (BuildConfig.DEBUG) {
addPreferencesFromResource(R.xml.preferences_debug);
findPreference(getString(R.string.debug_unlock_purchases)).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
preferences.setBoolean(R.string.p_purchased_dashclock, true);
preferences.setBoolean(R.string.p_purchased_tasker, true);
preferences.setBoolean(R.string.p_purchased_tesla_unread, true);
preferences.setBoolean(R.string.p_purchased_themes, true);
recreate();
return true;
}
findPreference(getString(R.string.debug_unlock_purchases)).setOnPreferenceClickListener(preference -> {
preferences.setBoolean(R.string.p_purchased_dashclock, true);
preferences.setBoolean(R.string.p_purchased_tasker, true);
preferences.setBoolean(R.string.p_purchased_tesla_unread, true);
preferences.setBoolean(R.string.p_purchased_themes, true);
recreate();
return true;
});
findPreference(getString(R.string.debug_consume_purchases)).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
purchaseHelper.consumePurchases();
recreate();
return true;
}
findPreference(getString(R.string.debug_consume_purchases)).setOnPreferenceClickListener(preference -> {
purchaseHelper.consumePurchases();
recreate();
return true;
});
}
@ -239,12 +200,9 @@ public class BasicPreferences extends InjectingPreferenceActivity implements
}
private void setupActivity(int key, final Class<?> target) {
findPreference(getString(key)).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
startActivityForResult(new Intent(BasicPreferences.this, target), RC_PREFS);
return true;
}
findPreference(getString(key)).setOnPreferenceClickListener(preference -> {
startActivityForResult(new Intent(BasicPreferences.this, target), RC_PREFS);
return true;
});
}
@ -310,14 +268,9 @@ public class BasicPreferences extends InjectingPreferenceActivity implements
private void showRestartDialog() {
dialogBuilder.newDialog()
.setMessage(R.string.restart_required)
.setPositiveButton(R.string.restart_now, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
ProcessPhoenix.triggerRebirth(BasicPreferences.this, new Intent(BasicPreferences.this, TaskListActivity.class) {{
putExtra(TaskListActivity.OPEN_FILTER, (Filter) null);
}});
}
})
.setPositiveButton(R.string.restart_now, (dialogInterface, i) -> ProcessPhoenix.triggerRebirth(BasicPreferences.this, new Intent(BasicPreferences.this, TaskListActivity.class) {{
putExtra(TaskListActivity.OPEN_FILTER, (Filter) null);
}}))
.setNegativeButton(R.string.restart_later, null)
.show();
}
@ -339,20 +292,17 @@ public class BasicPreferences extends InjectingPreferenceActivity implements
@Override
public void purchaseCompleted(final boolean success, final String sku) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (getString(R.string.sku_tasker).equals(sku)) {
((TwoStatePreference) getPref(R.string.p_purchased_tasker)).setChecked(success);
} else if (getString(R.string.sku_tesla_unread).equals(sku)) {
((TwoStatePreference) getPref(R.string.p_tesla_unread_enabled)).setChecked(success);
} else if (getString(R.string.sku_dashclock).equals(sku)) {
((TwoStatePreference) getPref(R.string.p_purchased_dashclock)).setChecked(success);
} else if (getString(R.string.sku_themes).equals(sku)) {
((TwoStatePreference) getPref(R.string.p_purchased_themes)).setChecked(success);
} else {
Timber.d("Unhandled sku: %s", sku);
}
runOnUiThread(() -> {
if (getString(R.string.sku_tasker).equals(sku)) {
((TwoStatePreference) getPref(R.string.p_purchased_tasker)).setChecked(success);
} else if (getString(R.string.sku_tesla_unread).equals(sku)) {
((TwoStatePreference) getPref(R.string.p_tesla_unread_enabled)).setChecked(success);
} else if (getString(R.string.sku_dashclock).equals(sku)) {
((TwoStatePreference) getPref(R.string.p_purchased_dashclock)).setChecked(success);
} else if (getString(R.string.sku_themes).equals(sku)) {
((TwoStatePreference) getPref(R.string.p_purchased_themes)).setChecked(success);
} else {
Timber.d("Unhandled sku: %s", sku);
}
});
}

@ -53,15 +53,12 @@ public class DateShortcutPreferences extends InjectingPreferenceActivity impleme
private void initializeTimePreference(final TimePreference preference, final int requestCode) {
preference.setOnPreferenceChangeListener(this);
preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference ignored) {
final DateTime current = new DateTime().withMillisOfDay(preference.getMillisOfDay());
startActivityForResult(new Intent(DateShortcutPreferences.this, TimePickerActivity.class) {{
putExtra(TimePickerActivity.EXTRA_TIMESTAMP, current.getMillis());
}}, requestCode);
return true;
}
preference.setOnPreferenceClickListener(ignored -> {
final DateTime current = new DateTime().withMillisOfDay(preference.getMillisOfDay());
startActivityForResult(new Intent(DateShortcutPreferences.this, TimePickerActivity.class) {{
putExtra(TimePickerActivity.EXTRA_TIMESTAMP, current.getMillis());
}}, requestCode);
return true;
});
}

@ -84,15 +84,12 @@ public class MiscellaneousPreferences extends InjectingPreferenceActivity {
}
private void initializeAttachmentDirectoryPreference() {
findPreference(getString(R.string.p_attachment_dir)).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference p) {
Intent filesDir = new Intent(MiscellaneousPreferences.this, FileExplore.class);
filesDir.putExtra(FileExplore.EXTRA_DIRECTORY_MODE, true);
filesDir.putExtra(FileExplore.EXTRA_START_PATH, getAttachmentDirectory());
startActivityForResult(filesDir, REQUEST_CODE_FILES_DIR);
return true;
}
findPreference(getString(R.string.p_attachment_dir)).setOnPreferenceClickListener(p -> {
Intent filesDir = new Intent(MiscellaneousPreferences.this, FileExplore.class);
filesDir.putExtra(FileExplore.EXTRA_DIRECTORY_MODE, true);
filesDir.putExtra(FileExplore.EXTRA_START_PATH, getAttachmentDirectory());
startActivityForResult(filesDir, REQUEST_CODE_FILES_DIR);
return true;
});
updateAttachmentDirectory();
}
@ -108,45 +105,39 @@ public class MiscellaneousPreferences extends InjectingPreferenceActivity {
private void initializeCalendarReminderPreference() {
CheckBoxPreference calendarReminderPreference = (CheckBoxPreference) findPreference(getString(R.string.p_calendar_reminders));
calendarReminderPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (newValue == null) {
return false;
}
if (!(Boolean) newValue) {
return true;
}
if (permissionRequestor.requestCalendarPermissions()) {
backgroundScheduler.scheduleCalendarNotifications();
return true;
}
calendarReminderPreference.setOnPreferenceChangeListener((preference, newValue) -> {
if (newValue == null) {
return false;
}
if (!(Boolean) newValue) {
return true;
}
if (permissionRequestor.requestCalendarPermissions()) {
backgroundScheduler.scheduleCalendarNotifications();
return true;
}
return false;
});
calendarReminderPreference.setChecked(calendarReminderPreference.isChecked() && permissionChecker.canAccessCalendars());
}
private void initializeVoiceReminderPreference() {
findPreference(getString(R.string.p_voiceRemindersEnabled)).setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
boolean enabled = (boolean) newValue;
try {
if (enabled && !voiceOutputAssistant.isTTSInitialized()) {
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, REQUEST_CODE_TTS_CHECK);
} else if (!enabled && voiceOutputAssistant.isTTSInitialized()) {
voiceOutputAssistant.shutdown();
}
} catch (VerifyError e) {
Timber.e(e, e.getMessage());
preference.setEnabled(false);
preferences.setBoolean(preference.getKey(), false);
findPreference(getString(R.string.p_voiceRemindersEnabled)).setOnPreferenceChangeListener((preference, newValue) -> {
boolean enabled = (boolean) newValue;
try {
if (enabled && !voiceOutputAssistant.isTTSInitialized()) {
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, REQUEST_CODE_TTS_CHECK);
} else if (!enabled && voiceOutputAssistant.isTTSInitialized()) {
voiceOutputAssistant.shutdown();
}
return true;
} catch (VerifyError e) {
Timber.e(e, e.getMessage());
preference.setEnabled(false);
preferences.setBoolean(preference.getKey(), false);
}
return true;
});
}

@ -35,15 +35,10 @@ public class ListNotificationReceiver extends InjectingBroadcastReceiver {
tracker.reportEvent(Tracking.Events.LEGACY_TASKER_TRIGGER);
executorService.execute(new Runnable() {
@Override
public void run() {
notifier.triggerFilterNotification(
intent.getStringExtra(EXTRA_FILTER_TITLE),
intent.getStringExtra(EXTRA_FILTER_QUERY),
intent.getStringExtra(EXTRA_FILTER_VALUES));
}
});
executorService.execute(() -> notifier.triggerFilterNotification(
intent.getStringExtra(EXTRA_FILTER_TITLE),
intent.getStringExtra(EXTRA_FILTER_QUERY),
intent.getStringExtra(EXTRA_FILTER_VALUES)));
}
@Override

@ -72,13 +72,10 @@ public class RepeatConfirmationReceiver extends BroadcastReceiver {
String dueDateString = getRelativeDateAndTimeString(activity, newDueDate);
String snackbarText = activity.getString(R.string.repeat_snackbar, task.getTitle(), dueDateString);
taskListFragment.makeSnackbar(snackbarText)
.setAction(R.string.DLG_undo, new View.OnClickListener() {
@Override
public void onClick(View v) {
task.setDueDateAdjustingHideUntil(oldDueDate);
task.setCompletionDate(0L);
taskService.save(task);
}
.setAction(R.string.DLG_undo, v -> {
task.setDueDateAdjustingHideUntil(oldDueDate);
task.setCompletionDate(0L);
taskService.save(task);
})
.show();
}

@ -25,14 +25,9 @@ public class TaskNotificationReceiver extends InjectingBroadcastReceiver {
public void onReceive(Context context, final Intent intent) {
super.onReceive(context, intent);
executorService.execute(new Runnable() {
@Override
public void run() {
notifier.triggerTaskNotification(
intent.getLongExtra(ID_KEY, 0),
intent.getIntExtra(EXTRAS_TYPE, (byte) 0));
}
});
executorService.execute(() -> notifier.triggerTaskNotification(
intent.getLongExtra(ID_KEY, 0),
intent.getIntExtra(EXTRAS_TYPE, (byte) 0)));
}
@Override

@ -49,20 +49,17 @@ public class MissedCallDialog extends InjectingDialogFragment {
return dialogBuilder.newDialog()
.setTitle(title)
.setItems(actions, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
handler.callNow();
break;
case 1:
handler.callLater();
break;
default:
handler.ignore();
break;
}
.setItems(actions, (dialog, which) -> {
switch (which) {
case 0:
handler.callNow();
break;
case 1:
handler.callLater();
break;
default:
handler.ignore();
break;
}
})
.show();

@ -50,20 +50,17 @@ public class NotificationDialog extends InjectingDialogFragment {
return dialogBuilder.newDialog()
.setTitle(title)
.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
handler.edit();
break;
case 1:
handler.snooze();
break;
case 2:
handler.complete();
break;
}
.setItems(items, (dialog, which) -> {
switch (which) {
case 0:
handler.edit();
break;
case 1:
handler.snooze();
break;
case 2:
handler.complete();
break;
}
})
.show();

@ -46,20 +46,17 @@ public class SnoozeDialog extends InjectingDialogFragment {
return dialogBuilder.newDialog()
.setTitle(R.string.rmd_NoA_snooze)
.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
case 1:
case 2:
snoozeCallback.snoozeForTime(snoozeOptions.get(which).getDateTime());
break;
case 3:
dialog.dismiss();
snoozeCallback.pickDateTime();
break;
}
.setItems(items, (dialog, which) -> {
switch (which) {
case 0:
case 1:
case 2:
snoozeCallback.snoozeForTime(snoozeOptions.get(which).getDateTime());
break;
case 3:
dialog.dismiss();
snoozeCallback.pickDateTime();
break;
}
})
.show();

@ -65,14 +65,11 @@ public class BackupIntentService extends MidnightIntentService {
}
private void deleteOldBackups() {
FileFilter backupFileFilter = new FileFilter() {
@Override
public boolean accept(File file) {
if (file.getName().matches(BACKUP_FILE_NAME_REGEX)) {
return true;
}
return false;
FileFilter backupFileFilter = file -> {
if (file.getName().matches(BACKUP_FILE_NAME_REGEX)) {
return true;
}
return false;
};
File astridDir = preferences.getBackupDirectory();
if(astridDir == null) {
@ -85,12 +82,7 @@ public class BackupIntentService extends MidnightIntentService {
return;
}
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(File file1, File file2) {
return -Long.valueOf(file1.lastModified()).compareTo(file2.lastModified());
}
});
Arrays.sort(files, (file1, file2) -> -Long.valueOf(file1.lastModified()).compareTo(file2.lastModified()));
for(int i = DAYS_TO_KEEP_BACKUP; i < files.length; i++) {
if(!files[i].delete()) {
Timber.i("Unable to delete: %s", files[i]);

@ -41,12 +41,7 @@ public class RefreshScheduler {
Criterion criterion = Criterion.or(
Criterion.and(Task.HIDE_UNTIL.gt(now), Task.HIDE_UNTIL.lt(midnight)),
Criterion.and(Task.DUE_DATE.gt(now), Task.DUE_DATE.lt(midnight)));
taskDao.selectActive(criterion, new Callback<Task>() {
@Override
public void apply(Task task) {
scheduleRefresh(task);
}
});
taskDao.selectActive(criterion, this::scheduleRefresh);
}
public void scheduleRefresh(Task task) {

@ -39,17 +39,14 @@ public class SyncExecutor {
}
private Runnable wrapWithExceptionHandling(final SyncResultCallback callback, final Runnable command) {
return new Runnable() {
@Override
public void run() {
try {
command.run();
} catch (Exception e) {
Timber.e(e, e.getMessage());
tracker.reportException(e);
executor.shutdownNow();
callback.finished();
}
return () -> {
try {
command.run();
} catch (Exception e) {
Timber.e(e, e.getMessage());
tracker.reportException(e);
executor.shutdownNow();
callback.finished();
}
};
}

@ -217,12 +217,9 @@ public class CalendarControlSet extends TaskEditControlFragment {
clear();
} else {
dialogBuilder.newMessageDialog(R.string.delete_calendar_event_confirmation)
.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (permissionRequestor.requestCalendarPermissions(REQUEST_CODE_CLEAR_EVENT)) {
clear();
}
.setPositiveButton(R.string.delete, (dialog, which) -> {
if (permissionRequestor.requestCalendarPermissions(REQUEST_CODE_CLEAR_EVENT)) {
clear();
}
})
.setNegativeButton(android.R.string.cancel, null)

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

Loading…
Cancel
Save