More context cleanup

pull/189/head
Alex Baker 12 years ago
parent 68c88c7295
commit 43139c5268

@ -1,128 +0,0 @@
/**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.astrid.sync;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import com.todoroo.andlib.service.ContextManager;
import com.todoroo.andlib.utility.DateUtilities;
/**
* Sync Provider Utility class for accessing preferences
*/
abstract public class SyncProviderUtilities {
/**
* @return your plugin identifier
*/
abstract public String getIdentifier();
/**
* @return key for sync interval
*/
abstract public int getSyncIntervalKey();
// --- implementation
protected static final String PREF_TOKEN = "_token"; //$NON-NLS-1$
protected static final String PREF_LAST_SYNC = "_last_sync"; //$NON-NLS-1$
protected static final String PREF_LAST_ATTEMPTED_SYNC = "_last_attempted"; //$NON-NLS-1$
protected static final String PREF_LAST_ERROR = "_last_err"; //$NON-NLS-1$
protected static final String PREF_LAST_ERROR_TYPE = "_last_err_type"; //$NON-NLS-1$
protected static final String PREF_ONGOING = "_ongoing"; //$NON-NLS-1$
/** Get preferences object from the context */
protected static SharedPreferences getPrefs() {
return PreferenceManager.getDefaultSharedPreferences(ContextManager.getContext());
}
/**
* @return true if we have a token for this user, false otherwise
*/
public boolean isLoggedIn() {
return getPrefs().getString(getIdentifier() + PREF_TOKEN, null) != null;
}
/** authentication token, or null if doesn't exist */
public String getToken() {
return getPrefs().getString(getIdentifier() + PREF_TOKEN, null);
}
/** Sets the authentication token. Set to null to clear. */
public void setToken(String setting) {
Editor editor = getPrefs().edit();
editor.putString(getIdentifier() + PREF_TOKEN, setting);
editor.commit();
}
/** @return Last Successful Sync Date, or 0 */
public long getLastSyncDate() {
return getPrefs().getLong(getIdentifier() + PREF_LAST_SYNC, 0);
}
/** @return Last Attempted Sync Date, or 0 if it was successful */
public long getLastAttemptedSyncDate() {
return getPrefs().getLong(getIdentifier() + PREF_LAST_ATTEMPTED_SYNC, 0);
}
/** @return Last Error, or null if no last error */
public String getLastError() {
return getPrefs().getString(getIdentifier() + PREF_LAST_ERROR, null);
}
/** @return Last Error, or null if no last error */
public boolean isOngoing() {
return getPrefs().getBoolean(getIdentifier() + PREF_ONGOING, false);
}
/** Deletes Last Successful Sync Date */
public void clearLastSyncDate() {
Editor editor = getPrefs().edit();
editor.remove(getIdentifier() + PREF_LAST_SYNC);
editor.commit();
}
/** Set Last Error */
public void setLastError(String error, String type) {
Editor editor = getPrefs().edit();
editor.putString(getIdentifier() + PREF_LAST_ERROR, error);
editor.putString(getIdentifier() + PREF_LAST_ERROR_TYPE, type);
editor.commit();
}
/** Set Ongoing */
public void stopOngoing() {
Editor editor = getPrefs().edit();
editor.putBoolean(getIdentifier() + PREF_ONGOING, false);
editor.commit();
}
/** Set Last Successful Sync Date */
public void recordSuccessfulSync() {
Editor editor = getPrefs().edit();
editor.putLong(getIdentifier() + PREF_LAST_SYNC, DateUtilities.now() + 1000);
editor.putLong(getIdentifier() + PREF_LAST_ATTEMPTED_SYNC, 0);
editor.commit();
}
/** Set Last Attempted Sync Date */
public void recordSyncStart() {
Editor editor = getPrefs().edit();
editor.putLong(getIdentifier() + PREF_LAST_ATTEMPTED_SYNC,
DateUtilities.now());
editor.remove(getIdentifier() + PREF_LAST_ERROR);
editor.remove(getIdentifier() + PREF_LAST_ERROR_TYPE);
editor.putBoolean(getIdentifier() + PREF_ONGOING, true);
editor.commit();
}
}

@ -3,6 +3,7 @@
*/ */
package com.todoroo.astrid.activity; package com.todoroo.astrid.activity;
import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
@ -13,7 +14,7 @@ import com.todoroo.astrid.service.TaskService;
import com.todoroo.astrid.tags.TagService; import com.todoroo.astrid.tags.TagService;
import com.todoroo.astrid.ui.QuickAddBar; import com.todoroo.astrid.ui.QuickAddBar;
import org.tasks.preferences.Preferences; import org.tasks.injection.ForApplication;
import javax.inject.Inject; import javax.inject.Inject;
@ -28,6 +29,7 @@ public final class ShareLinkActivity extends TaskListActivity {
@Inject TagService tagService; @Inject TagService tagService;
@Inject MetadataService metadataService; @Inject MetadataService metadataService;
@Inject GCalHelper gcalHelper; @Inject GCalHelper gcalHelper;
@Inject @ForApplication Context context;
private String subject; private String subject;
private boolean handled; private boolean handled;
@ -52,7 +54,7 @@ public final class ShareLinkActivity extends TaskListActivity {
if (!handled) { if (!handled) {
Intent callerIntent = getIntent(); Intent callerIntent = getIntent();
Task task = QuickAddBar.basicQuickAddTask(gcalHelper, taskService, metadataService, tagService, subject); Task task = QuickAddBar.basicQuickAddTask(context, gcalHelper, taskService, metadataService, tagService, subject);
if (task != null) { if (task != null) {
task.setNotes(callerIntent.getStringExtra(Intent.EXTRA_TEXT)); task.setNotes(callerIntent.getStringExtra(Intent.EXTRA_TEXT));
taskService.save(task); taskService.save(task);

@ -10,7 +10,6 @@ import android.content.ComponentName;
import android.content.ContentValues; import android.content.ContentValues;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle; import android.os.Bundle;
import com.todoroo.andlib.data.AbstractModel; import com.todoroo.andlib.data.AbstractModel;
@ -70,7 +69,7 @@ public class GtasksFilterExposer extends InjectingBroadcastReceiver implements A
GtasksMetadata.LIST_ID.eq(list.getValue(GtasksList.REMOTE_ID)))).orderBy( GtasksMetadata.LIST_ID.eq(list.getValue(GtasksList.REMOTE_ID)))).orderBy(
Order.asc(Functions.cast(GtasksMetadata.ORDER, "LONG"))), //$NON-NLS-1$ Order.asc(Functions.cast(GtasksMetadata.ORDER, "LONG"))), //$NON-NLS-1$
values); values);
filter.customTaskList = new ComponentName(ContextManager.getContext(), GtasksListFragment.class); filter.customTaskList = new ComponentName(context, GtasksListFragment.class);
Bundle extras = new Bundle(); Bundle extras = new Bundle();
extras.putLong(GtasksListFragment.TOKEN_STORE_ID, list.getId()); extras.putLong(GtasksListFragment.TOKEN_STORE_ID, list.getId());
filter.customExtras = extras; filter.customExtras = extras;

@ -22,13 +22,14 @@ import javax.inject.Singleton;
@Singleton @Singleton
public class GtasksPreferenceService extends SyncProviderUtilities { public class GtasksPreferenceService extends SyncProviderUtilities {
/** add-on identifier */
public static final String IDENTIFIER = "gtasks"; //$NON-NLS-1$ public static final String IDENTIFIER = "gtasks"; //$NON-NLS-1$
private final Preferences preferences;
private static final String PREF_DEFAULT_LIST = IDENTIFIER + "_defaultlist"; //$NON-NLS-1$
private static final String PREF_USER_NAME = IDENTIFIER + "_user"; //$NON-NLS-1$
@Inject @Inject
public GtasksPreferenceService(Preferences preferences) { public GtasksPreferenceService(Preferences preferences) {
this.preferences = preferences; super(preferences);
} }
@Override @Override
@ -56,10 +57,4 @@ public class GtasksPreferenceService extends SyncProviderUtilities {
public void setUserName(String userName) { public void setUserName(String userName) {
preferences.setString(PREF_USER_NAME, userName); preferences.setString(PREF_USER_NAME, userName);
} }
/** GTasks user's default list id */
private static final String PREF_DEFAULT_LIST = IDENTIFIER + "_defaultlist"; //$NON-NLS-1$
/** GTasks user name */
public static final String PREF_USER_NAME = IDENTIFIER + "_user"; //$NON-NLS-1$
} }

@ -20,7 +20,6 @@ import com.todoroo.astrid.gtasks.api.GoogleTasksException;
import com.todoroo.astrid.gtasks.api.GtasksInvoker; import com.todoroo.astrid.gtasks.api.GtasksInvoker;
import org.tasks.R; import org.tasks.R;
import org.tasks.preferences.Preferences;
import java.io.IOException; import java.io.IOException;
@ -33,10 +32,10 @@ public class GtasksTokenValidator {
private static final String TOKEN_INTENT_RECEIVED = "intent!"; //$NON-NLS-1$ private static final String TOKEN_INTENT_RECEIVED = "intent!"; //$NON-NLS-1$
private static final int REVALIDATION_TRIES = 4; private static final int REVALIDATION_TRIES = 4;
private final Preferences preferences; private final GtasksPreferenceService preferences;
@Inject @Inject
public GtasksTokenValidator(Preferences preferences) { public GtasksTokenValidator(GtasksPreferenceService preferences) {
this.preferences = preferences; this.preferences = preferences;
} }
@ -53,7 +52,7 @@ public class GtasksTokenValidator {
} }
// If fail, token may have expired -- get a new one and return that // If fail, token may have expired -- get a new one and return that
String accountName = preferences.getStringValue(GtasksPreferenceService.PREF_USER_NAME); String accountName = preferences.getUserName();
Account a = accountManager.getAccountByName(accountName); Account a = accountManager.getAccountByName(accountName);
if (a == null) { if (a == null) {
throw new GoogleTasksException(c.getString(R.string.gtasks_error_accountNotFound, accountName), "account-not-found"); throw new GoogleTasksException(c.getString(R.string.gtasks_error_accountNotFound, accountName), "account-not-found");

@ -126,10 +126,8 @@ public class GtasksSyncV2Provider extends SyncV2Provider {
final GtasksInvoker invoker = new GtasksInvoker(gtasksTokenValidator, authToken); final GtasksInvoker invoker = new GtasksInvoker(gtasksTokenValidator, authToken);
try { try {
gtasksListService.updateLists(invoker.allGtaskLists()); gtasksListService.updateLists(invoker.allGtaskLists());
} catch (GoogleTasksException e) {
handler.handleException("gtasks-sync=io", e, e.getType()); //$NON-NLS-1$
} catch (IOException e) { } catch (IOException e) {
handler.handleException("gtasks-sync=io", e, e.toString()); //$NON-NLS-1$ handler.handleException("gtasks-sync=io", e); //$NON-NLS-1$
} }
StoreObject[] lists = gtasksListService.getLists(); StoreObject[] lists = gtasksListService.getLists();
@ -173,10 +171,8 @@ public class GtasksSyncV2Provider extends SyncV2Provider {
task.readFromCursor(queued); task.readFromCursor(queued);
try { try {
gtasksSyncService.pushTaskOnSave(task, task.getMergedValues(), invoker); gtasksSyncService.pushTaskOnSave(task, task.getMergedValues(), invoker);
} catch (GoogleTasksException e) {
handler.handleException("gtasks-sync-io", e, e.getType()); //$NON-NLS-1$
} catch (IOException e) { } catch (IOException e) {
handler.handleException("gtasks-sync-io", e, e.toString()); //$NON-NLS-1$ handler.handleException("gtasks-sync-io", e); //$NON-NLS-1$
} }
} }
} finally { } finally {
@ -286,13 +282,9 @@ public class GtasksSyncV2Provider extends SyncV2Provider {
gtasksTaskListUpdater.correctOrderAndIndentForList(listId); gtasksTaskListUpdater.correctOrderAndIndentForList(listId);
} }
} catch (GoogleTasksException e) {
if (errorHandler != null) {
errorHandler.handleException("gtasks-sync-io", e, e.getType()); //$NON-NLS-1$
}
} catch (IOException e) { } catch (IOException e) {
if (errorHandler != null) { if (errorHandler != null) {
errorHandler.handleException("gtasks-sync-io", e, e.toString()); //$NON-NLS-1$ errorHandler.handleException("gtasks-sync-io", e); //$NON-NLS-1$
} }
} }
} }

@ -32,7 +32,6 @@ import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener; import android.widget.TextView.OnEditorActionListener;
import com.todoroo.andlib.data.TodorooCursor; import com.todoroo.andlib.data.TodorooCursor;
import com.todoroo.andlib.service.ContextManager;
import com.todoroo.andlib.sql.Query; import com.todoroo.andlib.sql.Query;
import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.andlib.utility.DateUtilities;
import com.todoroo.astrid.actfm.ActFmCameraModule; import com.todoroo.astrid.actfm.ActFmCameraModule;
@ -145,7 +144,7 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene
try { try {
fetchTask(t); fetchTask(t);
} catch (SQLiteException e) { } catch (SQLiteException e) {
StartupService.handleSQLiteError(ContextManager.getContext(), e); StartupService.handleSQLiteError(fragment.getActivity(), e);
} }
if(task == null) { if(task == null) {
return; return;

@ -105,19 +105,19 @@ public class StartupService {
private static boolean hasStartedUp = false; private static boolean hasStartedUp = false;
/** Called when this application is started up */ /** Called when this application is started up */
public synchronized void onStartupApplication(final Activity context) { public synchronized void onStartupApplication(final Activity activity) {
if(hasStartedUp || context == null) { if(hasStartedUp || activity == null) {
return; return;
} }
// sets up context manager // sets up activity manager
ContextManager.setContext(context); ContextManager.setContext(activity);
database.addListener(new AbstractDatabase.DatabaseUpdateListener() { database.addListener(new AbstractDatabase.DatabaseUpdateListener() {
@Override @Override
public void onDatabaseUpdated() { public void onDatabaseUpdated() {
Astrid2TaskProvider.notifyDatabaseModification(context); Astrid2TaskProvider.notifyDatabaseModification(activity);
Astrid3ContentProvider.notifyDatabaseModification(context); Astrid3ContentProvider.notifyDatabaseModification(activity);
} }
}); });
@ -125,19 +125,16 @@ public class StartupService {
database.openForWriting(); database.openForWriting();
checkForMissingColumns(); checkForMissingColumns();
} catch (SQLiteException e) { } catch (SQLiteException e) {
handleSQLiteError(context, e); handleSQLiteError(activity, e);
return; return;
} }
// show notification if reminders are silenced // show notification if reminders are silenced
if(context instanceof Activity) { AudioManager audioManager = (AudioManager)activity.getSystemService( Context.AUDIO_SERVICE);
AudioManager audioManager = (AudioManager)context.getSystemService(
Context.AUDIO_SERVICE);
if(!preferences.getBoolean(R.string.p_rmd_enabled, true)) { if(!preferences.getBoolean(R.string.p_rmd_enabled, true)) {
Toast.makeText(context, R.string.TLA_notification_disabled, Toast.LENGTH_LONG).show(); Toast.makeText(activity, R.string.TLA_notification_disabled, Toast.LENGTH_LONG).show();
} else if(audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) == 0) { } else if(audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) == 0) {
Toast.makeText(context, R.string.TLA_notification_volume_low, Toast.LENGTH_LONG).show(); Toast.makeText(activity, R.string.TLA_notification_volume_low, Toast.LENGTH_LONG).show();
}
} }
// read current version // read current version
@ -151,7 +148,7 @@ public class StartupService {
int version = 0; int version = 0;
String versionName = "0"; //$NON-NLS-1$ String versionName = "0"; //$NON-NLS-1$
try { try {
PackageManager pm = context.getPackageManager(); PackageManager pm = activity.getPackageManager();
PackageInfo pi = pm.getPackageInfo(Constants.PACKAGE, PackageManager.GET_META_DATA); PackageInfo pi = pm.getPackageInfo(Constants.PACKAGE, PackageManager.GET_META_DATA);
version = pi.versionCode; version = pi.versionCode;
versionName = pi.versionName; versionName = pi.versionName;
@ -162,13 +159,13 @@ public class StartupService {
Log.i("astrid", "Astrid Startup. " + latestSetVersion + //$NON-NLS-1$ //$NON-NLS-2$ Log.i("astrid", "Astrid Startup. " + latestSetVersion + //$NON-NLS-1$ //$NON-NLS-2$
" => " + version); //$NON-NLS-1$ " => " + version); //$NON-NLS-1$
databaseRestoreIfEmpty(context); databaseRestoreIfEmpty(activity);
// invoke upgrade service // invoke upgrade service
boolean justUpgraded = latestSetVersion != version; boolean justUpgraded = latestSetVersion != version;
if(justUpgraded && version > 0) { if(justUpgraded && version > 0) {
if(latestSetVersion > 0) { if(latestSetVersion > 0) {
upgradeService.performUpgrade(context, latestSetVersion); upgradeService.performUpgrade(activity, latestSetVersion);
} }
preferences.setCurrentVersion(version); preferences.setCurrentVersion(version);
preferences.setCurrentVersionName(versionName); preferences.setCurrentVersionName(versionName);
@ -188,23 +185,23 @@ public class StartupService {
gtasksPreferenceService.stopOngoing(); gtasksPreferenceService.stopOngoing();
// perform initialization // perform initialization
ReminderStartupReceiver.startReminderSchedulingService(context); ReminderStartupReceiver.startReminderSchedulingService(activity);
BackupService.scheduleService(preferences, context); BackupService.scheduleService(preferences, activity);
gtasksSyncService.initialize(); gtasksSyncService.initialize();
// get and display update messages // get and display update messages
if (finalLatestVersion != 0) { if (finalLatestVersion != 0) {
// new UpdateMessageService(context).processUpdates(); // new UpdateMessageService(activity).processUpdates();
} }
} }
}).start(); }).start();
preferences.setDefaults(); preferences.setDefaults();
calendarAlarmScheduler.scheduleCalendarAlarms(context, false); // This needs to be after set preference defaults for the purposes of ab testing calendarAlarmScheduler.scheduleCalendarAlarms(activity, false); // This needs to be after set preference defaults for the purposes of ab testing
showTaskKillerHelp(context); showTaskKillerHelp(activity);
hasStartedUp = true; hasStartedUp = true;
} }
@ -228,13 +225,9 @@ public class StartupService {
}); });
} }
public static void handleSQLiteError(Context context, final SQLiteException e) { public static void handleSQLiteError(Activity activity, final SQLiteException e) {
if (context instanceof Activity) { log.error(e.getMessage(), e);
Activity activity = (Activity) context; DialogUtilities.okDialog(activity, activity.getString(R.string.DB_corrupted_title), 0, activity.getString(R.string.DB_corrupted_body));
DialogUtilities.okDialog(activity, activity.getString(R.string.DB_corrupted_title),
0, activity.getString(R.string.DB_corrupted_body));
}
e.printStackTrace();
} }
private void checkForMissingColumns() { private void checkForMissingColumns() {

@ -5,10 +5,14 @@
*/ */
package com.todoroo.astrid.service; package com.todoroo.astrid.service;
import android.content.Context;
import com.todoroo.astrid.gtasks.sync.GtasksSyncV2Provider; import com.todoroo.astrid.gtasks.sync.GtasksSyncV2Provider;
import com.todoroo.astrid.sync.SyncResultCallback; import com.todoroo.astrid.sync.SyncResultCallback;
import com.todoroo.astrid.sync.SyncV2Provider; import com.todoroo.astrid.sync.SyncV2Provider;
import org.tasks.injection.ForApplication;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@ -32,9 +36,11 @@ public class SyncV2Service {
* for responding to sync requests through this new API. * for responding to sync requests through this new API.
*/ */
private final SyncV2Provider[] providers; private final SyncV2Provider[] providers;
private final Context context;
@Inject @Inject
public SyncV2Service(GtasksSyncV2Provider gtasksSyncV2Provider) { public SyncV2Service(@ForApplication Context context, GtasksSyncV2Provider gtasksSyncV2Provider) {
this.context = context;
providers = new SyncV2Provider[] { providers = new SyncV2Provider[] {
gtasksSyncV2Provider gtasksSyncV2Provider
}; };
@ -68,9 +74,9 @@ public class SyncV2Service {
} }
if (active.size() > 1) { // This should never happen anymore--they can't be active at the same time, but if for some reason they both are, just use ActFm if (active.size() > 1) { // This should never happen anymore--they can't be active at the same time, but if for some reason they both are, just use ActFm
active.get(1).synchronizeActiveTasks(manual, new WidgetUpdatingCallbackWrapper(callback)); active.get(1).synchronizeActiveTasks(manual, new WidgetUpdatingCallbackWrapper(context, callback));
} else if (active.size() == 1) { } else if (active.size() == 1) {
active.get(0).synchronizeActiveTasks(manual, new WidgetUpdatingCallbackWrapper(callback)); active.get(0).synchronizeActiveTasks(manual, new WidgetUpdatingCallbackWrapper(context, callback));
} }
return true; return true;
@ -86,7 +92,7 @@ public class SyncV2Service {
public void synchronizeList(Object list, boolean manual, SyncResultCallback callback) { public void synchronizeList(Object list, boolean manual, SyncResultCallback callback) {
for(SyncV2Provider provider : providers) { for(SyncV2Provider provider : providers) {
if(provider.isActive()) { if(provider.isActive()) {
provider.synchronizeList(list, manual, new WidgetUpdatingCallbackWrapper(callback)); provider.synchronizeList(list, manual, new WidgetUpdatingCallbackWrapper(context, callback));
} }
} }
} }

@ -1,15 +1,18 @@
package com.todoroo.astrid.service; package com.todoroo.astrid.service;
import com.todoroo.andlib.service.ContextManager; import android.content.Context;
import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.andlib.utility.DateUtilities;
import com.todoroo.astrid.sync.SyncResultCallback; import com.todoroo.astrid.sync.SyncResultCallback;
import com.todoroo.astrid.widget.TasksWidget; import com.todoroo.astrid.widget.TasksWidget;
public class WidgetUpdatingCallbackWrapper implements SyncResultCallback { public class WidgetUpdatingCallbackWrapper implements SyncResultCallback {
private final Context context;
private SyncResultCallback wrap; private SyncResultCallback wrap;
public WidgetUpdatingCallbackWrapper(SyncResultCallback wrap) { public WidgetUpdatingCallbackWrapper(Context context, SyncResultCallback wrap) {
this.context = context;
this.wrap = wrap; this.wrap = wrap;
} }
@ -23,6 +26,6 @@ public class WidgetUpdatingCallbackWrapper implements SyncResultCallback {
public void finished() { public void finished() {
wrap.finished(); wrap.finished();
TasksWidget.suppressUpdateFlag = 0L; TasksWidget.suppressUpdateFlag = 0L;
TasksWidget.updateWidgets(ContextManager.getContext()); TasksWidget.updateWidgets(context);
} }
} }

@ -0,0 +1,109 @@
/**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.astrid.sync;
import com.todoroo.andlib.utility.DateUtilities;
import org.tasks.preferences.Preferences;
/**
* Sync Provider Utility class for accessing preferences
*/
abstract public class SyncProviderUtilities {
protected final Preferences preferences;
public SyncProviderUtilities(Preferences preferences) {
this.preferences = preferences;
}
/**
* @return your plugin identifier
*/
abstract public String getIdentifier();
/**
* @return key for sync interval
*/
abstract public int getSyncIntervalKey();
// --- implementation
protected static final String PREF_TOKEN = "_token"; //$NON-NLS-1$
protected static final String PREF_LAST_SYNC = "_last_sync"; //$NON-NLS-1$
protected static final String PREF_LAST_ATTEMPTED_SYNC = "_last_attempted"; //$NON-NLS-1$
protected static final String PREF_LAST_ERROR = "_last_err"; //$NON-NLS-1$
protected static final String PREF_ONGOING = "_ongoing"; //$NON-NLS-1$
/**
* @return true if we have a token for this user, false otherwise
*/
public boolean isLoggedIn() {
return preferences.getStringValue(getIdentifier() + PREF_TOKEN) != null;
}
/** authentication token, or null if doesn't exist */
public String getToken() {
return preferences.getStringValue(getIdentifier() + PREF_TOKEN);
}
/** Sets the authentication token. Set to null to clear. */
public void setToken(String setting) {
preferences.setString(getIdentifier() + PREF_TOKEN, setting);
}
/** @return Last Successful Sync Date, or 0 */
public long getLastSyncDate() {
return preferences.getLong(getIdentifier() + PREF_LAST_SYNC, 0);
}
/** @return Last Attempted Sync Date, or 0 if it was successful */
public long getLastAttemptedSyncDate() {
return preferences.getLong(getIdentifier() + PREF_LAST_ATTEMPTED_SYNC, 0);
}
/** @return Last Error, or null if no last error */
public String getLastError() {
return preferences.getStringValue(getIdentifier() + PREF_LAST_ERROR);
}
/** @return Last Error, or null if no last error */
public boolean isOngoing() {
return preferences.getBoolean(getIdentifier() + PREF_ONGOING, false);
}
/** Deletes Last Successful Sync Date */
public void clearLastSyncDate() {
preferences.clear(getIdentifier() + PREF_LAST_SYNC);
}
/** Set Last Error */
public void setLastError(String error) {
preferences.setString(getIdentifier() + PREF_LAST_ERROR, error);
}
/** Set Ongoing */
public void stopOngoing() {
preferences.setBoolean(getIdentifier() + PREF_ONGOING, false);
}
/** Set Last Successful Sync Date */
public void recordSuccessfulSync() {
preferences.setLong(getIdentifier() + PREF_LAST_SYNC, DateUtilities.now() + 1000);
preferences.setLong(getIdentifier() + PREF_LAST_ATTEMPTED_SYNC, 0);
}
/** Set Last Attempted Sync Date */
public void recordSyncStart() {
preferences.setLong(getIdentifier() + PREF_LAST_ATTEMPTED_SYNC, DateUtilities.now());
preferences.clear(getIdentifier() + PREF_LAST_ERROR);
preferences.setBoolean(getIdentifier() + PREF_ONGOING, true);
}
}

@ -14,8 +14,8 @@ abstract public class SyncV2Provider {
private static final Logger log = LoggerFactory.getLogger(SyncV2Provider.class); private static final Logger log = LoggerFactory.getLogger(SyncV2Provider.class);
public class SyncExceptionHandler { public class SyncExceptionHandler {
public void handleException(String tag, Exception e, String type) { public void handleException(String tag, Exception e) {
getUtilities().setLastError(e.toString(), type); getUtilities().setLastError(e.toString());
log.error("{}: {}", tag, e.getMessage(), e); log.error("{}: {}", tag, e.getMessage(), e);
} }
} }

@ -24,7 +24,6 @@ import android.widget.LinearLayout;
import android.widget.TextView; import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener; import android.widget.TextView.OnEditorActionListener;
import com.todoroo.andlib.service.ContextManager;
import com.todoroo.andlib.utility.DialogUtilities; import com.todoroo.andlib.utility.DialogUtilities;
import com.todoroo.astrid.activity.AstridActivity; import com.todoroo.astrid.activity.AstridActivity;
import com.todoroo.astrid.activity.TaskEditFragment; import com.todoroo.astrid.activity.TaskEditFragment;
@ -46,6 +45,7 @@ import com.todoroo.astrid.voice.VoiceRecognizer;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.tasks.R; import org.tasks.R;
import org.tasks.injection.ForApplication;
import org.tasks.injection.Injector; import org.tasks.injection.Injector;
import org.tasks.preferences.ActivityPreferences; import org.tasks.preferences.ActivityPreferences;
@ -79,6 +79,7 @@ public class QuickAddBar extends LinearLayout {
@Inject GCalHelper gcalHelper; @Inject GCalHelper gcalHelper;
@Inject ActivityPreferences preferences; @Inject ActivityPreferences preferences;
@Inject DateChangedAlerts dateChangedAlerts; @Inject DateChangedAlerts dateChangedAlerts;
@Inject @ForApplication Context context;
private VoiceRecognizer voiceRecognizer; private VoiceRecognizer voiceRecognizer;
@ -283,7 +284,7 @@ public class QuickAddBar extends LinearLayout {
resetControlSets(); resetControlSets();
addToCalendar(gcalHelper, taskService, task, title); addToCalendar(context, gcalHelper, taskService, task, title);
TextView quickAdd = (TextView) findViewById(R.id.quickAddText); TextView quickAdd = (TextView) findViewById(R.id.quickAddText);
quickAdd.setText(""); //$NON-NLS-1$ quickAdd.setText(""); //$NON-NLS-1$
@ -307,13 +308,13 @@ public class QuickAddBar extends LinearLayout {
} }
} }
private static void addToCalendar(GCalHelper gcalHelper, TaskService taskService, Task task, String title) { private static void addToCalendar(Context context, GCalHelper gcalHelper, TaskService taskService, Task task, String title) {
boolean gcalCreateEventEnabled = gcalHelper.getDefaultCalendar() != null boolean gcalCreateEventEnabled = gcalHelper.getDefaultCalendar() != null
&& !gcalHelper.getDefaultCalendar().equals("-1") && task.hasDueDate(); //$NON-NLS-1$ && !gcalHelper.getDefaultCalendar().equals("-1") && task.hasDueDate(); //$NON-NLS-1$
if (!TextUtils.isEmpty(title) && gcalCreateEventEnabled && TextUtils.isEmpty(task.getCalendarURI())) { if (!TextUtils.isEmpty(title) && gcalCreateEventEnabled && TextUtils.isEmpty(task.getCalendarURI())) {
Uri calendarUri = gcalHelper.createTaskEvent(task, Uri calendarUri = gcalHelper.createTaskEvent(task,
ContextManager.getContext().getContentResolver(), new ContentValues()); context.getContentResolver(), new ContentValues());
task.setCalendarUri(calendarUri.toString()); task.setCalendarUri(calendarUri.toString());
task.putTransitory(SyncFlags.GTASKS_SUPPRESS_SYNC, true); task.putTransitory(SyncFlags.GTASKS_SUPPRESS_SYNC, true);
taskService.save(task); taskService.save(task);
@ -324,7 +325,7 @@ public class QuickAddBar extends LinearLayout {
* Static method to quickly add tasks without all the control set nonsense. * Static method to quickly add tasks without all the control set nonsense.
* Used from the share link activity. * Used from the share link activity.
*/ */
public static Task basicQuickAddTask(GCalHelper gcalHelper, TaskService taskService, MetadataService metadataService, TagService tagService, String title) { public static Task basicQuickAddTask(Context context, GCalHelper gcalHelper, TaskService taskService, MetadataService metadataService, TagService tagService, String title) {
if (TextUtils.isEmpty(title)) { if (TextUtils.isEmpty(title)) {
return null; return null;
} }
@ -332,7 +333,7 @@ public class QuickAddBar extends LinearLayout {
title = title.trim(); title = title.trim();
Task task = TaskService.createWithValues(taskService, metadataService, tagService, null, title); Task task = TaskService.createWithValues(taskService, metadataService, tagService, null, title);
addToCalendar(gcalHelper, taskService, task, title); addToCalendar(context, gcalHelper, taskService, task, title);
return task; return task;
} }

@ -11,6 +11,7 @@ import com.todoroo.astrid.service.TaskService;
import com.todoroo.astrid.tags.TagService; import com.todoroo.astrid.tags.TagService;
import org.tasks.R; import org.tasks.R;
import org.tasks.injection.ForApplication;
import org.tasks.injection.InjectingActivity; import org.tasks.injection.InjectingActivity;
import javax.inject.Inject; import javax.inject.Inject;
@ -23,6 +24,7 @@ public class VoiceCommandActivity extends InjectingActivity {
@Inject MetadataService metadataService; @Inject MetadataService metadataService;
@Inject TagService tagService; @Inject TagService tagService;
@Inject TaskService taskService; @Inject TaskService taskService;
@Inject @ForApplication Context context;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
@ -33,7 +35,7 @@ public class VoiceCommandActivity extends InjectingActivity {
switch (intent.getAction()) { switch (intent.getAction()) {
case "com.google.android.gm.action.AUTO_SEND": case "com.google.android.gm.action.AUTO_SEND":
final String text = intent.getStringExtra(Intent.EXTRA_TEXT); final String text = intent.getStringExtra(Intent.EXTRA_TEXT);
basicQuickAddTask(gcalHelper, taskService, metadataService, tagService, text); basicQuickAddTask(context, gcalHelper, taskService, metadataService, tagService, text);
Context context = getApplicationContext(); Context context = getApplicationContext();
if (context != null) { if (context != null) {
Toast.makeText(context, getString(R.string.voice_command_added_task), Toast.LENGTH_LONG).show(); Toast.makeText(context, getString(R.string.voice_command_added_task), Toast.LENGTH_LONG).show();

Loading…
Cancel
Save