code
stringlengths
3
1.18M
language
stringclasses
1 value
package org.dodgybits.shuffle.android.synchronisation.tracks; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryTracksSyncCompletedEvent; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryTracksSyncError; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryTracksSyncStartedEvent; import java.util.LinkedList; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.android.core.model.Task; import org.dodgybits.shuffle.android.core.model.persistence.ContextPersister; import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister; import org.dodgybits.shuffle.android.core.model.persistence.ProjectPersister; import org.dodgybits.shuffle.android.core.model.persistence.TaskPersister; import org.dodgybits.shuffle.android.preference.model.Preferences; import org.dodgybits.shuffle.android.preference.view.Progress; import roboguice.inject.ContentResolverProvider; import android.content.ContentResolver; import android.content.Context; import android.content.ContextWrapper; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; /** * This task synchronizes shuffle with a tracks service. * * @author Morten Nielsen */ public class TracksSynchronizer extends AsyncTask<String, Progress, Void> { private static final String cTag = "TracksSynchronizer"; private static TracksSynchronizer synchronizer; private static LinkedList<SyncProgressListener> progressListeners = new LinkedList<SyncProgressListener>(); private final Context mContext; private final LinkedList<Integer> mMessages; private final ContextSynchronizer mContextSynchronizer; private final ProjectSynchronizer mProjectSynchronizer; private final TaskSynchronizer mTaskSynchronizer; private Analytics mAnalytics; // TODO inject sync classes (BIG job) public static TracksSynchronizer getActiveSynchronizer( ContextWrapper context, Analytics analytics) throws ApiException { TracksSynchronizer synchronizer = getSingletonSynchronizer(context, analytics); while (synchronizer.getStatus() == Status.FINISHED) { synchronizer = getSingletonSynchronizer(context, analytics); } return synchronizer; } private static TracksSynchronizer getSingletonSynchronizer(Context context, Analytics analytics) throws ApiException { if (synchronizer == null || synchronizer.getStatus() == Status.FINISHED) { synchronizer = new TracksSynchronizer( context, analytics, new WebClient(context, Preferences.getTracksUser(context), Preferences.getTracksPassword(context), Preferences.isTracksSelfSignedCert(context)), Preferences.getTracksUrl(context) ); } return synchronizer; } private TracksSynchronizer( Context context, Analytics analytics, WebClient client, String tracksUrl) { mContext = context; //TODO inject this ContentResolverProvider provider = new ContentResolverProvider() { @Override public ContentResolver get() { return mContext.getContentResolver(); } }; mAnalytics = analytics; EntityPersister<Task> taskPersister = new TaskPersister(provider, analytics); EntityPersister<org.dodgybits.shuffle.android.core.model.Context> contextPersister = new ContextPersister(provider, analytics); EntityPersister<Project> projectPersister = new ProjectPersister(provider, analytics); mContextSynchronizer = new ContextSynchronizer(contextPersister, this, client, context, mAnalytics, 0, tracksUrl); mProjectSynchronizer = new ProjectSynchronizer(projectPersister, this, client, context, mAnalytics, 33, tracksUrl); mTaskSynchronizer = new TaskSynchronizer(taskPersister, this, client, context, mAnalytics, 66, tracksUrl); mMessages = new LinkedList<Integer>(); } @Override protected void onProgressUpdate(Progress... progresses) { for (SyncProgressListener listener : progressListeners) { listener.progressUpdate(progresses[0]); } } public void registerListener(SyncProgressListener listener) { if (!progressListeners.contains(listener)) progressListeners.add(listener); } public void unRegisterListener(SyncProgressListener listener) { progressListeners.remove(listener); } @Override protected Void doInBackground(String... strings) { try { mAnalytics.onEvent(cFlurryTracksSyncStartedEvent); mContextSynchronizer.synchronize(); mProjectSynchronizer.synchronize(); mTaskSynchronizer.synchronize(); publishProgress(Progress.createProgress(100, "Synchronization Complete")); mAnalytics.onEvent(cFlurryTracksSyncCompletedEvent); } catch (ApiException e) { Log.w(cTag, "Tracks call failed", e); publishProgress(Progress.createErrorProgress(mContext.getString(R.string.web_error_message))); mAnalytics.onError(cFlurryTracksSyncError, e.getMessage(), getClass().getName()); } catch (Exception e) { Log.w(cTag, "Synch failed", e); publishProgress(Progress.createErrorProgress(mContext.getString(R.string.error_message))); mAnalytics.onError(cFlurryTracksSyncError, e.getMessage(), getClass().getName()); } return null; } @Override protected void onPostExecute(Void result) { if (mMessages.size() > 0) { for (Integer textId : mMessages) { Toast toast = Toast.makeText(mContext.getApplicationContext(), textId , Toast.LENGTH_SHORT); toast.show(); } } try { synchronizer = getSingletonSynchronizer(mContext, mAnalytics); } catch (ApiException ignored) { } } public void reportProgress(Progress progress) { publishProgress(progress); } public void postSyncMessage(int toastMessage) { mMessages.add(toastMessage); } }
Java
package org.dodgybits.shuffle.android.synchronisation.tracks; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.dodgybits.shuffle.android.core.model.EntityBuilder; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister; import org.dodgybits.shuffle.android.persistence.provider.ContextProvider; import org.dodgybits.shuffle.android.persistence.provider.ProjectProvider; import org.dodgybits.shuffle.android.preference.view.Progress; import org.dodgybits.shuffle.android.synchronisation.tracks.ApiException; import org.dodgybits.shuffle.android.synchronisation.tracks.model.TracksEntity; import org.dodgybits.shuffle.android.synchronisation.tracks.parsing.IContextLookup; import org.dodgybits.shuffle.android.synchronisation.tracks.parsing.IProjectLookup; import org.dodgybits.shuffle.android.synchronisation.tracks.parsing.Parser; import android.database.Cursor; import android.net.Uri; import android.provider.BaseColumns; import android.text.TextUtils; import android.util.Log; /** * Base class for handling synchronization, template method object. * * @author Morten Nielsen */ public abstract class Synchronizer<Entity extends TracksEntity> implements IProjectLookup,IContextLookup { private static final String cTag = "Synchronizer"; protected EntityPersister<Entity> mPersister; protected WebClient mWebClient; protected android.content.Context mContext; protected final TracksSynchronizer mTracksSynchronizer; private int mBasePercent; public Synchronizer( EntityPersister<Entity> persister, TracksSynchronizer tracksSynchronizer, WebClient client, android.content.Context context, int basePercent) { mPersister = persister; mTracksSynchronizer = tracksSynchronizer; mWebClient = client; mContext = context; mBasePercent = basePercent; } public void synchronize() throws ApiException { mTracksSynchronizer.reportProgress(Progress.createProgress(mBasePercent, readingLocalText())); Map<Id, Entity> localEntities = getShuffleEntities(); verifyEntitiesForSynchronization(localEntities); mTracksSynchronizer.reportProgress(Progress.createProgress(mBasePercent, readingRemoteText())); TracksEntities<Entity> tracksEntities = getTrackEntities(); mergeAlreadySynchronizedEntities(localEntities, tracksEntities); addNewEntitiesToShuffle(tracksEntities); mTracksSynchronizer.reportProgress(Progress.createProgress( mBasePercent + 33, stageFinishedText())); } private void mergeAlreadySynchronizedEntities( Map<Id, Entity> localEntities, TracksEntities<Entity> tracksEntities) { int startCounter = localEntities.size() + 1; int count = 0; for (Entity localEntity : localEntities.values()) { count++; mTracksSynchronizer.reportProgress(Progress.createProgress(calculatePercent(startCounter, count), processingText())); mergeSingle(tracksEntities, localEntity); } } private int calculatePercent(int startCounter, int count) { int percent = mBasePercent + Math.round(((count * 100) / startCounter) * 0.33f); return percent; } private void addNewEntitiesToShuffle(TracksEntities<Entity> tracksEntities) { for (Entity remoteEntity : tracksEntities.getEntities().values()) { insertEntity(remoteEntity); } } public Id findProjectIdByTracksId(Id tracksId) { return findEntityLocalIdByTracksId(tracksId, ProjectProvider.Projects.CONTENT_URI); } public Id findContextIdByTracksId(Id tracksId) { return findEntityLocalIdByTracksId(tracksId, ContextProvider.Contexts.CONTENT_URI); } protected Id findTracksIdByProjectId(Id projectId) { return findEntityTracksIdByLocalId(projectId, ProjectProvider.Projects.CONTENT_URI); } protected Id findTracksIdByContextId(Id contextId) { return findEntityTracksIdByLocalId(contextId, ContextProvider.Contexts.CONTENT_URI); } protected abstract void verifyEntitiesForSynchronization(Map<Id, Entity> localEntities); protected abstract String readingRemoteText(); protected abstract String processingText(); protected abstract String readingLocalText(); protected abstract String stageFinishedText(); protected abstract String entityIndexUrl(); protected abstract Entity createMergedLocalEntity(Entity localEntity, Entity newEntity); protected abstract String createEntityUrl(Entity localEntity); protected abstract String createDocumentForEntity(Entity localEntity); protected abstract EntityBuilder<Entity> createBuilder(); private TracksEntities<Entity> getTrackEntities() throws ApiException { String tracksEntityXml; try { WebResult result = mWebClient.getUrlContent(entityIndexUrl()); StatusLine status = result.getStatus(); if(status.getStatusCode() == HttpStatus.SC_OK) tracksEntityXml = result.getContent(); else throw new ApiException("Invalid response from server: " + status.toString()); } catch (ApiException e) { Log.w(cTag, e); throw e; } return getEntityParser().parseDocument(tracksEntityXml); } protected abstract Parser<Entity> getEntityParser(); private Id findEntityLocalIdByTracksId(Id tracksId, Uri contentUri) { Id id = Id.NONE; Cursor cursor = mContext.getContentResolver().query( contentUri, new String[] { BaseColumns._ID}, "tracks_id = ?", new String[] {tracksId.toString()}, null); if (cursor.moveToFirst()) { id = Id.create(cursor.getLong(0)); } cursor.close(); return id; } private Id findEntityTracksIdByLocalId(Id localId, Uri contentUri) { Id id = Id.NONE; Cursor cursor = mContext.getContentResolver().query( contentUri, new String[] { "tracks_id" }, BaseColumns._ID + " = ?", new String[] {localId.toString()}, null); if (cursor.moveToFirst()) { id = Id.create(cursor.getLong(0)); } cursor.close(); return id; } private void insertEntity(Entity entity) { mPersister.insert(entity); } private void updateEntity(Entity entity) { mPersister.update(entity); } protected boolean deleteEntity(Entity entity) { return mPersister.updateDeletedFlag(entity.getLocalId(), true); } private Entity findEntityByLocalName(Collection<Entity> remoteEntities, Entity localEntity) { Entity foundEntity = null; for (Entity entity : remoteEntities) if (entity.getLocalName().equals(localEntity.getLocalName())) { foundEntity = entity; } return foundEntity; } private void mergeSingle(TracksEntities<Entity> tracksEntities, Entity localEntity) { final Map<Id, Entity> remoteEntities = tracksEntities.getEntities(); if (!localEntity.getTracksId().isInitialised()) { handleLocalEntityNotYetInTracks(localEntity, remoteEntities); return; } Entity remoteEntity = remoteEntities.get(localEntity.getTracksId()); if (remoteEntity != null) { mergeLocalAndRemoteEntityBasedOnModifiedDate(localEntity, remoteEntity); remoteEntities.remove(remoteEntity.getTracksId()); } else if (tracksEntities.isErrorFree()){ // only delete entities if we didn't encounter errors parsing deleteEntity(localEntity); } } private void handleLocalEntityNotYetInTracks(Entity localEntity, final Map<Id, Entity> remoteEntities) { Entity newEntity = findEntityByLocalName(remoteEntities.values(), localEntity); if (newEntity != null) { remoteEntities.remove(newEntity.getTracksId()); } else { newEntity = createEntityInTracks(localEntity); } if (newEntity != null) { updateEntity(createMergedLocalEntity(localEntity, newEntity)); } } private void mergeLocalAndRemoteEntityBasedOnModifiedDate(Entity localEntity, Entity remoteEntity) { final long remoteModified = remoteEntity.getModifiedDate(); final long localModified = localEntity.getModifiedDate(); if (remoteModified == localModified && remoteEntity.isDeleted() == localEntity.isDeleted()) return; if (remoteModified >= localModified) { updateEntity(createMergedLocalEntity(localEntity, remoteEntity)); } else { updateTracks(localEntity); } } private void updateTracks(Entity localEntity) { String document = createDocumentForEntity(localEntity); try { mWebClient.putContentToUrl(createEntityUrl(localEntity), document); } catch (ApiException e) { Log.w(cTag, "Failed to update entity in tracks " + localEntity + ":" + e.getMessage(), e); } } private Entity createEntityInTracks(Entity entity) { String document = createDocumentForEntity(entity); try { String location = mWebClient.postContentToUrl(entityIndexUrl(), document); if (!TextUtils.isEmpty(location.trim())) { Id id = parseIdFromLocation(location); EntityBuilder<Entity> builder = createBuilder(); builder.mergeFrom(entity); builder.setTracksId(id); entity = builder.build(); } } catch (ApiException e) { Log.w(cTag, "Failed to create entity in tracks " + entity + ":" + e.getMessage(), e); } return entity; } private Id parseIdFromLocation(String location) { String[] parts = location.split("/"); String document = parts[parts.length - 1]; long id = Long.parseLong( document ); return Id.create(id); } private Map<Id, Entity> getShuffleEntities() { Map<Id, Entity> list = new HashMap<Id, Entity>(); Cursor cursor = mContext.getContentResolver().query( mPersister.getContentUri(), mPersister.getFullProjection(), null, null, null); while (cursor.moveToNext()) { Entity entity = mPersister.read(cursor); list.put(entity.getLocalId(), entity); } cursor.close(); return list; } }
Java
package org.dodgybits.shuffle.android.synchronisation.tracks.parsing; public class ParseResult<T> { private boolean mSuccess; private T mResult; public ParseResult(T result, boolean success) { mSuccess = success; mResult = result; } public ParseResult() { mSuccess = false; mResult = null; } public T getResult() { return mResult; } public boolean isSuccess(){ return mSuccess; } }
Java
package org.dodgybits.shuffle.android.synchronisation.tracks.parsing; public interface Applier { boolean apply(String value); }
Java
package org.dodgybits.shuffle.android.synchronisation.tracks.parsing; import java.text.ParseException; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; import org.dodgybits.shuffle.android.core.model.EntityBuilder; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.android.core.model.Project.Builder; import org.dodgybits.shuffle.android.core.util.DateUtils; import android.text.TextUtils; import android.util.Log; public class ProjectParser extends Parser<Project> { private Builder specificBuilder; private IContextLookup mContextLookup; public ProjectParser(IContextLookup contextLookup, Analytics analytics) { super("project", analytics); mContextLookup = contextLookup; appliers.put("name", new Applier(){ @Override public boolean apply(String value) { specificBuilder.setName(value); return true; } }); appliers.put("state", new Applier(){ @Override public boolean apply(String value) { String v = value.toLowerCase(); Log.d("projectparser",v); if(v.equals("completed")) { // ignore completed for now? // specificBuilder.setDeleted(true); return true; } if(v.equals("hidden")) { specificBuilder.setActive(false); return true; } if(v.equals("active")) { specificBuilder.setActive(true); return true; } return false; } }); appliers.put("id", new Applier(){ @Override public boolean apply(String value) { Id tracksId = Id.create(Long.parseLong(value)); specificBuilder.setTracksId(tracksId); return true; } }); appliers.put("updated-at", new Applier(){ @Override public boolean apply(String value) { long date; try { date = DateUtils.parseIso8601Date(value); specificBuilder.setModifiedDate(date); return true; } catch (ParseException e) { return false; } } }); appliers.put("default-context-id", new Applier(){ @Override public boolean apply(String value) { if (!TextUtils.isEmpty(value)) { Id tracksId = Id.create(Long.parseLong(value)); Id defaultContextId = mContextLookup.findContextIdByTracksId(tracksId); if (defaultContextId.isInitialised()) { specificBuilder.setDefaultContextId(defaultContextId); } } return true; } }); } @Override protected EntityBuilder<Project> createBuilder() { return specificBuilder = Project.newBuilder(); } }
Java
package org.dodgybits.shuffle.android.synchronisation.tracks.parsing; import java.text.ParseException; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; import org.dodgybits.shuffle.android.core.model.EntityBuilder; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Task; import org.dodgybits.shuffle.android.core.model.Task.Builder; import org.dodgybits.shuffle.android.core.util.DateUtils; import android.text.TextUtils; import roboguice.util.Ln; public class TaskParser extends Parser<Task> { private Builder specificBuilder; protected IContextLookup mContextLookup; protected IProjectLookup mProjectLookup; public TaskParser(IContextLookup contextLookup, IProjectLookup projectLookup, Analytics analytics) { super("todo", analytics); mContextLookup = contextLookup; mProjectLookup = projectLookup; appliers.put("state", new Applier() { @Override public boolean apply(String value) { Ln.d("Got status %s", value); if( value.equals("completed")) { specificBuilder.setComplete(true); } return true; } }); appliers.put("description", new Applier(){ @Override public boolean apply(String value) { specificBuilder.setDescription(value); return true; } }); appliers.put("notes", new Applier(){ @Override public boolean apply(String value) { specificBuilder.setDetails(value); return true; } }); appliers.put("id", new Applier(){ @Override public boolean apply(String value) { Id tracksId = Id.create(Long.parseLong(value)); specificBuilder.setTracksId(tracksId); return true; } }); appliers.put("updated-at", new Applier(){ @Override public boolean apply(String value) { long date; try { date = DateUtils.parseIso8601Date(value); specificBuilder.setModifiedDate(date); return true; } catch (ParseException e) { return false; } } }); appliers.put("context-id", new Applier(){ @Override public boolean apply(String value) { if (!TextUtils.isEmpty(value)) { Id tracksId = Id.create(Long.parseLong(value)); Id context = mContextLookup.findContextIdByTracksId(tracksId); if (context.isInitialised()) { specificBuilder.setContextId(context); } } return true; } }); appliers.put("project-id", new Applier(){ @Override public boolean apply(String value) { if (!TextUtils.isEmpty(value)) { Id tracksId = Id.create(Long.parseLong(value)); Id project = mProjectLookup.findProjectIdByTracksId(tracksId); if (project.isInitialised()) { specificBuilder.setProjectId(project); } } return true; } }); appliers.put("created-at", new Applier(){ @Override public boolean apply(String value) { if (!TextUtils.isEmpty(value)) { try { long created = DateUtils.parseIso8601Date(value); specificBuilder.setCreatedDate(created); } catch (ParseException e) { // TODO Auto-generated catch block return false; } } return true; } }); appliers.put("due", new Applier(){ @Override public boolean apply(String value) { if (!TextUtils.isEmpty(value)) { try { long due = DateUtils.parseIso8601Date(value); specificBuilder.setDueDate(due); } catch (ParseException e) { // TODO Auto-generated catch block return false; } } return true; } }); appliers.put("show-from", new Applier(){ @Override public boolean apply(String value) { if (!TextUtils.isEmpty(value)) { try { long showFrom = DateUtils.parseIso8601Date(value); specificBuilder.setStartDate(showFrom); } catch (ParseException e) { // TODO Auto-generated catch block return false; } } return true; } }); } @Override protected EntityBuilder<Task> createBuilder() { return specificBuilder = Task.newBuilder(); } }
Java
package org.dodgybits.shuffle.android.synchronisation.tracks.parsing; import java.text.ParseException; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.EntityBuilder; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Context.Builder; import org.dodgybits.shuffle.android.core.util.DateUtils; public class ContextParser extends Parser<Context> { private Builder specificBuilder; public ContextParser(Analytics analytics) { super("context", analytics); appliers.put("name", new Applier(){ @Override public boolean apply(String value) { specificBuilder.setName(value); return true; } }); appliers.put("hide", new Applier(){ @Override public boolean apply(String value) { boolean v = Boolean.parseBoolean(value); specificBuilder.setActive(!v); return true; } }); appliers.put("id", new Applier(){ @Override public boolean apply(String value) { Id tracksId = Id.create(Long.parseLong(value)); specificBuilder.setTracksId(tracksId); return true; } }); appliers.put("updated-at", new Applier(){ @Override public boolean apply(String value) { long date; try { date = DateUtils.parseIso8601Date(value); specificBuilder.setModifiedDate(date); return true; } catch (ParseException e) { return false; } } }); } @Override protected EntityBuilder<Context> createBuilder() { return specificBuilder = Context.newBuilder(); } }
Java
package org.dodgybits.shuffle.android.synchronisation.tracks.parsing; import org.dodgybits.shuffle.android.core.model.Id; public interface IProjectLookup { Id findProjectIdByTracksId(Id tracksId); }
Java
package org.dodgybits.shuffle.android.synchronisation.tracks.parsing; import org.dodgybits.shuffle.android.core.model.Id; public interface IContextLookup { Id findContextIdByTracksId(Id tracksId); }
Java
package org.dodgybits.shuffle.android.synchronisation.tracks.parsing; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryTracksSyncError; import java.io.IOException; import java.io.StringReader; import java.util.HashMap; import java.util.Map; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; import org.dodgybits.shuffle.android.core.model.EntityBuilder; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.synchronisation.tracks.TracksEntities; import org.dodgybits.shuffle.android.synchronisation.tracks.model.TracksEntity; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.util.Log; import android.util.Xml; public abstract class Parser<E extends TracksEntity> { private static final String cTag = "Parser"; protected HashMap<String, Applier> appliers; private String mEntityName; private Analytics mAnalytics; public Parser(String entityName, Analytics analytics) { appliers = new HashMap<String, Applier>(); mEntityName = entityName; mAnalytics = analytics; } public TracksEntities<E> parseDocument(String tracksEntityXml) { Map<Id, E> entities = new HashMap<Id, E>(); boolean errorFree = true; XmlPullParser parser = Xml.newPullParser(); try { parser.setInput(new StringReader(tracksEntityXml)); int eventType = parser.getEventType(); boolean done = false; while (eventType != XmlPullParser.END_DOCUMENT && !done) { ParseResult<E> result = null; try { result = parseSingle(parser); } catch (Exception e) { logTracksError(e); errorFree = false; } if(!result.isSuccess()) { errorFree = false; } E entity = result.getResult(); if (entity != null && entity.isValid()) { entities.put(entity.getTracksId(), entity); } eventType = parser.getEventType(); String name = parser.getName(); if (eventType == XmlPullParser.END_TAG && name.equalsIgnoreCase(endIndexTag())) { done = true; } } } catch (XmlPullParserException e) { logTracksError(e); errorFree = false; } return new TracksEntities<E>(entities, errorFree); } private void logTracksError(Exception e) { Log.e(cTag, "Failed to parse " + endIndexTag() + " " + e.getMessage()); mAnalytics.onError(cFlurryTracksSyncError, e.getMessage(), getClass().getName()); } private String endIndexTag() { return this.mEntityName + "s"; } public ParseResult<E> parseSingle(XmlPullParser parser) { EntityBuilder<E> builder = createBuilder(); E entity = null; boolean success = true; try { int eventType = parser.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT && entity == null) { String name = parser.getName(); switch (eventType) { case XmlPullParser.START_DOCUMENT: break; case XmlPullParser.START_TAG: Applier applier = appliers.get(name); if(applier != null) { success &= applier.apply(parser.nextText()); } break; case XmlPullParser.END_TAG: if (name.equalsIgnoreCase(mEntityName)) { entity = builder.build(); } break; } eventType = parser.next(); } } catch (IOException e) { Log.d("Exception", "IO EXception", e); return new ParseResult<E>(); } catch (XmlPullParserException e) { Log.d("Exception", "pullparser exception", e); return new ParseResult<E>(); } return new ParseResult<E>(entity, success); } protected abstract EntityBuilder<E> createBuilder(); }
Java
package org.dodgybits.shuffle.android.synchronisation.tracks.model; import org.dodgybits.shuffle.android.core.model.Entity; import org.dodgybits.shuffle.android.core.model.Id; public interface TracksEntity extends Entity { Id getTracksId(); }
Java
package org.dodgybits.shuffle.android.synchronisation.tracks.activity; import javax.annotation.Nullable; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity; import org.dodgybits.shuffle.android.preference.model.Preferences; import org.dodgybits.shuffle.android.preference.view.Progress; import org.dodgybits.shuffle.android.synchronisation.tracks.ApiException; import org.dodgybits.shuffle.android.synchronisation.tracks.SyncProgressListener; import org.dodgybits.shuffle.android.synchronisation.tracks.TracksSynchronizer; import roboguice.inject.InjectView; import android.os.AsyncTask; import android.os.Bundle; import android.widget.ProgressBar; import android.widget.TextView; import com.google.inject.Inject; /** * Activity to handle synchronization * * @author Morten Nielsen */ public class SynchronizeActivity extends FlurryEnabledActivity implements SyncProgressListener { private TracksSynchronizer synchronizer = null; @InjectView(R.id.info_text) @Nullable TextView mInfo; @InjectView(R.id.progress_horizontal) @Nullable ProgressBar mProgress; @Inject Analytics mAnalytics; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.synchronize); setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); super.onCreate(savedInstanceState); TextView url = (TextView) findViewById(R.id.syncUrl); TextView user = (TextView) findViewById(R.id.syncUser); url.setText(Preferences.getTracksUrl(this)); user.setText(Preferences.getTracksUser(this)); } @Override public void onResume() { super.onResume(); try { synchronizer = TracksSynchronizer.getActiveSynchronizer(this, mAnalytics); } catch (ApiException ignored) { } if (synchronizer != null) { synchronizer.registerListener(this); if (synchronizer.getStatus() != AsyncTask.Status.RUNNING) { synchronizer.execute(); } } } @Override public void onPause() { super.onPause(); if (synchronizer != null) { synchronizer.unRegisterListener(this); } } @Override public void progressUpdate(Progress progress) { if (mInfo != null) { mInfo.setText(progress.getDetails()); } if (mProgress != null) { mProgress.setProgress(progress.getProgressPercent()); } } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.dodgybits.shuffle.android.synchronisation.gae; import android.content.Context; import android.content.Intent; import android.media.AudioManager; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.Bundle; /** * Display a message as a notification, with an accompanying sound. */ public class MessageDisplay { private MessageDisplay() { } /* * App-specific methods for the sample application - 1) parse the incoming * message; 2) generate a notification; 3) play a sound */ public static void displayMessage(Context context, Intent intent) { Bundle extras = intent.getExtras(); if (extras != null) { String sender = (String) extras.get("sender"); String message = (String) extras.get("message"); Util.generateNotification(context, "Message from " + sender + ": " + message); playNotificationSound(context); } } private static void playNotificationSound(Context context) { Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); if (uri != null) { Ringtone rt = RingtoneManager.getRingtone(context, uri); if (rt != null) { rt.setStreamType(AudioManager.STREAM_NOTIFICATION); rt.play(); } } } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.dodgybits.shuffle.android.synchronisation.gae; import com.google.web.bindery.requestfactory.shared.RequestTransport; import com.google.web.bindery.requestfactory.shared.ServerFailure; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; /** * An implementation of RequestTransport for use between an Android client and a * Google AppEngine server. */ public class AndroidRequestTransport implements RequestTransport { private final URI uri; private final String cookie; /** * Constructs an AndroidRequestTransport instance. * * @param uri the URI for the RequestFactory service * @param cookie the ACSID or SACSID cookie used for authentication */ public AndroidRequestTransport(URI uri, String cookie) { this.uri = uri; this.cookie = cookie; } public void send(String payload, TransportReceiver receiver) { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(); post.setHeader("Content-Type", "application/json;charset=UTF-8"); post.setHeader("Cookie", cookie); post.setURI(uri); Throwable ex; try { post.setEntity(new StringEntity(payload, "UTF-8")); HttpResponse response = client.execute(post); if (200 == response.getStatusLine().getStatusCode()) { String contents = readStreamAsString(response.getEntity().getContent()); receiver.onTransportSuccess(contents); } else { receiver.onTransportFailure(new ServerFailure(response.getStatusLine() .getReasonPhrase())); } return; } catch (UnsupportedEncodingException e) { ex = e; } catch (ClientProtocolException e) { ex = e; } catch (IOException e) { ex = e; } receiver.onTransportFailure(new ServerFailure(ex.getMessage())); } /** * Reads an entire input stream as a String. Closes the input stream. */ private String readStreamAsString(InputStream in) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(1024); byte[] buffer = new byte[1024]; int count; do { count = in.read(buffer); if (count > 0) { out.write(buffer, 0, count); } } while (count >= 0); return out.toString("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("The JVM does not support the compiler's default encoding.", e); } catch (IOException e) { return null; } finally { try { in.close(); } catch (IOException ignored) { } } } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.dodgybits.shuffle.android.synchronisation.gae; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.preference.model.Preferences; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.res.AssetManager; import android.util.Log; import com.google.web.bindery.event.shared.SimpleEventBus; import com.google.web.bindery.requestfactory.shared.RequestFactory; import com.google.web.bindery.requestfactory.vm.RequestFactorySource; /** * Utility methods for getting the base URL for client-server communication. */ public class Util { /** * Tag for logging. */ private static final String TAG = "Util"; /* * URL suffix for the RequestFactory servlet. */ public static final String RF_METHOD = "/gwtRequest"; /** * An intent name for receiving registration/unregistration status. */ public static final String UPDATE_UI_INTENT = "org.dodgybits.android.shuffle.UPDATE_UI"; // End shared constants /** * Cache containing the base URL for a given context. */ private static final Map<Context, String> URL_MAP = new HashMap<Context, String>(); /** * Display a notification containing the given string. */ public static void generateNotification(Context context, String message) { int icon = R.drawable.status_icon; long when = System.currentTimeMillis(); Notification notification = new Notification(icon, message, when); notification.setLatestEventInfo(context, "C2DM Example", message, PendingIntent.getActivity(context, 0, null, PendingIntent.FLAG_CANCEL_CURRENT)); notification.flags |= Notification.FLAG_AUTO_CANCEL; int notificatonID = Preferences.getNotificationId(context); NotificationManager nm = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); nm.notify(notificatonID, notification); Preferences.incrementNotificationId(context); } /** * Returns the (debug or production) URL associated with the registration * service. */ public static String getBaseUrl(Context context) { String url = URL_MAP.get(context); if (url == null) { // if a debug_url raw resource exists, use its contents as the url url = getDebugUrl(context); // otherwise, use the production url if (url == null) { url = Setup.PROD_URL; } URL_MAP.put(context, url); } return url; } /** * Creates and returns an initialized {@link RequestFactory} of the given * type. */ public static <T extends RequestFactory> T getRequestFactory(Context context, Class<T> factoryClass) { T requestFactory = RequestFactorySource.create(factoryClass); String authCookie = Preferences.getGoogleAuthCookie(context); String uriString = Util.getBaseUrl(context) + RF_METHOD; URI uri; try { uri = new URI(uriString); } catch (URISyntaxException e) { Log.w(TAG, "Bad URI: " + uriString, e); return null; } requestFactory.initialize(new SimpleEventBus(), new AndroidRequestTransport(uri, authCookie)); return requestFactory; } /** * Returns true if we are running against a dev mode appengine instance. */ public static boolean isDebug(Context context) { // Although this is a bit roundabout, it has the nice side effect // of caching the result. return !Setup.PROD_URL.equals(getBaseUrl(context)); } /** * Returns a debug url, or null. To set the url, create a file * {@code assets/debugging_prefs.properties} with a line of the form * 'url=http:/<ip address>:<port>'. A numeric IP address may be required in * situations where the device or emulator will not be able to resolve the * hostname for the dev mode server. */ private static String getDebugUrl(Context context) { BufferedReader reader = null; String url = null; try { AssetManager assetManager = context.getAssets(); InputStream is = assetManager.open("debugging_prefs.properties"); reader = new BufferedReader(new InputStreamReader(is)); while (true) { String s = reader.readLine(); if (s == null) { break; } if (s.startsWith("url=")) { url = s.substring(4).trim(); break; } } } catch (FileNotFoundException e) { // O.K., we will use the production server return null; } catch (Exception e) { Log.w(TAG, "Got exception " + e); Log.w(TAG, Log.getStackTraceString(e)); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { Log.w(TAG, "Got exception " + e); Log.w(TAG, Log.getStackTraceString(e)); } } } return url; } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.dodgybits.shuffle.android.synchronisation.gae; import java.io.IOException; import org.dodgybits.shuffle.android.preference.model.Preferences; import android.content.Context; import android.content.Intent; import com.google.android.c2dm.C2DMBaseReceiver; /** * Receive a push message from the Cloud to Device Messaging (C2DM) service. * This class should be modified to include functionality specific to your * application. This class must have a no-arg constructor and pass the sender id * to the superclass constructor. */ public class C2DMReceiver extends C2DMBaseReceiver { public C2DMReceiver() { super(Setup.SENDER_ID); } /** * Called when a registration token has been received. * * @param context the Context * @param registrationId the registration id as a String * @throws IOException if registration cannot be performed */ @Override public void onRegistered(Context context, String registration) { DeviceRegistrar.registerOrUnregister(context, registration, true); } /** * Called when the device has been unregistered. * * @param context the Context */ @Override public void onUnregistered(Context context) { String deviceRegistrationID = Preferences.getGooglDeviceRegistrationId(context); DeviceRegistrar.registerOrUnregister(context, deviceRegistrationID, false); } /** * Called on registration error. This is called in the context of a Service * - no dialog or UI. * * @param context the Context * @param errorId an error message, defined in {@link C2DMBaseReceiver} */ @Override public void onError(Context context, String errorId) { context.sendBroadcast(new Intent(Util.UPDATE_UI_INTENT)); } /** * Called when a cloud message has been received. */ @Override public void onMessage(Context context, Intent intent) { /* * Replace this with your application-specific code */ MessageDisplay.displayMessage(context, intent); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.dodgybits.shuffle.android.synchronisation.gae; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.params.HttpClientParams; import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.preference.model.Preferences; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AccountManagerCallback; import android.accounts.AccountManagerFuture; import android.accounts.AuthenticatorException; import android.accounts.OperationCanceledException; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.provider.Settings; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import com.google.android.c2dm.C2DMessaging; /** * Account selections activity - handles device registration and unregistration. */ public class AccountsActivity extends Activity { /** * Tag for logging. */ private static final String TAG = "AccountsActivity"; /** * Cookie name for authorization. */ private static final String AUTH_COOKIE_NAME = "SACSID"; /** * The selected position in the ListView of accounts. */ private int mAccountSelectedPosition = 0; /** * True if we are waiting for App Engine authorization. */ private boolean mPendingAuth = false; /** * The current context. */ private Context mContext = this; /** * Begins the activity. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setScreenContent(); } @Override public boolean onOptionsItemSelected(MenuItem item) { setScreenContent(); return true; } /** * Resumes the activity. */ @Override protected void onResume() { super.onResume(); if (mPendingAuth) { mPendingAuth = false; String regId = C2DMessaging.getRegistrationId(mContext); if (regId != null && !"".equals(regId)) { DeviceRegistrar.registerOrUnregister(mContext, regId, true); } else { C2DMessaging.register(mContext, Setup.SENDER_ID); } } } // Manage UI Screens /** * Sets up the 'connect' screen content. */ private void setConnectScreenContent() { List<String> accounts = getGoogleAccounts(); if (accounts.size() == 0) { // Show a dialog and invoke the "Add Account" activity if requested AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setMessage(R.string.needs_account); builder.setPositiveButton(R.string.add_account, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { startActivity(new Intent(Settings.ACTION_ADD_ACCOUNT)); } }); builder.setNegativeButton(R.string.skip, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); builder.setIcon(android.R.drawable.stat_sys_warning); builder.setTitle(R.string.attention); builder.show(); } else { final ListView listView = (ListView) findViewById(R.id.select_account); listView.setAdapter(new ArrayAdapter<String>(mContext, R.layout.account, accounts)); listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); listView.setItemChecked(mAccountSelectedPosition, true); final Button connectButton = (Button) findViewById(R.id.connect); connectButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { // Register in the background and terminate the activity mAccountSelectedPosition = listView.getCheckedItemPosition(); TextView account = (TextView) listView.getChildAt(mAccountSelectedPosition); register((String) account.getText()); finish(); } }); final Button exitButton = (Button) findViewById(R.id.exit); exitButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { finish(); } }); } } /** * Sets up the 'disconnected' screen. */ private void setDisconnectScreenContent() { String accountName = Preferences.getGoogleAccountName(mContext); // Format the disconnect message with the currently connected account // name TextView disconnectText = (TextView) findViewById(R.id.disconnect_text); String message = getResources().getString(R.string.disconnect_text); String formatted = String.format(message, accountName); disconnectText.setText(formatted); Button disconnectButton = (Button) findViewById(R.id.disconnect); disconnectButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { // Delete the current account from shared preferences Editor editor = Preferences.getEditor(mContext); editor.putString(Preferences.GOOGLE_AUTH_COOKIE, null); editor.putString(Preferences.GOOGLE_DEVICE_REGISTRATION_ID, null); editor.commit(); // Unregister in the background and terminate the activity C2DMessaging.unregister(mContext); finish(); } }); Button exitButton = (Button) findViewById(R.id.exit); exitButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { finish(); } }); } /** * Sets the screen content based on whether a device id is set already. */ private void setScreenContent() { String deviceRegistrationID = Preferences.getGooglDeviceRegistrationId(mContext); if (deviceRegistrationID == null) { // Show the 'connect' screen if we are not connected setContentView(R.layout.connect); setConnectScreenContent(); } else { // Show the 'disconnect' screen if we are connected setContentView(R.layout.disconnect); setDisconnectScreenContent(); } } // Register and Unregister /** * Registers for C2DM messaging with the given account name. * * @param accountName a String containing a Google account name */ private void register(final String accountName) { // Store the account name in shared preferences SharedPreferences.Editor editor = Preferences.getEditor(mContext); editor.putString(Preferences.GOOGLE_ACCOUNT_NAME, accountName); editor.putString(Preferences.GOOGLE_AUTH_COOKIE, null); editor.commit(); // Obtain an auth token and register AccountManager mgr = AccountManager.get(mContext); Account[] accts = mgr.getAccountsByType("com.google"); for (Account acct : accts) { if (acct.name.equals(accountName)) { if (Util.isDebug(mContext)) { // Use a fake cookie for the dev mode app engine server // The cookie has the form email:isAdmin:userId // We set the userId to be the same as the account name String authCookie = "dev_appserver_login=" + accountName + ":false:" + accountName; Preferences.getEditor(mContext).putString(Preferences.GOOGLE_AUTH_COOKIE, authCookie).commit(); C2DMessaging.register(mContext, Setup.SENDER_ID); } else { // Get the auth token from the AccountManager and convert // it into a cookie for the appengine server mgr.getAuthToken(acct, "ah", null, this, new AccountManagerCallback<Bundle>() { public void run(AccountManagerFuture<Bundle> future) { try { Bundle authTokenBundle = future.getResult(); String authToken = authTokenBundle .get(AccountManager.KEY_AUTHTOKEN).toString(); String authCookie = getAuthCookie(authToken); Preferences.getEditor(mContext).putString(Preferences.GOOGLE_AUTH_COOKIE, authCookie).commit(); C2DMessaging.register(mContext, Setup.SENDER_ID); } catch (AuthenticatorException e) { Log.w(TAG, "Got AuthenticatorException " + e); Log.w(TAG, Log.getStackTraceString(e)); } catch (IOException e) { Log.w(TAG, "Got IOException " + Log.getStackTraceString(e)); Log.w(TAG, Log.getStackTraceString(e)); } catch (OperationCanceledException e) { Log.w(TAG, "Got OperationCanceledException " + e); Log.w(TAG, Log.getStackTraceString(e)); } } }, null); } break; } } } // Utility Methods /** * Retrieves the authorization cookie associated with the given token. This * method should only be used when running against a production appengine * backend (as opposed to a dev mode server). */ private String getAuthCookie(String authToken) { try { // Get SACSID cookie DefaultHttpClient client = new DefaultHttpClient(); String continueURL = Setup.PROD_URL; URI uri = new URI(Setup.PROD_URL + "/_ah/login?continue=" + URLEncoder.encode(continueURL, "UTF-8") + "&auth=" + authToken); HttpGet method = new HttpGet(uri); final HttpParams getParams = new BasicHttpParams(); HttpClientParams.setRedirecting(getParams, false); method.setParams(getParams); HttpResponse res = client.execute(method); Header[] headers = res.getHeaders("Set-Cookie"); if (res.getStatusLine().getStatusCode() != 302 || headers.length == 0) { return null; } for (Cookie cookie : client.getCookieStore().getCookies()) { if (AUTH_COOKIE_NAME.equals(cookie.getName())) { return AUTH_COOKIE_NAME + "=" + cookie.getValue(); } } } catch (IOException e) { Log.w(TAG, "Got IOException " + e); Log.w(TAG, Log.getStackTraceString(e)); } catch (URISyntaxException e) { Log.w(TAG, "Got URISyntaxException " + e); Log.w(TAG, Log.getStackTraceString(e)); } return null; } /** * Returns a list of registered Google account names. If no Google accounts * are registered on the device, a zero-length list is returned. */ private List<String> getGoogleAccounts() { ArrayList<String> result = new ArrayList<String>(); Account[] accounts = AccountManager.get(mContext).getAccounts(); for (Account account : accounts) { if (account.type.equals("com.google")) { result.add(account.name); } } return result; } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.dodgybits.shuffle.android.synchronisation.gae; import org.dodgybits.shuffle.android.preference.model.Preferences; import org.dodgybits.shuffle.client.ShuffleRequestFactory; import org.dodgybits.shuffle.client.ShuffleRequestFactory.RegistrationInfoRequest; import org.dodgybits.shuffle.shared.RegistrationInfoProxy; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.provider.Settings.Secure; import android.util.Log; import com.google.web.bindery.requestfactory.shared.Receiver; import com.google.web.bindery.requestfactory.shared.Request; import com.google.web.bindery.requestfactory.shared.ServerFailure; /** * Register/unregister with the third-party App Engine server using * RequestFactory. */ public class DeviceRegistrar { public static final String STATUS_EXTRA = "Status"; public static final int REGISTERED_STATUS = 1; public static final int UNREGISTERED_STATUS = 2; public static final int ERROR_STATUS = 3; private static final String TAG = "DeviceRegistrar"; public static void registerOrUnregister(final Context context, final String deviceRegistrationId, final boolean register) { final Intent updateUIIntent = new Intent(Util.UPDATE_UI_INTENT); RegistrationInfoRequest request = getRequest(context); RegistrationInfoProxy proxy = request.create(RegistrationInfoProxy.class); proxy.setDeviceRegistrationId(deviceRegistrationId); String deviceId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID); proxy.setDeviceId(deviceId); Request<Void> req; if (register) { req = request.register().using(proxy); } else { req = request.unregister().using(proxy); } req.fire(new Receiver<Void>() { @Override public void onFailure(ServerFailure failure) { Log.w(TAG, "Failure, got :" + failure.getMessage()); updateUIIntent.putExtra(STATUS_EXTRA, ERROR_STATUS); context.sendBroadcast(updateUIIntent); } @Override public void onSuccess(Void response) { SharedPreferences.Editor editor = Preferences.getEditor(context); if (register) { editor.putString(Preferences.GOOGLE_DEVICE_REGISTRATION_ID, deviceRegistrationId); } else { editor.remove(Preferences.GOOGLE_DEVICE_REGISTRATION_ID); } editor.commit(); updateUIIntent.putExtra(STATUS_EXTRA, register ? REGISTERED_STATUS : UNREGISTERED_STATUS); context.sendBroadcast(updateUIIntent); } }); } private static RegistrationInfoRequest getRequest(Context context) { ShuffleRequestFactory requestFactory = Util.getRequestFactory(context, ShuffleRequestFactory.class); RegistrationInfoRequest request = requestFactory.registrationInfoRequest(); return request; } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.dodgybits.shuffle.android.synchronisation.gae; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.preference.model.Preferences; import org.dodgybits.shuffle.client.ShuffleRequestFactory; import org.dodgybits.shuffle.client.ShuffleRequestFactory.HelloWorldRequest; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import com.google.web.bindery.requestfactory.shared.Receiver; import com.google.web.bindery.requestfactory.shared.ServerFailure; /** * Main activity - requests "Hello, World" messages from the server and provides * a menu item to invoke the accounts activity. */ public class ShuffleActivity extends Activity { /** * Tag for logging. */ private static final String TAG = "ShuffleActivity"; /** * The current context. */ private Context mContext = this; /** * A {@link BroadcastReceiver} to receive the response from a register or * unregister request, and to update the UI. */ private final BroadcastReceiver mUpdateUIReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int status = intent.getIntExtra(DeviceRegistrar.STATUS_EXTRA, DeviceRegistrar.ERROR_STATUS); String message = null; if (status == DeviceRegistrar.REGISTERED_STATUS) { message = getResources().getString(R.string.registration_succeeded); } else if (status == DeviceRegistrar.UNREGISTERED_STATUS) { message = getResources().getString(R.string.unregistration_succeeded); } else { message = getResources().getString(R.string.registration_error); } // Display a notification String accountName = Preferences.getGoogleAccountName(mContext); Util.generateNotification(mContext, String.format(message, accountName)); } }; /** * Begins the activity. */ @Override public void onCreate(Bundle savedInstanceState) { Log.i(TAG, "onCreate"); super.onCreate(savedInstanceState); setScreenContent(R.layout.hello_world); // Register a receiver to provide register/unregister notifications registerReceiver(mUpdateUIReceiver, new IntentFilter(Util.UPDATE_UI_INTENT)); } /** * Shuts down the activity. */ @Override public void onDestroy() { unregisterReceiver(mUpdateUIReceiver); super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); // Invoke the Register activity menu.getItem(0).setIntent(new Intent(this, AccountsActivity.class)); return true; } // Manage UI Screens private void setHelloWorldScreenContent() { setContentView(R.layout.hello_world); final TextView helloWorld = (TextView) findViewById(R.id.hello_world); final Button sayHelloButton = (Button) findViewById(R.id.say_hello); sayHelloButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { sayHelloButton.setEnabled(false); helloWorld.setText(R.string.contacting_server); // Use an AsyncTask to avoid blocking the UI thread new AsyncTask<Void, Void, String>() { private String message; @Override protected String doInBackground(Void... arg0) { ShuffleRequestFactory requestFactory = Util.getRequestFactory(mContext, ShuffleRequestFactory.class); final HelloWorldRequest request = requestFactory.helloWorldRequest(); String accountName = Preferences.getGoogleAccountName(mContext); Log.i(TAG, "Sending request to server for account " + accountName); request.getMessage().fire(new Receiver<String>() { @Override public void onFailure(ServerFailure error) { message = "Failure: " + error.getMessage(); } @Override public void onSuccess(String result) { message = result; } }); return message; } @Override protected void onPostExecute(String result) { helloWorld.setText(result); sayHelloButton.setEnabled(true); } }.execute(); } }); } /** * Sets the screen content based on the screen id. */ private void setScreenContent(int screenId) { setContentView(screenId); switch (screenId) { case R.layout.hello_world: setHelloWorldScreenContent(); break; } } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.dodgybits.shuffle.android.synchronisation.gae; /** * Class to be customized with app-specific data. The Eclipse plugin will set * these values when the project is created. */ public class Setup { /** * The AppEngine app name, used to construct the production service URL * below. */ private static final String APP_NAME = "android-shuffle"; /** * The URL of the production service. */ public static final String PROD_URL = "https://" + APP_NAME + ".appspot.com"; /** * The C2DM sender ID for the server. A C2DM registration with this name * must exist for the app to function correctly. */ public static final String SENDER_ID = "gtd.shuffle@gmail.com"; }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.editor.activity; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity; import org.dodgybits.shuffle.android.core.util.TextColours; import org.dodgybits.shuffle.android.list.view.LabelView; import roboguice.inject.InjectView; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.AdapterView.OnItemClickListener; public class ColourPickerActivity extends FlurryEnabledActivity implements OnItemClickListener { public static final String TYPE = "vnd.android.cursor.dir/vnd.dodgybits.colours"; @InjectView(R.id.colourGrid) GridView mGrid; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.colour_picker); mGrid.setAdapter(new IconAdapter(this)); mGrid.setOnItemClickListener(this); } public void onItemClick(AdapterView<?> parent, View v, int position, long id) { Bundle bundle = new Bundle(); bundle.putString("colour", String.valueOf(position)); Intent mIntent = new Intent(); mIntent.putExtras(bundle); setResult(RESULT_OK, mIntent); finish(); } public class IconAdapter extends BaseAdapter { private TextColours textColours; public IconAdapter(Context context) { textColours = TextColours.getInstance(context); } public View getView(int position, View convertView, ViewGroup parent) { LabelView view; if (convertView instanceof LabelView) { view = (LabelView)convertView; } else { view = new LabelView(ColourPickerActivity.this); view.setText("Abc"); view.setGravity(Gravity.CENTER); } view.setColourIndex(position); view.setIcon(null); return view; } public final int getCount() { return textColours.getNumColours(); } public final Object getItem(int position) { return textColours.getTextColour(position); } public final long getItemId(int position) { return position; } } }
Java
package org.dodgybits.shuffle.android.editor.activity; import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity; import roboguice.util.Ln; import android.os.Bundle; public class TaskEditorSchedulingActivity extends FlurryEnabledActivity { // private boolean mShowStart; // private Time mStartTime; // private boolean mShowDue; // private Time mDueTime; // // private @InjectView(R.id.start_date) Button mStartDateButton; // private @InjectView(R.id.due_date) Button mDueDateButton; // private @InjectView(R.id.start_time) Button mStartTimeButton; // private @InjectView(R.id.due_time) Button mDueTimeButton; // private @InjectView(R.id.clear_dates) Button mClearButton; // private @InjectView(R.id.is_all_day) CheckBox mAllDayCheckBox; // // private @InjectView(R.id.gcal_entry) View mUpdateCalendarEntry; // private CheckBox mUpdateCalendarCheckBox; // private TextView mCalendarLabel; // private TextView mCalendarDetail; @Override protected void onCreate(Bundle icicle) { Ln.d("onCreate+"); super.onCreate(icicle); // mStartTime = new Time(); // mDueTime = new Time(); } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.editor.activity; import android.widget.*; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.Context.Builder; import org.dodgybits.shuffle.android.core.model.encoding.EntityEncoder; import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister; import org.dodgybits.shuffle.android.core.util.TextColours; import org.dodgybits.shuffle.android.core.view.ContextIcon; import org.dodgybits.shuffle.android.core.view.DrawableUtils; import org.dodgybits.shuffle.android.list.activity.State; import org.dodgybits.shuffle.android.list.view.ContextView; import org.dodgybits.shuffle.android.persistence.provider.ContextProvider; import roboguice.inject.InjectView; import android.app.Activity; import android.content.Intent; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.GradientDrawable.Orientation; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.View; import com.google.inject.Inject; public class ContextEditorActivity extends AbstractEditorActivity<Context> implements TextWatcher { private static final String cTag = "ContextEditorActivity"; private static final int COLOUR_PICKER = 0; private static final int ICON_PICKER = 1; private int mColourIndex; private ContextIcon mIcon; @InjectView(R.id.name) private EditText mNameWidget; @InjectView(R.id.colour_display) private TextView mColourWidget; @InjectView(R.id.icon_display) private ImageView mIconWidget; @InjectView(R.id.icon_none) private TextView mIconNoneWidget; @InjectView(R.id.icon_clear_button) private ImageButton mClearIconButton; @InjectView(R.id.context_preview) private ContextView mContext; private @InjectView(R.id.deleted_entry) View mDeletedEntry; private CheckBox mDeletedCheckBox; private @InjectView(R.id.active_entry) View mActiveEntry; private @InjectView(R.id.active_entry_checkbox) CheckBox mActiveCheckBox; @Inject private EntityPersister<Context> mPersister; @Inject private EntityEncoder<Context> mEncoder; @Override protected void onCreate(Bundle icicle) { Log.d(cTag, "onCreate+"); super.onCreate(icicle); loadCursor(); findViewsAndAddListeners(); if (mState == State.STATE_EDIT) { // Make sure we are at the one and only row in the cursor. mCursor.moveToFirst(); setTitle(R.string.title_edit_context); mOriginalItem = mPersister.read(mCursor); updateUIFromItem(mOriginalItem); } else if (mState == State.STATE_INSERT) { setTitle(R.string.title_new_context); mDeletedEntry.setVisibility(View.GONE); mDeletedCheckBox.setChecked(false); mActiveCheckBox.setChecked(true); Bundle extras = getIntent().getExtras(); updateUIFromExtras(extras); } } @Override protected boolean isValid() { String name = mNameWidget.getText().toString(); return !TextUtils.isEmpty(name); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(cTag, "Got resultCode " + resultCode + " with data " + data); switch (requestCode) { case COLOUR_PICKER: if (resultCode == Activity.RESULT_OK) { if (data != null) { mColourIndex = Integer.parseInt(data.getStringExtra("colour")); displayColour(); updatePreview(); } } break; case ICON_PICKER: if (resultCode == Activity.RESULT_OK) { if (data != null) { String iconName = data.getStringExtra("iconName"); mIcon = ContextIcon.createIcon(iconName, getResources()); displayIcon(); updatePreview(); } } break; default: Log.e(cTag, "Unknown requestCode: " + requestCode); } } /** * Take care of deleting a context. Simply deletes the entry. */ @Override protected void doDeleteAction() { super.doDeleteAction(); mNameWidget.setText(""); } /** * @return id of layout for this view */ @Override protected int getContentViewResId() { return R.layout.context_editor; } @Override protected Intent getInsertIntent() { return new Intent(Intent.ACTION_INSERT, ContextProvider.Contexts.CONTENT_URI); } @Override protected CharSequence getItemName() { return getString(R.string.context_name); } @Override protected Context createItemFromUI(boolean commitValues) { Builder builder = Context.newBuilder(); if (mOriginalItem != null) { builder.mergeFrom(mOriginalItem); } builder.setName(mNameWidget.getText().toString()); builder.setModifiedDate(System.currentTimeMillis()); builder.setColourIndex(mColourIndex); builder.setIconName(mIcon.iconName); builder.setDeleted(mDeletedCheckBox.isChecked()); builder.setActive(mActiveCheckBox.isChecked()); return builder.build(); } @Override protected void updateUIFromExtras(Bundle extras) { if (mColourIndex == -1) { mColourIndex = 0; } displayIcon(); displayColour(); updatePreview(); } @Override protected void updateUIFromItem(Context context) { mNameWidget.setTextKeepState(context.getName()); mColourIndex = context.getColourIndex(); displayColour(); final String iconName = context.getIconName(); mIcon = ContextIcon.createIcon(iconName, getResources()); displayIcon(); updatePreview(); mActiveCheckBox.setChecked(context.isActive()); mDeletedEntry.setVisibility(context.isDeleted() ? View.VISIBLE : View.GONE); mDeletedCheckBox.setChecked(context.isDeleted()); if (mOriginalItem == null) { mOriginalItem = context; } } @Override protected EntityEncoder<Context> getEncoder() { return mEncoder; } @Override protected EntityPersister<Context> getPersister() { return mPersister; } private void loadCursor() { if (mUri != null && mState == State.STATE_EDIT) { mCursor = managedQuery(mUri, ContextProvider.Contexts.FULL_PROJECTION, null, null, null); if (mCursor == null || mCursor.getCount() == 0) { // The cursor is empty. This can happen if the event was deleted. finish(); } } } private void findViewsAndAddListeners() { // The text view for our context description, identified by its ID in the XML file. mNameWidget.addTextChangedListener(this); mColourIndex = -1; mIcon = ContextIcon.NONE; View colourEntry = findViewById(R.id.colour_entry); colourEntry.setOnClickListener(this); colourEntry.setOnFocusChangeListener(this); View iconEntry = findViewById(R.id.icon_entry); iconEntry.setOnClickListener(this); iconEntry.setOnFocusChangeListener(this); mClearIconButton.setOnClickListener(this); mClearIconButton.setOnFocusChangeListener(this); mActiveEntry.setOnClickListener(this); mActiveEntry.setOnFocusChangeListener(this); mDeletedEntry.setOnClickListener(this); mDeletedEntry.setOnFocusChangeListener(this); mDeletedCheckBox = (CheckBox) mDeletedEntry.findViewById(R.id.deleted_entry_checkbox); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.colour_entry: { // Launch activity to pick colour Intent intent = new Intent(Intent.ACTION_PICK); intent.setType(ColourPickerActivity.TYPE); startActivityForResult(intent, COLOUR_PICKER); break; } case R.id.icon_entry: { // Launch activity to pick icon Intent intent = new Intent(Intent.ACTION_PICK); intent.setType(IconPickerActivity.TYPE); startActivityForResult(intent, ICON_PICKER); break; } case R.id.icon_clear_button: { mIcon = ContextIcon.NONE; displayIcon(); updatePreview(); break; } case R.id.active_entry: { mActiveCheckBox.toggle(); break; } case R.id.deleted_entry: { mDeletedCheckBox.toggle(); break; } default: super.onClick(v); break; } } private void displayColour() { int bgColour = TextColours.getInstance(this).getBackgroundColour(mColourIndex); GradientDrawable drawable = DrawableUtils.createGradient(bgColour, Orientation.TL_BR); drawable.setCornerRadius(8.0f); mColourWidget.setBackgroundDrawable(drawable); } private void displayIcon() { if (mIcon == ContextIcon.NONE) { mIconNoneWidget.setVisibility(View.VISIBLE); mIconWidget.setVisibility(View.GONE); mClearIconButton.setEnabled(false); } else { mIconNoneWidget.setVisibility(View.GONE); mIconWidget.setImageResource(mIcon.largeIconId); mIconWidget.setVisibility(View.VISIBLE); mClearIconButton.setEnabled(true); } } private void updatePreview() { String name = mNameWidget.getText().toString(); if (TextUtils.isEmpty(name) || mColourIndex == -1) { mContext.setVisibility(View.INVISIBLE); } else { mContext.updateView(createItemFromUI(false)); mContext.setVisibility(View.VISIBLE); } } @Override public void afterTextChanged(Editable s) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { updatePreview(); } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.editor.activity; import java.util.ArrayList; import java.util.Arrays; import java.util.TimeZone; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Task; import org.dodgybits.shuffle.android.core.model.Task.Builder; import org.dodgybits.shuffle.android.core.model.encoding.EntityEncoder; import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister; import org.dodgybits.shuffle.android.core.model.persistence.TaskPersister; import org.dodgybits.shuffle.android.core.util.CalendarUtils; import org.dodgybits.shuffle.android.core.util.Constants; import org.dodgybits.shuffle.android.list.activity.State; import org.dodgybits.shuffle.android.persistence.provider.ContextProvider; import org.dodgybits.shuffle.android.persistence.provider.ProjectProvider; import org.dodgybits.shuffle.android.persistence.provider.ReminderProvider; import org.dodgybits.shuffle.android.persistence.provider.TaskProvider; import org.dodgybits.shuffle.android.preference.model.Preferences; import roboguice.inject.InjectView; import android.app.Activity; import android.app.DatePickerDialog; import android.app.DatePickerDialog.OnDateSetListener; import android.app.TimePickerDialog; import android.app.TimePickerDialog.OnTimeSetListener; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.text.format.DateFormat; import android.text.format.DateUtils; import android.text.format.Time; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.TimePicker; import com.google.inject.Inject; /** * A generic activity for editing a task in the database. This can be used * either to simply view a task (Intent.VIEW_ACTION), view and edit a task * (Intent.EDIT_ACTION), or create a new task (Intent.INSERT_ACTION). */ public class TaskEditorActivity extends AbstractEditorActivity<Task> implements CompoundButton.OnCheckedChangeListener { private static final String cTag = "TaskEditorActivity"; private static final String[] cContextProjection = new String[] { ContextProvider.Contexts._ID, ContextProvider.Contexts.NAME }; private static final String[] cProjectProjection = new String[] { ProjectProvider.Projects._ID, ProjectProvider.Projects.NAME }; private static final String REMINDERS_WHERE = ReminderProvider.Reminders.TASK_ID + "=? AND (" + ReminderProvider.Reminders.METHOD + "=" + ReminderProvider.Reminders.METHOD_ALERT + " OR " + ReminderProvider.Reminders.METHOD + "=" + ReminderProvider.Reminders.METHOD_DEFAULT + ")"; private static final int MAX_REMINDERS = 3; private static final int cNewContextCode = 100; private static final int cNewProjectCode = 101; private @InjectView(R.id.description) EditText mDescriptionWidget; private @InjectView(R.id.context) Spinner mContextSpinner; private @InjectView(R.id.project) Spinner mProjectSpinner; private @InjectView(R.id.details) EditText mDetailsWidget; private String[] mContextNames; private long[] mContextIds; private String[] mProjectNames; private long[] mProjectIds; private boolean mSchedulingExpanded; private @InjectView(R.id.start_date) Button mStartDateButton; private @InjectView(R.id.due_date) Button mDueDateButton; private @InjectView(R.id.start_time) Button mStartTimeButton; private @InjectView(R.id.due_time) Button mDueTimeButton; private @InjectView(R.id.clear_dates) Button mClearButton; private @InjectView(R.id.is_all_day) CheckBox mAllDayCheckBox; private boolean mShowStart; private Time mStartTime; private boolean mShowDue; private Time mDueTime; private View mSchedulingExtra; private TextView mSchedulingDetail; private View mExpandButton; private View mCollapseButton; private @InjectView(R.id.completed_entry) View mCompleteEntry; private CheckBox mCompletedCheckBox; private @InjectView(R.id.deleted_entry) View mDeletedEntry; private @InjectView(R.id.deleted_entry_checkbox) CheckBox mDeletedCheckBox; private @InjectView(R.id.gcal_entry) View mUpdateCalendarEntry; private CheckBox mUpdateCalendarCheckBox; private TextView mCalendarLabel; private TextView mCalendarDetail; private ArrayList<Integer> mReminderValues; private ArrayList<String> mReminderLabels; private int mDefaultReminderMinutes; private @InjectView(R.id.reminder_items_container) LinearLayout mRemindersContainer; private ArrayList<Integer> mOriginalMinutes = new ArrayList<Integer>(); private ArrayList<LinearLayout> mReminderItems = new ArrayList<LinearLayout>(0); @Inject private TaskPersister mPersister; @Inject private EntityEncoder<Task> mEncoder; @Override protected void onCreate(Bundle icicle) { Log.d(cTag, "onCreate+"); super.onCreate(icicle); mStartTime = new Time(); mDueTime = new Time(); loadCursors(); findViewsAndAddListeners(); if (mState == State.STATE_EDIT) { // Make sure we are at the one and only row in the cursor. mCursor.moveToFirst(); // Modify our overall title depending on the mode we are running in. setTitle(R.string.title_edit_task); mCompleteEntry.setVisibility(View.VISIBLE); mOriginalItem = mPersister.read(mCursor); updateUIFromItem(mOriginalItem); } else if (mState == State.STATE_INSERT) { setTitle(R.string.title_new_task); mCompleteEntry.setVisibility(View.GONE); mDeletedEntry.setVisibility(View.GONE); mDeletedCheckBox.setChecked(false); // see if the context or project were suggested for this task Bundle extras = getIntent().getExtras(); updateUIFromExtras(extras); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(cTag, "Got resultCode " + resultCode + " with data " + data); switch (requestCode) { case cNewContextCode: if (resultCode == Activity.RESULT_OK) { if (data != null) { long newContextId = ContentUris.parseId(data.getData()); setupContextSpinner(); setSpinnerSelection(mContextSpinner, mContextIds, newContextId); } } break; case cNewProjectCode: if (resultCode == Activity.RESULT_OK) { if (data != null) { long newProjectId = ContentUris.parseId(data.getData()); setupProjectSpinner(); setSpinnerSelection(mProjectSpinner, mProjectIds, newProjectId); } } break; default: Log.e(cTag, "Unknown requestCode: " + requestCode); } } @Override protected boolean isValid() { String description = mDescriptionWidget.getText().toString(); return !TextUtils.isEmpty(description); } @Override protected void updateUIFromExtras(Bundle extras) { if (extras != null) { Long contextId = extras.getLong(TaskProvider.Tasks.CONTEXT_ID); setSpinnerSelection(mContextSpinner, mContextIds, contextId); Long projectId = extras.getLong(TaskProvider.Tasks.PROJECT_ID); setSpinnerSelection(mProjectSpinner, mProjectIds, projectId); } setWhenDefaults(); populateWhen(); setSchedulingVisibility(false); mStartTimeButton.setVisibility(View.VISIBLE); mDueTimeButton.setVisibility(View.VISIBLE); updateCalendarPanel(); updateRemindersVisibility(); } @Override protected void updateUIFromItem(Task task) { // If we hadn't previously retrieved the original task, do so // now. This allows the user to revert their changes. if (mOriginalItem == null) { mOriginalItem = task; } final String details = task.getDetails(); mDetailsWidget.setTextKeepState(details == null ? "" : details); mDescriptionWidget.setTextKeepState(task.getDescription()); final Id contextId = task.getContextId(); if (contextId.isInitialised()) { setSpinnerSelection(mContextSpinner, mContextIds, contextId.getId()); } final Id projectId = task.getProjectId(); if (projectId.isInitialised()) { setSpinnerSelection(mProjectSpinner, mProjectIds, projectId.getId()); } boolean allDay = task.isAllDay(); if (allDay) { String tz = mStartTime.timezone; mStartTime.timezone = Time.TIMEZONE_UTC; mStartTime.set(task.getStartDate()); mStartTime.timezone = tz; // Calling normalize to calculate isDst mStartTime.normalize(true); } else { mStartTime.set(task.getStartDate()); } if (allDay) { String tz = mStartTime.timezone; mDueTime.timezone = Time.TIMEZONE_UTC; mDueTime.set(task.getDueDate()); mDueTime.timezone = tz; // Calling normalize to calculate isDst mDueTime.normalize(true); } else { mDueTime.set(task.getDueDate()); } setWhenDefaults(); populateWhen(); // show scheduling section if either start or due date are set mSchedulingExpanded = mShowStart || mShowDue; setSchedulingVisibility(mSchedulingExpanded); mAllDayCheckBox.setChecked(allDay); updateTimeVisibility(!allDay); mCompletedCheckBox.setChecked(task.isComplete()); mDeletedEntry.setVisibility(task.isDeleted() ? View.VISIBLE : View.GONE); mDeletedCheckBox.setChecked(task.isDeleted()); updateCalendarPanel(); // Load reminders (if there are any) if (task.hasAlarms()) { Uri uri = ReminderProvider.Reminders.CONTENT_URI; ContentResolver cr = getContentResolver(); Cursor reminderCursor = cr.query(uri, ReminderProvider.Reminders.cFullProjection, REMINDERS_WHERE, new String[] {String.valueOf(task.getLocalId().getId())}, null); try { // First pass: collect all the custom reminder minutes (e.g., // a reminder of 8 minutes) into a global list. while (reminderCursor.moveToNext()) { int minutes = reminderCursor.getInt(ReminderProvider.Reminders.MINUTES_INDEX); addMinutesToList(this, mReminderValues, mReminderLabels, minutes); } // Second pass: create the reminder spinners reminderCursor.moveToPosition(-1); while (reminderCursor.moveToNext()) { int minutes = reminderCursor.getInt(ReminderProvider.Reminders.MINUTES_INDEX); mOriginalMinutes.add(minutes); addReminder(this, this, mReminderItems, mReminderValues, mReminderLabels, minutes); } } finally { reminderCursor.close(); } } updateRemindersVisibility(); } @Override protected Task createItemFromUI(boolean commitValues) { Builder builder = Task.newBuilder(); if (mOriginalItem != null) { builder.mergeFrom(mOriginalItem); } final String description = mDescriptionWidget.getText().toString(); final long modified = System.currentTimeMillis(); final String details = mDetailsWidget.getText().toString(); final Id contextId = getSpinnerSelectedId(mContextSpinner, mContextIds); final Id projectId = getSpinnerSelectedId(mProjectSpinner, mProjectIds); final boolean allDay = mAllDayCheckBox.isChecked(); final boolean complete = mCompletedCheckBox.isChecked(); final boolean hasAlarms = !mReminderItems.isEmpty(); final boolean deleted = mDeletedCheckBox.isChecked(); final boolean active = true; builder .setDescription(description) .setModifiedDate(modified) .setDetails(details) .setContextId(contextId) .setProjectId(projectId) .setAllDay(allDay) .setComplete(complete) .setDeleted(deleted) .setActive(active) .setHasAlarm(hasAlarms); // If we are creating a new task, set the creation date if (mState == State.STATE_INSERT) { builder.setCreatedDate(modified); } String timezone; long startMillis = 0L; long dueMillis = 0L; if (allDay) { // Reset start and end time, increment the monthDay by 1, and set // the timezone to UTC, as required for all-day events. timezone = Time.TIMEZONE_UTC; mStartTime.hour = 0; mStartTime.minute = 0; mStartTime.second = 0; mStartTime.timezone = timezone; startMillis = mStartTime.normalize(true); mDueTime.hour = 0; mDueTime.minute = 0; mDueTime.second = 0; mDueTime.monthDay++; mDueTime.timezone = timezone; dueMillis = mDueTime.normalize(true); } else { if (mShowStart && !Time.isEpoch(mStartTime)) { startMillis = mStartTime.toMillis(true); } if (mShowDue && !Time.isEpoch(mDueTime)) { dueMillis = mDueTime.toMillis(true); } if (mState == State.STATE_INSERT) { // The timezone for a new task is the currently displayed timezone timezone = TimeZone.getDefault().getID(); } else { timezone = mOriginalItem.getTimezone(); // The timezone might be null if we are changing an existing // all-day task to a non-all-day event. We need to assign // a timezone to the non-all-day task. if (TextUtils.isEmpty(timezone)) { timezone = TimeZone.getDefault().getID(); } } } final int order; if (commitValues) { order = mPersister.calculateTaskOrder(mOriginalItem, projectId, dueMillis); } else if (mOriginalItem == null) { order = 0; } else { order = mOriginalItem.getOrder(); } builder .setTimezone(timezone) .setStartDate(startMillis) .setDueDate(dueMillis) .setOrder(order); Id eventId = mOriginalItem == null ? Id.NONE : mOriginalItem.getCalendarEventId(); final boolean updateCalendar = mUpdateCalendarCheckBox.isChecked(); if (updateCalendar) { Uri calEntryUri = addOrUpdateCalendarEvent( eventId, description, details, projectId, contextId, timezone, startMillis, dueMillis, allDay); if (calEntryUri != null) { eventId = Id.create(ContentUris.parseId(calEntryUri)); mNextIntent = new Intent(Intent.ACTION_EDIT, calEntryUri); mNextIntent.putExtra("beginTime", startMillis); mNextIntent.putExtra("endTime", dueMillis); } Log.i(cTag, "Updated calendar event " + eventId); } builder.setCalendarEventId(eventId); return builder.build(); } @Override protected EntityEncoder<Task> getEncoder() { return mEncoder; } @Override protected EntityPersister<Task> getPersister() { return mPersister; } private Uri addOrUpdateCalendarEvent( Id calEventId, String title, String description, Id projectId, Id contextId, String timezone, long start, long end, boolean allDay) { if (projectId.isInitialised()) { String projectName = getProjectName(projectId); title = projectName + " - " + title; } if (description == null) { description = ""; } ContentValues values = new ContentValues(); if (!TextUtils.isEmpty(timezone)) { values.put("eventTimezone", timezone); } values.put("calendar_id", Preferences.getCalendarId(this)); values.put("title", title); values.put("allDay", allDay ? 1 : 0); if (start > 0L) { values.put("dtstart", start); // long (start date in ms) } if (end > 0L) { values.put("dtend", end); // long (end date in ms) } values.put("description", description); values.put("hasAlarm", 0); values.put("transparency", 0); values.put("visibility", 0); if (contextId.isInitialised()) { String contextName = getContextName(contextId); values.put("eventLocation", contextName); } Uri eventUri = null; try { eventUri = addCalendarEntry(values, calEventId, CalendarUtils.getEventContentUri()); } catch (Exception e) { Log.e(cTag, "Attempt failed to create calendar entry", e); mAnalytics.onError(Constants.cFlurryCalendarUpdateError, e.getMessage(), getClass().getName()); } return eventUri; } private Uri addCalendarEntry(ContentValues values, Id oldId, Uri baseUri) { ContentResolver cr = getContentResolver(); int updateCount = 0; Uri eventUri = null; if (oldId.isInitialised()) { eventUri = ContentUris.appendId(baseUri.buildUpon(), oldId.getId()).build(); // it's possible the old event was deleted, check number of records updated updateCount = cr.update(eventUri, values, null, null); } if (updateCount == 0) { eventUri = cr.insert(baseUri, values); } return eventUri; } @Override protected Intent getInsertIntent() { Intent intent = new Intent(Intent.ACTION_INSERT, TaskProvider.Tasks.CONTENT_URI); // give new task the same project and context as this one Bundle extras = intent.getExtras(); if (extras == null) extras = new Bundle(); Id contextId = getSpinnerSelectedId(mContextSpinner, mContextIds); if (contextId.isInitialised()) { extras.putLong(TaskProvider.Tasks.CONTEXT_ID, contextId.getId()); } Id projectId = getSpinnerSelectedId(mProjectSpinner, mProjectIds); if (projectId.isInitialised()) { extras.putLong(TaskProvider.Tasks.PROJECT_ID, projectId.getId()); } intent.putExtras(extras); return intent; } @Override protected Uri create() { Uri uri = super.create(); if (uri != null) { ContentResolver cr = getContentResolver(); ArrayList<Integer> reminderMinutes = reminderItemsToMinutes(mReminderItems, mReminderValues); long taskId = ContentUris.parseId(uri); saveReminders(cr, taskId, reminderMinutes, mOriginalMinutes); } return uri; } @Override protected Uri save() { Uri uri = super.save(); if (uri != null) { ContentResolver cr = getContentResolver(); ArrayList<Integer> reminderMinutes = reminderItemsToMinutes(mReminderItems, mReminderValues); long taskId = ContentUris.parseId(uri); saveReminders(cr, taskId, reminderMinutes, mOriginalMinutes); } return uri; } /** * @return id of layout for this view */ @Override protected int getContentViewResId() { return R.layout.task_editor; } @Override protected CharSequence getItemName() { return getString(R.string.task_name); } /** * Take care of deleting a task. Simply deletes the entry. */ @Override protected void doDeleteAction() { super.doDeleteAction(); mDescriptionWidget.setText(""); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.context_add: { Intent addContextIntent = new Intent(Intent.ACTION_INSERT, ContextProvider.Contexts.CONTENT_URI); startActivityForResult(addContextIntent, cNewContextCode); break; } case R.id.project_add: { Intent addProjectIntent = new Intent(Intent.ACTION_INSERT, ProjectProvider.Projects.CONTENT_URI); startActivityForResult(addProjectIntent, cNewProjectCode); break; } case R.id.scheduling_entry: { toggleSchedulingSection(); break; } case R.id.completed_entry: { mCompletedCheckBox.toggle(); break; } case R.id.deleted_entry: { mDeletedCheckBox.toggle(); break; } case R.id.gcal_entry: { CheckBox checkBox = (CheckBox) v.findViewById(R.id.update_calendar_checkbox); checkBox.toggle(); break; } case R.id.clear_dates: { mAllDayCheckBox.setChecked(false); mStartTime = new Time(); mDueTime = new Time(); setWhenDefaults(); populateWhen(); updateCalendarPanel(); break; } case R.id.reminder_remove: { LinearLayout reminderItem = (LinearLayout) v.getParent(); LinearLayout parent = (LinearLayout) reminderItem.getParent(); parent.removeView(reminderItem); mReminderItems.remove(reminderItem); updateRemindersVisibility(); break; } default: super.onClick(v); break; } } public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { if (mDueTime.hour == 0 && mDueTime.minute == 0) { mDueTime.monthDay--; // Do not allow an event to have an end time before the start time. if (mDueTime.before(mStartTime)) { mDueTime.set(mStartTime); } } } else { if (mDueTime.hour == 0 && mDueTime.minute == 0) { mDueTime.monthDay++; } } mShowStart = true; long startMillis = mStartTime.normalize(true); setDate(mStartDateButton, startMillis, mShowStart); setTime(mStartTimeButton, startMillis, mShowStart); mShowDue = true; long dueMillis = mDueTime.normalize(true); setDate(mDueDateButton, dueMillis, mShowDue); setTime(mDueTimeButton, dueMillis, mShowDue); updateTimeVisibility(!isChecked); } private void updateTimeVisibility(boolean showTime) { if (showTime) { mStartTimeButton.setVisibility(View.VISIBLE); mDueTimeButton.setVisibility(View.VISIBLE); } else { mStartTimeButton.setVisibility(View.GONE); mDueTimeButton.setVisibility(View.GONE); } } private void loadCursors() { // Get the task if we're editing if (mUri != null && mState == State.STATE_EDIT) { mCursor = managedQuery(mUri, TaskProvider.Tasks.FULL_PROJECTION, null, null, null); if (mCursor == null || mCursor.getCount() == 0) { // The cursor is empty. This can happen if the event was deleted. finish(); } } } private void findViewsAndAddListeners() { // The text view for our task description, identified by its ID in the XML file. setupContextSpinner(); ImageButton addContextButton = (ImageButton) findViewById(R.id.context_add); addContextButton.setOnClickListener(this); addContextButton.setOnFocusChangeListener(this); setupProjectSpinner(); ImageButton addProjectButton = (ImageButton) findViewById(R.id.project_add); addProjectButton.setOnClickListener(this); addProjectButton.setOnFocusChangeListener(this); mCompleteEntry.setOnClickListener(this); mCompleteEntry.setOnFocusChangeListener(this); mCompletedCheckBox = (CheckBox) mCompleteEntry.findViewById(R.id.completed_entry_checkbox); mDeletedEntry.setOnClickListener(this); mDeletedEntry.setOnFocusChangeListener(this); mUpdateCalendarEntry.setOnClickListener(this); mUpdateCalendarEntry.setOnFocusChangeListener(this); mUpdateCalendarCheckBox = (CheckBox) mUpdateCalendarEntry.findViewById(R.id.update_calendar_checkbox); mCalendarLabel = (TextView) mUpdateCalendarEntry.findViewById(R.id.gcal_label); mCalendarDetail = (TextView) mUpdateCalendarEntry.findViewById(R.id.gcal_detail); mStartDateButton.setOnClickListener(new DateClickListener(mStartTime)); mStartTimeButton.setOnClickListener(new TimeClickListener(mStartTime)); mDueDateButton.setOnClickListener(new DateClickListener(mDueTime)); mDueTimeButton.setOnClickListener(new TimeClickListener(mDueTime)); mAllDayCheckBox.setOnCheckedChangeListener(this); mClearButton.setOnClickListener(this); ViewGroup schedulingSection = (ViewGroup) findViewById(R.id.scheduling_section); View schedulingEntry = findViewById(R.id.scheduling_entry); schedulingEntry.setOnClickListener(this); schedulingEntry.setOnFocusChangeListener(this); mSchedulingExtra = schedulingSection.findViewById(R.id.scheduling_extra); mExpandButton = schedulingEntry.findViewById(R.id.expand); mCollapseButton = schedulingEntry.findViewById(R.id.collapse); mSchedulingDetail = (TextView) schedulingEntry.findViewById(R.id.scheduling_detail); mSchedulingExpanded = mSchedulingExtra.getVisibility() == View.VISIBLE; // Initialize the reminder values array. Resources r = getResources(); String[] strings = r.getStringArray(R.array.reminder_minutes_values); ArrayList<Integer> list = new ArrayList<Integer>(strings.length); for (String numberString: strings) { list.add(Integer.parseInt(numberString)); } mReminderValues = list; String[] labels = r.getStringArray(R.array.reminder_minutes_labels); mReminderLabels = new ArrayList<String>(Arrays.asList(labels)); mDefaultReminderMinutes = Preferences.getDefaultReminderMinutes(this); // Setup the + Add Reminder Button ImageButton reminderAddButton = (ImageButton) findViewById(R.id.reminder_add); reminderAddButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { addReminder(); } }); } private void setupContextSpinner() { Cursor contextCursor = getContentResolver().query( ContextProvider.Contexts.CONTENT_URI, cContextProjection, ContextProvider.Contexts.DELETED + "=0", null, ContextProvider.Contexts.NAME + " ASC"); int arraySize = contextCursor.getCount() + 1; mContextIds = new long[arraySize]; mContextIds[0] = 0; mContextNames = new String[arraySize]; mContextNames[0] = getText(R.string.none_empty).toString(); for (int i = 1; i < arraySize; i++) { contextCursor.moveToNext(); mContextIds[i] = contextCursor.getLong(0); mContextNames[i] = contextCursor.getString(1); } contextCursor.close(); ArrayAdapter<String> adapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, mContextNames); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mContextSpinner.setAdapter(adapter); } private void setupProjectSpinner() { Cursor projectCursor = getContentResolver().query( ProjectProvider.Projects.CONTENT_URI, cProjectProjection, ProjectProvider.Projects.DELETED + " = 0", null, ProjectProvider.Projects.NAME + " ASC"); int arraySize = projectCursor.getCount() + 1; mProjectIds = new long[arraySize]; mProjectIds[0] = 0; mProjectNames = new String[arraySize]; mProjectNames[0] = getText(R.string.none_empty).toString(); for (int i = 1; i < arraySize; i++) { projectCursor.moveToNext(); mProjectIds[i] = projectCursor.getLong(0); mProjectNames[i] = projectCursor.getString(1); } projectCursor.close(); ArrayAdapter<String> adapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, mProjectNames); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mProjectSpinner.setAdapter(adapter); } private Id getSpinnerSelectedId(Spinner spinner, long[] ids) { Id id = Id.NONE; int selectedItemPosition = spinner.getSelectedItemPosition(); if (selectedItemPosition > 0) { id = Id.create(ids[selectedItemPosition]); } return id; } private void setSpinnerSelection(Spinner spinner, long[] ids, Long id) { if (id == null || id == 0) { spinner.setSelection(0); } else { for (int i = 1; i < ids.length; i++) { if (ids[i] == id) { spinner.setSelection(i); break; } } } } private String getContextName(Id contextId) { String name = ""; final long id = contextId.getId(); for(int i = 0; i < mContextIds.length; i++) { long currentId = mContextIds[i]; if (currentId == id) { name = mContextNames[i]; break; } } return name; } private String getProjectName(Id projectId) { String name = ""; final long id = projectId.getId(); for(int i = 0; i < mProjectIds.length; i++) { long currentId = mProjectIds[i]; if (currentId == id) { name = mProjectNames[i]; break; } } return name; } private void addReminder() { if (mDefaultReminderMinutes == 0) { addReminder(this, this, mReminderItems, mReminderValues, mReminderLabels, 10 /* minutes */); } else { addReminder(this, this, mReminderItems, mReminderValues, mReminderLabels, mDefaultReminderMinutes); } updateRemindersVisibility(); } // Adds a reminder to the displayed list of reminders. // Returns true if successfully added reminder, false if no reminders can // be added. static boolean addReminder(Activity activity, View.OnClickListener listener, ArrayList<LinearLayout> items, ArrayList<Integer> values, ArrayList<String> labels, int minutes) { if (items.size() >= MAX_REMINDERS) { return false; } LayoutInflater inflater = activity.getLayoutInflater(); LinearLayout parent = (LinearLayout) activity.findViewById(R.id.reminder_items_container); LinearLayout reminderItem = (LinearLayout) inflater.inflate(R.layout.edit_reminder_item, null); parent.addView(reminderItem); Spinner spinner = (Spinner) reminderItem.findViewById(R.id.reminder_value); Resources res = activity.getResources(); spinner.setPrompt(res.getString(R.string.reminders_title)); int resource = android.R.layout.simple_spinner_item; ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity, resource, labels); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); ImageButton reminderRemoveButton; reminderRemoveButton = (ImageButton) reminderItem.findViewById(R.id.reminder_remove); reminderRemoveButton.setOnClickListener(listener); int index = findMinutesInReminderList(values, minutes); spinner.setSelection(index); items.add(reminderItem); return true; } private void toggleSchedulingSection() { mSchedulingExpanded = !mSchedulingExpanded; setSchedulingVisibility(mSchedulingExpanded); } private void setSchedulingVisibility(boolean visible) { if (visible) { mSchedulingExtra.setVisibility(View.VISIBLE); mExpandButton.setVisibility(View.GONE); mCollapseButton.setVisibility(View.VISIBLE); mSchedulingDetail.setText(R.string.scheduling_expanded); } else { mSchedulingExtra.setVisibility(View.GONE); mExpandButton.setVisibility(View.VISIBLE); mCollapseButton.setVisibility(View.GONE); mSchedulingDetail.setText(R.string.scheduling_collapsed); } } private void setWhenDefaults() { // it's possible to have: // 1) no times set // 2) due time set, but not start time // 3) start and due time set mShowStart = !Time.isEpoch(mStartTime); mShowDue = !Time.isEpoch(mDueTime); if (!mShowStart && !mShowDue) { mStartTime.setToNow(); // Round the time to the nearest half hour. mStartTime.second = 0; int minute = mStartTime.minute; if (minute > 0 && minute <= 30) { mStartTime.minute = 30; } else { mStartTime.minute = 0; mStartTime.hour += 1; } long startMillis = mStartTime.normalize(true /* ignore isDst */); mDueTime.set(startMillis + DateUtils.HOUR_IN_MILLIS); } else if (!mShowStart) { // default start to same as due mStartTime.set(mDueTime); } } private void populateWhen() { long startMillis = mStartTime.toMillis(false /* use isDst */); long endMillis = mDueTime.toMillis(false /* use isDst */); setDate(mStartDateButton, startMillis, mShowStart); setDate(mDueDateButton, endMillis, mShowDue); setTime(mStartTimeButton, startMillis, mShowStart); setTime(mDueTimeButton, endMillis, mShowDue); } private void setDate(TextView view, long millis, boolean showValue) { CharSequence value; if (showValue) { int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_ABBREV_WEEKDAY; value = DateUtils.formatDateTime(this, millis, flags); } else { value = ""; } view.setText(value); } private void setTime(TextView view, long millis, boolean showValue) { CharSequence value; if (showValue) { int flags = DateUtils.FORMAT_SHOW_TIME; if (DateFormat.is24HourFormat(this)) { flags |= DateUtils.FORMAT_24HOUR; } value = DateUtils.formatDateTime(this, millis, flags); } else { value = ""; } view.setText(value); } static void addMinutesToList(android.content.Context context, ArrayList<Integer> values, ArrayList<String> labels, int minutes) { int index = values.indexOf(minutes); if (index != -1) { return; } // The requested "minutes" does not exist in the list, so insert it // into the list. String label = constructReminderLabel(context, minutes, false); int len = values.size(); for (int i = 0; i < len; i++) { if (minutes < values.get(i)) { values.add(i, minutes); labels.add(i, label); return; } } values.add(minutes); labels.add(len, label); } /** * Finds the index of the given "minutes" in the "values" list. * * @param values the list of minutes corresponding to the spinner choices * @param minutes the minutes to search for in the values list * @return the index of "minutes" in the "values" list */ private static int findMinutesInReminderList(ArrayList<Integer> values, int minutes) { int index = values.indexOf(minutes); if (index == -1) { // This should never happen. Log.e(cTag, "Cannot find minutes (" + minutes + ") in list"); return 0; } return index; } // Constructs a label given an arbitrary number of minutes. For example, // if the given minutes is 63, then this returns the string "63 minutes". // As another example, if the given minutes is 120, then this returns // "2 hours". static String constructReminderLabel(android.content.Context context, int minutes, boolean abbrev) { Resources resources = context.getResources(); int value, resId; if (minutes % 60 != 0) { value = minutes; if (abbrev) { resId = R.plurals.Nmins; } else { resId = R.plurals.Nminutes; } } else if (minutes % (24 * 60) != 0) { value = minutes / 60; resId = R.plurals.Nhours; } else { value = minutes / ( 24 * 60); resId = R.plurals.Ndays; } String format = resources.getQuantityString(resId, value); return String.format(format, value); } private void updateRemindersVisibility() { if (mReminderItems.size() == 0) { mRemindersContainer.setVisibility(View.GONE); } else { mRemindersContainer.setVisibility(View.VISIBLE); } } private void updateCalendarPanel() { boolean enabled = true; if (mOriginalItem != null && mOriginalItem.getCalendarEventId().isInitialised()) { mCalendarLabel.setText(getString(R.string.update_gcal_title)); mCalendarDetail.setText(getString(R.string.update_gcal_detail)); } else if (mShowDue && mShowStart) { mCalendarLabel.setText(getString(R.string.add_to_gcal_title)); mCalendarDetail.setText(getString(R.string.add_to_gcal_detail)); } else { mCalendarLabel.setText(getString(R.string.add_to_gcal_title)); mCalendarDetail.setText(getString(R.string.add_to_gcal_detail_disabled)); enabled = false; } mUpdateCalendarEntry.setEnabled(enabled); mUpdateCalendarCheckBox.setEnabled(enabled); } static ArrayList<Integer> reminderItemsToMinutes(ArrayList<LinearLayout> reminderItems, ArrayList<Integer> reminderValues) { int len = reminderItems.size(); ArrayList<Integer> reminderMinutes = new ArrayList<Integer>(len); for (int index = 0; index < len; index++) { LinearLayout layout = reminderItems.get(index); Spinner spinner = (Spinner) layout.findViewById(R.id.reminder_value); int minutes = reminderValues.get(spinner.getSelectedItemPosition()); reminderMinutes.add(minutes); } return reminderMinutes; } /** * Saves the reminders, if they changed. Returns true if the database * was updated. * * @param cr the ContentResolver * @param taskId the id of the task whose reminders are being updated * @param reminderMinutes the array of reminders set by the user * @param originalMinutes the original array of reminders * @return true if the database was updated */ static boolean saveReminders(ContentResolver cr, long taskId, ArrayList<Integer> reminderMinutes, ArrayList<Integer> originalMinutes ) { // If the reminders have not changed, then don't update the database if (reminderMinutes.equals(originalMinutes)) { return false; } // Delete all the existing reminders for this event String where = ReminderProvider.Reminders.TASK_ID + "=?"; String[] args = new String[] { Long.toString(taskId) }; cr.delete(ReminderProvider.Reminders.CONTENT_URI, where, args); ContentValues values = new ContentValues(); int len = reminderMinutes.size(); // Insert the new reminders, if any for (int i = 0; i < len; i++) { int minutes = reminderMinutes.get(i); values.clear(); values.put(ReminderProvider.Reminders.MINUTES, minutes); values.put(ReminderProvider.Reminders.METHOD, ReminderProvider.Reminders.METHOD_ALERT); values.put(ReminderProvider.Reminders.TASK_ID, taskId); cr.insert(ReminderProvider.Reminders.CONTENT_URI, values); } return true; } /* This class is used to update the time buttons. */ private class TimeListener implements OnTimeSetListener { private View mView; public TimeListener(View view) { mView = view; } public void onTimeSet(TimePicker view, int hourOfDay, int minute) { // Cache the member variables locally to avoid inner class overhead. Time startTime = mStartTime; Time dueTime = mDueTime; // Cache the start and due millis so that we limit the number // of calls to normalize() and toMillis(), which are fairly // expensive. long startMillis; long dueMillis; if (mView == mStartTimeButton) { // The start time was changed. int hourDuration = dueTime.hour - startTime.hour; int minuteDuration = dueTime.minute - startTime.minute; startTime.hour = hourOfDay; startTime.minute = minute; startMillis = startTime.normalize(true); mShowStart = true; // Also update the due time to keep the duration constant. dueTime.hour = hourOfDay + hourDuration; dueTime.minute = minute + minuteDuration; dueMillis = dueTime.normalize(true); mShowDue = true; } else { // The due time was changed. startMillis = startTime.toMillis(true); dueTime.hour = hourOfDay; dueTime.minute = minute; dueMillis = dueTime.normalize(true); mShowDue = true; if (mShowStart) { // Do not allow an event to have a due time before the start time. if (dueTime.before(startTime)) { dueTime.set(startTime); dueMillis = startMillis; } } else { // if start time is not shown, default it to be the same as due time startTime.set(dueTime); mShowStart = true; } } // update all 4 buttons in case visibility has changed setDate(mStartDateButton, startMillis, mShowStart); setTime(mStartTimeButton, startMillis, mShowStart); setDate(mDueDateButton, dueMillis, mShowDue); setTime(mDueTimeButton, dueMillis, mShowDue); updateCalendarPanel(); } } private class TimeClickListener implements View.OnClickListener { private Time mTime; public TimeClickListener(Time time) { mTime = time; } public void onClick(View v) { new TimePickerDialog(TaskEditorActivity.this, new TimeListener(v), mTime.hour, mTime.minute, DateFormat.is24HourFormat(TaskEditorActivity.this)).show(); } } private class DateListener implements OnDateSetListener { View mView; public DateListener(View view) { mView = view; } public void onDateSet(DatePicker view, int year, int month, int monthDay) { // Cache the member variables locally to avoid inner class overhead. Time startTime = mStartTime; Time dueTime = mDueTime; // Cache the start and due millis so that we limit the number // of calls to normalize() and toMillis(), which are fairly // expensive. long startMillis; long dueMillis; if (mView == mStartDateButton) { // The start date was changed. int yearDuration = dueTime.year - startTime.year; int monthDuration = dueTime.month - startTime.month; int monthDayDuration = dueTime.monthDay - startTime.monthDay; startTime.year = year; startTime.month = month; startTime.monthDay = monthDay; startMillis = startTime.normalize(true); mShowStart = true; // Also update the end date to keep the duration constant. dueTime.year = year + yearDuration; dueTime.month = month + monthDuration; dueTime.monthDay = monthDay + monthDayDuration; dueMillis = dueTime.normalize(true); mShowDue = true; } else { // The end date was changed. startMillis = startTime.toMillis(true); dueTime.year = year; dueTime.month = month; dueTime.monthDay = monthDay; dueMillis = dueTime.normalize(true); mShowDue = true; if (mShowStart) { // Do not allow an event to have an end time before the start time. if (dueTime.before(startTime)) { dueTime.set(startTime); dueMillis = startMillis; } } else { // if start time is not shown, default it to be the same as due time startTime.set(dueTime); mShowStart = true; } } // update all 4 buttons in case visibility has changed setDate(mStartDateButton, startMillis, mShowStart); setTime(mStartTimeButton, startMillis, mShowStart); setDate(mDueDateButton, dueMillis, mShowDue); setTime(mDueTimeButton, dueMillis, mShowDue); updateCalendarPanel(); } } private class DateClickListener implements View.OnClickListener { private Time mTime; public DateClickListener(Time time) { mTime = time; } public void onClick(View v) { new DatePickerDialog(TaskEditorActivity.this, new DateListener(v), mTime.year, mTime.month, mTime.monthDay).show(); } } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.editor.activity; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.android.core.model.Project.Builder; import org.dodgybits.shuffle.android.core.model.encoding.EntityEncoder; import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister; import org.dodgybits.shuffle.android.list.activity.State; import org.dodgybits.shuffle.android.persistence.provider.ContextProvider; import org.dodgybits.shuffle.android.persistence.provider.ProjectProvider; import roboguice.inject.InjectView; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import com.google.inject.Inject; public class ProjectEditorActivity extends AbstractEditorActivity<Project> { private static final String cTag = "ProjectEditorActivity"; @InjectView(R.id.name) EditText mNameWidget; @InjectView(R.id.default_context) Spinner mDefaultContextSpinner; @InjectView(R.id.parallel_entry) RelativeLayout mParallelEntry; @InjectView(R.id.parallel_label) TextView mParallelLabel; @InjectView(R.id.parallel_icon) ImageView mParallelButton; private @InjectView(R.id.active_entry) View mActiveEntry; private @InjectView(R.id.active_entry_checkbox) CheckBox mActiveCheckBox; private @InjectView(R.id.deleted_entry) View mDeletedEntry; private CheckBox mDeletedCheckBox; @Inject private EntityPersister<Project> mPersister; @Inject private EntityEncoder<Project> mEncoder; private String[] mContextNames; private long[] mContextIds; private boolean isParallel; @Override protected void onCreate(Bundle icicle) { Log.d(cTag, "onCreate+"); super.onCreate(icicle); loadCursor(); findViewsAndAddListeners(); if (mState == State.STATE_EDIT) { // Make sure we are at the one and only row in the cursor. mCursor.moveToFirst(); setTitle(R.string.title_edit_project); mOriginalItem = mPersister.read(mCursor); updateUIFromItem(mOriginalItem); } else if (mState == State.STATE_INSERT) { isParallel = false; setTitle(R.string.title_new_project); mDeletedEntry.setVisibility(View.GONE); mDeletedCheckBox.setChecked(false); mActiveCheckBox.setChecked(true); Bundle extras = getIntent().getExtras(); updateUIFromExtras(extras); } } private void findViewsAndAddListeners() { Cursor contactCursor = getContentResolver().query( ContextProvider.Contexts.CONTENT_URI, new String[] {ContextProvider.Contexts._ID, ContextProvider.Contexts.NAME}, null, null, null); int size = contactCursor.getCount() + 1; mContextIds = new long[size]; mContextIds[0] = 0; mContextNames = new String[size]; mContextNames[0] = getText(R.string.none_empty).toString(); for (int i = 1; i < size; i++) { contactCursor.moveToNext(); mContextIds[i] = contactCursor.getLong(0); mContextNames[i] = contactCursor.getString(1); } contactCursor.close(); ArrayAdapter<String> adapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, mContextNames); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mDefaultContextSpinner.setAdapter(adapter); mParallelEntry.setOnClickListener(this); mActiveEntry.setOnClickListener(this); mActiveEntry.setOnFocusChangeListener(this); mDeletedEntry.setOnClickListener(this); mDeletedEntry.setOnFocusChangeListener(this); mDeletedCheckBox = (CheckBox) mDeletedEntry.findViewById(R.id.deleted_entry_checkbox); } @Override protected boolean isValid() { String name = mNameWidget.getText().toString(); return !TextUtils.isEmpty(name); } @Override protected void doDeleteAction() { super.doDeleteAction(); mNameWidget.setText(""); } @Override protected Project createItemFromUI(boolean commitValues) { Builder builder = Project.newBuilder(); if (mOriginalItem != null) { builder.mergeFrom(mOriginalItem); } builder.setName(mNameWidget.getText().toString()); builder.setModifiedDate(System.currentTimeMillis()); builder.setParallel(isParallel); Id defaultContextId = Id.NONE; int selectedItemPosition = mDefaultContextSpinner.getSelectedItemPosition(); if (selectedItemPosition > 0) { defaultContextId = Id.create(mContextIds[selectedItemPosition]); } builder.setDefaultContextId(defaultContextId); builder.setDeleted(mDeletedCheckBox.isChecked()); builder.setActive(mActiveCheckBox.isChecked()); return builder.build(); } @Override protected void updateUIFromExtras(Bundle extras) { // do nothing for now } @Override protected void updateUIFromItem(Project project) { mNameWidget.setTextKeepState(project.getName()); Id defaultContextId = project.getDefaultContextId(); if (defaultContextId.isInitialised()) { for (int i = 1; i < mContextIds.length; i++) { if (mContextIds[i] == defaultContextId.getId()) { mDefaultContextSpinner.setSelection(i); break; } } } else { mDefaultContextSpinner.setSelection(0); } isParallel = project.isParallel(); updateParallelSection(); mActiveCheckBox.setChecked(project.isActive()); mDeletedEntry.setVisibility(project.isDeleted() ? View.VISIBLE : View.GONE); mDeletedCheckBox.setChecked(project.isDeleted()); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.parallel_entry: { isParallel = !isParallel; updateParallelSection(); break; } case R.id.active_entry: { mActiveCheckBox.toggle(); break; } case R.id.deleted_entry: { mDeletedCheckBox.toggle(); break; } default: super.onClick(v); break; } } /** * @return id of layout for this view */ @Override protected int getContentViewResId() { return R.layout.project_editor; } @Override protected Intent getInsertIntent() { return new Intent(Intent.ACTION_INSERT, ProjectProvider.Projects.CONTENT_URI); } @Override protected CharSequence getItemName() { return getString(R.string.project_name); } @Override protected EntityEncoder<Project> getEncoder() { return mEncoder; } @Override protected EntityPersister<Project> getPersister() { return mPersister; } private void loadCursor() { if (mUri != null && mState == State.STATE_EDIT) { mCursor = managedQuery(mUri, ProjectProvider.Projects.FULL_PROJECTION, null, null, null); if (mCursor == null || mCursor.getCount() == 0) { // The cursor is empty. This can happen if the event was deleted. finish(); return; } } } private void updateParallelSection() { if (isParallel) { mParallelLabel.setText(R.string.parallel_title); mParallelButton.setImageResource(R.drawable.parallel); } else { mParallelLabel.setText(R.string.sequence_title); mParallelButton.setImageResource(R.drawable.sequence); } } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.editor.activity; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity; import org.dodgybits.shuffle.android.core.model.Entity; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.encoding.EntityEncoder; import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister; import org.dodgybits.shuffle.android.core.view.MenuUtils; import org.dodgybits.shuffle.android.list.activity.State; import org.dodgybits.shuffle.android.preference.model.Preferences; import android.content.ContentUris; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; /** * A generic activity for editing an item in a database. This can be used either * to simply view an item (Intent.VIEW_ACTION), view and edit an item * (Intent.EDIT_ACTION), or create a new item (Intent.INSERT_ACTION). */ public abstract class AbstractEditorActivity<E extends Entity> extends FlurryEnabledActivity implements View.OnClickListener, View.OnFocusChangeListener { private static final String cTag = "AbstractEditorActivity"; protected int mState; protected Uri mUri; protected Cursor mCursor; protected E mOriginalItem; protected Intent mNextIntent; @Override protected void onCreate(Bundle icicle) { Log.d(cTag, "onCreate+"); super.onCreate(icicle); processIntent(); setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); setContentView(getContentViewResId()); addSavePanelListeners(); Log.d(cTag, "onCreate-"); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: doSaveAction(); break; } return super.onKeyDown(keyCode, event); } @Override public void finish() { if (mNextIntent != null) { startActivity(mNextIntent); } super.finish(); } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); MenuItem item = menu.findItem(MenuUtils.SYNC_ID); if (item != null) { item.setVisible(Preferences.validateTracksSettings(this)); } return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuUtils.addEditorMenuItems(menu, mState); MenuUtils.addPrefsHelpMenuItems(this, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle all of the possible menu actions. switch (item.getItemId()) { case MenuUtils.SAVE_ID: doSaveAction(); break; case MenuUtils.SAVE_AND_ADD_ID: // create an Intent for the new item based on the current item startActivity(getInsertIntent()); doSaveAction(); break; case MenuUtils.DELETE_ID: doDeleteAction(); finish(); break; case MenuUtils.DISCARD_ID: doRevertAction(); break; case MenuUtils.REVERT_ID: doRevertAction(); break; } if (MenuUtils.checkCommonItemsSelected(item, this, MenuUtils.INBOX_ID)) { return true; } return super.onOptionsItemSelected(item); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); E item = createItemFromUI(false); saveItem(outState, item); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); E item = restoreItem(savedInstanceState); updateUIFromItem(item); } @Override public void onFocusChange(View v, boolean hasFocus) { // Because we're emulating a ListView, we need to setSelected() for // views as they are focused. v.setSelected(hasFocus); } public void onClick(View v) { switch (v.getId()) { case R.id.saveButton: doSaveAction(); break; case R.id.discardButton: doRevertAction(); break; } } protected void doSaveAction() { // Save or create the contact if needed Uri result = null; switch (mState) { case State.STATE_EDIT: result = save(); break; case State.STATE_INSERT: result = create(); break; default: Log.e(cTag, "Unknown state in doSaveAction: " + mState); break; } if (result == null) { setResult(RESULT_CANCELED); } else { setResult(RESULT_OK, new Intent().setData(result)); } finish(); } /** * Take care of canceling work on a item. Deletes the item if we had created * it, otherwise reverts to the original text. */ protected void doRevertAction() { if (mCursor != null) { if (mState == State.STATE_EDIT) { // Put the original item back into the database mCursor.close(); mCursor = null; getPersister().update(mOriginalItem); } else if (mState == State.STATE_INSERT) { // if inserting, there's nothing to delete } } setResult(RESULT_CANCELED); finish(); } /** * Take care of deleting a item. Simply deletes the entry. */ protected void doDeleteAction() { // if inserting, there's nothing to delete if (mState == State.STATE_EDIT && mCursor != null) { mCursor.close(); mCursor = null; Id id = Id.create(ContentUris.parseId(mUri)); getPersister().updateDeletedFlag(id, true); } } protected final void showSaveToast() { String text; if (mState == State.STATE_EDIT) { text = getResources().getString(R.string.itemSavedToast, getItemName()); } else { text = getResources().getString(R.string.itemCreatedToast, getItemName()); } Toast.makeText(this, text, Toast.LENGTH_SHORT).show(); } protected boolean isValid() { return true; } protected Uri create() { Uri uri = null; if (isValid()) { E item = createItemFromUI(true); uri = getPersister().insert(item); showSaveToast(); } return uri; } protected Uri save() { Uri uri = null; if (isValid()) { E item = createItemFromUI(true); getPersister().update(item); showSaveToast(); uri = mUri; } return uri; } protected final E restoreItem(Bundle icicle) { return getEncoder().restore(icicle); } protected final void saveItem(Bundle outState, E item) { getEncoder().save(outState, item); } /** * @return id of layout for this view */ abstract protected int getContentViewResId(); abstract protected E createItemFromUI(boolean commitValues); abstract protected void updateUIFromItem(E item); abstract protected void updateUIFromExtras(Bundle extras); abstract protected EntityPersister<E> getPersister(); abstract protected EntityEncoder<E> getEncoder(); abstract protected Intent getInsertIntent(); abstract protected CharSequence getItemName(); private void processIntent() { final Intent intent = getIntent(); // Do some setup based on the action being performed. final String action = intent.getAction(); mUri = intent.getData(); if (action.equals(Intent.ACTION_EDIT)) { // Requested to edit: set that state, and the data being edited. mState = State.STATE_EDIT; } else if (action.equals(Intent.ACTION_INSERT)) { // Requested to insert: set that state, and create a new entry // in the container. mState = State.STATE_INSERT; } else { // Whoops, unknown action! Bail. Log.e(cTag, "Unknown action " + action + ", exiting"); finish(); return; } } private void addSavePanelListeners() { // Setup the bottom buttons View view = findViewById(R.id.saveButton); view.setOnClickListener(this); view = findViewById(R.id.discardButton); view.setOnClickListener(this); } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.editor.activity; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity; import roboguice.inject.InjectView; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.AdapterView.OnItemClickListener; public class IconPickerActivity extends FlurryEnabledActivity implements OnItemClickListener { @SuppressWarnings("unused") private static final String cTag = "IconPickerActivity"; public static final String TYPE = "vnd.android.cursor.dir/vnd.dodgybits.icons"; @InjectView(R.id.iconGrid) GridView mGrid; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.icon_picker); mGrid.setAdapter(new IconAdapter(this)); mGrid.setOnItemClickListener(this); } public void onItemClick(AdapterView<?> parent, View v, int position, long id) { Bundle bundle = new Bundle(); int iconId = (Integer)mGrid.getAdapter().getItem(position); String iconName = getResources().getResourceEntryName(iconId); bundle.putString("iconName", iconName); Intent mIntent = new Intent(); mIntent.putExtras(bundle); setResult(RESULT_OK, mIntent); finish(); } public class IconAdapter extends BaseAdapter { public IconAdapter(Context context) { loadIcons(); } private int[] mIconIds; private void loadIcons() { mIconIds = new int[] { R.drawable.accessories_calculator, R.drawable.accessories_text_editor, R.drawable.applications_accessories, R.drawable.applications_development, R.drawable.applications_games, R.drawable.applications_graphics, R.drawable.applications_internet, R.drawable.applications_office, R.drawable.applications_system, R.drawable.audio_x_generic, R.drawable.camera_photo, R.drawable.computer, R.drawable.emblem_favorite, R.drawable.emblem_important, R.drawable.format_justify_fill, R.drawable.go_home, R.drawable.network_wireless, R.drawable.office_calendar, R.drawable.start_here, R.drawable.system_file_manager, R.drawable.system_search, R.drawable.system_users, R.drawable.utilities_terminal, R.drawable.video_x_generic, R.drawable.weather_showers_scattered, R.drawable.x_office_address_book, }; } public View getView(int position, View convertView, ViewGroup parent) { ImageView i = new ImageView(IconPickerActivity.this); Integer iconId = mIconIds[position]; i.setImageResource(iconId); i.setScaleType(ImageView.ScaleType.FIT_CENTER); return i; } public final int getCount() { return mIconIds.length; } public final Object getItem(int position) { return mIconIds[position]; } public final long getItemId(int position) { return position; } } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.core.view; import org.dodgybits.android.shuffle.R; import android.app.AlertDialog.Builder; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.util.Log; public class AlertUtils { private static final String cTag = "AlertUtils"; private AlertUtils() { //deny } public static void showDeleteGroupWarning(final Context context, final String groupName, final String childName, final int childCount, final OnClickListener buttonListener) { CharSequence title = context.getString(R.string.warning_title); CharSequence message = context.getString(R.string.delete_warning, groupName.toLowerCase(), childCount, childName.toLowerCase()); CharSequence deleteButtonText = context.getString(R.string.menu_delete); CharSequence cancelButtonText = context.getString(R.string.cancel_button_title); OnCancelListener cancelListener = new OnCancelListener() { public void onCancel(DialogInterface dialog) { Log.d(cTag, "Cancelled delete. Do nothing."); } }; Builder builder = new Builder(context); builder.setTitle(title).setIcon(R.drawable.dialog_warning) .setMessage(message) .setNegativeButton(cancelButtonText, buttonListener) .setPositiveButton(deleteButtonText, buttonListener) .setOnCancelListener(cancelListener); builder.create().show(); } public static void showCleanUpInboxMessage(final Context context) { CharSequence title = context.getString(R.string.info_title); CharSequence message = context.getString(R.string.clean_inbox_message); CharSequence buttonText = context.getString(R.string.ok_button_title); Builder builder = new Builder(context); builder.setTitle(title).setIcon(R.drawable.dialog_information) .setMessage(message) .setPositiveButton(buttonText, null); builder.create().show(); } public static void showWarning(final Context context, final String message) { CharSequence title = context.getString(R.string.warning_title); CharSequence buttonText = context.getString(R.string.ok_button_title); Builder builder = new Builder(context); builder.setTitle(title).setIcon(R.drawable.dialog_warning) .setMessage(message) .setPositiveButton(buttonText, null); builder.create().show(); } public static void showFileExistsWarning(final Context context, final String filename, final OnClickListener buttonListener, final OnCancelListener cancelListener) { CharSequence title = context.getString(R.string.warning_title); CharSequence message = context.getString(R.string.warning_filename_exists, filename); CharSequence replaceButtonText = context.getString(R.string.replace_button_title); CharSequence cancelButtonText = context.getString(R.string.cancel_button_title); Builder builder = new Builder(context); builder.setTitle(title).setIcon(R.drawable.dialog_warning) .setMessage(message) .setNegativeButton(cancelButtonText, buttonListener) .setPositiveButton(replaceButtonText, buttonListener) .setOnCancelListener(cancelListener); builder.create().show(); } }
Java
package org.dodgybits.shuffle.android.core.view; import android.content.res.Resources; import android.text.TextUtils; public class ContextIcon { private static final String cPackage = "org.dodgybits.android.shuffle"; private static final String cType = "drawable"; public static final ContextIcon NONE = new ContextIcon(null, 0, 0); public final String iconName; public final int largeIconId; public final int smallIconId; private ContextIcon(String iconName, int largeIconId, int smallIconId) { this.iconName = iconName; this.largeIconId = largeIconId; this.smallIconId = smallIconId; } public static ContextIcon createIcon(String iconName, Resources res) { if (TextUtils.isEmpty(iconName)) return NONE; int largeId = res.getIdentifier(iconName, cType, cPackage); int smallId = res.getIdentifier(iconName + "_small", cType, cPackage); return new ContextIcon(iconName, largeId, smallId); } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.core.view; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.HelpActivity; import org.dodgybits.shuffle.android.list.activity.ContextsActivity; import org.dodgybits.shuffle.android.list.activity.ProjectsActivity; import org.dodgybits.shuffle.android.list.activity.State; import org.dodgybits.shuffle.android.list.activity.expandable.ExpandableContextsActivity; import org.dodgybits.shuffle.android.list.activity.expandable.ExpandableProjectsActivity; import org.dodgybits.shuffle.android.list.activity.task.*; import org.dodgybits.shuffle.android.preference.activity.PreferencesActivity; import org.dodgybits.shuffle.android.preference.model.Preferences; import org.dodgybits.shuffle.android.synchronisation.tracks.activity.SynchronizeActivity; public class MenuUtils { private static final String cTag = "MenuUtils"; private MenuUtils() { // deny } // Identifiers for our menu items. public static final int SAVE_ID = Menu.FIRST; public static final int SAVE_AND_ADD_ID = Menu.FIRST + 1; public static final int REVERT_ID = Menu.FIRST + 2; public static final int DISCARD_ID = Menu.FIRST + 3; public static final int DELETE_ID = Menu.FIRST + 4; public static final int INSERT_ID = Menu.FIRST + 5; public static final int INSERT_CHILD_ID = Menu.FIRST + 6; public static final int INSERT_GROUP_ID = Menu.FIRST + 7; public static final int INBOX_ID = Menu.FIRST + 10; public static final int CALENDAR_ID = Menu.FIRST + 11; public static final int TOP_TASKS_ID = Menu.FIRST + 12; public static final int PROJECT_ID = Menu.FIRST + 13; public static final int CONTEXT_ID = Menu.FIRST + 14; public static final int TICKLER_ID = Menu.FIRST + 15; public static final int PREFERENCE_ID = Menu.FIRST + 20; public static final int HELP_ID = Menu.FIRST + 21; public static final int SYNC_ID = Menu.FIRST + 22; public static final int SEARCH_ID = Menu.FIRST + 23; public static final int CLEAN_INBOX_ID = Menu.FIRST + 50; public static final int PERMANENTLY_DELETE_ID = Menu.FIRST + 51; // Menu item for activity specific items public static final int PUT_BACK_ID = Menu.FIRST + 100; public static final int COMPLETE_ID = Menu.FIRST + 101; public static final int MOVE_UP_ID = Menu.FIRST + 102; public static final int MOVE_DOWN_ID = Menu.FIRST + 103; // Editor menus private static final int SAVE_ORDER = 1; private static final int SAVE_AND_ADD_ORDER = 2; private static final int REVERT_ORDER = 3; private static final int DISCARD_ORDER = 3; // Context menus private static final int EDIT_ORDER = 1; private static final int PUT_BACK_ORDER = 3; private static final int COMPLETE_ORDER = 4; private static final int MOVE_UP_ORDER = 5; private static final int MOVE_DOWN_ORDER = 6; private static final int DELETE_ORDER = 10; // List menus private static final int INSERT_ORDER = 1; private static final int INSERT_CHILD_ORDER = 1; private static final int INSERT_GROUP_ORDER = 2; private static final int CLEAN_INBOX_ORDER = 101; private static final int PERMANENTLY_DELETE_ORDER = 102; // General menus private static final int PERSPECTIVE_ORDER = 201; private static final int PREFERENCE_ORDER = 202; private static final int SYNCH_ORDER = 203; private static final int SEARCH_ORDER = 204; private static final int HELP_ORDER = 205; public static void addInsertMenuItems(Menu menu, String itemName, boolean isTaskList, Context context) { String menuName = context.getResources().getString(R.string.menu_insert, itemName); menu.add(Menu.NONE, INSERT_ID, INSERT_ORDER, menuName) .setIcon(android.R.drawable.ic_menu_add) .setAlphabeticShortcut(isTaskList ? 'c' : 'a'); } public static void addExpandableInsertMenuItems(Menu menu, String groupName, String childName, Context context) { String menuName; menuName = context.getResources().getString(R.string.menu_insert, childName); menu.add(Menu.NONE, INSERT_CHILD_ID, INSERT_CHILD_ORDER, menuName) .setIcon(android.R.drawable.ic_menu_add).setAlphabeticShortcut('c'); menuName = context.getResources().getString(R.string.menu_insert, groupName); menu.add(Menu.NONE, INSERT_GROUP_ID, INSERT_GROUP_ORDER, menuName) .setIcon(android.R.drawable.ic_menu_add).setAlphabeticShortcut('a'); } public static void addViewMenuItems(Menu menu, int currentViewMenuId) { SubMenu viewMenu = menu.addSubMenu(Menu.NONE, Menu.NONE, PERSPECTIVE_ORDER, R.string.menu_view) .setIcon(R.drawable.preferences_system_windows); viewMenu.add(Menu.NONE, INBOX_ID, 0, R.string.title_inbox) .setChecked(INBOX_ID == currentViewMenuId); viewMenu.add(Menu.NONE, CALENDAR_ID, 1, R.string.title_due_tasks) .setChecked(CALENDAR_ID == currentViewMenuId); viewMenu.add(Menu.NONE, TOP_TASKS_ID, 2, R.string.title_next_tasks) .setChecked(TOP_TASKS_ID == currentViewMenuId); viewMenu.add(Menu.NONE, PROJECT_ID, 3, R.string.title_project) .setChecked(PROJECT_ID == currentViewMenuId); viewMenu.add(Menu.NONE, CONTEXT_ID, 4, R.string.title_context) .setChecked(CONTEXT_ID == currentViewMenuId); viewMenu.add(Menu.NONE, TICKLER_ID, 5, R.string.title_tickler) .setChecked(TICKLER_ID == currentViewMenuId); } public static void addEditorMenuItems(Menu menu, int state) { menu.add(Menu.NONE, SAVE_ID, SAVE_ORDER, R.string.menu_save) .setIcon(android.R.drawable.ic_menu_save).setAlphabeticShortcut('s'); menu.add(Menu.NONE, SAVE_AND_ADD_ID, SAVE_AND_ADD_ORDER, R.string.menu_save_and_add) .setIcon(android.R.drawable.ic_menu_save); // Build the menus that are shown when editing. if (state == State.STATE_EDIT) { menu.add(Menu.NONE, REVERT_ID, REVERT_ORDER, R.string.menu_revert) .setIcon(android.R.drawable.ic_menu_revert).setAlphabeticShortcut('r'); menu.add(Menu.NONE, DELETE_ID, DELETE_ORDER, R.string.menu_delete) .setIcon(android.R.drawable.ic_menu_delete).setAlphabeticShortcut('d'); // Build the menus that are shown when inserting. } else { menu.add(Menu.NONE, DISCARD_ID, DISCARD_ORDER, R.string.menu_discard) .setIcon(android.R.drawable.ic_menu_close_clear_cancel).setAlphabeticShortcut('d'); } } public static void addPrefsHelpMenuItems(Context context, Menu menu) { menu.add(Menu.NONE, PREFERENCE_ID, PREFERENCE_ORDER, R.string.menu_preferences) .setIcon(android.R.drawable.ic_menu_preferences).setAlphabeticShortcut('p'); menu.add(Menu.NONE, HELP_ID, HELP_ORDER, R.string.menu_help) .setIcon(android.R.drawable.ic_menu_help).setAlphabeticShortcut('h'); } public static void addSyncMenuItem(Context context, Menu menu) { menu.add(Menu.NONE, SYNC_ID, SYNCH_ORDER, R.string.menu_sync) .setIcon(android.R.drawable.ic_menu_rotate).setVisible(Preferences.validateTracksSettings(context)); } public static void addSearchMenuItem(Context context, Menu menu) { menu.add(Menu.NONE, SEARCH_ID, SEARCH_ORDER, R.string.menu_search) .setIcon(android.R.drawable.ic_menu_search).setAlphabeticShortcut('s'); } public static void addSelectedAlternativeMenuItems(Menu menu, Uri uri, boolean includeView) { // Build menu... always starts with the EDIT action... int viewIndex = 0; int editIndex = (includeView ? 1 : 0); Intent[] specifics = new Intent[editIndex + 1]; MenuItem[] items = new MenuItem[editIndex + 1]; if (includeView) { specifics[viewIndex] = new Intent(Intent.ACTION_VIEW, uri); } specifics[editIndex] = new Intent(Intent.ACTION_EDIT, uri); // ... is followed by whatever other actions are available... Intent intent = new Intent(null, uri); intent.addCategory(Intent.CATEGORY_ALTERNATIVE); menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, Menu.NONE, EDIT_ORDER, null, specifics, intent, 0, items); // Give a shortcut to the edit action. if (items[editIndex] != null) { items[editIndex].setAlphabeticShortcut('e'); items[editIndex].setIcon(android.R.drawable.ic_menu_edit); } if (includeView && items[viewIndex] != null) { items[viewIndex].setAlphabeticShortcut('v'); items[viewIndex].setIcon(android.R.drawable.ic_menu_view); } } public static void addPutBackMenuItem(Menu menu) { menu.add(Menu.CATEGORY_ALTERNATIVE, PUT_BACK_ID, PUT_BACK_ORDER, R.string.menu_put_back); } public static void addCompleteMenuItem(Menu menu, boolean isComplete) { int labelId = isComplete ? R.string.menu_incomplete : R.string.menu_complete; menu.add(Menu.CATEGORY_ALTERNATIVE, COMPLETE_ID, COMPLETE_ORDER, labelId) .setIcon(R.drawable.btn_check_on).setAlphabeticShortcut('x'); } public static void addDeleteMenuItem(Menu menu, boolean isDeleted) { int labelId = isDeleted ? R.string.menu_undelete : R.string.menu_delete; menu.add(Menu.CATEGORY_ALTERNATIVE, DELETE_ID, DELETE_ORDER, labelId) .setIcon(android.R.drawable.ic_menu_delete).setAlphabeticShortcut('d'); } public static void addCleanInboxMenuItem(Menu menu) { menu.add(Menu.NONE, CLEAN_INBOX_ID, CLEAN_INBOX_ORDER, R.string.clean_inbox_button_title) .setIcon(R.drawable.edit_clear).setAlphabeticShortcut('i'); } public static void addPermanentlyDeleteMenuItem(Menu menu) { menu.add(Menu.NONE, PERMANENTLY_DELETE_ID, PERMANENTLY_DELETE_ORDER, R.string.permanently_delete_button_title) .setIcon(R.drawable.icon_delete); } public static void addMoveMenuItems(Menu menu, boolean enableUp, boolean enableDown) { if (enableUp) { menu.add(Menu.CATEGORY_ALTERNATIVE, MOVE_UP_ID, MOVE_UP_ORDER, R.string.menu_move_up) .setIcon(R.drawable.go_up).setAlphabeticShortcut('k'); } if (enableDown) { menu.add(Menu.CATEGORY_ALTERNATIVE, MOVE_DOWN_ID, MOVE_DOWN_ORDER, R.string.menu_move_down) .setIcon(R.drawable.go_down).setAlphabeticShortcut('j'); } } public static boolean checkCommonItemsSelected(MenuItem item, Activity activity, int currentViewMenuId) { return checkCommonItemsSelected(item.getItemId(), activity, currentViewMenuId, true); } public static boolean checkCommonItemsSelected(int menuItemId, Activity activity, int currentViewMenuId) { return checkCommonItemsSelected(menuItemId, activity, currentViewMenuId, true); } public static boolean checkCommonItemsSelected(int menuItemId, Activity activity, int currentViewMenuId, boolean finishCurrentActivity) { switch (menuItemId) { case MenuUtils.INBOX_ID: if (currentViewMenuId != INBOX_ID) { Log.d(cTag, "Switching to inbox"); activity.startActivity(new Intent(activity, InboxActivity.class)); if (finishCurrentActivity) activity.finish(); } return true; case MenuUtils.CALENDAR_ID: if (currentViewMenuId != CALENDAR_ID) { Log.d(cTag, "Switching to calendar"); activity.startActivity(new Intent(activity, TabbedDueActionsActivity.class)); if (finishCurrentActivity) activity.finish(); } return true; case MenuUtils.TOP_TASKS_ID: if (currentViewMenuId != TOP_TASKS_ID) { Log.d(cTag, "Switching to top tasks"); activity.startActivity(new Intent(activity, TopTasksActivity.class)); if (finishCurrentActivity) activity.finish(); } return true; case MenuUtils.PROJECT_ID: if (currentViewMenuId != PROJECT_ID) { Log.d(cTag, "Switching to project list"); Class<? extends Activity> activityClass = null; if (Preferences.isProjectViewExpandable(activity)) { activityClass = ExpandableProjectsActivity.class; } else { activityClass = ProjectsActivity.class; } activity.startActivity(new Intent(activity, activityClass)); if (finishCurrentActivity) activity.finish(); } return true; case CONTEXT_ID: if (currentViewMenuId != CONTEXT_ID) { Log.d(cTag, "Switching to context list"); Class<? extends Activity> activityClass = null; if (Preferences.isContextViewExpandable(activity)) { activityClass = ExpandableContextsActivity.class; } else { activityClass = ContextsActivity.class; } activity.startActivity(new Intent(activity, activityClass)); if (finishCurrentActivity) activity.finish(); } return true; case TICKLER_ID: Log.d(cTag, "Switching to tickler list"); activity.startActivity(new Intent(activity, TicklerActivity.class)); return true; case PREFERENCE_ID: Log.d(cTag, "Bringing up preferences"); activity.startActivity(new Intent(activity, PreferencesActivity.class)); return true; case HELP_ID: Log.d(cTag, "Bringing up help"); Intent intent = new Intent(activity, HelpActivity.class); intent.putExtra(HelpActivity.cHelpPage, getHelpScreen(currentViewMenuId)); activity.startActivity(intent); return true; case SYNC_ID: Log.d(cTag, "starting sync"); activity.startActivity(new Intent(activity, SynchronizeActivity.class)); return true; case SEARCH_ID: Log.d(cTag, "starting search"); activity.onSearchRequested(); return true; } return false; } private static int getHelpScreen(int currentViewMenuId) { int result = 0; switch (currentViewMenuId) { case INBOX_ID: result = 1; break; case PROJECT_ID: result = 2; break; case CONTEXT_ID: result = 3; break; case TOP_TASKS_ID: result = 4; break; case CALENDAR_ID: result = 5; break; } return result; } }
Java
package org.dodgybits.shuffle.android.core.view; import org.dodgybits.android.shuffle.R; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; public class IconArrayAdapter extends ArrayAdapter<CharSequence> { private Integer[] mIconIds; public IconArrayAdapter( Context context, int resource, int textViewResourceId, CharSequence[] objects, Integer[] iconIds) { super(context, resource, textViewResourceId, objects); mIconIds = iconIds; } public View getView(int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); TextView nameView = (TextView) view.findViewById(R.id.name); // don't use toString in order to preserve colour change nameView.setText(getItem(position)); Integer iconId = null; if (position < mIconIds.length) { iconId = mIconIds[position]; if (iconId != null) { nameView.setCompoundDrawablesWithIntrinsicBounds( getContext().getResources().getDrawable(iconId), null, null, null); } } return view; } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.core.view; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.GradientDrawable.Orientation; public class DrawableUtils { private DrawableUtils() { //deny } public static GradientDrawable createGradient(int colour, Orientation orientation) { return createGradient(colour, orientation, 1.1f, 0.9f); } public static GradientDrawable createGradient(int colour, Orientation orientation, float startOffset, float endOffset) { int[] colours = new int[2]; float[] hsv1 = new float[3]; float[] hsv2 = new float[3]; Color.colorToHSV(colour, hsv1); Color.colorToHSV(colour, hsv2); hsv1[2] *= startOffset; hsv2[2] *= endOffset; colours[0] = Color.HSVToColor(hsv1); colours[1] = Color.HSVToColor(hsv2); return new GradientDrawable(orientation, colours); } }
Java
package org.dodgybits.shuffle.android.core.configuration; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.android.core.model.Task; import org.dodgybits.shuffle.android.core.model.encoding.ContextEncoder; import org.dodgybits.shuffle.android.core.model.encoding.EntityEncoder; import org.dodgybits.shuffle.android.core.model.encoding.ProjectEncoder; import org.dodgybits.shuffle.android.core.model.encoding.TaskEncoder; import org.dodgybits.shuffle.android.core.model.persistence.ContextPersister; import org.dodgybits.shuffle.android.core.model.persistence.DefaultEntityCache; import org.dodgybits.shuffle.android.core.model.persistence.EntityCache; import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister; import org.dodgybits.shuffle.android.core.model.persistence.ProjectPersister; import org.dodgybits.shuffle.android.core.model.persistence.TaskPersister; import org.dodgybits.shuffle.android.core.model.persistence.selector.Flag; import org.dodgybits.shuffle.android.core.view.MenuUtils; import org.dodgybits.shuffle.android.list.annotation.ContextTasks; import org.dodgybits.shuffle.android.list.annotation.Contexts; import org.dodgybits.shuffle.android.list.annotation.DueTasks; import org.dodgybits.shuffle.android.list.annotation.ExpandableContexts; import org.dodgybits.shuffle.android.list.annotation.ExpandableProjects; import org.dodgybits.shuffle.android.list.annotation.Inbox; import org.dodgybits.shuffle.android.list.annotation.ProjectTasks; import org.dodgybits.shuffle.android.list.annotation.Projects; import org.dodgybits.shuffle.android.list.annotation.Tickler; import org.dodgybits.shuffle.android.list.annotation.TopTasks; import org.dodgybits.shuffle.android.list.config.AbstractTaskListConfig; import org.dodgybits.shuffle.android.list.config.ContextListConfig; import org.dodgybits.shuffle.android.list.config.ContextTasksListConfig; import org.dodgybits.shuffle.android.list.config.DueActionsListConfig; import org.dodgybits.shuffle.android.list.config.ProjectListConfig; import org.dodgybits.shuffle.android.list.config.ProjectTasksListConfig; import org.dodgybits.shuffle.android.list.config.StandardTaskQueries; import org.dodgybits.shuffle.android.list.config.TaskListConfig; import org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings; import android.content.ContextWrapper; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.TypeLiteral; public class ShuffleModule extends AbstractModule { @Override protected void configure() { addCaches(); addPersisters(); addEncoders(); addListPreferenceSettings(); addListConfig(); } private void addCaches() { bind(new TypeLiteral<EntityCache<Context>>() {}).to(new TypeLiteral<DefaultEntityCache<Context>>() {}); bind(new TypeLiteral<EntityCache<Project>>() {}).to(new TypeLiteral<DefaultEntityCache<Project>>() {}); } private void addPersisters() { bind(new TypeLiteral<EntityPersister<Context>>() {}).to(ContextPersister.class); bind(new TypeLiteral<EntityPersister<Project>>() {}).to(ProjectPersister.class); bind(new TypeLiteral<EntityPersister<Task>>() {}).to(TaskPersister.class); } private void addEncoders() { bind(new TypeLiteral<EntityEncoder<Context>>() {}).to(ContextEncoder.class); bind(new TypeLiteral<EntityEncoder<Project>>() {}).to(ProjectEncoder.class); bind(new TypeLiteral<EntityEncoder<Task>>() {}).to(TaskEncoder.class); } private void addListPreferenceSettings() { bind(ListPreferenceSettings.class).annotatedWith(Inbox.class).toInstance( new ListPreferenceSettings(StandardTaskQueries.cInbox)); bind(ListPreferenceSettings.class).annotatedWith(TopTasks.class).toInstance( new ListPreferenceSettings(StandardTaskQueries.cNextTasks) .setDefaultCompleted(Flag.no) .disableCompleted() .disableDeleted() .disableActive()); ListPreferenceSettings projectSettings = new ListPreferenceSettings(StandardTaskQueries.cProjectFilterPrefs); bind(ListPreferenceSettings.class).annotatedWith(ProjectTasks.class).toInstance(projectSettings); bind(ListPreferenceSettings.class).annotatedWith(Projects.class).toInstance(projectSettings); bind(ListPreferenceSettings.class).annotatedWith(ExpandableProjects.class).toInstance(projectSettings); ListPreferenceSettings contextSettings = new ListPreferenceSettings(StandardTaskQueries.cContextFilterPrefs); bind(ListPreferenceSettings.class).annotatedWith(ContextTasks.class).toInstance(contextSettings); bind(ListPreferenceSettings.class).annotatedWith(Contexts.class).toInstance(contextSettings); bind(ListPreferenceSettings.class).annotatedWith(ExpandableContexts.class).toInstance(contextSettings); bind(ListPreferenceSettings.class).annotatedWith(DueTasks.class).toInstance( new ListPreferenceSettings(StandardTaskQueries.cDueTasksFilterPrefs).setDefaultCompleted(Flag.no)); bind(ListPreferenceSettings.class).annotatedWith(Tickler.class).toInstance( new ListPreferenceSettings(StandardTaskQueries.cTickler) .setDefaultCompleted(Flag.no) .setDefaultActive(Flag.no)); } private void addListConfig() { bind(DueActionsListConfig.class).annotatedWith(DueTasks.class).to(DueActionsListConfig.class); bind(ContextTasksListConfig.class).annotatedWith(ContextTasks.class).to(ContextTasksListConfig.class); bind(ProjectTasksListConfig.class).annotatedWith(ProjectTasks.class).to(ProjectTasksListConfig.class); bind(ProjectListConfig.class).annotatedWith(Projects.class).to(ProjectListConfig.class); bind(ContextListConfig.class).annotatedWith(Contexts.class).to(ContextListConfig.class); } @Provides @Inbox TaskListConfig providesInboxTaskListConfig(TaskPersister taskPersister, @Inbox ListPreferenceSettings settings) { return new AbstractTaskListConfig( StandardTaskQueries.getQuery(StandardTaskQueries.cInbox), taskPersister, settings) { public int getCurrentViewMenuId() { return MenuUtils.INBOX_ID; } public String createTitle(ContextWrapper context) { return context.getString(R.string.title_inbox); } }; } @Provides @TopTasks TaskListConfig providesTopTasksTaskListConfig(TaskPersister taskPersister, @TopTasks ListPreferenceSettings settings) { return new AbstractTaskListConfig( StandardTaskQueries.getQuery(StandardTaskQueries.cNextTasks), taskPersister, settings) { public int getCurrentViewMenuId() { return MenuUtils.TOP_TASKS_ID; } public String createTitle(ContextWrapper context) { return context.getString(R.string.title_next_tasks); } }; } @Provides @Tickler TaskListConfig providesTicklerTaskListConfig(TaskPersister taskPersister, @Tickler ListPreferenceSettings settings) { return new AbstractTaskListConfig( StandardTaskQueries.getQuery(StandardTaskQueries.cTickler), taskPersister, settings) { public int getCurrentViewMenuId() { return MenuUtils.INBOX_ID; } public String createTitle(ContextWrapper context) { return context.getString(R.string.title_tickler); } }; } }
Java
package org.dodgybits.shuffle.android.core.util; import java.lang.reflect.Field; import android.os.Build; public class OSUtils { public static boolean osAtLeastFroyo() { boolean isFroyoOrAbove = false; try { Field field = Build.VERSION.class.getDeclaredField("SDK_INT"); int version = field.getInt(null); isFroyoOrAbove = version >= Build.VERSION_CODES.FROYO; } catch (Exception e) { // ignore exception - field not available } return isFroyoOrAbove; } }
Java
package org.dodgybits.shuffle.android.core.util; import java.util.List; public class StringUtils { public static String repeat(int count, String token) { return repeat(count, token, ""); } public static String repeat(int count, String token, String delim) { StringBuilder builder = new StringBuilder(); for (int i = 1; i <= count; i++) { builder.append(token); if (i < count) { builder.append(delim); } } return builder.toString(); } public static String join(List<String> items, String delim) { StringBuilder result = new StringBuilder(); final int len = items.size(); for(int i = 0; i < len; i++) { result.append(items.get(i)); if (i < len - 1) { result.append(delim); } } return result.toString(); } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.core.util; import static android.text.format.DateUtils.FORMAT_ABBREV_MONTH; import static android.text.format.DateUtils.FORMAT_ABBREV_TIME; import static android.text.format.DateUtils.FORMAT_SHOW_DATE; import static android.text.format.DateUtils.FORMAT_SHOW_TIME; import java.lang.ref.SoftReference; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import android.content.Context; import android.text.format.Time; public class DateUtils { /** * Lazily create date format objects, one per thread. Use soft references so format * may be collected when low on memory. */ private static final ThreadLocal<SoftReference<DateFormat>> cDateFormat = new ThreadLocal<SoftReference<DateFormat>>() { private SoftReference<DateFormat> createValue() { return new SoftReference<DateFormat>(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")); } @Override public SoftReference<DateFormat> get() { SoftReference<DateFormat> value = super.get(); if (value == null || value.get() == null) { value = createValue(); set(value); } return value; } }; /** * Accepts strings in ISO 8601 format. This includes the following cases: * <ul> * <li>2009-08-15T12:50:03+01:00</li> * <li>2009-08-15T12:50:03+0200</li> * <li>2010-04-07T04:00:00Z</li> * </ul> */ public static long parseIso8601Date(String dateStr) throws ParseException { // normalize timezone first String timezone = dateStr.substring(19); timezone = timezone.replaceAll(":", ""); if ("Z".equals(timezone)) { // Z indicates UTC, so convert to standard representation timezone = "+0000"; } String cleanedDateStr = dateStr.substring(0, 19) + timezone; DateFormat f = cDateFormat.get().get(); Date d = f.parse(cleanedDateStr); return d.getTime(); } public static String formatIso8601Date(long ms) { DateFormat f = cDateFormat.get().get(); String dateStr = f.format(new Date(ms)); if (dateStr.length() == 24) { dateStr = dateStr.substring(0, 22) + ":" + dateStr.substring(22); } return dateStr; } public static boolean isSameDay(long millisX, long millisY) { return Time.getJulianDay(millisX, 0) == Time.getJulianDay(millisY, 0); } public static CharSequence displayDateRange(Context context, long startMs, long endMs, boolean includeTime) { CharSequence result = ""; final boolean includeStart = startMs > 0L; final boolean includeEnd = endMs > 0L; if (includeStart) { if (includeEnd) { int flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_MONTH; if (includeTime) { flags |= FORMAT_SHOW_TIME | FORMAT_ABBREV_TIME; } result = android.text.format.DateUtils.formatDateRange( context, startMs, endMs, flags); } else { result = displayShortDateTime(context, startMs); } } else if (includeEnd) { result = displayShortDateTime(context, endMs); } return result; } /** * Display date time in short format using the user's date format settings * as a guideline. * * For epoch, display nothing. * For today, only show the time. * Otherwise, only show the day and month. * * @param context * @param timeInMs datetime to display * @return locale specific representation */ public static CharSequence displayShortDateTime(Context context, long timeInMs) { long now = System.currentTimeMillis(); CharSequence result; if (timeInMs == 0L) { result = ""; } else { int flags; if (isSameDay(timeInMs, now)) { flags = FORMAT_SHOW_TIME | FORMAT_ABBREV_TIME; } else { flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_MONTH; } result = android.text.format.DateUtils.formatDateRange( context, timeInMs, timeInMs, flags); } return result; } }
Java
package org.dodgybits.shuffle.android.core.util; import android.net.Uri; public class CalendarUtils { // We can't use the constants from the provider since it's not a public portion of the SDK. private static final Uri CALENDAR_CONTENT_URI = Uri.parse("content://calendar/calendars"); // Calendars.CONTENT_URI private static final Uri CALENDAR_CONTENT_URI_FROYO_PLUS = Uri.parse("content://com.android.calendar/calendars"); // Calendars.CONTENT_URI private static final Uri EVENT_CONTENT_URI = Uri.parse("content://calendar/events"); // Calendars.CONTENT_URI private static final Uri EVENT_CONTENT_URI_FROYO_PLUS = Uri.parse("content://com.android.calendar/events"); // Calendars.CONTENT_URI public static final String EVENT_BEGIN_TIME = "beginTime"; // android.provider.Calendar.EVENT_BEGIN_TIME public static final String EVENT_END_TIME = "endTime"; // android.provider.Calendar.EVENT_END_TIME public static Uri getCalendarContentUri() { Uri uri; if(OSUtils.osAtLeastFroyo()) { uri = CALENDAR_CONTENT_URI_FROYO_PLUS; } else { uri = CALENDAR_CONTENT_URI; } return uri; } public static Uri getEventContentUri() { Uri uri; if(OSUtils.osAtLeastFroyo()) { uri = EVENT_CONTENT_URI_FROYO_PLUS; } else { uri = EVENT_CONTENT_URI; } return uri; } }
Java
package org.dodgybits.shuffle.android.core.util; import java.lang.ref.SoftReference; import java.util.HashMap; import android.util.Log; /** * Generic in-memory cache based on Romain Guy's suggestion. * See http://code.google.com/events/io/2009/sessions/TurboChargeUiAndroidFast.html */ public class ItemCache<K,V> { private static final String cTag = "ItemCache"; private final HashMap<K, SoftReference<V>> mCache; private final ValueBuilder<K,V> mBuilder; public ItemCache(ValueBuilder<K,V> builder) { mCache = new HashMap<K, SoftReference<V>>(); mBuilder = builder; } public void put(K key, V value) { mCache.put(key, new SoftReference<V>(value)); } public V get(K key) { V value = null; SoftReference<V> reference = mCache.get(key); if (reference != null) { value = reference.get(); } // not in cache or gc'd if (value == null) { Log.d(cTag, "Cache miss for " + key); value = mBuilder.build(key); put(key, value); } return value; } public void remove(K key) { mCache.remove(key); } public void clear() { mCache.clear(); } public interface ValueBuilder<K,V> { V build(K key); } }
Java
package org.dodgybits.shuffle.android.core.util; public final class Constants { private Constants() { //deny } public static final String cPackage = "org.dodgybits.android.shuffle"; public static final int cVersion = 40; public static final String cFlurryApiKey = "T7KF1PCGVU6V2FS8LILF"; public static final String cFlurryCreateEntityEvent = "createEntity"; public static final String cFlurryUpdateEntityEvent = "updateEntity"; public static final String cFlurryDeleteEntityEvent = "deleteEntity"; public static final String cFlurryReorderTasksEvent = "reorderTasks"; public static final String cFlurryCompleteTaskEvent = "completeTask"; public static final String cFlurryTracksSyncStartedEvent = "tracsSyncStarted"; public static final String cFlurryTracksSyncCompletedEvent = "tracsSyncCompleted"; public static final String cFlurryTracksSyncError = "tracksSyncError"; public static final String cFlurryCountParam = "count"; public static final String cFlurryEntityTypeParam = "entityType"; public static final String cFlurryCalendarUpdateError = "calendarUpdateError"; public static final String cIdType = "id"; public static final String cStringType = "string"; }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.core.util; import org.dodgybits.android.shuffle.R; import android.content.Context; import android.graphics.Color; import android.util.Log; public class TextColours { private static final String cTag = "TextColours"; private static TextColours instance = null; private int[] textColours; private int[] bgColours; public static TextColours getInstance(Context context) { if (instance == null) { instance = new TextColours(context); } return instance; } private TextColours(Context context) { Log.d(cTag, "Fetching colours"); String[] colourStrings = context.getResources().getStringArray(R.array.text_colours); Log.d(cTag, "Fetched colours"); textColours = parseColourString(colourStrings); colourStrings = context.getResources().getStringArray(R.array.background_colours); bgColours = parseColourString(colourStrings); } private int[] parseColourString(String[] colourStrings) { int[] colours = new int[colourStrings.length]; for (int i = 0; i < colourStrings.length; i++) { String colourString = '#' + colourStrings[i].substring(1); Log.d(cTag, "Parsing " + colourString); colours[i] = Color.parseColor(colourString); } return colours; } public int getNumColours() { return textColours.length; } public int getTextColour(int position) { return textColours[position]; } public int getBackgroundColour(int position) { return bgColours[position]; } }
Java
package org.dodgybits.shuffle.android.core.model.protocol; import java.util.HashMap; import java.util.Map; import org.dodgybits.shuffle.android.core.model.Id; public class HashEntityDirectory<Entity> implements EntityDirectory<Entity> { private Map<String,Entity> mItemsByName; private Map<Id, Entity> mItemsById; public HashEntityDirectory() { mItemsByName = new HashMap<String,Entity>(); mItemsById = new HashMap<Id,Entity>(); } public void addItem(Id id, String name, Entity item) { mItemsById.put(id, item); mItemsByName.put(name, item); } @Override public Entity findById(Id id) { return mItemsById.get(id); } @Override public Entity findByName(String name) { return mItemsByName.get(name); } }
Java
package org.dodgybits.shuffle.android.core.model.protocol; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.dto.ShuffleProtos.Project.Builder; public class ProjectProtocolTranslator implements EntityProtocolTranslator<Project, org.dodgybits.shuffle.dto.ShuffleProtos.Project> { private EntityDirectory<Context> mContextDirectory; public ProjectProtocolTranslator(EntityDirectory<Context> contextDirectory) { mContextDirectory = contextDirectory; } public org.dodgybits.shuffle.dto.ShuffleProtos.Project toMessage(Project project) { Builder builder = org.dodgybits.shuffle.dto.ShuffleProtos.Project.newBuilder(); builder .setId(project.getLocalId().getId()) .setName((project.getName())) .setModified(ProtocolUtil.toDate(project.getModifiedDate())) .setParallel(project.isParallel()) .setActive(project.isActive()) .setDeleted(project.isDeleted()); final Id defaultContextId = project.getDefaultContextId(); if (defaultContextId.isInitialised()) { builder.setDefaultContextId(defaultContextId.getId()); } final Id tracksId = project.getTracksId(); if (tracksId.isInitialised()) { builder.setTracksId(tracksId.getId()); } return builder.build(); } public Project fromMessage( org.dodgybits.shuffle.dto.ShuffleProtos.Project dto) { Project.Builder builder = Project.newBuilder(); builder .setLocalId(Id.create(dto.getId())) .setName(dto.getName()) .setModifiedDate(ProtocolUtil.fromDate(dto.getModified())) .setParallel(dto.getParallel()); if (dto.hasActive()) { builder.setActive(dto.getActive()); } else { builder.setActive(true); } if (dto.hasDeleted()) { builder.setDeleted(dto.getDeleted()); } else { builder.setDeleted(false); } if (dto.hasDefaultContextId()) { Id defaultContextId = Id.create(dto.getDefaultContextId()); Context context = mContextDirectory.findById(defaultContextId); // it's possible the default context no longer exists so check for it builder.setDefaultContextId(context == null ? Id.NONE : context.getLocalId()); } if (dto.hasTracksId()) { builder.setTracksId(Id.create(dto.getTracksId())); } return builder.build(); } }
Java
package org.dodgybits.shuffle.android.core.model.protocol; import org.dodgybits.shuffle.android.core.model.Id; /** * A lookup service for entities. Useful when matching up entities from different * sources that may have conflicting ids (e.g. backup or remote synching). */ public interface EntityDirectory<Entity> { public Entity findById(Id id); public Entity findByName(String name); }
Java
package org.dodgybits.shuffle.android.core.model.protocol; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.dto.ShuffleProtos.Context.Builder; public class ContextProtocolTranslator implements EntityProtocolTranslator<Context , org.dodgybits.shuffle.dto.ShuffleProtos.Context>{ public org.dodgybits.shuffle.dto.ShuffleProtos.Context toMessage(Context context) { Builder builder = org.dodgybits.shuffle.dto.ShuffleProtos.Context.newBuilder(); builder .setId(context.getLocalId().getId()) .setName((context.getName())) .setModified(ProtocolUtil.toDate(context.getModifiedDate())) .setColourIndex(context.getColourIndex()) .setActive(context.isActive()) .setDeleted(context.isDeleted()); final Id tracksId = context.getTracksId(); if (tracksId.isInitialised()) { builder.setTracksId(tracksId.getId()); } final String iconName = context.getIconName(); if (iconName != null) { builder.setIcon(iconName); } return builder.build(); } public Context fromMessage( org.dodgybits.shuffle.dto.ShuffleProtos.Context dto) { Context.Builder builder = Context.newBuilder(); builder .setLocalId(Id.create(dto.getId())) .setName(dto.getName()) .setModifiedDate(ProtocolUtil.fromDate(dto.getModified())) .setColourIndex(dto.getColourIndex()); if (dto.hasActive()) { builder.setActive(dto.getActive()); } else { builder.setActive(true); } if (dto.hasDeleted()) { builder.setDeleted(dto.getDeleted()); } else { builder.setDeleted(false); } if (dto.hasTracksId()) { builder.setTracksId(Id.create(dto.getTracksId())); } if (dto.hasIcon()) { builder.setIconName(dto.getIcon()); } return builder.build(); } }
Java
package org.dodgybits.shuffle.android.core.model.protocol; import org.dodgybits.shuffle.dto.ShuffleProtos.Date; public final class ProtocolUtil { private ProtocolUtil() { // deny } public static Date toDate(long millis) { return Date.newBuilder() .setMillis(millis) .build(); } public static long fromDate(Date date) { long millis = 0L; if (date != null) { millis = date.getMillis(); } return millis; } }
Java
package org.dodgybits.shuffle.android.core.model.protocol; import com.google.protobuf.MessageLite; public interface EntityProtocolTranslator<E,M extends MessageLite> { E fromMessage(M message); M toMessage(E entity); }
Java
package org.dodgybits.shuffle.android.core.model.protocol; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.android.core.model.Task; import org.dodgybits.shuffle.dto.ShuffleProtos.Task.Builder; public class TaskProtocolTranslator implements EntityProtocolTranslator<Task, org.dodgybits.shuffle.dto.ShuffleProtos.Task> { private final EntityDirectory<Context> mContextDirectory; private final EntityDirectory<Project> mProjectDirectory; public TaskProtocolTranslator( EntityDirectory<Context> contextDirectory, EntityDirectory<Project> projectDirectory) { mContextDirectory = contextDirectory; mProjectDirectory = projectDirectory; } public org.dodgybits.shuffle.dto.ShuffleProtos.Task toMessage(Task task) { Builder builder = org.dodgybits.shuffle.dto.ShuffleProtos.Task.newBuilder(); builder .setId(task.getLocalId().getId()) .setDescription(task.getDescription()) .setCreated(ProtocolUtil.toDate(task.getCreatedDate())) .setModified(ProtocolUtil.toDate(task.getModifiedDate())) .setStartDate(ProtocolUtil.toDate(task.getStartDate())) .setDueDate(ProtocolUtil.toDate(task.getDueDate())) .setAllDay(task.isAllDay()) .setOrder(task.getOrder()) .setComplete(task.isComplete()) .setActive(task.isActive()) .setDeleted(task.isDeleted()); final String details = task.getDetails(); if (details != null) { builder.setDetails(details); } final Id contextId = task.getContextId(); if (contextId.isInitialised()) { builder.setContextId(contextId.getId()); } final Id projectId = task.getProjectId(); if (projectId.isInitialised()) { builder.setProjectId(projectId.getId()); } final String timezone = task.getTimezone(); if (timezone != null) { builder.setTimezone(timezone); } final Id calEventId = task.getCalendarEventId(); if (calEventId.isInitialised()) { builder.setCalEventId(calEventId.getId()); } final Id tracksId = task.getTracksId(); if (tracksId.isInitialised()) { builder.setTracksId(tracksId.getId()); } return builder.build(); } public Task fromMessage( org.dodgybits.shuffle.dto.ShuffleProtos.Task dto) { Task.Builder builder = Task.newBuilder(); builder .setLocalId(Id.create(dto.getId())) .setDescription(dto.getDescription()) .setDetails(dto.getDetails()) .setCreatedDate(ProtocolUtil.fromDate(dto.getCreated())) .setModifiedDate(ProtocolUtil.fromDate(dto.getModified())) .setStartDate(ProtocolUtil.fromDate(dto.getStartDate())) .setDueDate(ProtocolUtil.fromDate(dto.getDueDate())) .setTimezone(dto.getTimezone()) .setAllDay(dto.getAllDay()) .setHasAlarm(false) .setOrder(dto.getOrder()) .setComplete(dto.getComplete()); if (dto.hasActive()) { builder.setActive(dto.getActive()); } else { builder.setActive(true); } if (dto.hasDeleted()) { builder.setDeleted(dto.getDeleted()); } else { builder.setDeleted(false); } if (dto.hasContextId()) { Id contextId = Id.create(dto.getContextId()); Context context = mContextDirectory.findById(contextId); builder.setContextId(context == null ? Id.NONE : context.getLocalId()); } if (dto.hasProjectId()) { Id projectId = Id.create(dto.getProjectId()); Project project = mProjectDirectory.findById(projectId); builder.setProjectId(project == null ? Id.NONE : project.getLocalId()); } if (dto.hasCalEventId()) { builder.setCalendarEventId(Id.create(dto.getCalEventId())); } if (dto.hasTracksId()) { builder.setTracksId(Id.create(dto.getTracksId())); } return builder.build(); } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.core.model; import org.dodgybits.shuffle.android.synchronisation.tracks.model.TracksEntity; import android.text.TextUtils; public class Project implements TracksEntity { private Id mLocalId = Id.NONE; private String mName; private Id mDefaultContextId = Id.NONE; private long mModifiedDate; private boolean mParallel; private boolean mArchived; private Id mTracksId = Id.NONE; private boolean mDeleted; private boolean mActive = true; private Project() { }; public final Id getLocalId() { return mLocalId; } public final String getName() { return mName; } public final Id getDefaultContextId() { return mDefaultContextId; } public final long getModifiedDate() { return mModifiedDate; } public final boolean isParallel() { return mParallel; } public final boolean isArchived() { return mArchived; } public final Id getTracksId() { return mTracksId; } public final String getLocalName() { return mName; } @Override public final boolean isDeleted() { return mDeleted; } public final boolean isValid() { if (TextUtils.isEmpty(mName)) { return false; } return true; } @Override public boolean isActive() { return mActive; } @Override public final String toString() { return String.format( "[Project id=%1$s name='%2$s' defaultContextId='%3$s' " + "parallel=%4$s archived=%5$s tracksId='%6$s' deleted=%7$s active=%8$s]", mLocalId, mName, mDefaultContextId, mParallel, mArchived, mTracksId, mDeleted, mActive); } public static Builder newBuilder() { return Builder.create(); } public static class Builder implements EntityBuilder<Project> { private Builder() { } private Project result; private static Builder create() { Builder builder = new Builder(); builder.result = new Project(); return builder; } public Id getLocalId() { return result.mLocalId; } public Builder setLocalId(Id value) { assert value != null; result.mLocalId = value; return this; } public String getName() { return result.mName; } public Builder setName(String value) { result.mName = value; return this; } public Id getDefaultContextId() { return result.mDefaultContextId; } public Builder setDefaultContextId(Id value) { assert value != null; result.mDefaultContextId = value; return this; } public long getModifiedDate() { return result.mModifiedDate; } public Builder setModifiedDate(long value) { result.mModifiedDate = value; return this; } public boolean isParallel() { return result.mParallel; } public Builder setParallel(boolean value) { result.mParallel = value; return this; } public boolean isArchived() { return result.mArchived; } public Builder setArchived(boolean value) { result.mArchived = value; return this; } public Id getTracksId() { return result.mTracksId; } public Builder setTracksId(Id value) { assert value != null; result.mTracksId = value; return this; } public boolean isActive() { return result.mActive; } @Override public Builder setActive(boolean value) { result.mActive = value; return this; } public boolean isDeleted() { return result.mDeleted; } @Override public Builder setDeleted(boolean value) { result.mDeleted = value; return this; } public final boolean isInitialized() { return result.isValid(); } public Project build() { if (result == null) { throw new IllegalStateException( "build() has already been called on this Builder."); } Project returnMe = result; result = null; return returnMe; } public Builder mergeFrom(Project project) { setLocalId(project.mLocalId); setName(project.mName); setDefaultContextId(project.mDefaultContextId); setModifiedDate(project.mModifiedDate); setParallel(project.mParallel); setArchived(project.mArchived); setTracksId(project.mTracksId); setDeleted(project.mDeleted); setActive(project.mActive); return this; } } }
Java
package org.dodgybits.shuffle.android.core.model.encoding; import android.os.Bundle; public interface EntityEncoder<Entity> { void save(Bundle icicle, Entity e); Entity restore(Bundle icicle); }
Java
package org.dodgybits.shuffle.android.core.model.encoding; import static android.provider.BaseColumns._ID; import static org.dodgybits.shuffle.android.persistence.provider.ContextProvider.Contexts.COLOUR; import static org.dodgybits.shuffle.android.persistence.provider.ContextProvider.Contexts.ICON; import static org.dodgybits.shuffle.android.persistence.provider.ContextProvider.Contexts.MODIFIED_DATE; import static org.dodgybits.shuffle.android.persistence.provider.ContextProvider.Contexts.NAME; import static org.dodgybits.shuffle.android.persistence.provider.ContextProvider.Contexts.TRACKS_ID; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.Context.Builder; import android.os.Bundle; import com.google.inject.Singleton; @Singleton public class ContextEncoder extends AbstractEntityEncoder implements EntityEncoder<Context> { @Override public void save(Bundle icicle, Context context) { putId(icicle, _ID, context.getLocalId()); putId(icicle, TRACKS_ID, context.getTracksId()); icicle.putLong(MODIFIED_DATE, context.getModifiedDate()); putString(icicle, NAME, context.getName()); icicle.putInt(COLOUR, context.getColourIndex()); putString(icicle, ICON, context.getIconName()); } @Override public Context restore(Bundle icicle) { if (icicle == null) return null; Builder builder = Context.newBuilder(); builder.setLocalId(getId(icicle, _ID)); builder.setModifiedDate(icicle.getLong(MODIFIED_DATE, 0L)); builder.setTracksId(getId(icicle, TRACKS_ID)); builder.setName(getString(icicle, NAME)); builder.setColourIndex(icicle.getInt(COLOUR)); builder.setIconName(getString(icicle, ICON)); return builder.build(); } }
Java
package org.dodgybits.shuffle.android.core.model.encoding; import static android.provider.BaseColumns._ID; import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.ARCHIVED; import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.DEFAULT_CONTEXT_ID; import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.MODIFIED_DATE; import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.NAME; import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.PARALLEL; import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.TRACKS_ID; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.android.core.model.Project.Builder; import android.os.Bundle; import com.google.inject.Singleton; @Singleton public class ProjectEncoder extends AbstractEntityEncoder implements EntityEncoder<Project> { @Override public void save(Bundle icicle, Project project) { putId(icicle, _ID, project.getLocalId()); putId(icicle, TRACKS_ID, project.getTracksId()); icicle.putLong(MODIFIED_DATE, project.getModifiedDate()); putString(icicle, NAME, project.getName()); putId(icicle, DEFAULT_CONTEXT_ID, project.getDefaultContextId()); icicle.putBoolean(ARCHIVED, project.isArchived()); icicle.putBoolean(PARALLEL, project.isParallel()); } @Override public Project restore(Bundle icicle) { if (icicle == null) return null; Builder builder = Project.newBuilder(); builder.setLocalId(getId(icicle, _ID)); builder.setModifiedDate(icicle.getLong(MODIFIED_DATE, 0L)); builder.setTracksId(getId(icicle, TRACKS_ID)); builder.setName(getString(icicle, NAME)); builder.setDefaultContextId(getId(icicle, DEFAULT_CONTEXT_ID)); builder.setArchived(icicle.getBoolean(ARCHIVED)); builder.setParallel(icicle.getBoolean(PARALLEL)); return builder.build(); } }
Java
package org.dodgybits.shuffle.android.core.model.encoding; import org.dodgybits.shuffle.android.core.model.Id; import android.os.Bundle; public abstract class AbstractEntityEncoder { protected static Id getId(Bundle icicle, String key) { Id result = Id.NONE; if (icicle.containsKey(key)) { result = Id.create(icicle.getLong(key)); } return result; } protected static void putId(Bundle icicle, String key, Id value) { if (value.isInitialised()) { icicle.putLong(key, value.getId()); } } protected static String getString(Bundle icicle, String key) { String result = null; if (icicle.containsKey(key)) { result = icicle.getString(key); } return result; } protected static void putString(Bundle icicle, String key, String value) { if (value != null) { icicle.putString(key, value); } } }
Java
package org.dodgybits.shuffle.android.core.model.encoding; import static android.provider.BaseColumns._ID; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.ALL_DAY; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.CAL_EVENT_ID; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.COMPLETE; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.CONTEXT_ID; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.CREATED_DATE; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.DESCRIPTION; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.DETAILS; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.DISPLAY_ORDER; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.DUE_DATE; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.HAS_ALARM; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.MODIFIED_DATE; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.PROJECT_ID; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.START_DATE; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.TIMEZONE; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.TRACKS_ID; import org.dodgybits.shuffle.android.core.model.Task; import org.dodgybits.shuffle.android.core.model.Task.Builder; import android.os.Bundle; import com.google.inject.Singleton; @Singleton public class TaskEncoder extends AbstractEntityEncoder implements EntityEncoder<Task> { @Override public void save(Bundle icicle, Task task) { putId(icicle, _ID, task.getLocalId()); putId(icicle, TRACKS_ID, task.getTracksId()); icicle.putLong(MODIFIED_DATE, task.getModifiedDate()); putString(icicle, DESCRIPTION, task.getDescription()); putString(icicle, DETAILS, task.getDetails()); putId(icicle, CONTEXT_ID, task.getContextId()); putId(icicle, PROJECT_ID, task.getProjectId()); icicle.putLong(CREATED_DATE, task.getCreatedDate()); icicle.putLong(START_DATE, task.getStartDate()); icicle.putLong(DUE_DATE, task.getDueDate()); putString(icicle, TIMEZONE, task.getTimezone()); putId(icicle, CAL_EVENT_ID, task.getCalendarEventId()); icicle.putBoolean(ALL_DAY, task.isAllDay()); icicle.putBoolean(HAS_ALARM, task.hasAlarms()); icicle.putInt(DISPLAY_ORDER, task.getOrder()); icicle.putBoolean(COMPLETE, task.isComplete()); } @Override public Task restore(Bundle icicle) { if (icicle == null) return null; Builder builder = Task.newBuilder(); builder.setLocalId(getId(icicle, _ID)); builder.setModifiedDate(icicle.getLong(MODIFIED_DATE, 0L)); builder.setTracksId(getId(icicle, TRACKS_ID)); builder.setDescription(getString(icicle, DESCRIPTION)); builder.setDetails(getString(icicle, DETAILS)); builder.setContextId(getId(icicle, CONTEXT_ID)); builder.setProjectId(getId(icicle, PROJECT_ID)); builder.setCreatedDate(icicle.getLong(CREATED_DATE, 0L)); builder.setStartDate(icicle.getLong(START_DATE, 0L)); builder.setDueDate(icicle.getLong(DUE_DATE, 0L)); builder.setTimezone(getString(icicle, TIMEZONE)); builder.setCalendarEventId(getId(icicle, CAL_EVENT_ID)); builder.setAllDay(icicle.getBoolean(ALL_DAY)); builder.setHasAlarm(icicle.getBoolean(HAS_ALARM)); builder.setOrder(icicle.getInt(DISPLAY_ORDER)); builder.setComplete(icicle.getBoolean(COMPLETE)); return builder.build(); } }
Java
package org.dodgybits.shuffle.android.core.model; public interface EntityBuilder<E> { EntityBuilder<E> mergeFrom(E e); EntityBuilder<E> setLocalId(Id id); EntityBuilder<E> setModifiedDate(long ms); EntityBuilder<E> setTracksId(Id id); EntityBuilder<E> setActive(boolean value); EntityBuilder<E> setDeleted(boolean value); E build(); }
Java
package org.dodgybits.shuffle.android.core.model; public final class Id { private final long mId; public static final Id NONE = new Id(0L); private Id(long id) { mId = id; } public long getId() { return mId; } public boolean isInitialised() { return mId != 0L; } @Override public String toString() { return isInitialised() ? String.valueOf(mId) : ""; } @Override public boolean equals(Object o) { boolean result = false; if (o instanceof Id) { result = ((Id)o).mId == mId; } return result; } @Override public int hashCode() { return (int)mId; } public static Id create(long id) { Id result = NONE; if (id != 0L) { result = new Id(id); } return result; } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.core.model; import org.dodgybits.shuffle.android.synchronisation.tracks.model.TracksEntity; import android.text.TextUtils; public class Context implements TracksEntity { private Id mLocalId = Id.NONE; private String mName; private int mColourIndex; private String mIconName; private long mModifiedDate; private boolean mDeleted; private boolean mActive = true; private Id mTracksId = Id.NONE; private Context() { }; public final Id getLocalId() { return mLocalId; } public final String getName() { return mName; } public final int getColourIndex() { return mColourIndex; } public final String getIconName() { return mIconName; } public final long getModifiedDate() { return mModifiedDate; } public final Id getTracksId() { return mTracksId; } public final String getLocalName() { return mName; } @Override public boolean isDeleted() { return mDeleted; } @Override public boolean isActive() { return mActive; } public final boolean isValid() { if (TextUtils.isEmpty(mName)) { return false; } return true; } @Override public final String toString() { return String.format( "[Context id=%1$s name='%2$s' colourIndex='%3$s' " + "iconName=%4$s tracksId='%5$s' active=%6$s deleted=%7$s]", mLocalId, mName, mColourIndex, mIconName, mTracksId, mActive, mDeleted); } public static Builder newBuilder() { return Builder.create(); } public static class Builder implements EntityBuilder<Context> { private Builder() { } private Context result; private static Builder create() { Builder builder = new Builder(); builder.result = new Context(); return builder; } public Id getLocalId() { return result.mLocalId; } public Builder setLocalId(Id value) { assert value != null; result.mLocalId = value; return this; } public String getName() { return result.mName; } public Builder setName(String value) { result.mName = value; return this; } public int getColourIndex() { return result.mColourIndex; } public Builder setColourIndex(int value) { result.mColourIndex = value; return this; } public String getIconName() { return result.mIconName; } public Builder setIconName(String value) { result.mIconName = value; return this; } public long getModifiedDate() { return result.mModifiedDate; } public Builder setModifiedDate(long value) { result.mModifiedDate = value; return this; } public Id getTracksId() { return result.mTracksId; } public Builder setTracksId(Id value) { assert value != null; result.mTracksId = value; return this; } public boolean isActive() { return result.mActive; } public Builder setActive(boolean value) { result.mActive = value; return this; } public boolean isDeleted() { return result.mDeleted; } @Override public Builder setDeleted(boolean value) { result.mDeleted = value; return this; } public final boolean isInitialized() { return result.isValid(); } public Context build() { if (result == null) { throw new IllegalStateException( "build() has already been called on this Builder."); } Context returnMe = result; result = null; return returnMe; } public Builder mergeFrom(Context context) { setLocalId(context.mLocalId); setName(context.mName); setColourIndex(context.mColourIndex); setIconName(context.mIconName); setModifiedDate(context.mModifiedDate); setTracksId(context.mTracksId); setDeleted(context.mDeleted); setActive(context.mActive); return this; } } }
Java
package org.dodgybits.shuffle.android.core.model.persistence; import java.util.Collection; import org.dodgybits.shuffle.android.core.model.Entity; import org.dodgybits.shuffle.android.core.model.Id; import android.database.Cursor; import android.net.Uri; public interface EntityPersister<E extends Entity> { Uri getContentUri(); String[] getFullProjection(); E findById(Id localId); E read(Cursor cursor); Uri insert(E e); void bulkInsert(Collection<E> entities); void update(E e); /** * Set deleted flag entity with the given id to isDeleted. * * @param id entity id * @param isDeleted flag to set deleted flag to * @return whether the operation succeeded */ boolean updateDeletedFlag(Id id, boolean isDeleted); /** * Set deleted flag for entities that match the criteria to isDeleted. * * @param selection where clause * @param selectionArgs parameter values from where clause * @param isDeleted flag to set deleted flag to * @return number of entities updates */ int updateDeletedFlag(String selection, String[] selectionArgs, boolean isDeleted); /** * Permanently delete all items that currently flagged as deleted. * * @return number of entities removed */ int emptyTrash(); /** * Permanently delete entity with the given id. * * @return whether the operation succeeded */ boolean deletePermanently(Id id); }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.core.model.persistence; import java.util.Calendar; import java.util.TimeZone; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.android.core.model.Task; import org.dodgybits.shuffle.android.persistence.provider.ContextProvider; import org.dodgybits.shuffle.android.persistence.provider.ProjectProvider; import org.dodgybits.shuffle.android.persistence.provider.TaskProvider; import roboguice.inject.ContentResolverProvider; import roboguice.inject.ResourcesProvider; import com.google.inject.Inject; import android.content.ContentResolver; import android.content.ContentUris; import android.content.res.Resources; import android.net.Uri; import android.os.Handler; import android.text.format.DateUtils; import android.util.Log; public class InitialDataGenerator { private static final String cTag = "InitialDataGenerator"; private static final int AT_HOME_INDEX = 0; private static final int AT_WORK_INDEX = 1; private static final int AT_COMPUTER_INDEX = 2; private static final int ERRANDS_INDEX = 3; private static final int COMMUNICATION_INDEX = 4; private static final int READ_INDEX = 5; private Context[] mPresetContexts = null; private EntityPersister<Context> mContextPersister; private EntityPersister<Project> mProjectPersister; private EntityPersister<Task> mTaskPersister; private ContentResolver mContentResolver; private Resources mResources; @Inject public InitialDataGenerator(EntityPersister<Context> contextPersister, EntityPersister<Project> projectPersister, EntityPersister<Task> taskPersister, ContentResolverProvider provider, ResourcesProvider resourcesProvider ) { mContentResolver = provider.get(); mResources = resourcesProvider.get(); mContextPersister = contextPersister; mProjectPersister = projectPersister; mTaskPersister = taskPersister; initPresetContexts(); } public Context getSampleContext() { return mPresetContexts[ERRANDS_INDEX]; } /** * Delete any existing projects, contexts and tasks and create the standard * contexts. * * @param handler the android message handler */ public void cleanSlate(Handler handler) { initPresetContexts(); int deletedRows = mContentResolver.delete( TaskProvider.Tasks.CONTENT_URI, null, null); Log.d(cTag, "Deleted " + deletedRows + " tasks."); deletedRows = mContentResolver.delete( ProjectProvider.Projects.CONTENT_URI, null, null); Log.d(cTag, "Deleted " + deletedRows + " projects."); deletedRows = mContentResolver.delete( ContextProvider.Contexts.CONTENT_URI, null, null); Log.d(cTag, "Deleted " + deletedRows + " contexts."); for (int i = 0; i < mPresetContexts.length; i++) { mPresetContexts[i] = insertContext(mPresetContexts[i]); } if (handler != null) handler.sendEmptyMessage(0); } /** * Clean out the current data and populate the database with a set of sample * data. * @param handler the message handler */ public void createSampleData(Handler handler) { cleanSlate(null); Calendar cal = Calendar.getInstance(); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); long now = cal.getTimeInMillis(); cal.add(Calendar.DAY_OF_YEAR, -1); long yesterday = cal.getTimeInMillis(); cal.add(Calendar.DAY_OF_YEAR, 3); long twoDays = cal.getTimeInMillis(); cal.add(Calendar.DAY_OF_YEAR, 5); long oneWeek = cal.getTimeInMillis(); cal.add(Calendar.WEEK_OF_YEAR, 1); long twoWeeks = cal.getTimeInMillis(); Project sellBike = createProject("Sell old Powerbook", Id.NONE); sellBike = insertProject(sellBike); insertTask( createTask("Backup data", null, AT_COMPUTER_INDEX, sellBike, now, now + DateUtils.HOUR_IN_MILLIS)); insertTask( createTask("Reformat HD", "Install Leopard and updates", AT_COMPUTER_INDEX, sellBike, twoDays, twoDays + 2 * DateUtils.HOUR_IN_MILLIS)); insertTask( createTask("Determine good price", "Take a look on ebay for similar systems", AT_COMPUTER_INDEX, sellBike, oneWeek, oneWeek + 2 * DateUtils.HOUR_IN_MILLIS)); insertTask( createTask("Put up ad", AT_COMPUTER_INDEX, sellBike, twoWeeks)); Project cleanGarage = createProject("Clean out garage", Id.NONE); cleanGarage = insertProject(cleanGarage); insertTask( createTask("Sort out contents", "Split into keepers and junk", AT_HOME_INDEX, cleanGarage, yesterday, yesterday)); insertTask( createTask("Advertise garage sale", "Local paper(s) and on craigslist", AT_COMPUTER_INDEX, cleanGarage, oneWeek, oneWeek + 2 * DateUtils.HOUR_IN_MILLIS)); insertTask( createTask("Contact local charities", "See what they want or maybe just put in charity bins", COMMUNICATION_INDEX, cleanGarage, now, now)); insertTask( createTask("Take rest to tip", "Hire trailer?", ERRANDS_INDEX, cleanGarage, now, now)); Project skiTrip = createProject("Organise ski trip", Id.NONE); skiTrip = insertProject(skiTrip); insertTask( createTask("Send email to determine best week", null, COMMUNICATION_INDEX, skiTrip, now, now + 2 * DateUtils.HOUR_IN_MILLIS)); insertTask( createTask("Look up package deals", AT_COMPUTER_INDEX, skiTrip, 0L)); insertTask( createTask("Book chalet", AT_COMPUTER_INDEX, skiTrip, 0L)); insertTask( createTask("Book flights", AT_COMPUTER_INDEX, skiTrip, 0L)); insertTask( createTask("Book hire car", AT_COMPUTER_INDEX, skiTrip, 0L)); insertTask( createTask("Get board waxed", ERRANDS_INDEX, skiTrip, 0L)); Project discussI8n = createProject("Discuss internationalization", mPresetContexts[AT_WORK_INDEX].getLocalId()); discussI8n = insertProject(discussI8n); insertTask( createTask("Read up on options", null, AT_COMPUTER_INDEX, discussI8n, twoDays, twoDays + 2 * DateUtils.HOUR_IN_MILLIS)); insertTask( createTask("Kickoff meeting", null, COMMUNICATION_INDEX, discussI8n, oneWeek, oneWeek + 2 * DateUtils.HOUR_IN_MILLIS)); insertTask( createTask("Produce report", null, AT_WORK_INDEX, discussI8n, twoWeeks, twoWeeks + 2 * DateUtils.HOUR_IN_MILLIS)); // a few stand alone tasks insertTask( createTask("Organise music collection", AT_COMPUTER_INDEX, null, 0L)); insertTask( createTask("Make copy of door keys", ERRANDS_INDEX, null, yesterday)); insertTask( createTask("Read Falling Man", READ_INDEX, null, 0L)); insertTask( createTask("Buy Tufte books", ERRANDS_INDEX, null, oneWeek)); if (handler != null) handler.sendEmptyMessage(0); } private void initPresetContexts() { if (mPresetContexts == null) { mPresetContexts = new Context[] { createContext(mResources.getText(R.string.context_athome).toString(), 5, "go_home"), // 0 createContext(mResources.getText(R.string.context_atwork).toString(), 19, "system_file_manager"), // 1 createContext(mResources.getText(R.string.context_online).toString(), 1, "applications_internet"), // 2 createContext(mResources.getText(R.string.context_errands).toString(), 14, "applications_development"), // 3 createContext(mResources.getText(R.string.context_contact).toString(), 22, "system_users"), // 4 createContext(mResources.getText(R.string.context_read).toString(), 16, "format_justify_fill") // 5 }; } } private Context createContext(String name, int colourIndex, String iconName) { Context.Builder builder = Context.newBuilder(); builder .setName(name) .setActive(true) .setDeleted(false) .setColourIndex(colourIndex) .setIconName(iconName); return builder.build(); } private Task createTask(String description, int contextIndex, Project project, long start) { return createTask(description, null, contextIndex, project, start); } private Task createTask(String description, String details, int contextIndex, Project project, long start) { return createTask(description, details, contextIndex, project, start, start); } private int ORDER = 1; private Task createTask(String description, String details, int contextIndex, Project project, long start, long due) { Id contextId = contextIndex > -1 ? mPresetContexts[contextIndex].getLocalId() : Id.NONE; long created = System.currentTimeMillis(); String timezone = TimeZone.getDefault().getID(); Task.Builder builder = Task.newBuilder(); builder .setDescription(description) .setDetails(details) .setContextId(contextId) .setProjectId(project == null ? Id.NONE : project.getLocalId()) .setCreatedDate(created) .setModifiedDate(created) .setStartDate(start) .setDueDate(due) .setTimezone(timezone) .setActive(true) .setDeleted(false) .setOrder(ORDER++); return builder.build(); } private Project createProject(String name, Id defaultContextId) { Project.Builder builder = Project.newBuilder(); builder .setName(name) .setActive(true) .setDeleted(false) .setDefaultContextId(defaultContextId) .setModifiedDate(System.currentTimeMillis()); return builder.build(); } private Context insertContext( org.dodgybits.shuffle.android.core.model.Context context) { Uri uri = mContextPersister.insert(context); long id = ContentUris.parseId(uri); Log.d(cTag, "Created context id=" + id + " uri=" + uri); Context.Builder builder = Context.newBuilder(); builder.mergeFrom(context); builder.setLocalId(Id.create(id)); context = builder.build(); return context; } private Project insertProject( Project project) { Uri uri = mProjectPersister.insert(project); long id = ContentUris.parseId(uri); Log.d(cTag, "Created project id=" + id + " uri=" + uri); Project.Builder builder = Project.newBuilder(); builder.mergeFrom(project); builder.setLocalId(Id.create(id)); project = builder.build(); return project; } private Task insertTask( Task task) { Uri uri = mTaskPersister.insert(task); long id = ContentUris.parseId(uri); Log.d(cTag, "Created task id=" + id); Task.Builder builder = Task.newBuilder(); builder.mergeFrom(task); builder.setLocalId(Id.create(id)); task = builder.build(); return task; } }
Java
package org.dodgybits.shuffle.android.core.model.persistence; import static org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider.ShuffleTable.ACTIVE; import static org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider.ShuffleTable.DELETED; import static org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider.ShuffleTable.MODIFIED_DATE; import static org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider.ShuffleTable.TRACKS_ID; import static org.dodgybits.shuffle.android.persistence.provider.ContextProvider.Contexts.COLOUR; import static org.dodgybits.shuffle.android.persistence.provider.ContextProvider.Contexts.ICON; import static org.dodgybits.shuffle.android.persistence.provider.ContextProvider.Contexts.NAME; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.Context.Builder; import org.dodgybits.shuffle.android.persistence.provider.ContextProvider; import roboguice.inject.ContentResolverProvider; import roboguice.inject.ContextSingleton; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import com.google.inject.Inject; @ContextSingleton public class ContextPersister extends AbstractEntityPersister<Context> { private static final int ID_INDEX = 0; private static final int NAME_INDEX = 1; private static final int COLOUR_INDEX = 2; private static final int ICON_INDEX = 3; private static final int TRACKS_ID_INDEX = 4; private static final int MODIFIED_INDEX = 5; private static final int DELETED_INDEX = 6; private static final int ACTIVE_INDEX = 7; @Inject public ContextPersister(ContentResolverProvider provider, Analytics analytics) { super(provider.get(), analytics); } @Override public Context read(Cursor cursor) { Builder builder = Context.newBuilder(); builder .setLocalId(readId(cursor, ID_INDEX)) .setModifiedDate(cursor.getLong(MODIFIED_INDEX)) .setTracksId(readId(cursor, TRACKS_ID_INDEX)) .setName(readString(cursor, NAME_INDEX)) .setColourIndex(cursor.getInt(COLOUR_INDEX)) .setIconName(readString(cursor, ICON_INDEX)) .setDeleted(readBoolean(cursor, DELETED_INDEX)) .setActive(readBoolean(cursor, ACTIVE_INDEX)); return builder.build(); } @Override protected void writeContentValues(ContentValues values, Context context) { // never write id since it's auto generated values.put(MODIFIED_DATE, context.getModifiedDate()); writeId(values, TRACKS_ID, context.getTracksId()); writeString(values, NAME, context.getName()); values.put(COLOUR, context.getColourIndex()); writeString(values, ICON, context.getIconName()); writeBoolean(values, DELETED, context.isDeleted()); writeBoolean(values, ACTIVE, context.isActive()); } @Override protected String getEntityName() { return "context"; } @Override public Uri getContentUri() { return ContextProvider.Contexts.CONTENT_URI; } @Override public String[] getFullProjection() { return ContextProvider.Contexts.FULL_PROJECTION; } }
Java
package org.dodgybits.shuffle.android.core.model.persistence; import org.dodgybits.shuffle.android.core.model.Entity; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.util.ItemCache; import org.dodgybits.shuffle.android.core.util.ItemCache.ValueBuilder; import roboguice.inject.ContextSingleton; import android.util.Log; import com.google.inject.Inject; @ContextSingleton public class DefaultEntityCache<E extends Entity> implements EntityCache<E> { private static final String cTag = "DefaultEntityCache"; private EntityPersister<E> mPersister; private Builder mBuilder; private ItemCache<Id, E> mCache; @Inject public DefaultEntityCache(EntityPersister<E> persister) { Log.d(cTag, "Created entity cache with " + persister); mPersister = persister; mBuilder = new Builder(); mCache = new ItemCache<Id, E>(mBuilder); } public E findById(Id localId) { E entity = null; if (localId.isInitialised()) { entity = mCache.get(localId); } return entity; } private class Builder implements ValueBuilder<Id, E> { @Override public E build(Id key) { return mPersister.findById(key); } } }
Java
package org.dodgybits.shuffle.android.core.model.persistence.selector; public enum Flag { yes, no, ignored }
Java
package org.dodgybits.shuffle.android.core.model.persistence.selector; import static org.dodgybits.shuffle.android.core.model.persistence.selector.Flag.ignored; import static org.dodgybits.shuffle.android.core.model.persistence.selector.Flag.no; import static org.dodgybits.shuffle.android.core.model.persistence.selector.Flag.yes; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import android.net.Uri; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.util.StringUtils; import org.dodgybits.shuffle.android.persistence.provider.TaskProvider; import org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings; import org.dodgybits.shuffle.android.preference.model.Preferences; import android.text.format.DateUtils; import android.util.Log; public class TaskSelector extends AbstractEntitySelector<TaskSelector> { private static final String cTag = "TaskSelector"; private static final String[] cUndefinedArgs = new String[] {}; private PredefinedQuery mPredefined; private List<Id> mProjects; private List<Id> mContexts; private Flag mComplete = ignored; private Flag mPending = ignored; private String mSelection = null; private String[] mSelectionArgs = cUndefinedArgs; private TaskSelector() { } public final PredefinedQuery getPredefinedQuery() { return mPredefined; } public final List<Id> getProjects() { return mProjects; } public final List<Id> getContexts() { return mContexts; } public final Flag getComplete() { return mComplete; } public final Flag getPending() { return mPending; } @Override public Uri getContentUri() { return TaskProvider.Tasks.CONTENT_URI; } public final String getSelection(android.content.Context context) { if (mSelection == null) { List<String> expressions = getSelectionExpressions(context); mSelection = StringUtils.join(expressions, " AND "); Log.d(cTag, mSelection); } return mSelection; } @Override protected List<String> getSelectionExpressions(android.content.Context context) { List<String> expressions = super.getSelectionExpressions(context); if (mPredefined != null) { expressions.add(predefinedSelection(context)); } addActiveExpression(expressions); addDeletedExpression(expressions); addPendingExpression(expressions); addListExpression(expressions, TaskProvider.Tasks.PROJECT_ID, mProjects); addListExpression(expressions, TaskProvider.Tasks.CONTEXT_ID, mContexts); addFlagExpression(expressions, TaskProvider.Tasks.COMPLETE, mComplete); return expressions; } private void addActiveExpression(List<String> expressions) { if (mActive == yes) { // A task is active if it is active and both project and context are active. String expression = "(task.active = 1 " + "AND (projectId is null OR projectId IN (select p._id from project p where p.active = 1)) " + "AND (contextId is null OR contextId IN (select c._id from context c where c.active = 1)) " + ")"; expressions.add(expression); } else if (mActive == no) { // task is inactive if it is inactive or project in active or context is inactive String expression = "(task.active = 0 " + "OR (projectId is not null AND projectId IN (select p._id from project p where p.active = 0)) " + "OR (contextId is not null AND contextId IN (select c._id from context c where c.active = 0)) " + ")"; expressions.add(expression); } } private void addDeletedExpression(List<String> expressions) { if (mDeleted == yes) { // task is deleted if it is deleted or project is deleted or context is deleted String expression = "(task.deleted = 1 " + "OR (projectId is not null AND projectId IN (select p._id from project p where p.deleted = 1)) " + "OR (contextId is not null AND contextId IN (select c._id from context c where c.deleted = 1)) " + ")"; expressions.add(expression); } else if (mDeleted == no) { // task is not deleted if it is not deleted and project is not deleted and context is not deleted String expression = "(task.deleted = 0 " + "AND (projectId is null OR projectId IN (select p._id from project p where p.deleted = 0)) " + "AND (contextId is null OR contextId IN (select c._id from context c where c.deleted = 0)) " + ")"; expressions.add(expression); } } private void addPendingExpression(List<String> expressions) { long now = System.currentTimeMillis(); if (mPending == yes) { String expression = "(start > " + now + ")"; expressions.add(expression); } else if (mPending == no) { String expression = "(start <= " + now + ")"; expressions.add(expression); } } private String predefinedSelection(android.content.Context context) { String result; long now = System.currentTimeMillis(); switch (mPredefined) { case nextTasks: result = "((complete = 0) AND " + " (start < " + now + ") AND " + " ((projectId is null) OR " + " (projectId IN (select p._id from project p where p.parallel = 1)) OR " + " (task._id = (select t2._id FROM task t2 WHERE " + " t2.projectId = task.projectId AND t2.complete = 0 AND " + " t2.deleted = 0 " + " ORDER BY displayOrder ASC limit 1))" + "))"; break; case inbox: long lastCleanMS = Preferences.getLastInboxClean(context); result = "((projectId is null AND contextId is null) OR (created > " + lastCleanMS + "))"; break; case tickler: // by default show all results (completely customizable) result = "(1 == 1)"; break; case dueToday: case dueNextWeek: case dueNextMonth: long startMS = 0L; long endOfToday = getEndDate(); long endOfTomorrow = endOfToday + DateUtils.DAY_IN_MILLIS; result = "(due > " + startMS + ")" + " AND ( (due < " + endOfToday + ") OR" + "( allDay = 1 AND due < " + endOfTomorrow + " ))"; break; default: throw new RuntimeException("Unknown predefined selection " + mPredefined); } return result; } private long getEndDate() { long endMS = 0L; Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); switch (mPredefined) { case dueToday: cal.add(Calendar.DAY_OF_YEAR, 1); endMS = cal.getTimeInMillis(); break; case dueNextWeek: cal.add(Calendar.DAY_OF_YEAR, 7); endMS = cal.getTimeInMillis(); break; case dueNextMonth: cal.add(Calendar.MONTH, 1); endMS = cal.getTimeInMillis(); break; } if (Log.isLoggable(cTag, Log.INFO)) { Log.i(cTag, "Due date ends " + endMS); } return endMS; } public final String[] getSelectionArgs() { if (mSelectionArgs == cUndefinedArgs) { List<String> args = new ArrayList<String>(); addIdListArgs(args, mProjects); addIdListArgs(args, mContexts); Log.d(cTag,args.toString()); mSelectionArgs = args.size() > 0 ? args.toArray(new String[0]): null; } return mSelectionArgs; } @Override public Builder builderFrom() { return newBuilder().mergeFrom(this); } @Override public final String toString() { return String.format( "[TaskSelector predefined=%1$s projects=%2$s contexts=%3$s " + "complete=%4$s sortOrder=%5$s active=%6$s deleted=%7$s pending=%8$s]", mPredefined, mProjects, mContexts, mComplete, mSortOrder, mActive, mDeleted, mPending); } public static Builder newBuilder() { return Builder.create(); } public static class Builder extends AbstractBuilder<TaskSelector> { private Builder() { } private static Builder create() { Builder builder = new Builder(); builder.mResult = new TaskSelector(); return builder; } public PredefinedQuery getPredefined() { return mResult.mPredefined; } public Builder setPredefined(PredefinedQuery value) { mResult.mPredefined = value; return this; } public List<Id> getProjects() { return mResult.mProjects; } public Builder setProjects(List<Id> value) { mResult.mProjects = value; return this; } public List<Id> getContexts() { return mResult.mContexts; } public Builder setContexts(List<Id> value) { mResult.mContexts = value; return this; } public Flag getComplete() { return mResult.mComplete; } public Builder setComplete(Flag value) { mResult.mComplete = value; return this; } public Flag getPending() { return mResult.mPending; } public Builder setPending(Flag value) { mResult.mPending = value; return this; } public Builder mergeFrom(TaskSelector query) { super.mergeFrom(query); setPredefined(query.mPredefined); setProjects(query.mProjects); setContexts(query.mContexts); setComplete(query.mComplete); setPending(query.mPending); return this; } public Builder applyListPreferences(android.content.Context context, ListPreferenceSettings settings) { super.applyListPreferences(context, settings); setComplete(settings.getCompleted(context)); setPending(settings.getPending(context)); return this; } } public enum PredefinedQuery { nextTasks, dueToday, dueNextWeek, dueNextMonth, inbox, tickler } }
Java
package org.dodgybits.shuffle.android.core.model.persistence.selector; import android.content.Context; import android.net.Uri; import org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings; public interface EntitySelector<E extends EntitySelector<E>> { Uri getContentUri(); Flag getActive(); Flag getDeleted(); String getSelection(Context context); String[] getSelectionArgs(); String getSortOrder(); Builder<E> builderFrom(); public interface Builder<E extends EntitySelector<E>> { Flag getActive(); Builder<E> setActive(Flag value); Flag getDeleted(); Builder<E> setDeleted(Flag value); String getSortOrder(); Builder<E> setSortOrder(String value); E build(); Builder<E> mergeFrom(E selector); Builder<E> applyListPreferences(android.content.Context context, ListPreferenceSettings settings); } }
Java
package org.dodgybits.shuffle.android.core.model.persistence.selector; import android.net.Uri; import org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider; import org.dodgybits.shuffle.android.persistence.provider.ContextProvider; import java.util.List; public class ContextSelector extends AbstractEntitySelector<ContextSelector> { private ContextSelector() { } @Override public Uri getContentUri() { return ContextProvider.Contexts.CONTENT_URI; } @Override protected List<String> getSelectionExpressions(android.content.Context context) { List<String> expressions = super.getSelectionExpressions(context); addFlagExpression(expressions, AbstractCollectionProvider.ShuffleTable.ACTIVE, mActive); addFlagExpression(expressions, AbstractCollectionProvider.ShuffleTable.DELETED, mDeleted); return expressions; } public final String[] getSelectionArgs() { return null; } @Override public final String toString() { return String.format( "[ContextSelector sortOrder=%1$s active=%2$s deleted=%3$s]", mSortOrder, mActive, mDeleted); } @Override public Builder builderFrom() { return newBuilder().mergeFrom(this); } public static Builder newBuilder() { return Builder.create(); } public static class Builder extends AbstractBuilder<ContextSelector> { private Builder() { } private static Builder create() { Builder builder = new Builder(); builder.mResult = new ContextSelector(); return builder; } public Builder mergeFrom(ContextSelector query) { super.mergeFrom(query); return this; } } }
Java
package org.dodgybits.shuffle.android.core.model.persistence.selector; import android.net.Uri; import org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider; import org.dodgybits.shuffle.android.persistence.provider.ProjectProvider; import java.util.List; public class ProjectSelector extends AbstractEntitySelector<ProjectSelector> { @Override public Uri getContentUri() { return ProjectProvider.Projects.CONTENT_URI; } @Override protected List<String> getSelectionExpressions(android.content.Context context) { List<String> expressions = super.getSelectionExpressions(context); addFlagExpression(expressions, AbstractCollectionProvider.ShuffleTable.ACTIVE, mActive); addFlagExpression(expressions, AbstractCollectionProvider.ShuffleTable.DELETED, mDeleted); return expressions; } public final String[] getSelectionArgs() { return null; } @Override public Builder builderFrom() { return newBuilder().mergeFrom(this); } @Override public final String toString() { return String.format( "[ProjectSelector sortOrder=%1$s active=%2$s deleted=%3$s]", mSortOrder, mActive, mDeleted); } public static Builder newBuilder() { return Builder.create(); } public static class Builder extends AbstractBuilder<ProjectSelector> { private Builder() { } private static Builder create() { Builder builder = new Builder(); builder.mResult = new ProjectSelector(); return builder; } public Builder mergeFrom(ProjectSelector query) { super.mergeFrom(query); return this; } } }
Java
package org.dodgybits.shuffle.android.core.model.persistence.selector; import android.util.Log; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.util.StringUtils; import org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings; import java.util.ArrayList; import java.util.List; import static org.dodgybits.shuffle.android.core.model.persistence.selector.Flag.ignored; public abstract class AbstractEntitySelector<E extends EntitySelector<E>> implements EntitySelector<E> { private static final String cTag = "AbstractEntitySelector"; protected Flag mActive = ignored; protected Flag mDeleted = ignored; protected String mSortOrder; @Override public Flag getActive() { return mActive; } @Override public Flag getDeleted() { return mDeleted; } @Override public final String getSortOrder() { return mSortOrder; } @Override public String getSelection(android.content.Context context) { List<String> expressions = getSelectionExpressions(context); String selection = StringUtils.join(expressions, " AND "); Log.d(cTag, selection); return selection; } protected List<String> getSelectionExpressions(android.content.Context context) { List<String> expressions = new ArrayList<String>(); return expressions; } protected void addFlagExpression(List<String> expressions, String field, Flag flag) { if (flag != Flag.ignored) { String expression = field + "=" + (flag == Flag.yes ? "1" : "0"); expressions.add(expression); } } protected void addListExpression(List<String> expressions, String field, List<Id> ids) { if (ids != null) { expressions.add(idListSelection(ids, field)); } } private String idListSelection(List<Id> ids, String idName) { StringBuilder result = new StringBuilder(); if (ids.size() > 0) { result.append(idName) .append(" in (") .append(StringUtils.repeat(ids.size(), "?", ",")) .append(')'); } else { result.append(idName) .append(" is null"); } return result.toString(); } protected void addIdListArgs(List<String> args, List<Id> ids) { if (ids != null && ids.size() > 0) { for(Id id : ids) { args.add(String.valueOf(id.getId())); } } } public abstract static class AbstractBuilder<E extends AbstractEntitySelector<E>> implements EntitySelector.Builder<E> { protected E mResult; @Override public Flag getDeleted() { return mResult.getDeleted(); } @Override public Flag getActive() { return mResult.getActive(); } @Override public String getSortOrder() { return mResult.getSortOrder(); } @Override public AbstractBuilder<E> setSortOrder(String value) { mResult.mSortOrder = value; return this; } @Override public AbstractBuilder<E> setActive(Flag value) { mResult.mActive = value; return this; } @Override public AbstractBuilder<E> setDeleted(Flag value) { mResult.mDeleted = value; return this; } @Override public E build() { if (mResult == null) { throw new IllegalStateException( "build() has already been called on this Builder."); } E returnMe = mResult; mResult = null; Log.d(cTag,returnMe.toString()); return returnMe; } @Override public AbstractBuilder<E> mergeFrom(E selector) { setActive(selector.mActive); setDeleted(selector.mDeleted); setSortOrder(selector.mSortOrder); return this; } @Override public AbstractBuilder<E> applyListPreferences(android.content.Context context, ListPreferenceSettings settings) { setActive(settings.getActive(context)); setDeleted(settings.getDeleted(context)); return this; } } }
Java
package org.dodgybits.shuffle.android.core.model.persistence; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryCompleteTaskEvent; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryCountParam; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryDeleteEntityEvent; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryReorderTasksEvent; import static org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider.ShuffleTable.ACTIVE; import static org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider.ShuffleTable.DELETED; import static org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider.ShuffleTable.MODIFIED_DATE; import static org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider.ShuffleTable.TRACKS_ID; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.ALL_DAY; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.CAL_EVENT_ID; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.COMPLETE; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.CONTEXT_ID; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.CREATED_DATE; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.DESCRIPTION; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.DETAILS; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.DISPLAY_ORDER; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.DUE_DATE; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.HAS_ALARM; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.PROJECT_ID; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.START_DATE; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.TIMEZONE; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TimeZone; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Task; import org.dodgybits.shuffle.android.core.model.Task.Builder; import org.dodgybits.shuffle.android.core.model.persistence.selector.Flag; import org.dodgybits.shuffle.android.core.model.persistence.selector.TaskSelector; import org.dodgybits.shuffle.android.core.util.StringUtils; import org.dodgybits.shuffle.android.persistence.provider.TaskProvider; import roboguice.inject.ContentResolverProvider; import roboguice.inject.ContextSingleton; import roboguice.util.Ln; import android.content.ContentUris; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.provider.BaseColumns; import android.text.TextUtils; import android.text.format.Time; import android.util.Log; import android.util.SparseIntArray; import com.google.inject.Inject; @ContextSingleton public class TaskPersister extends AbstractEntityPersister<Task> { private static final String cTag = "TaskPersister"; private static final int ID_INDEX = 0; private static final int DESCRIPTION_INDEX = ID_INDEX + 1; private static final int DETAILS_INDEX = DESCRIPTION_INDEX + 1; private static final int PROJECT_INDEX = DETAILS_INDEX + 1; private static final int CONTEXT_INDEX = PROJECT_INDEX + 1; private static final int CREATED_INDEX = CONTEXT_INDEX + 1; private static final int MODIFIED_INDEX = CREATED_INDEX + 1; private static final int START_INDEX = MODIFIED_INDEX + 1; private static final int DUE_INDEX = START_INDEX + 1; private static final int TIMEZONE_INDEX = DUE_INDEX + 1; private static final int CAL_EVENT_INDEX = TIMEZONE_INDEX + 1; private static final int DISPLAY_ORDER_INDEX = CAL_EVENT_INDEX + 1; private static final int COMPLETE_INDEX = DISPLAY_ORDER_INDEX + 1; private static final int ALL_DAY_INDEX = COMPLETE_INDEX + 1; private static final int HAS_ALARM_INDEX = ALL_DAY_INDEX + 1; private static final int TASK_TRACK_INDEX = HAS_ALARM_INDEX + 1; private static final int DELETED_INDEX = TASK_TRACK_INDEX +1; private static final int ACTIVE_INDEX = DELETED_INDEX +1; @Inject public TaskPersister(ContentResolverProvider provider, Analytics analytics) { super(provider.get(), analytics); } @Override public Task read(Cursor cursor) { Builder builder = Task.newBuilder(); builder .setLocalId(readId(cursor, ID_INDEX)) .setDescription(readString(cursor, DESCRIPTION_INDEX)) .setDetails(readString(cursor, DETAILS_INDEX)) .setProjectId(readId(cursor, PROJECT_INDEX)) .setContextId(readId(cursor, CONTEXT_INDEX)) .setCreatedDate(readLong(cursor, CREATED_INDEX)) .setModifiedDate(readLong(cursor, MODIFIED_INDEX)) .setStartDate(readLong(cursor, START_INDEX)) .setDueDate(readLong(cursor, DUE_INDEX)) .setTimezone(readString(cursor, TIMEZONE_INDEX)) .setCalendarEventId(readId(cursor, CAL_EVENT_INDEX)) .setOrder(cursor.getInt(DISPLAY_ORDER_INDEX)) .setComplete(readBoolean(cursor, COMPLETE_INDEX)) .setAllDay(readBoolean(cursor, ALL_DAY_INDEX)) .setHasAlarm(readBoolean(cursor, HAS_ALARM_INDEX)) .setTracksId(readId(cursor, TASK_TRACK_INDEX)) .setDeleted(readBoolean(cursor, DELETED_INDEX)) .setActive(readBoolean(cursor, ACTIVE_INDEX)); return builder.build(); } @Override protected void writeContentValues(ContentValues values, Task task) { // never write id since it's auto generated writeString(values, DESCRIPTION, task.getDescription()); writeString(values, DETAILS, task.getDetails()); writeId(values, PROJECT_ID, task.getProjectId()); writeId(values, CONTEXT_ID, task.getContextId()); values.put(CREATED_DATE, task.getCreatedDate()); values.put(MODIFIED_DATE, task.getModifiedDate()); values.put(START_DATE, task.getStartDate()); values.put(DUE_DATE, task.getDueDate()); writeBoolean(values, DELETED, task.isDeleted()); writeBoolean(values, ACTIVE, task.isActive()); String timezone = task.getTimezone(); if (TextUtils.isEmpty(timezone)) { if (task.isAllDay()) { timezone = Time.TIMEZONE_UTC; } else { timezone = TimeZone.getDefault().getID(); } } values.put(TIMEZONE, timezone); writeId(values, CAL_EVENT_ID, task.getCalendarEventId()); values.put(DISPLAY_ORDER, task.getOrder()); writeBoolean(values, COMPLETE, task.isComplete()); writeBoolean(values, ALL_DAY, task.isAllDay()); writeBoolean(values, HAS_ALARM, task.hasAlarms()); writeId(values, TRACKS_ID, task.getTracksId()); } @Override protected String getEntityName() { return "task"; } @Override public Uri getContentUri() { return TaskProvider.Tasks.CONTENT_URI; } @Override public String[] getFullProjection() { return TaskProvider.Tasks.FULL_PROJECTION; } @Override public int emptyTrash() { // find tasks that are deleted or who's context or project is deleted TaskSelector selector = TaskSelector.newBuilder().setDeleted(Flag.yes).build(); Cursor cursor = mResolver.query(getContentUri(), new String[] {BaseColumns._ID}, selector.getSelection(null), selector.getSelectionArgs(), selector.getSortOrder()); List<String> ids = new ArrayList<String>(); while (cursor.moveToNext()) { ids.add(cursor.getString(ID_INDEX)); } cursor.close(); int rowsDeleted = 0; if (ids.size() > 0) { Ln.i("About to delete tasks %s", ids); String queryString = "_id IN (" + StringUtils.join(ids, ",") + ")"; rowsDeleted = mResolver.delete(getContentUri(), queryString, null); Map<String, String> params = new HashMap<String, String>(mFlurryParams); params.put(cFlurryCountParam, String.valueOf(rowsDeleted)); mAnalytics.onEvent(cFlurryDeleteEntityEvent, params); } return rowsDeleted; } public int deleteCompletedTasks() { int deletedRows = updateDeletedFlag(TaskProvider.Tasks.COMPLETE + " = 1", null, true); Log.d(cTag, "Deleting " + deletedRows + " completed tasks."); Map<String, String> params = new HashMap<String,String>(mFlurryParams); params.put(cFlurryCountParam, String.valueOf(deletedRows)); mAnalytics.onEvent(cFlurryDeleteEntityEvent, params); return deletedRows; } public void updateCompleteFlag(Id id, boolean isComplete) { ContentValues values = new ContentValues(); writeBoolean(values, COMPLETE, isComplete); values.put(MODIFIED_DATE, System.currentTimeMillis()); mResolver.update(getUri(id), values, null, null); if (isComplete) { mAnalytics.onEvent(cFlurryCompleteTaskEvent); } } /** * Calculate where this task should appear on the list for the given project. * If no project is defined, order is meaningless, so return -1. * * New tasks go on the end of the list if no due date is defined. * If due date is defined, add either to the start, or after the task * closest to the end of the list with an earlier due date. * * For existing tasks, check if the project changed, and if so * treat like a new task, otherwise leave the order as is. * * @param originalTask the task before any changes or null if this is a new task * @param newProjectId the project selected for this task * @param dueMillis due date of this task (or 0L if not defined) * @return 0-indexed order of task when displayed in the project view */ public int calculateTaskOrder(Task originalTask, Id newProjectId, long dueMillis) { if (!newProjectId.isInitialised()) return -1; int order; if (originalTask == null || !originalTask.getProjectId().equals(newProjectId)) { // get current highest order value Cursor cursor = mResolver.query( TaskProvider.Tasks.CONTENT_URI, new String[] {BaseColumns._ID, TaskProvider.Tasks.DISPLAY_ORDER, TaskProvider.Tasks.DUE_DATE}, TaskProvider.Tasks.PROJECT_ID + " = ?", new String[] {String.valueOf(newProjectId.getId())}, TaskProvider.Tasks.DISPLAY_ORDER + " desc"); if (cursor.moveToFirst()) { if (dueMillis > 0L) { Ln.d("Due date defined - finding best place to insert in project task list"); Map<Long,Integer> updateValues = new HashMap<Long,Integer>(); do { long previousId = cursor.getLong(0); int previousOrder = cursor.getInt(1); long previousDueDate = cursor.getLong(2); if (previousDueDate > 0L && previousDueDate < dueMillis) { order = previousOrder + 1; Ln.d("Placing after task %d with earlier due date", previousId); break; } updateValues.put(previousId, previousOrder + 1); order = previousOrder; } while (cursor.moveToNext()); moveFollowingTasks(updateValues); } else { // no due date so put at end of list int highestOrder = cursor.getInt(1); order = highestOrder + 1; } } else { // no tasks in the project yet. order = 0; } cursor.close(); } else { order = originalTask.getOrder(); } return order; } private void moveFollowingTasks(Map<Long,Integer> updateValues) { Set<Long> ids = updateValues.keySet(); ContentValues values = new ContentValues(); for (long id : ids) { values.clear(); values.put(DISPLAY_ORDER, updateValues.get(id)); Uri uri = ContentUris.withAppendedId(TaskProvider.Tasks.CONTENT_URI, id); mResolver.update(uri, values, null, null); } } /** * Swap the display order of two tasks at the given cursor positions. * The cursor is committed and re-queried after the update. */ public void swapTaskPositions(Cursor cursor, int pos1, int pos2) { cursor.moveToPosition(pos1); Id id1 = readId(cursor, ID_INDEX); int positionValue1 = cursor.getInt(DISPLAY_ORDER_INDEX); cursor.moveToPosition(pos2); Id id2 = readId(cursor, ID_INDEX); int positionValue2 = cursor.getInt(DISPLAY_ORDER_INDEX); Uri uri = ContentUris.withAppendedId(getContentUri(), id1.getId()); ContentValues values = new ContentValues(); values.put(DISPLAY_ORDER, positionValue2); mResolver.update(uri, values, null, null); uri = ContentUris.withAppendedId(getContentUri(), id2.getId()); values.clear(); values.put(DISPLAY_ORDER, positionValue1); mResolver.update(uri, values, null, null); mAnalytics.onEvent(cFlurryReorderTasksEvent); } private static final int TASK_COUNT_INDEX = 1; public SparseIntArray readCountArray(Cursor cursor) { SparseIntArray countMap = new SparseIntArray(); while (cursor.moveToNext()) { Integer id = cursor.getInt(ID_INDEX); Integer count = cursor.getInt(TASK_COUNT_INDEX); countMap.put(id, count); } return countMap; } }
Java
package org.dodgybits.shuffle.android.core.model.persistence; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryCountParam; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryCreateEntityEvent; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryDeleteEntityEvent; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryEntityTypeParam; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryUpdateEntityEvent; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; import org.dodgybits.shuffle.android.core.model.Entity; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider.ShuffleTable; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.provider.BaseColumns; public abstract class AbstractEntityPersister<E extends Entity> implements EntityPersister<E> { protected Analytics mAnalytics; protected ContentResolver mResolver; protected Map<String, String> mFlurryParams; public AbstractEntityPersister(ContentResolver resolver, Analytics analytics) { mResolver = resolver; mAnalytics = analytics; Map<String, String> params = new HashMap<String,String>(); params.put(cFlurryEntityTypeParam, getEntityName()); mFlurryParams = Collections.unmodifiableMap(params); } @Override public E findById(Id localId) { E entity = null; if (localId.isInitialised()) { Cursor cursor = mResolver.query( getContentUri(), getFullProjection(), BaseColumns._ID + " = ?", new String[] {localId.toString()}, null); if (cursor.moveToFirst()) { entity = read(cursor); } cursor.close(); } return entity; } @Override public Uri insert(E e) { validate(e); Uri uri = mResolver.insert(getContentUri(), null); update(uri, e); mAnalytics.onEvent(cFlurryCreateEntityEvent, mFlurryParams); return uri; } @Override public void bulkInsert(Collection<E> entities) { int numEntities = entities.size(); if (numEntities > 0) { ContentValues[] valuesArray = new ContentValues[numEntities]; int i = 0; for(E entity : entities) { validate(entity); ContentValues values = new ContentValues(); writeContentValues(values, entity); valuesArray[i++] = values; } int rowsCreated = mResolver.bulkInsert(getContentUri(), valuesArray); Map<String, String> params = new HashMap<String, String>(mFlurryParams); params.put(cFlurryCountParam, String.valueOf(rowsCreated)); mAnalytics.onEvent(cFlurryCreateEntityEvent, params); } } @Override public void update(E e) { validate(e); Uri uri = getUri(e); update(uri, e); mAnalytics.onEvent(cFlurryUpdateEntityEvent, mFlurryParams); } @Override public boolean updateDeletedFlag(Id id, boolean isDeleted) { ContentValues values = new ContentValues(); writeBoolean(values, ShuffleTable.DELETED, isDeleted); values.put(ShuffleTable.MODIFIED_DATE, System.currentTimeMillis()); return (mResolver.update(getUri(id), values, null, null) == 1); } @Override public int updateDeletedFlag(String selection, String[] selectionArgs, boolean isDeleted) { ContentValues values = new ContentValues(); writeBoolean(values, ShuffleTable.DELETED, isDeleted); values.put(ShuffleTable.MODIFIED_DATE, System.currentTimeMillis()); return mResolver.update(getContentUri(), values, selection, selectionArgs); } @Override public int emptyTrash() { int rowsDeleted = mResolver.delete(getContentUri(), "deleted = 1", null); Map<String, String> params = new HashMap<String, String>(mFlurryParams); params.put(cFlurryCountParam, String.valueOf(rowsDeleted)); mAnalytics.onEvent(cFlurryDeleteEntityEvent, params); return rowsDeleted; } @Override public boolean deletePermanently(Id id) { Uri uri = getUri(id); boolean success = (mResolver.delete(uri, null, null) == 1); if (success) { mAnalytics.onEvent(cFlurryDeleteEntityEvent, mFlurryParams); } return success; } abstract public Uri getContentUri(); abstract protected void writeContentValues(ContentValues values, E e); abstract protected String getEntityName(); private void validate(E e) { if (e == null || !e.isValid()) { throw new IllegalArgumentException("Cannot persist uninitialised entity " + e); } } protected Uri getUri(E e) { return getUri(e.getLocalId()); } protected Uri getUri(Id localId) { return ContentUris.appendId( getContentUri().buildUpon(), localId.getId()).build(); } private void update(Uri uri, E e) { ContentValues values = new ContentValues(); writeContentValues(values, e); mResolver.update(uri, values, null, null); } protected static Id readId(Cursor cursor, int index) { Id result = Id.NONE; if (!cursor.isNull(index)) { result = Id.create(cursor.getLong(index)); } return result; } protected static String readString(Cursor cursor, int index) { return (cursor.isNull(index) ? null : cursor.getString(index)); } protected static long readLong(Cursor cursor, int index) { return readLong(cursor, index, 0L); } protected static long readLong(Cursor cursor, int index, long defaultValue) { long result = defaultValue; if (!cursor.isNull(index)) { result = cursor.getLong(index); } return result; } protected static Boolean readBoolean(Cursor cursor, int index) { return (cursor.getInt(index) == 1); } protected static void writeId(ContentValues values, String key, Id id) { if (id.isInitialised()) { values.put(key, id.getId()); } else { values.putNull(key); } } protected static void writeBoolean(ContentValues values, String key, boolean value) { values.put(key, value ? 1 : 0); } protected static void writeString(ContentValues values, String key, String value) { if (value == null) { values.putNull(key); } else { values.put(key, value); } } }
Java
package org.dodgybits.shuffle.android.core.model.persistence; import static org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider.ShuffleTable.ACTIVE; import static org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider.ShuffleTable.DELETED; import static org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider.ShuffleTable.MODIFIED_DATE; import static org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider.ShuffleTable.TRACKS_ID; import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.ARCHIVED; import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.DEFAULT_CONTEXT_ID; import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.NAME; import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.PARALLEL; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.android.core.model.Project.Builder; import org.dodgybits.shuffle.android.persistence.provider.ProjectProvider; import roboguice.inject.ContentResolverProvider; import roboguice.inject.ContextSingleton; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import com.google.inject.Inject; @ContextSingleton public class ProjectPersister extends AbstractEntityPersister<Project> { private static final int ID_INDEX = 0; private static final int NAME_INDEX = 1; private static final int DEFAULT_CONTEXT_INDEX = 2; private static final int TRACKS_ID_INDEX = 3; private static final int MODIFIED_INDEX = 4; private static final int PARALLEL_INDEX = 5; private static final int ARCHIVED_INDEX = 6; private static final int DELETED_INDEX = 7; private static final int ACTIVE_INDEX = 8; @Inject public ProjectPersister(ContentResolverProvider provider, Analytics analytics) { super(provider.get(), analytics); } @Override public Project read(Cursor cursor) { Builder builder = Project.newBuilder(); builder .setLocalId(readId(cursor, ID_INDEX)) .setModifiedDate(cursor.getLong(MODIFIED_INDEX)) .setTracksId(readId(cursor, TRACKS_ID_INDEX)) .setName(readString(cursor, NAME_INDEX)) .setDefaultContextId(readId(cursor, DEFAULT_CONTEXT_INDEX)) .setParallel(readBoolean(cursor, PARALLEL_INDEX)) .setArchived(readBoolean(cursor, ARCHIVED_INDEX)) .setDeleted(readBoolean(cursor, DELETED_INDEX)) .setActive(readBoolean(cursor, ACTIVE_INDEX)); return builder.build(); } @Override protected void writeContentValues(ContentValues values, Project project) { // never write id since it's auto generated values.put(MODIFIED_DATE, project.getModifiedDate()); writeId(values, TRACKS_ID, project.getTracksId()); writeString(values, NAME, project.getName()); writeId(values, DEFAULT_CONTEXT_ID, project.getDefaultContextId()); writeBoolean(values, PARALLEL, project.isParallel()); writeBoolean(values, ARCHIVED, project.isArchived()); writeBoolean(values, DELETED, project.isDeleted()); writeBoolean(values, ACTIVE, project.isActive()); } @Override protected String getEntityName() { return "project"; } @Override public Uri getContentUri() { return ProjectProvider.Projects.CONTENT_URI; } @Override public String[] getFullProjection() { return ProjectProvider.Projects.FULL_PROJECTION; } }
Java
package org.dodgybits.shuffle.android.core.model.persistence; import org.dodgybits.shuffle.android.core.model.Entity; import org.dodgybits.shuffle.android.core.model.Id; public interface EntityCache<E extends Entity> { E findById(Id localId); }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.core.model; import org.dodgybits.shuffle.android.synchronisation.tracks.model.TracksEntity; import android.text.TextUtils; public final class Task implements TracksEntity { private Id mLocalId = Id.NONE; private String mDescription; private String mDetails; private Id mContextId = Id.NONE; private Id mProjectId = Id.NONE; private long mCreatedDate; private long mModifiedDate; private long mStartDate; private long mDueDate; private String mTimezone; private boolean mAllDay; private boolean mHasAlarms; private boolean mActive = true; private boolean mDeleted; private Id mCalendarEventId = Id.NONE; // 0-indexed order within a project. private int mOrder; private boolean mComplete; private Id mTracksId = Id.NONE; private Task() { }; @Override public final Id getLocalId() { return mLocalId; } public final String getDescription() { return mDescription; } public final String getDetails() { return mDetails; } public final Id getContextId() { return mContextId; } public final Id getProjectId() { return mProjectId; } public final long getCreatedDate() { return mCreatedDate; } @Override public final long getModifiedDate() { return mModifiedDate; } public final long getStartDate() { return mStartDate; } public final long getDueDate() { return mDueDate; } public final String getTimezone() { return mTimezone; } public final boolean isAllDay() { return mAllDay; } public final boolean hasAlarms() { return mHasAlarms; } public final Id getCalendarEventId() { return mCalendarEventId; } public final int getOrder() { return mOrder; } public final boolean isComplete() { return mComplete; } public final Id getTracksId() { return mTracksId; } public final String getLocalName() { return mDescription; } @Override public boolean isDeleted() { return mDeleted; } @Override public boolean isActive() { return mActive; } public boolean isPending() { long now = System.currentTimeMillis(); return mStartDate > now; } @Override public final boolean isValid() { if (TextUtils.isEmpty(mDescription)) { return false; } return true; } @Override public final String toString() { return String.format( "[Task id=%8$s description='%1$s' detail='%2$s' contextId=%3$s projectId=%4$s " + "order=%5$s complete=%6$s tracksId='%7$s' deleted=%9$s active=%10$s]", mDescription, mDetails, mContextId, mProjectId, mOrder, mComplete, mTracksId, mLocalId, mDeleted, mActive); } public static Builder newBuilder() { return Builder.create(); } public static class Builder implements EntityBuilder<Task> { private Builder() { } private Task result; private static Builder create() { Builder builder = new Builder(); builder.result = new Task(); return builder; } public Id getLocalId() { return result.mLocalId; } public Builder setLocalId(Id value) { assert value != null; result.mLocalId = value; return this; } public String getDescription() { return result.mDescription; } public Builder setDescription(String value) { result.mDescription = value; return this; } public String getDetails() { return result.mDetails; } public Builder setDetails(String value) { result.mDetails = value; return this; } public Id getContextId() { return result.mContextId; } public Builder setContextId(Id value) { assert value != null; result.mContextId = value; return this; } public Id getProjectId() { return result.mProjectId; } public Builder setProjectId(Id value) { assert value != null; result.mProjectId = value; return this; } public long getCreatedDate() { return result.mCreatedDate; } public Builder setCreatedDate(long value) { result.mCreatedDate = value; return this; } public long getModifiedDate() { return result.mModifiedDate; } public Builder setModifiedDate(long value) { result.mModifiedDate = value; return this; } public long getStartDate() { return result.mStartDate; } public Builder setStartDate(long value) { result.mStartDate = value; return this; } public long getDueDate() { return result.mDueDate; } public Builder setDueDate(long value) { result.mDueDate = value; return this; } public String getTimezone() { return result.mTimezone; } public Builder setTimezone(String value) { result.mTimezone = value; return this; } public boolean isAllDay() { return result.mAllDay; } public Builder setAllDay(boolean value) { result.mAllDay = value; return this; } public boolean hasAlarms() { return result.mHasAlarms; } public Builder setHasAlarm(boolean value) { result.mHasAlarms = value; return this; } public Id getCalendarEventId() { return result.mCalendarEventId; } public Builder setCalendarEventId(Id value) { assert value != null; result.mCalendarEventId = value; return this; } public int getOrder() { return result.mOrder; } public Builder setOrder(int value) { result.mOrder = value; return this; } public boolean isComplete() { return result.mComplete; } public Builder setComplete(boolean value) { result.mComplete = value; return this; } public Id getTracksId() { return result.mTracksId; } public Builder setTracksId(Id value) { assert value != null; result.mTracksId = value; return this; } public boolean isDeleted() { return result.mDeleted; } @Override public Builder setDeleted(boolean value) { result.mDeleted = value; return this; } public boolean isActive() { return result.mActive; } @Override public Builder setActive(boolean value) { result.mActive = value; return this; } public final boolean isInitialized() { return result.isValid(); } public Task build() { if (result == null) { throw new IllegalStateException( "build() has already been called on this Builder."); } Task returnMe = result; result = null; return returnMe; } public Builder mergeFrom(Task task) { setLocalId(task.mLocalId); setDescription(task.mDescription); setDetails(task.mDetails); setContextId(task.mContextId); setProjectId(task.mProjectId); setCreatedDate(task.mCreatedDate); setModifiedDate(task.mModifiedDate); setStartDate(task.mStartDate); setDueDate(task.mDueDate); setTimezone(task.mTimezone); setAllDay(task.mAllDay); setDeleted(task.mDeleted); setHasAlarm(task.mHasAlarms); setCalendarEventId(task.mCalendarEventId); setOrder(task.mOrder); setComplete(task.mComplete); setTracksId(task.mTracksId); setDeleted(task.mDeleted); setActive(task.mActive); return this; } } }
Java
package org.dodgybits.shuffle.android.core.model; public class Reminder { public Integer id; public final int minutes; public final Method method; public Reminder(Integer id, int minutes, Method method) { this.id = id; this.minutes = minutes; this.method = method; } public Reminder(int minutes, Method method) { this(null, minutes, method); } public static enum Method { DEFAULT, ALERT; } }
Java
package org.dodgybits.shuffle.android.core.model; public interface Entity { /** * @return primary key for entity in local sqlite DB. 0L indicates an unsaved entity. */ Id getLocalId(); /** * @return ms since epoch entity was last modified. */ long getModifiedDate(); boolean isActive(); boolean isDeleted(); boolean isValid(); String getLocalName(); }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.core.activity; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledListActivity; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.Entity; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.android.core.model.Task; import org.dodgybits.shuffle.android.core.model.persistence.selector.ContextSelector; import org.dodgybits.shuffle.android.core.model.persistence.selector.EntitySelector; import org.dodgybits.shuffle.android.core.model.persistence.selector.ProjectSelector; import org.dodgybits.shuffle.android.core.model.persistence.selector.TaskSelector; import org.dodgybits.shuffle.android.core.util.Constants; import org.dodgybits.shuffle.android.core.view.IconArrayAdapter; import org.dodgybits.shuffle.android.core.view.MenuUtils; import org.dodgybits.shuffle.android.list.annotation.Contexts; import org.dodgybits.shuffle.android.list.annotation.DueTasks; import org.dodgybits.shuffle.android.list.annotation.Inbox; import org.dodgybits.shuffle.android.list.annotation.Projects; import org.dodgybits.shuffle.android.list.annotation.Tickler; import org.dodgybits.shuffle.android.list.annotation.TopTasks; import org.dodgybits.shuffle.android.list.config.ContextListConfig; import org.dodgybits.shuffle.android.list.config.DueActionsListConfig; import org.dodgybits.shuffle.android.list.config.ListConfig; import org.dodgybits.shuffle.android.list.config.ProjectListConfig; import org.dodgybits.shuffle.android.list.config.TaskListConfig; import org.dodgybits.shuffle.android.preference.model.Preferences; import roboguice.inject.ContextSingleton; import android.app.AlertDialog; import android.app.Dialog; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import android.text.SpannableString; import android.text.Spanned; import android.text.style.ForegroundColorSpan; import android.util.AndroidException; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import com.google.inject.Inject; @ContextSingleton /** * Displays a list of the main activities. */ public class TopLevelActivity extends FlurryEnabledListActivity { private static final String cTag = "TopLevelActivity"; private static final int INBOX = 0; private static final int DUE_TASKS = 1; private static final int TOP_TASKS = 2; private static final int PROJECTS = 3; private static final int CONTEXTS = 4; private static final int TICKLER = 5; private static final int ITEM_COUNT = 6; private static final String[] cProjection = new String[]{"_id"}; private final static int WHATS_NEW_DIALOG = 0; private Integer[] mIconIds = new Integer[ITEM_COUNT]; private AsyncTask<?, ?, ?> mTask; @Inject @Inbox private TaskListConfig mInboxConfig; @Inject @DueTasks private DueActionsListConfig mDueTasksConfig; @Inject @TopTasks private TaskListConfig mTopTasksConfig; @Inject @Tickler private TaskListConfig mTicklerConfig; @Inject @Projects private ProjectListConfig mProjectsConfig; @Inject @Contexts private ContextListConfig mContextsConfig; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.top_level); setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); addVersionToTitle(); checkLastVersion(); } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuItem item = menu.findItem(MenuUtils.SYNC_ID); if (item != null) { item.setVisible(Preferences.validateTracksSettings(this)); } return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuUtils.addPrefsHelpMenuItems(this, menu); MenuUtils.addSearchMenuItem(this, menu); MenuUtils.addSyncMenuItem(this, menu); return true; } @Override protected void onResume() { Log.d(cTag, "onResume+"); super.onResume(); CursorGenerator[] generators = new CursorGenerator[ITEM_COUNT]; generators[INBOX] = new EntityCursorGenerator<Task,TaskSelector>(mInboxConfig); generators[DUE_TASKS] = new EntityCursorGenerator<Task,TaskSelector>(mDueTasksConfig); generators[TOP_TASKS] = new EntityCursorGenerator<Task,TaskSelector>(mTopTasksConfig); generators[PROJECTS] = new EntityCursorGenerator<Project,ProjectSelector>(mProjectsConfig); generators[CONTEXTS] = new EntityCursorGenerator<Context,ContextSelector>(mContextsConfig); generators[TICKLER] = new EntityCursorGenerator<Task,TaskSelector>(mTicklerConfig); mIconIds[INBOX] = R.drawable.inbox; mIconIds[DUE_TASKS] = R.drawable.due_actions; mIconIds[TOP_TASKS] = R.drawable.next_actions; mIconIds[PROJECTS] = R.drawable.projects; mIconIds[CONTEXTS] = R.drawable.contexts; mIconIds[TICKLER] = R.drawable.ic_media_pause; mTask = new CalculateCountTask().execute(generators); String[] perspectives = getResources().getStringArray(R.array.perspectives).clone(); ArrayAdapter<CharSequence> adapter = new IconArrayAdapter( this, R.layout.list_item_view, R.id.name, perspectives, mIconIds); setListAdapter(adapter); } @Override protected void onDestroy() { super.onDestroy(); if (mTask != null && mTask.getStatus() != AsyncTask.Status.RUNNING) { mTask.cancel(true); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (MenuUtils.checkCommonItemsSelected(item, this, -1)) { return true; } return super.onOptionsItemSelected(item); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { MenuUtils.checkCommonItemsSelected(position + MenuUtils.INBOX_ID, this, -1, false); } @Override protected Dialog onCreateDialog(int id) { Dialog dialog; if (id == WHATS_NEW_DIALOG) { dialog = new AlertDialog.Builder(this) .setTitle(R.string.whats_new_dialog_title) .setPositiveButton(R.string.ok_button_title, null) .setMessage(R.string.whats_new_dialog_message) .create(); } else { dialog = super.onCreateDialog(id); } return dialog; } private interface CursorGenerator { Cursor generate(); } private class EntityCursorGenerator<T extends Entity, E extends EntitySelector<E>> implements CursorGenerator { private EntitySelector<E> mEntitySelector; public EntityCursorGenerator(ListConfig<T,E> config) { mEntitySelector = config.getEntitySelector(); mEntitySelector = mEntitySelector.builderFrom() .applyListPreferences(TopLevelActivity.this, config.getListPreferenceSettings()) .build(); } public Cursor generate() { return getContentResolver().query( mEntitySelector.getContentUri(), cProjection, mEntitySelector.getSelection(TopLevelActivity.this), mEntitySelector.getSelectionArgs(), mEntitySelector.getSortOrder()); } } private class CalculateCountTask extends AsyncTask<CursorGenerator, CharSequence[], Void> { public Void doInBackground(CursorGenerator... params) { String[] perspectives = getResources().getStringArray(R.array.perspectives); int colour = getResources().getColor(R.drawable.pale_blue); ForegroundColorSpan span = new ForegroundColorSpan(colour); CharSequence[] labels = new CharSequence[perspectives.length]; int length = perspectives.length; for (int i = 0; i < length; i++) { labels[i] = " " + perspectives[i]; } int[] cachedCounts = Preferences.getTopLevelCounts(TopLevelActivity.this); if (cachedCounts != null && cachedCounts.length == length) { for (int i = 0; i < length; i++) { CharSequence label = labels[i] + " (" + cachedCounts[i] + ")"; SpannableString spannable = new SpannableString(label); spannable.setSpan(span, labels[i].length(), label.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); labels[i] = spannable; } } publishProgress(labels); String cachedCountStr = ""; for (int i = 0; i < length; i++) { CursorGenerator generator = params[i]; Cursor cursor = generator.generate(); int count = cursor.getCount(); cursor.close(); CharSequence label = " " + perspectives[i] + " (" + count + ")"; SpannableString spannable = new SpannableString(label); spannable.setSpan(span, perspectives[i].length() + 2, label.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); labels[i] = spannable; publishProgress(labels); cachedCountStr += count; if (i < length - 1) { cachedCountStr += ","; } } // updated cached counts SharedPreferences.Editor editor = Preferences.getEditor(TopLevelActivity.this); editor.putString(Preferences.TOP_LEVEL_COUNTS_KEY, cachedCountStr); editor.commit(); return null; } @Override public void onProgressUpdate(CharSequence[]... progress) { CharSequence[] labels = progress[0]; ArrayAdapter<CharSequence> adapter = new IconArrayAdapter( TopLevelActivity.this, R.layout.list_item_view, R.id.name, labels, mIconIds); int position = getSelectedItemPosition(); setListAdapter(adapter); setSelection(position); } @SuppressWarnings("unused") public void onPostExecute() { mTask = null; } } private void addVersionToTitle() { String title = getTitle().toString(); try { PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0); title += " " + info.versionName; setTitle(title); } catch (AndroidException e) { Log.e(cTag, "Failed to add version to title: " + e.getMessage()); } } private void checkLastVersion() { final int lastVersion = Preferences.getLastVersion(this); if (Math.abs(lastVersion) < Math.abs(Constants.cVersion)) { // This is a new install or an upgrade. // show what's new message SharedPreferences.Editor editor = Preferences.getEditor(this); editor.putInt(Preferences.LAST_VERSION, Constants.cVersion); editor.commit(); showDialog(WHATS_NEW_DIALOG); } } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.core.activity; import static org.dodgybits.shuffle.android.core.util.Constants.cPackage; import static org.dodgybits.shuffle.android.core.util.Constants.cStringType; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity; import roboguice.inject.InjectView; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.TextView; import android.widget.AdapterView.OnItemSelectedListener; public class HelpActivity extends FlurryEnabledActivity { public static final String cHelpPage = "helpPage"; @InjectView(R.id.help_screen) Spinner mHelpSpinner; @InjectView(R.id.help_text) TextView mHelpContent; @InjectView(R.id.previous_button) Button mPrevious; @InjectView(R.id.next_button) Button mNext; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.help); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.help_screens, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mHelpSpinner.setAdapter(adapter); mHelpSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { public void onNothingSelected(AdapterView<?> arg0) { // do nothing } public void onItemSelected(AdapterView<?> parent, View v, int position, long id) { int resId = HelpActivity.this.getResources().getIdentifier( "help" + position, cStringType, cPackage); mHelpContent.setText(HelpActivity.this.getText(resId)); updateNavigationButtons(); } }); mPrevious.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { int position = mHelpSpinner.getSelectedItemPosition(); mHelpSpinner.setSelection(position - 1); } }); mNext.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { int position = mHelpSpinner.getSelectedItemPosition(); mHelpSpinner.setSelection(position + 1); } }); setSelectionFromBundle(getIntent().getExtras()); } private void setSelectionFromBundle(Bundle bundle) { int position = 0; if (bundle != null) { position = bundle.getInt(cHelpPage, 0); } mHelpSpinner.setSelection(position); } private void updateNavigationButtons() { int position = mHelpSpinner.getSelectedItemPosition(); mPrevious.setEnabled(position > 0); mNext.setEnabled(position < mHelpSpinner.getCount() - 1); } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.core.activity; import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity; import org.dodgybits.shuffle.android.preference.model.Preferences; import org.dodgybits.shuffle.android.synchronisation.tracks.service.SynchronizationService; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; public class BootstrapActivity extends FlurryEnabledActivity { private static final String cTag = "BootstrapActivity"; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); Class<? extends Activity> activityClass = null; boolean firstTime = Preferences.isFirstTime(this); if (firstTime) { Log.i(cTag, "First time using Shuffle. Show intro screen"); activityClass = WelcomeActivity.class; } else { activityClass = TopLevelActivity.class; } startService(new Intent(this, SynchronizationService.class)); startActivity(new Intent(this, activityClass)); finish(); } }
Java
package org.dodgybits.shuffle.android.core.activity; import java.util.ArrayList; import java.util.List; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledListActivity; import org.dodgybits.shuffle.android.core.view.IconArrayAdapter; import org.dodgybits.shuffle.android.core.view.MenuUtils; import org.dodgybits.shuffle.android.persistence.provider.TaskProvider; import android.content.Intent; import android.os.Bundle; import android.os.Parcelable; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; public class LauncherShortcutActivity extends FlurryEnabledListActivity { private static final String cScreenId = "screenId"; private static final int NEW_TASK = 0; private static final int INBOX = 1; private static final int DUE_TASKS = 2; private static final int TOP_TASKS = 3; private static final int PROJECTS = 4; private static final int CONTEXTS = 5; private List<String> mLabels; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); final String action = getIntent().getAction(); setContentView(R.layout.launcher_shortcut); setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); String[] perspectives = getResources().getStringArray(R.array.perspectives); mLabels = new ArrayList<String>(); // TODO figure out a non-retarded way of added padding between text and icon mLabels.add(0, " " + getString(R.string.title_new_task)); for (String label : perspectives) { mLabels.add(" " + label); } if (!Intent.ACTION_CREATE_SHORTCUT.equals(action)) { int screenId = getIntent().getExtras().getInt(cScreenId, -1); if (screenId < INBOX && screenId > CONTEXTS) { // unknown id - just go to BootstrapActivity startActivity(new Intent(this, BootstrapActivity.class)); } else { int menuIndex = (screenId - INBOX) + MenuUtils.INBOX_ID; MenuUtils.checkCommonItemsSelected( menuIndex, this, -1, false); } finish(); return; } setTitle(R.string.title_shortcut_picker); Integer[] iconIds = new Integer[6]; iconIds[NEW_TASK] = R.drawable.list_add; iconIds[INBOX] = R.drawable.inbox; iconIds[DUE_TASKS] = R.drawable.due_actions; iconIds[TOP_TASKS] = R.drawable.next_actions; iconIds[PROJECTS] = R.drawable.projects; iconIds[CONTEXTS] = R.drawable.contexts; ArrayAdapter<CharSequence> adapter = new IconArrayAdapter( this, R.layout.text_item_view, R.id.name, mLabels.toArray(new String[0]), iconIds); setListAdapter(adapter); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { Intent shortcutIntent; Parcelable iconResource; if (position == NEW_TASK) { shortcutIntent = new Intent(Intent.ACTION_INSERT, TaskProvider.Tasks.CONTENT_URI); iconResource = Intent.ShortcutIconResource.fromContext( this, R.drawable.shuffle_icon_add); } else { shortcutIntent = new Intent(this, LauncherShortcutActivity.class); shortcutIntent.putExtra(cScreenId, position); iconResource = Intent.ShortcutIconResource.fromContext( this, R.drawable.shuffle_icon); } Intent intent = new Intent(); intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, mLabels.get(position).trim()); intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource); // Now, return the result to the launcher setResult(RESULT_OK, intent); finish(); } }
Java
package org.dodgybits.shuffle.android.core.activity.flurry; import android.content.Intent; import com.google.inject.Inject; import roboguice.service.RoboService; public abstract class FlurryEnabledService extends RoboService { @Inject protected Analytics mAnalytics; @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); mAnalytics.start(); } @Override public void onDestroy() { super.onDestroy(); mAnalytics.stop(); } }
Java
package org.dodgybits.shuffle.android.core.activity.flurry; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryApiKey; import java.util.Map; import org.dodgybits.shuffle.android.preference.model.Preferences; import android.content.Context; import com.flurry.android.FlurryAgent; import com.google.inject.Inject; public class Analytics { private Context mContext; @Inject public Analytics(Context context) { mContext = context; } public void start() { if (isEnabled()) { FlurryAgent.onStartSession(mContext, cFlurryApiKey); } } public void stop() { if (isEnabled()) { FlurryAgent.onEndSession(mContext); } } public void onEvent(String eventId, Map<String, String> parameters) { if (isEnabled()) { FlurryAgent.onEvent(eventId, parameters); } } public void onEvent(String eventId) { if (isEnabled()) { FlurryAgent.onEvent(eventId); } } public void onError(String errorId, String message, String errorClass) { if (isEnabled()) { FlurryAgent.onError(errorId, message, errorClass); } } public void onPageView(Context context) { if (isEnabled()) { FlurryAgent.onPageView(); } } private boolean isEnabled() { return Preferences.isAnalyticsEnabled(mContext); } }
Java
package org.dodgybits.shuffle.android.core.activity.flurry; import com.google.inject.Inject; import roboguice.activity.RoboExpandableListActivity; public abstract class FlurryEnabledExpandableListActivity extends RoboExpandableListActivity { @Inject protected Analytics mAnalytics; @Override public void onStart() { super.onStart(); mAnalytics.start(); } @Override public void onStop() { super.onStop(); mAnalytics.stop(); } }
Java
package org.dodgybits.shuffle.android.core.activity.flurry; import com.google.inject.Inject; import roboguice.activity.RoboActivity; public abstract class FlurryEnabledActivity extends RoboActivity { @Inject protected Analytics mAnalytics; @Override public void onStart() { super.onStart(); mAnalytics.start(); } @Override public void onStop() { super.onStop(); mAnalytics.stop(); } }
Java
package org.dodgybits.shuffle.android.core.activity.flurry; import com.google.inject.Inject; import roboguice.activity.RoboPreferenceActivity; public abstract class FlurryEnabledPreferenceActivity extends RoboPreferenceActivity { @Inject protected Analytics mAnalytics; @Override public void onStart() { super.onStart(); mAnalytics.start(); } @Override public void onStop() { super.onStop(); mAnalytics.stop(); } }
Java
package org.dodgybits.shuffle.android.core.activity.flurry; import com.google.inject.Inject; import roboguice.activity.RoboListActivity; public abstract class FlurryEnabledListActivity extends RoboListActivity { @Inject protected Analytics mAnalytics; @Override public void onStart() { super.onStart(); mAnalytics.start(); } @Override public void onStop() { super.onStop(); mAnalytics.stop(); } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.core.activity; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity; import org.dodgybits.shuffle.android.core.model.persistence.InitialDataGenerator; import org.dodgybits.shuffle.android.core.view.MenuUtils; import org.dodgybits.shuffle.android.preference.model.Preferences; import roboguice.inject.InjectView; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.Button; import com.google.inject.Inject; public class WelcomeActivity extends FlurryEnabledActivity { private static final String cTag = "WelcomeActivity"; @InjectView(R.id.sample_data_button) Button mSampleDataButton; @InjectView(R.id.clean_slate_button) Button mCleanSlateButton; @Inject InitialDataGenerator mGenerator; private Handler mHandler; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); Log.d(cTag, "onCreate"); setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.welcome); mSampleDataButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { disableButtons(); startProgressAnimation(); performCreateSampleData(); } }); mCleanSlateButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { disableButtons(); startProgressAnimation(); performCleanSlate(); } }); mHandler = new Handler() { @Override public void handleMessage(Message msg) { updateFirstTimePref(false); // Stop the spinner getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, Window.PROGRESS_VISIBILITY_OFF); startActivity(new Intent(WelcomeActivity.this, TopLevelActivity.class)); finish(); } }; } private void disableButtons() { mCleanSlateButton.setEnabled(false); mSampleDataButton.setEnabled(false); } private void startProgressAnimation() { // Start the spinner getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, Window.PROGRESS_VISIBILITY_ON); } private void performCreateSampleData() { Log.i(cTag, "Adding sample data"); setProgressBarVisibility(true); new Thread() { public void run() { mGenerator.createSampleData(mHandler); } }.start(); } private void performCleanSlate() { Log.i(cTag, "Cleaning the slate"); setProgressBarVisibility(true); new Thread() { public void run() { mGenerator.cleanSlate(mHandler); } }.start(); } private void updateFirstTimePref(boolean value) { SharedPreferences.Editor editor = Preferences.getEditor(this); editor.putBoolean(Preferences.FIRST_TIME, value); editor.commit(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuUtils.addPrefsHelpMenuItems(this, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { return MenuUtils.checkCommonItemsSelected(item, this, MenuUtils.INBOX_ID) || super.onOptionsItemSelected(item); } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.config; import org.dodgybits.shuffle.android.core.model.Entity; import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister; import android.app.Activity; import android.content.ContextWrapper; import android.database.Cursor; import org.dodgybits.shuffle.android.core.model.persistence.selector.EntitySelector; import org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings; public interface ListConfig<T extends Entity, E extends EntitySelector<E>> { String createTitle(ContextWrapper context); String getItemName(ContextWrapper context); /** * @return id of layout for this view */ int getContentViewResId(); EntityPersister<T> getPersister(); EntitySelector<E> getEntitySelector(); int getCurrentViewMenuId(); boolean supportsViewAction(); boolean isTaskList(); Cursor createQuery(Activity activity); ListPreferenceSettings getListPreferenceSettings(); }
Java
package org.dodgybits.shuffle.android.list.config; import java.util.Arrays; import java.util.List; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.persistence.TaskPersister; import org.dodgybits.shuffle.android.core.model.persistence.selector.TaskSelector; import org.dodgybits.shuffle.android.list.annotation.ContextTasks; import org.dodgybits.shuffle.android.persistence.provider.TaskProvider; import org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings; import android.content.ContextWrapper; import com.google.inject.Inject; public class ContextTasksListConfig extends AbstractTaskListConfig { private Id mContextId; private Context mContext; @Inject public ContextTasksListConfig(TaskPersister persister, @ContextTasks ListPreferenceSettings settings) { super(null, persister, settings); } @Override public int getCurrentViewMenuId() { return 0; } @Override public String createTitle(ContextWrapper context) { return context.getString(R.string.title_context_tasks, mContext.getName()); } @Override public boolean showTaskContext() { return false; } public void setContextId(Id contextId) { mContextId = contextId; setTaskSelector(createTaskQuery()); } public void setContext(Context context) { mContext = context; } private TaskSelector createTaskQuery() { List<Id> ids = Arrays.asList(new Id[]{mContextId}); TaskSelector query = TaskSelector.newBuilder() .setContexts(ids) .setSortOrder(TaskProvider.Tasks.CREATED_DATE + " ASC") .build(); return query; } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.config; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister; import org.dodgybits.shuffle.android.core.model.persistence.ProjectPersister; import org.dodgybits.shuffle.android.core.model.persistence.TaskPersister; import org.dodgybits.shuffle.android.core.model.persistence.selector.ProjectSelector; import org.dodgybits.shuffle.android.core.view.MenuUtils; import org.dodgybits.shuffle.android.list.annotation.ProjectTasks; import org.dodgybits.shuffle.android.persistence.provider.ProjectProvider; import org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings; import android.app.Activity; import android.content.ContextWrapper; import android.database.Cursor; import com.google.inject.Inject; public class ProjectListConfig implements DrilldownListConfig<Project, ProjectSelector> { private ProjectPersister mGroupPersister; private TaskPersister mChildPersister; private ListPreferenceSettings mSettings; private ProjectSelector mSelector; @Inject public ProjectListConfig(ProjectPersister projectPersister, TaskPersister taskPersister, @ProjectTasks ListPreferenceSettings settings) { mGroupPersister = projectPersister; mChildPersister = taskPersister; mSettings = settings; mSelector = ProjectSelector.newBuilder().setSortOrder(ProjectProvider.Projects.NAME + " ASC").build(); } @Override public String getChildName(ContextWrapper context) { return context.getString(R.string.task_name); } @Override public String createTitle(ContextWrapper context) { return context.getString(R.string.title_project); } @Override public int getContentViewResId() { return R.layout.projects; } @Override public int getCurrentViewMenuId() { return MenuUtils.PROJECT_ID; } @Override public String getItemName(ContextWrapper context) { return context.getString(R.string.project_name); } @Override public boolean isTaskList() { return false; } @Override public boolean supportsViewAction() { return false; } @Override public EntityPersister<Project> getPersister() { return mGroupPersister; } @Override public TaskPersister getChildPersister() { return mChildPersister; } @Override public ProjectSelector getEntitySelector() { return mSelector; } @Override public Cursor createQuery(Activity activity) { ProjectSelector selector = getEntitySelector().builderFrom(). applyListPreferences(activity, getListPreferenceSettings()).build(); return activity.managedQuery( getPersister().getContentUri(), ProjectProvider.Projects.FULL_PROJECTION, selector.getSelection(activity), selector.getSelectionArgs(), selector.getSortOrder()); } @Override public ListPreferenceSettings getListPreferenceSettings() { return mSettings; } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.config; import org.dodgybits.shuffle.android.core.model.Entity; import org.dodgybits.shuffle.android.core.model.persistence.TaskPersister; import org.dodgybits.shuffle.android.core.model.persistence.selector.EntitySelector; import android.content.ContextWrapper; public interface DrilldownListConfig<G extends Entity, E extends EntitySelector<E>> extends ListConfig<G, E> { public String getChildName(ContextWrapper context); TaskPersister getChildPersister(); }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.config; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.model.Task; import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister; import org.dodgybits.shuffle.android.core.model.persistence.TaskPersister; import org.dodgybits.shuffle.android.core.model.persistence.selector.TaskSelector; import org.dodgybits.shuffle.android.persistence.provider.TaskProvider; import org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings; import android.app.Activity; import android.content.ContextWrapper; import android.database.Cursor; public abstract class AbstractTaskListConfig implements TaskListConfig { private TaskPersister mPersister; private TaskSelector mTaskSelector; private ListPreferenceSettings mSettings; public AbstractTaskListConfig(TaskSelector selector, TaskPersister persister, ListPreferenceSettings settings) { mTaskSelector = selector; mPersister = persister; mSettings = settings; } @Override public int getContentViewResId() { return R.layout.task_list; } @Override public String getItemName(ContextWrapper context) { return context.getString(R.string.task_name); } @Override public EntityPersister<Task> getPersister() { return mPersister; } public TaskPersister getTaskPersister() { return mPersister; } @Override public boolean supportsViewAction() { return true; } @Override public boolean isTaskList() { return true; } @Override public TaskSelector getEntitySelector() { return mTaskSelector; } @Override public void setTaskSelector(TaskSelector query) { mTaskSelector = query; } @Override public Cursor createQuery(Activity activity) { TaskSelector selector = getEntitySelector().builderFrom(). applyListPreferences(activity, getListPreferenceSettings()).build(); return activity.managedQuery( selector.getContentUri(), TaskProvider.Tasks.FULL_PROJECTION, selector.getSelection(activity), selector.getSelectionArgs(), selector.getSortOrder()); } @Override public ListPreferenceSettings getListPreferenceSettings() { return mSettings; } @Override public boolean showTaskContext() { return true; } @Override public boolean showTaskProject() { return true; } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.config; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.persistence.ContextPersister; import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister; import org.dodgybits.shuffle.android.core.model.persistence.TaskPersister; import org.dodgybits.shuffle.android.core.model.persistence.selector.ContextSelector; import org.dodgybits.shuffle.android.core.view.MenuUtils; import org.dodgybits.shuffle.android.list.annotation.ContextTasks; import org.dodgybits.shuffle.android.persistence.provider.ContextProvider; import org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings; import roboguice.inject.ContextSingleton; import android.app.Activity; import android.content.ContextWrapper; import android.database.Cursor; import com.google.inject.Inject; @ContextSingleton public class ContextListConfig implements DrilldownListConfig<Context, ContextSelector> { private ContextPersister mGroupPersister; private TaskPersister mChildPersister; private ListPreferenceSettings mSettings; private ContextSelector mSelector; @Inject public ContextListConfig(ContextPersister contextPersister, TaskPersister taskPersister, @ContextTasks ListPreferenceSettings settings) { mGroupPersister = contextPersister; mChildPersister = taskPersister; mSettings = settings; mSelector = ContextSelector.newBuilder().setSortOrder(ContextProvider.Contexts.NAME + " ASC").build(); } @Override public String createTitle(ContextWrapper context) { return context.getString(R.string.title_context); } @Override public int getContentViewResId() { return R.layout.contexts; } @Override public int getCurrentViewMenuId() { return MenuUtils.CONTEXT_ID; } @Override public String getItemName(ContextWrapper context) { return context.getString(R.string.context_name); } @Override public boolean isTaskList() { return false; } @Override public EntityPersister<Context> getPersister() { return mGroupPersister; } @Override public TaskPersister getChildPersister() { return mChildPersister; } @Override public ContextSelector getEntitySelector() { return mSelector; } @Override public boolean supportsViewAction() { return false; } @Override public String getChildName(ContextWrapper context) { return context.getString(R.string.task_name); } @Override public Cursor createQuery(Activity activity) { ContextSelector selector = getEntitySelector().builderFrom(). applyListPreferences(activity, getListPreferenceSettings()).build(); return activity.managedQuery( getPersister().getContentUri(), ContextProvider.Contexts.FULL_PROJECTION, selector.getSelection(activity), selector.getSelectionArgs(), selector.getSortOrder()); } @Override public ListPreferenceSettings getListPreferenceSettings() { return mSettings; } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.config; import org.dodgybits.shuffle.android.core.model.Entity; import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister; import org.dodgybits.shuffle.android.core.model.persistence.TaskPersister; import org.dodgybits.shuffle.android.core.model.persistence.selector.EntitySelector; import org.dodgybits.shuffle.android.core.model.persistence.selector.TaskSelector; import org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings; import android.content.ContextWrapper; public interface ExpandableListConfig<G extends Entity, E extends EntitySelector<E>> { /** * @return id of layout for this view */ int getContentViewResId(); int getCurrentViewMenuId(); String getGroupName(ContextWrapper context); String getChildName(ContextWrapper context); /** * @return the name of the database column holding the key from the child to the parent */ String getGroupIdColumnName(); E getGroupSelector(); TaskSelector getChildSelector(); EntityPersister<G> getGroupPersister(); TaskPersister getChildPersister(); ListPreferenceSettings getListPreferenceSettings(); }
Java
package org.dodgybits.shuffle.android.list.config; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.model.persistence.TaskPersister; import org.dodgybits.shuffle.android.core.model.persistence.selector.TaskSelector; import org.dodgybits.shuffle.android.core.view.MenuUtils; import org.dodgybits.shuffle.android.list.annotation.DueTasks; import org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings; import android.content.ContextWrapper; import com.google.inject.Inject; public class DueActionsListConfig extends AbstractTaskListConfig { private TaskSelector.PredefinedQuery mMode = TaskSelector.PredefinedQuery.dueToday; @Inject public DueActionsListConfig(TaskPersister persister, @DueTasks ListPreferenceSettings settings) { super( createSelector(TaskSelector.PredefinedQuery.dueToday), persister, settings); } public TaskSelector.PredefinedQuery getMode() { return mMode; } public void setMode(TaskSelector.PredefinedQuery mode) { mMode = mode; setTaskSelector(createSelector(mode)); } @Override public int getContentViewResId() { return R.layout.tabbed_due_tasks; } public int getCurrentViewMenuId() { return MenuUtils.CALENDAR_ID; } public String createTitle(ContextWrapper context) { return context.getString(R.string.title_calendar, getSelectedPeriod(context)); } private String getSelectedPeriod(ContextWrapper context) { String result = null; switch (mMode) { case dueToday: result = context.getString(R.string.day_button_title).toLowerCase(); break; case dueNextWeek: result = context.getString(R.string.week_button_title).toLowerCase(); break; case dueNextMonth: result = context.getString(R.string.month_button_title).toLowerCase(); break; } return result; } private static TaskSelector createSelector(TaskSelector.PredefinedQuery mMode) { return TaskSelector.newBuilder().setPredefined(mMode).build(); } }
Java
package org.dodgybits.shuffle.android.list.config; import java.util.Arrays; import java.util.List; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.android.core.model.persistence.TaskPersister; import org.dodgybits.shuffle.android.core.model.persistence.selector.TaskSelector; import org.dodgybits.shuffle.android.list.annotation.ProjectTasks; import org.dodgybits.shuffle.android.persistence.provider.TaskProvider; import org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings; import android.content.ContextWrapper; import com.google.inject.Inject; public class ProjectTasksListConfig extends AbstractTaskListConfig { private Id mProjectId; private Project mProject; @Inject public ProjectTasksListConfig(TaskPersister persister, @ProjectTasks ListPreferenceSettings settings) { super(null, persister, settings); } @Override public int getCurrentViewMenuId() { return 0; } @Override public String createTitle(ContextWrapper context) { return context.getString(R.string.title_project_tasks, mProject.getName()); } @Override public boolean showTaskProject() { return false; } public void setProjectId(Id projectId) { mProjectId = projectId; setTaskSelector(createTaskQuery()); } public void setProject(Project project) { mProject = project; } private TaskSelector createTaskQuery() { List<Id> ids = Arrays.asList(new Id[]{mProjectId}); TaskSelector query = TaskSelector.newBuilder() .setProjects(ids) .setSortOrder(TaskProvider.Tasks.DISPLAY_ORDER + " ASC") .build(); return query; } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.config; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister; import org.dodgybits.shuffle.android.core.model.persistence.ProjectPersister; import org.dodgybits.shuffle.android.core.model.persistence.TaskPersister; import org.dodgybits.shuffle.android.core.model.persistence.selector.ProjectSelector; import org.dodgybits.shuffle.android.core.model.persistence.selector.TaskSelector; import org.dodgybits.shuffle.android.core.view.MenuUtils; import org.dodgybits.shuffle.android.list.annotation.ExpandableProjects; import org.dodgybits.shuffle.android.persistence.provider.ProjectProvider; import org.dodgybits.shuffle.android.persistence.provider.TaskProvider; import org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings; import android.content.ContextWrapper; import com.google.inject.Inject; public class ProjectExpandableListConfig implements ExpandableListConfig<Project, ProjectSelector> { private ProjectPersister mGroupPersister; private TaskPersister mChildPersister; private ListPreferenceSettings mSettings; private TaskSelector mTaskSelector; private ProjectSelector mProjectSelector; @Inject public ProjectExpandableListConfig(ProjectPersister projectPersister, TaskPersister taskPersister, @ExpandableProjects ListPreferenceSettings settings) { mGroupPersister = projectPersister; mChildPersister = taskPersister; mSettings = settings; mTaskSelector = TaskSelector.newBuilder(). setSortOrder(TaskProvider.Tasks.DISPLAY_ORDER + " ASC").build(); mProjectSelector = ProjectSelector.newBuilder(). setSortOrder(ProjectProvider.Projects.NAME + " ASC").build(); } @Override public ProjectSelector getGroupSelector() { return mProjectSelector; } @Override public TaskSelector getChildSelector() { return mTaskSelector; } @Override public String getChildName(ContextWrapper context) { return context.getString(R.string.task_name); } @Override public int getContentViewResId() { return R.layout.expandable_projects; } @Override public int getCurrentViewMenuId() { return MenuUtils.PROJECT_ID; } @Override public String getGroupIdColumnName() { return TaskProvider.Tasks.PROJECT_ID; } @Override public String getGroupName(ContextWrapper context) { return context.getString(R.string.project_name); } @Override public TaskPersister getChildPersister() { return mChildPersister; } @Override public EntityPersister<Project> getGroupPersister() { return mGroupPersister; } @Override public ListPreferenceSettings getListPreferenceSettings() { return mSettings; } }
Java
package org.dodgybits.shuffle.android.list.config; import org.dodgybits.shuffle.android.core.model.Task; import org.dodgybits.shuffle.android.core.model.persistence.TaskPersister; import org.dodgybits.shuffle.android.core.model.persistence.selector.TaskSelector; public interface TaskListConfig extends ListConfig<Task, TaskSelector> { TaskPersister getTaskPersister(); void setTaskSelector(TaskSelector query); boolean showTaskContext(); boolean showTaskProject(); }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.config; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.persistence.ContextPersister; import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister; import org.dodgybits.shuffle.android.core.model.persistence.TaskPersister; import org.dodgybits.shuffle.android.core.model.persistence.selector.ContextSelector; import org.dodgybits.shuffle.android.core.model.persistence.selector.TaskSelector; import org.dodgybits.shuffle.android.core.view.MenuUtils; import org.dodgybits.shuffle.android.list.annotation.ExpandableContexts; import org.dodgybits.shuffle.android.persistence.provider.TaskProvider; import org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings; import android.content.ContextWrapper; import com.google.inject.Inject; public class ContextExpandableListConfig implements ExpandableListConfig<Context, ContextSelector> { private ContextPersister mGroupPersister; private TaskPersister mChildPersister; private ListPreferenceSettings mSettings; private TaskSelector mTaskSelector; private ContextSelector mContextSelector; @Inject public ContextExpandableListConfig(ContextPersister contextPersister, TaskPersister taskPersister, @ExpandableContexts ListPreferenceSettings settings) { mGroupPersister = contextPersister; mChildPersister = taskPersister; mSettings = settings; mTaskSelector = TaskSelector.newBuilder().build(); mContextSelector = ContextSelector.newBuilder().build(); } @Override public ContextSelector getGroupSelector() { return mContextSelector; } @Override public TaskSelector getChildSelector() { return mTaskSelector; } @Override public String getChildName(ContextWrapper context) { return context.getString(R.string.task_name); } @Override public int getContentViewResId() { return R.layout.expandable_contexts; } @Override public int getCurrentViewMenuId() { return MenuUtils.CONTEXT_ID; } @Override public String getGroupIdColumnName() { return TaskProvider.Tasks.CONTEXT_ID; } @Override public String getGroupName(ContextWrapper context) { return context.getString(R.string.context_name); } @Override public TaskPersister getChildPersister() { return mChildPersister; } @Override public EntityPersister<Context> getGroupPersister() { return mGroupPersister; } @Override public ListPreferenceSettings getListPreferenceSettings() { return mSettings; } }
Java
package org.dodgybits.shuffle.android.list.config; import java.util.HashMap; import org.dodgybits.shuffle.android.core.model.persistence.selector.TaskSelector; import org.dodgybits.shuffle.android.core.model.persistence.selector.TaskSelector.PredefinedQuery; import org.dodgybits.shuffle.android.list.activity.task.InboxActivity; import org.dodgybits.shuffle.android.list.activity.task.TabbedDueActionsActivity; import org.dodgybits.shuffle.android.list.activity.task.TicklerActivity; import org.dodgybits.shuffle.android.list.activity.task.TopTasksActivity; import android.content.Context; import android.content.Intent; public class StandardTaskQueries { public static final String cInbox = "inbox"; public static final String cDueToday = "due_today"; public static final String cDueNextWeek = "due_next_week"; public static final String cDueNextMonth = "due_next_month"; public static final String cNextTasks = "next_tasks"; public static final String cTickler = "tickler"; public static final String cDueTasksFilterPrefs = "due_tasks"; public static final String cProjectFilterPrefs = "project"; public static final String cContextFilterPrefs = "context"; private static final TaskSelector cInboxQuery = TaskSelector.newBuilder().setPredefined(PredefinedQuery.inbox).build(); private static final TaskSelector cDueTodayQuery = TaskSelector.newBuilder().setPredefined(PredefinedQuery.dueToday).build(); private static final TaskSelector cDueNextWeekQuery = TaskSelector.newBuilder().setPredefined(PredefinedQuery.dueNextWeek).build(); private static final TaskSelector cDueNextMonthQuery = TaskSelector.newBuilder().setPredefined(PredefinedQuery.dueNextMonth).build(); private static final TaskSelector cNextTasksQuery = TaskSelector.newBuilder().setPredefined(PredefinedQuery.nextTasks).build(); private static final TaskSelector cTicklerQuery = TaskSelector.newBuilder().setPredefined(PredefinedQuery.tickler).build(); private static final HashMap<String,TaskSelector> cQueryMap = new HashMap<String,TaskSelector>(); static { cQueryMap.put(cInbox, cInboxQuery); cQueryMap.put(cDueToday, cDueTodayQuery); cQueryMap.put(cDueNextWeek, cDueNextWeekQuery); cQueryMap.put(cDueNextMonth, cDueNextMonthQuery); cQueryMap.put(cNextTasks, cNextTasksQuery); cQueryMap.put(cTickler, cTicklerQuery); } private static final HashMap<String,String> cFilterPrefsMap = new HashMap<String,String>(); static { cFilterPrefsMap.put(cInbox, cInbox); cFilterPrefsMap.put(cDueToday, cDueTasksFilterPrefs); cFilterPrefsMap.put(cDueNextWeek, cDueTasksFilterPrefs); cFilterPrefsMap.put(cDueNextMonth, cDueTasksFilterPrefs); cFilterPrefsMap.put(cNextTasks, cNextTasks); cFilterPrefsMap.put(cTickler, cTickler); } public static TaskSelector getQuery(String name) { return cQueryMap.get(name); } public static String getFilterPrefsKey(String name) { return cFilterPrefsMap.get(name); } public static Intent getActivityIntent(Context context, String name) { if (cInbox.equals(name)) { return new Intent(context, InboxActivity.class); } if (cNextTasks.equals(name)) { return new Intent(context, TopTasksActivity.class); } if (cTickler.equals(name)) { return new Intent(context, TicklerActivity.class); } PredefinedQuery query = PredefinedQuery.dueToday; if (cDueNextWeek.equals(name)) { query = PredefinedQuery.dueNextWeek; } else if (cDueNextMonth.equals(name)) { query = PredefinedQuery.dueNextMonth; } Intent intent = new Intent(context, TabbedDueActionsActivity.class); intent.putExtra(TabbedDueActionsActivity.DUE_MODE, query.name()); return intent; } }
Java
package org.dodgybits.shuffle.android.list.annotation; import com.google.inject.BindingAnnotation; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; @BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) public @interface Tickler { }
Java
package org.dodgybits.shuffle.android.list.annotation; import com.google.inject.BindingAnnotation; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; @BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) public @interface Contexts { }
Java
package org.dodgybits.shuffle.android.list.annotation; import com.google.inject.BindingAnnotation; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; @BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) public @interface TopTasks { }
Java