code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
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);
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/persistence/EntityPersister.java | Java | asf20 | 1,525 |
/*
* 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;
}
} | 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/persistence/InitialDataGenerator.java | Java | asf20 | 11,653 |
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;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/persistence/ContextPersister.java | Java | asf20 | 3,425 |
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);
}
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/persistence/DefaultEntityCache.java | Java | asf20 | 1,318 |
package org.dodgybits.shuffle.android.core.model.persistence.selector;
public enum Flag {
yes, no, ignored
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/persistence/selector/Flag.java | Java | asf20 | 114 |
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
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/persistence/selector/TaskSelector.java | Java | asf20 | 11,214 |
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);
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/persistence/selector/EntitySelector.java | Java | asf20 | 966 |
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;
}
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/persistence/selector/ContextSelector.java | Java | asf20 | 1,820 |
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;
}
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/persistence/selector/ProjectSelector.java | Java | asf20 | 1,780 |
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;
}
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/persistence/selector/AbstractEntitySelector.java | Java | asf20 | 4,475 |
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;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/persistence/TaskPersister.java | Java | asf20 | 14,313 |
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);
}
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/persistence/AbstractEntityPersister.java | Java | asf20 | 7,181 |
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;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/persistence/ProjectPersister.java | Java | asf20 | 3,775 |
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);
} | 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/persistence/EntityCache.java | Java | asf20 | 249 |
/*
* 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;
}
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/Task.java | Java | asf20 | 9,326 |
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;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/Reminder.java | Java | asf20 | 416 |
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();
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/Entity.java | Java | asf20 | 433 |
/*
* 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);
}
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/activity/TopLevelActivity.java | Java | asf20 | 12,185 |
/*
* 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);
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/activity/HelpActivity.java | Java | asf20 | 3,581 |
/*
* 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();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/activity/BootstrapActivity.java | Java | asf20 | 1,693 |
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();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/activity/LauncherShortcutActivity.java | Java | asf20 | 3,847 |
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();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/activity/flurry/FlurryEnabledService.java | Java | asf20 | 538 |
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);
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/activity/flurry/Analytics.java | Java | asf20 | 1,482 |
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();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/activity/flurry/FlurryEnabledExpandableListActivity.java | Java | asf20 | 509 |
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();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/activity/flurry/FlurryEnabledActivity.java | Java | asf20 | 472 |
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();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/activity/flurry/FlurryEnabledPreferenceActivity.java | Java | asf20 | 497 |
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();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/activity/flurry/FlurryEnabledListActivity.java | Java | asf20 | 479 |
/*
* 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);
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/activity/WelcomeActivity.java | Java | asf20 | 4,453 |
/*
* 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();
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/config/ListConfig.java | Java | asf20 | 1,598 |
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;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/config/ContextTasksListConfig.java | Java | asf20 | 1,843 |
/*
* 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;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/config/ProjectListConfig.java | Java | asf20 | 3,755 |
/*
* 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();
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/config/DrilldownListConfig.java | Java | asf20 | 1,146 |
/*
* 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;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/config/AbstractTaskListConfig.java | Java | asf20 | 3,189 |
/*
* 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;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/config/ContextListConfig.java | Java | asf20 | 3,802 |
/*
* 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();
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/config/ExpandableListConfig.java | Java | asf20 | 1,837 |
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();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/config/DueActionsListConfig.java | Java | asf20 | 2,203 |
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;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/config/ProjectTasksListConfig.java | Java | asf20 | 1,844 |
/*
* 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;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/config/ProjectExpandableListConfig.java | Java | asf20 | 3,614 |
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();
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/config/TaskListConfig.java | Java | asf20 | 495 |
/*
* 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;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/config/ContextExpandableListConfig.java | Java | asf20 | 3,389 |
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;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/config/StandardTaskQueries.java | Java | asf20 | 4,008 |
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 {
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/annotation/Tickler.java | Java | asf20 | 512 |
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 {
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/annotation/Contexts.java | Java | asf20 | 512 |
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 {
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/annotation/TopTasks.java | Java | asf20 | 513 |
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 ProjectTasks {
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/annotation/ProjectTasks.java | Java | asf20 | 517 |
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 ExpandableProjects {
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/annotation/ExpandableProjects.java | Java | asf20 | 523 |
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 ExpandableContexts {
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/annotation/ExpandableContexts.java | Java | asf20 | 523 |
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 DueTasks {
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/annotation/DueTasks.java | Java | asf20 | 513 |
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 Projects {
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/annotation/Projects.java | Java | asf20 | 513 |
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 ContextTasks {
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/annotation/ContextTasks.java | Java | asf20 | 517 |
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 Inbox {
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/annotation/Inbox.java | Java | asf20 | 510 |
/*
* 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.view;
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.persistence.EntityCache;
import org.dodgybits.shuffle.android.core.util.DateUtils;
import org.dodgybits.shuffle.android.core.view.ContextIcon;
import org.dodgybits.shuffle.android.core.view.DrawableUtils;
import org.dodgybits.shuffle.android.preference.model.Preferences;
import roboguice.inject.ContextSingleton;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.StrikethroughSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import com.google.inject.Inject;
public class TaskView extends ItemView<Task> {
private EntityCache<Context> mContextCache;
private EntityCache<Project> mProjectCache;
protected LabelView mContext;
protected TextView mDescription;
protected TextView mDateDisplay;
protected TextView mProject;
protected TextView mDetails;
protected StatusView mStatus;
protected boolean mShowContext;
protected boolean mShowProject;
@Inject
public TaskView(
android.content.Context androidContext,
EntityCache<Context> contextCache,
EntityCache<Project> projectCache) {
super(androidContext);
mContextCache = contextCache;
mProjectCache = projectCache;
LayoutInflater vi = (LayoutInflater)androidContext.
getSystemService(android.content.Context.LAYOUT_INFLATER_SERVICE);
vi.inflate(getViewResourceId(), this, true);
mContext = (LabelView) findViewById(R.id.context);
mDescription = (TextView) findViewById(R.id.description);
mDateDisplay = (TextView) findViewById(R.id.due_date);
mProject = (TextView) findViewById(R.id.project);
mDetails = (TextView) findViewById(R.id.details);
mStatus = (StatusView) findViewById(R.id.status);
mShowContext = true;
mShowProject = true;
int bgColour = getResources().getColor(R.drawable.list_background);
GradientDrawable drawable = DrawableUtils.createGradient(bgColour, Orientation.TOP_BOTTOM, 1.1f, 0.95f);
setBackgroundDrawable(drawable);
}
protected int getViewResourceId() {
return R.layout.list_task_view;
}
public void setShowContext(boolean showContext) {
mShowContext = showContext;
}
public void setShowProject(boolean showProject) {
mShowProject = showProject;
}
public void updateView(Task task) {
Project project = mProjectCache.findById(task.getProjectId());
Context context = mContextCache.findById(task.getContextId());
updateContext(context);
updateDescription(task);
updateWhen(task);
updateProject(project);
updateDetails(task);
updateStatus(task, context, project);
}
private void updateContext(Context context) {
boolean displayContext = Preferences.displayContextName(getContext());
boolean displayIcon = Preferences.displayContextIcon(getContext());
if (mShowContext && context != null && (displayContext || displayIcon)) {
mContext.setText(displayContext ? context.getName() : "");
mContext.setColourIndex(context.getColourIndex());
// add context icon if preferences indicate to
ContextIcon icon = ContextIcon.createIcon(context.getIconName(), getResources());
int id = icon.smallIconId;
if (id > 0 && displayIcon) {
mContext.setIcon(getResources().getDrawable(id));
} else {
mContext.setIcon(null);
}
mContext.setVisibility(View.VISIBLE);
} else {
mContext.setVisibility(View.GONE);
}
}
private void updateDescription(Task task) {
CharSequence description = task.getDescription();
if (task.isComplete()) {
// add strike-through for completed tasks
SpannableString desc = new SpannableString(description);
desc.setSpan(new StrikethroughSpan(), 0, description.length(), Spanned.SPAN_PARAGRAPH);
description = desc;
}
mDescription.setText(description);
}
private void updateWhen(Task task) {
if (Preferences.displayDueDate(getContext())) {
CharSequence dateRange = DateUtils.displayDateRange(
getContext(), task.getStartDate(), task.getDueDate(), !task.isAllDay());
mDateDisplay.setText(dateRange);
if (task.getDueDate() < System.currentTimeMillis()) {
// task is overdue
mDateDisplay.setTypeface(Typeface.DEFAULT_BOLD);
mDateDisplay.setTextColor(Color.RED);
} else {
mDateDisplay.setTypeface(Typeface.DEFAULT);
mDateDisplay.setTextColor(
getContext().getResources().getColor(R.drawable.dark_blue));
}
} else {
mDateDisplay.setText("");
}
}
private void updateProject(Project project) {
if (mShowProject && Preferences.displayProject(getContext()) && (project != null)) {
mProject.setText(project.getName());
} else {
mProject.setText("");
}
}
private void updateDetails(Task task) {
final String details = task.getDetails();
if (Preferences.displayDetails(getContext()) && (details != null)) {
mDetails.setText(details);
} else {
mDetails.setText("");
}
}
private void updateStatus(Task task, Context context, Project project) {
mStatus.updateStatus(task, context, project, false);
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/view/TaskView.java | Java | asf20 | 6,858 |
package org.dodgybits.shuffle.android.list.view;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import com.google.inject.Inject;
import org.dodgybits.android.shuffle.R;
import roboguice.RoboGuice;
import roboguice.event.EventManager;
public class ButtonBar extends LinearLayout implements View.OnClickListener {
private Button mAddItemButton;
private Button mOtherButton;
private ImageButton mFilterButton;
@Inject private EventManager mEventManager;
public ButtonBar(Context context) {
super(context);
init(context);
}
public ButtonBar(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
private void init(Context context) {
LayoutInflater vi = (LayoutInflater)context.
getSystemService(android.content.Context.LAYOUT_INFLATER_SERVICE);
vi.inflate(R.layout.button_bar, this, true);
// wire up this component
RoboGuice.getInjector(context).injectMembers(this);
mAddItemButton = (Button)findViewById(R.id.add_item_button);
Drawable addIcon = getResources().getDrawable(android.R.drawable.ic_menu_add);
addIcon.setBounds(0, 0, 24, 24);
mAddItemButton.setCompoundDrawables(addIcon, null, null, null);
mAddItemButton.setOnClickListener(this);
mOtherButton = (Button)findViewById(R.id.other_button);
mOtherButton.setOnClickListener(this);
mFilterButton = (ImageButton)findViewById(R.id.filter_button);
mFilterButton.setOnClickListener(this);
}
public Button getAddItemButton() {
return mAddItemButton;
}
public Button getOtherButton() {
return mOtherButton;
}
public ImageButton getFilterButton() {
return mFilterButton;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.add_item_button:
mEventManager.fire(new AddItemButtonClickEvent());
break;
case R.id.other_button:
mEventManager.fire(new OtherButtonClickEvent());
break;
case R.id.filter_button:
mEventManager.fire(new FilterButtonClickEvent());
break;
}
}
public class AddItemButtonClickEvent {};
public class OtherButtonClickEvent {};
public class FilterButtonClickEvent {};
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/view/ButtonBar.java | Java | asf20 | 2,619 |
/*
* 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.view;
import org.dodgybits.android.shuffle.R;
import android.content.Context;
public class ExpandableProjectView extends ProjectView {
public ExpandableProjectView(Context androidContext) {
super(androidContext);
}
protected int getViewResourceId() {
return R.layout.expandable_project_view;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/view/ExpandableProjectView.java | Java | asf20 | 979 |
/*
* 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.view;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.LinearLayout;
public abstract class ItemView<T> extends LinearLayout {
public ItemView(Context context) {
super(context);
}
public ItemView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public abstract void updateView(T item);
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/view/ItemView.java | Java | asf20 | 1,028 |
package org.dodgybits.shuffle.android.list.view;
import android.content.Context;
import android.text.ParcelableSpan;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.widget.TextView;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.model.Project;
import org.dodgybits.shuffle.android.core.model.Task;
public class StatusView extends TextView {
public static enum Status {
yes, no, fromContext, fromProject
}
private SpannableString mDeleted;
private SpannableString mDeletedFromContext;
private SpannableString mDeletedFromProject;
private SpannableString mActive;
private SpannableString mInactive;
private SpannableString mInactiveFromContext;
private SpannableString mInactiveFromProject;
public StatusView(Context context) {
super(context);
createStatusStrings();
}
public StatusView(Context context, AttributeSet attrs) {
super(context, attrs);
createStatusStrings();
}
public StatusView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
createStatusStrings();
}
private void createStatusStrings() {
int deletedColour = getResources().getColor(R.drawable.red);
ParcelableSpan deletedColorSpan = new ForegroundColorSpan(deletedColour);
int inactiveColour = getResources().getColor(R.drawable.mid_gray);
ParcelableSpan inactiveColorSpan = new ForegroundColorSpan(inactiveColour);
String deleted = getResources().getString(R.string.deleted);
String active = getResources().getString(R.string.active);
String inactive = getResources().getString(R.string.inactive);
String fromContext = getResources().getString(R.string.from_context);
String fromProject = getResources().getString(R.string.from_project);
mDeleted = new SpannableString(deleted);
mDeleted.setSpan(deletedColorSpan, 0, mDeleted.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
mDeletedFromContext = new SpannableString(deleted + " " + fromContext);
mDeletedFromContext.setSpan(deletedColorSpan, 0, mDeletedFromContext.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
mDeletedFromProject = new SpannableString(deleted + " " + fromProject);
mDeletedFromProject.setSpan(deletedColorSpan, 0, mDeletedFromProject.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
mActive = new SpannableString(active);
mInactive = new SpannableString(inactive);
mInactive.setSpan(inactiveColorSpan, 0, mInactive.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
mInactiveFromContext = new SpannableString(inactive + " " + fromContext);
mInactiveFromContext.setSpan(inactiveColorSpan, 0, mInactiveFromContext.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
mInactiveFromProject = new SpannableString(inactive + " " + fromProject);
mInactiveFromProject.setSpan(inactiveColorSpan, 0, mInactiveFromProject.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
}
public void updateStatus(Task task, org.dodgybits.shuffle.android.core.model.Context context, Project project, boolean showSomething) {
updateStatus(
activeStatus(task, context, project),
deletedStatus(task, context, project),
showSomething);
}
private Status activeStatus(Task task, org.dodgybits.shuffle.android.core.model.Context context, Project project) {
Status status = Status.no;
if (task.isActive()) {
if (context != null && !context.isActive()) {
status = Status.fromContext;
} else if (project != null && !project.isActive()) {
status = Status.fromProject;
} else {
status = Status.yes;
}
}
return status;
}
private Status deletedStatus(Task task, org.dodgybits.shuffle.android.core.model.Context context, Project project) {
Status status = Status.yes;
if (!task.isDeleted()) {
if (context != null && context.isDeleted()) {
status = Status.fromContext;
} else if (project != null && project.isDeleted()) {
status = Status.fromProject;
} else {
status = Status.no;
}
}
return status;
}
public void updateStatus(boolean active, boolean deleted, boolean showSomething) {
updateStatus(
active ? Status.yes : Status.no,
deleted ? Status.yes : Status.no,
showSomething);
}
public void updateStatus(Status active, Status deleted, boolean showSomething) {
SpannableStringBuilder builder = new SpannableStringBuilder();
switch (deleted) {
case yes:
builder.append(mDeleted);
break;
case fromContext:
builder.append(mDeletedFromContext);
break;
case fromProject:
builder.append(mDeletedFromProject);
break;
}
builder.append(" ");
switch (active) {
case yes:
if (showSomething && deleted == Status.no) builder.append(mActive);
break;
case no:
builder.append(mInactive);
break;
case fromContext:
builder.append(mInactiveFromContext);
break;
case fromProject:
builder.append(mInactiveFromProject);
break;
}
setText(builder);
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/view/StatusView.java | Java | asf20 | 5,847 |
/*
* 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.view;
import org.dodgybits.android.shuffle.R;
import android.content.Context;
public class ExpandableContextView extends ContextView {
public ExpandableContextView(Context androidContext) {
super(androidContext);
}
protected int getViewResourceId() {
return R.layout.expandable_context_view;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/view/ExpandableContextView.java | Java | asf20 | 979 |
/*
* 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.view;
public interface SwipeListItemListener {
public void onListItemSwiped(int position);
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/view/SwipeListItemListener.java | Java | asf20 | 764 |
/*
* 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.view;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.model.Project;
import android.content.Context;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.TextView;
public class ProjectView extends ItemView<Project> {
private TextView mName;
private ImageView mParallelIcon;
private StatusView mStatus;
private SparseIntArray mTaskCountArray;
private ForegroundColorSpan mSpan;
public ProjectView(Context androidContext) {
super(androidContext);
LayoutInflater vi = (LayoutInflater)androidContext.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi.inflate(getViewResourceId(), this, true);
mName = (TextView) findViewById(R.id.name);
mParallelIcon = (ImageView) findViewById(R.id.parallel_image);
mStatus = (StatusView)findViewById(R.id.status);
int colour = getResources().getColor(R.drawable.pale_blue);
mSpan = new ForegroundColorSpan(colour);
}
protected int getViewResourceId() {
return R.layout.list_project_view;
}
public void setTaskCountArray(SparseIntArray taskCountArray) {
mTaskCountArray = taskCountArray;
}
@Override
public void updateView(Project project) {
updateNameLabel(project);
updateStatus(project);
updateParallelIcon(project);
}
private void updateNameLabel(Project project) {
if (mTaskCountArray != null) {
Integer count = mTaskCountArray.get((int)project.getLocalId().getId());
if (count == null) count = 0;
CharSequence label = project.getName() + " (" + count + ")";
SpannableString spannable = new SpannableString(label);
spannable.setSpan(mSpan, project.getName().length(),
label.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
mName.setText(spannable);
} else {
mName.setText(project.getName());
}
}
private void updateStatus(Project project) {
mStatus.updateStatus(project.isActive(), project.isDeleted(), false);
}
private void updateParallelIcon(Project project) {
if (mParallelIcon != null) {
if (project.isParallel()) {
mParallelIcon.setImageResource(R.drawable.parallel);
} else {
mParallelIcon.setImageResource(R.drawable.sequence);
}
}
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/view/ProjectView.java | Java | asf20 | 3,236 |
/*
* 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.view;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.model.Context;
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 android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.util.AttributeSet;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class ContextView extends ItemView<Context> {
protected TextColours mTextColours;
private ImageView mIcon;
private TextView mName;
private StatusView mStatus;
private View mColour;
private SparseIntArray mTaskCountArray;
public ContextView(android.content.Context context) {
super(context);
init(context);
}
public ContextView(android.content.Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public void init(android.content.Context androidContext) {
LayoutInflater vi = (LayoutInflater)androidContext.
getSystemService(android.content.Context.LAYOUT_INFLATER_SERVICE);
vi.inflate(getViewResourceId(), this, true);
mColour = (View) findViewById(R.id.colour);
mName = (TextView) findViewById(R.id.name);
mStatus = (StatusView)findViewById(R.id.status);
mIcon = (ImageView) findViewById(R.id.icon);
mTextColours = TextColours.getInstance(androidContext);
}
protected int getViewResourceId() {
return R.layout.context_view;
}
public void setTaskCountArray(SparseIntArray taskCountArray) {
mTaskCountArray = taskCountArray;
}
@Override
public void updateView(Context context) {
updateIcon(context);
updateNameLabel(context);
updateStatus(context);
updateBackground(context);
}
private void updateIcon(Context context) {
ContextIcon icon = ContextIcon.createIcon(context.getIconName(), getResources());
int iconResource = icon.largeIconId;
if (iconResource > 0) {
mIcon.setImageResource(iconResource);
mIcon.setVisibility(View.VISIBLE);
} else {
mIcon.setVisibility(View.INVISIBLE);
}
}
private void updateNameLabel(Context context) {
if (mTaskCountArray != null) {
Integer count = mTaskCountArray.get((int)context.getLocalId().getId());
if (count == null) count = 0;
mName.setText(context.getName() + " (" + count + ")");
} else {
mName.setText(context.getName());
}
int textColour = mTextColours.getTextColour(context.getColourIndex());
mName.setTextColor(textColour);
}
private void updateStatus(Context context) {
if (mStatus != null) {
mStatus.updateStatus(context.isActive(), context.isDeleted(), false);
}
}
private void updateBackground(Context context) {
int bgColour = mTextColours.getBackgroundColour(context.getColourIndex());
GradientDrawable drawable = DrawableUtils.createGradient(bgColour, Orientation.TOP_BOTTOM);
drawable.setCornerRadius(12.0f);
mColour.setBackgroundDrawable(drawable);
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/view/ContextView.java | Java | asf20 | 4,007 |
/*
* 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.view;
import org.dodgybits.shuffle.android.core.util.TextColours;
import org.dodgybits.shuffle.android.core.view.DrawableUtils;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.util.AttributeSet;
import android.widget.TextView;
/**
* A TextView with coloured text and a round edged coloured background.
*/
public class LabelView extends TextView {
protected TextColours mTextColours;
protected Drawable mIcon;
protected int mTextColour;
protected int mBgColour;
public LabelView(Context context) {
super(context);
init(context);
}
public LabelView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public LabelView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
mTextColours = TextColours.getInstance(context);
}
public void setColourIndex(int colourIndex) {
mTextColour = mTextColours.getTextColour(colourIndex);
mBgColour = mTextColours.getBackgroundColour(colourIndex);
setTextColor(mTextColour);
GradientDrawable drawable = DrawableUtils.createGradient(mBgColour, Orientation.TOP_BOTTOM);
drawable.setCornerRadius(4.0f);
//drawable.setAlpha(240);
setBackgroundDrawable(drawable);
}
public void setIcon(Drawable icon) {
mIcon = icon;
setCompoundDrawablesWithIntrinsicBounds(mIcon, null, null, null);
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/view/LabelView.java | Java | asf20 | 2,263 |
/*
* 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.view;
import android.R;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ListView;
public class SwipeListItemWrapper extends FrameLayout {
private static final String cTag = "SwipeListItemWrapper";
private int mStartX;
private int mStartY;
private SwipeListItemListener mListener;
private int mPosition;
public SwipeListItemWrapper(Context context) {
super(context);
}
public SwipeListItemWrapper(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SwipeListItemWrapper(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
final int action = ev.getAction();
final int x = (int)ev.getX();
final int y = (int)ev.getY();
boolean stealEvent = false;
switch (action) {
case MotionEvent.ACTION_MOVE:
Log.d(cTag, "move event");
if (isValidSwipe(x, y)) {
stealEvent = true;
}
break;
case MotionEvent.ACTION_DOWN:
Log.d(cTag, "down event");
mStartX = x;
mStartY = y;
break;
case MotionEvent.ACTION_CANCEL:
Log.d(cTag, "cancel event");
mPosition = AdapterView.INVALID_POSITION;
// some parent component has stolen the event
// nothing to do
break;
case MotionEvent.ACTION_UP:
Log.d(cTag, "up event");
break;
}
return stealEvent;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
// we've got a valid swipe event. Notify the listener (if any)
if (mPosition != AdapterView.INVALID_POSITION && mListener != null) {
mListener.onListItemSwiped(mPosition);
}
}
return true;
}
public void setSwipeListItemListener(SwipeListItemListener listener) {
mListener = listener;
}
/**
* Check if this appears to be a swipe event.
*
* Consider it a swipe if it traverses at least a third of the screen,
* and is mostly horizontal.
*/
private boolean isValidSwipe(final int x, final int y) {
final int screenWidth = getWidth();
final int xDiff = Math.abs(x - mStartX);
final int yDiff = Math.abs(y - mStartY);
boolean horizontalValid = xDiff >= (screenWidth / 3);
boolean verticalValid = yDiff > 0 && (xDiff / yDiff) > 4;
mPosition = AdapterView.INVALID_POSITION;
if (horizontalValid && verticalValid) {
ListView list = (ListView) findViewById(R.id.list);
if (list != null) {
// adjust for list not being at top of screen
mPosition = list.pointToPosition(mStartX, mStartY - list.getTop());
}
}
Log.d(cTag, "isValidSwipe hValid=" + horizontalValid +
" vValid=" + verticalValid + " position=" + mPosition);
return horizontalValid && verticalValid;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/view/SwipeListItemWrapper.java | Java | asf20 | 3,874 |
/*
* 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.view;
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.persistence.EntityCache;
import com.google.inject.Inject;
import android.widget.RelativeLayout;
public class ExpandableTaskView extends TaskView {
@Inject
public ExpandableTaskView(
android.content.Context androidContext,
EntityCache<Context> contextCache,
EntityCache<Project> projectCache) {
super(androidContext, contextCache, projectCache);
RelativeLayout layout = (RelativeLayout) findViewById(R.id.relLayout);
// 36 is the current value of ?android:attr/expandableListPreferredItemPaddingLeft
// TODO get that value programatically
layout.setPadding(36, 0, 7, 0);
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/view/ExpandableTaskView.java | Java | asf20 | 1,509 |
/*
* 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.activity;
import android.os.Bundle;
import org.dodgybits.shuffle.android.core.model.Entity;
import org.dodgybits.shuffle.android.core.model.Id;
import org.dodgybits.shuffle.android.core.model.persistence.selector.EntitySelector;
import org.dodgybits.shuffle.android.core.view.AlertUtils;
import org.dodgybits.shuffle.android.list.config.DrilldownListConfig;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.util.Log;
import android.util.SparseIntArray;
/**
* A list whose items represent groups that lead to other list.
* A poor man's ExpandableListActivity. :-)
*/
public abstract class AbstractDrilldownListActivity<G extends Entity, E extends EntitySelector<E>> extends AbstractListActivity<G, E> {
private static final String cTag = "AbstractDrilldownListActivity";
protected SparseIntArray mTaskCountArray;
protected int getChildCount(Id groupId) {
return mTaskCountArray.get((int)groupId.getId());
}
protected final DrilldownListConfig<G, E> getDrilldownListConfig()
{
return (DrilldownListConfig<G, E>)getListConfig();
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mButtonBar.getAddItemButton().setText(getDrilldownListConfig().getItemName(this));
}
@Override
protected void onResume() {
super.onResume();
refreshChildCount();
}
/**
* Mark selected item for delete.
* Provide warning for items that have children.
*/
@Override
protected void toggleDeleted(final G entity) {
final Id groupId = entity.getLocalId();
int childCount = getChildCount(groupId);
if (childCount > 0 && !entity.isDeleted()) {
OnClickListener buttonListener = new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON1) {
Log.i(cTag, "Deleting group id " + groupId);
AbstractDrilldownListActivity.super.toggleDeleted(entity);
} else {
Log.d(cTag, "Hit Cancel button. Do nothing.");
}
}
};
AlertUtils.showDeleteGroupWarning(this, getDrilldownListConfig().getItemName(this),
getDrilldownListConfig().getChildName(this), childCount, buttonListener);
} else {
super.toggleDeleted(entity);
}
}
abstract void refreshChildCount();
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/activity/AbstractDrilldownListActivity.java | Java | asf20 | 3,058 |
package org.dodgybits.shuffle.android.list.activity;
import android.content.Intent;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.util.Constants;
import org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings;
import roboguice.util.Ln;
public class ListPreferenceActivity extends PreferenceActivity implements Preference.OnPreferenceChangeListener {
private ListPreferenceSettings mSettings;
private boolean mPrefsChanged;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSettings = ListPreferenceSettings.fromIntent(getIntent());
setupScreen();
}
@Override
public void onResume() {
super.onResume();
mPrefsChanged = false;
}
@Override
public void onPause() {
super.onPause();
if (mPrefsChanged) {
sendBroadcast(new Intent(ListPreferenceSettings.LIST_PREFERENCES_UPDATED));
}
}
private void setupScreen() {
PreferenceScreen screen = getPreferenceManager().createPreferenceScreen(this);
int screenId = getStringId("title_" + mSettings.getPrefix());
String title = getString(screenId) + " " + getString(R.string.list_settings_title);
screen.setTitle(title);
screen.addPreference(createList(
R.array.list_preferences_active_labels,
R.string.active_items_title,
mSettings.getActive(this).name(),
ListPreferenceSettings.LIST_FILTER_ACTIVE,
mSettings.getDefaultActive().name(),
mSettings.isActiveEnabled()
));
screen.addPreference(createList(
R.array.list_preferences_pending_labels,
R.string.pending_items_title,
mSettings.getPending(this).name(),
ListPreferenceSettings.LIST_FILTER_PENDING,
mSettings.getDefaultPending().name(),
mSettings.isPendingEnabled()
));
screen.addPreference(createList(
R.array.list_preferences_completed_labels,
R.string.completed_items_title,
mSettings.getCompleted(this).name(),
ListPreferenceSettings.LIST_FILTER_COMPLETED,
mSettings.getDefaultCompleted().name(),
mSettings.isCompletedEnabled()
));
screen.addPreference(createList(
R.array.list_preferences_deleted_labels,
R.string.deleted_items_title,
mSettings.getDeleted(this).name(),
ListPreferenceSettings.LIST_FILTER_DELETED,
mSettings.getDefaultDeleted().name(),
mSettings.isDeletedEnabled()
));
setPreferenceScreen(screen);
}
private int getStringId(String id) {
return getResources().getIdentifier(id, Constants.cStringType, Constants.cPackage);
}
private ListPreference createList(int entries, int title, String value, String keySuffix, Object defaultValue, boolean enabled) {
ListPreference listPreference = new ListPreference(this);
listPreference.setEntryValues(R.array.list_preferences_flag_values);
listPreference.setEntries(entries);
listPreference.setTitle(title);
String key = mSettings.getPrefix() + keySuffix;
listPreference.setKey(key);
listPreference.setDefaultValue(defaultValue);
listPreference.setOnPreferenceChangeListener(this);
listPreference.setEnabled(enabled);
CharSequence[] entryStrings = listPreference.getEntries();
int index = listPreference.findIndexOfValue(value);
if (index > -1) {
listPreference.setSummary(entryStrings[index]);
}
Ln.d("Creating list preference key=%s value=%s default=%s title=%s", key, value, defaultValue, title);
return listPreference;
}
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
ListPreference listPreference = (ListPreference)preference;
int index = listPreference.findIndexOfValue((String)o);
preference.setSummary(listPreference.getEntries()[index]);
mPrefsChanged = true;
return true;
}
} | 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/activity/ListPreferenceActivity.java | Java | asf20 | 4,506 |
/*
* 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.activity;
public class State {
// The different distinct states the activity can be run in.
public static final int STATE_EDIT = 0;
public static final int STATE_INSERT = 1;
private State() {
//deny instantiation
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/activity/State.java | Java | asf20 | 923 |
/*
* 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.activity;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.model.Context;
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.list.activity.task.ContextTasksActivity;
import org.dodgybits.shuffle.android.list.config.ContextListConfig;
import org.dodgybits.shuffle.android.list.config.ListConfig;
import org.dodgybits.shuffle.android.list.view.ContextView;
import org.dodgybits.shuffle.android.persistence.provider.ContextProvider;
import roboguice.inject.ContextSingleton;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;
import com.google.inject.Inject;
@ContextSingleton
/**
* Display list of contexts with task children.
*/
public class ContextsActivity extends AbstractDrilldownListActivity<Context, ContextSelector> {
@Inject ContextListConfig mListConfig;
@Override
protected void refreshChildCount() {
TaskSelector selector = TaskSelector.newBuilder()
.applyListPreferences(this, getListConfig().getListPreferenceSettings())
.build();
Cursor cursor = getContentResolver().query(
ContextProvider.Contexts.CONTEXT_TASKS_CONTENT_URI,
ContextProvider.Contexts.FULL_TASK_PROJECTION,
selector.getSelection(this),
selector.getSelectionArgs(),
selector.getSortOrder());
mTaskCountArray = getDrilldownListConfig().getChildPersister().readCountArray(cursor);
cursor.close();
}
@Override
protected ListConfig<Context, ContextSelector> createListConfig() {
return mListConfig;
}
@Override
protected ListAdapter createListAdapter(Cursor cursor) {
ListAdapter adapter =
new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, cursor,
new String[] { ContextProvider.Contexts.NAME },
new int[] { android.R.id.text1 }) {
public View getView(int position, View convertView, ViewGroup parent) {
Cursor cursor = (Cursor)getItem(position);
Context context = getListConfig().getPersister().read(cursor);
ContextView contextView;
if (convertView instanceof ContextView) {
contextView = (ContextView) convertView;
} else {
contextView = new ContextView(parent.getContext()) {
protected int getViewResourceId() {
return R.layout.list_context_view;
}
};
}
contextView.setTaskCountArray(mTaskCountArray);
contextView.updateView(context);
return contextView;
}
};
return adapter;
}
/**
* Return the intent generated when a list item is clicked.
*
* @param uri type of data selected
*/
@Override
protected Intent getClickIntent(Uri uri) {
// if a context is clicked on, show tasks for that context.
Intent intent = new Intent(this, ContextTasksActivity.class);
intent.setData(uri);
return intent;
}
} | 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/activity/ContextsActivity.java | Java | asf20 | 3,870 |
/*
* 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.activity;
import org.dodgybits.shuffle.android.core.model.Project;
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.list.activity.task.ProjectTasksActivity;
import org.dodgybits.shuffle.android.list.config.ListConfig;
import org.dodgybits.shuffle.android.list.config.ProjectListConfig;
import org.dodgybits.shuffle.android.list.view.ProjectView;
import org.dodgybits.shuffle.android.persistence.provider.ProjectProvider;
import roboguice.inject.ContextSingleton;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;
import com.google.inject.Inject;
@ContextSingleton
/**
* Display list of projects with task children.
*/
public class ProjectsActivity extends AbstractDrilldownListActivity<Project, ProjectSelector> {
@Inject ProjectListConfig mListConfig;
@Override
protected void refreshChildCount() {
TaskSelector selector = TaskSelector.newBuilder()
.applyListPreferences(this, getListConfig().getListPreferenceSettings())
.build();
Cursor cursor = getContentResolver().query(
ProjectProvider.Projects.PROJECT_TASKS_CONTENT_URI,
ProjectProvider.Projects.FULL_TASK_PROJECTION,
selector.getSelection(this),
selector.getSelectionArgs(),
selector.getSortOrder());
mTaskCountArray = getDrilldownListConfig().getChildPersister().readCountArray(cursor);
cursor.close();
}
@Override
protected ListConfig<Project,ProjectSelector> createListConfig() {
return mListConfig;
}
@Override
protected ListAdapter createListAdapter(Cursor cursor) {
ListAdapter adapter =
new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, cursor,
new String[] { ProjectProvider.Projects.NAME },
new int[] { android.R.id.text1 }) {
public View getView(int position, View convertView, ViewGroup parent) {
Cursor cursor = (Cursor)getItem(position);
Project project = getListConfig().getPersister().read(cursor);
ProjectView projectView;
if (convertView instanceof ProjectView) {
projectView = (ProjectView) convertView;
} else {
projectView = new ProjectView(parent.getContext());
}
projectView.setTaskCountArray(mTaskCountArray);
projectView.updateView(project);
return projectView;
}
};
return adapter;
}
/**
* Return the intent generated when a list item is clicked.
*
* @param uri type of data selected
*/
@Override
protected Intent getClickIntent(Uri uri) {
// if a project is clicked on, show tasks for that project.
Intent intent = new Intent(this, ProjectTasksActivity.class);
intent.setData(uri);
return intent;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/activity/ProjectsActivity.java | Java | asf20 | 3,717 |
/*
* 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.activity.expandable;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledExpandableListActivity;
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.EntityCache;
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.view.AlertUtils;
import org.dodgybits.shuffle.android.core.view.MenuUtils;
import org.dodgybits.shuffle.android.list.activity.ListPreferenceActivity;
import org.dodgybits.shuffle.android.list.config.ExpandableListConfig;
import org.dodgybits.shuffle.android.list.view.ButtonBar;
import org.dodgybits.shuffle.android.list.view.SwipeListItemListener;
import org.dodgybits.shuffle.android.list.view.SwipeListItemWrapper;
import org.dodgybits.shuffle.android.preference.model.Preferences;
import roboguice.event.Observes;
import roboguice.inject.InjectView;
import roboguice.util.Ln;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.SimpleCursorTreeAdapter;
import android.widget.Toast;
import com.google.inject.Inject;
public abstract class AbstractExpandableActivity<G extends Entity, E extends EntitySelector<E>> extends FlurryEnabledExpandableListActivity
implements SwipeListItemListener {
protected static final int FILTER_CONFIG = 600;
protected ExpandableListAdapter mAdapter;
@Inject protected EntityCache<org.dodgybits.shuffle.android.core.model.Context> mContextCache;
@Inject protected EntityCache<Project> mProjectCache;
@InjectView(R.id.button_bar)
protected ButtonBar mButtonBar;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(getListConfig().getContentViewResId());
setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);
// Inform the list we provide context menus for items
getExpandableListView().setOnCreateContextMenuListener(this);
Cursor groupCursor = createGroupQuery();
// Set up our adapter
mAdapter = createExpandableListAdapter(groupCursor);
setListAdapter(mAdapter);
// register self as swipe listener
SwipeListItemWrapper wrapper = (SwipeListItemWrapper) findViewById(R.id.swipe_wrapper);
wrapper.setSwipeListItemListener(this);
mButtonBar.getOtherButton().setText(getListConfig().getGroupName(this));
Drawable addIcon = getResources().getDrawable(android.R.drawable.ic_menu_add);
addIcon.setBounds(0, 0, 24, 24);
mButtonBar.getOtherButton().setCompoundDrawables(addIcon, null, null, null);
mButtonBar.getOtherButton().setVisibility(View.VISIBLE);
}
@Override
protected void onResume() {
super.onResume();
refreshChildCount();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_N:
// go to previous view
int prevView = getListConfig().getCurrentViewMenuId() - 1;
if (prevView < MenuUtils.INBOX_ID) {
prevView = MenuUtils.CONTEXT_ID;
}
MenuUtils.checkCommonItemsSelected(prevView, this, getListConfig().getCurrentViewMenuId());
return true;
case KeyEvent.KEYCODE_M:
// go to previous view
int nextView = getListConfig().getCurrentViewMenuId() + 1;
if (nextView > MenuUtils.CONTEXT_ID) {
nextView = MenuUtils.INBOX_ID;
}
MenuUtils.checkCommonItemsSelected(nextView, this, getListConfig().getCurrentViewMenuId());
return true;
}
return super.onKeyDown(keyCode, event);
}
@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.addExpandableInsertMenuItems(menu, getListConfig().getGroupName(this),
getListConfig().getChildName(this), this);
MenuUtils.addViewMenuItems(menu, getListConfig().getCurrentViewMenuId());
MenuUtils.addPrefsHelpMenuItems(this, menu);
MenuUtils.addSearchMenuItem(this, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
final EntityPersister<G> groupPersister = getListConfig().getGroupPersister();
final TaskPersister childPersister = getListConfig().getChildPersister();
switch (item.getItemId()) {
case MenuUtils.INSERT_CHILD_ID:
long packedPosition = getSelectedPosition();
int groupPosition = ExpandableListView.getPackedPositionGroup(packedPosition);
if (groupPosition > -1)
{
Cursor cursor = (Cursor) getExpandableListAdapter().getGroup(groupPosition);
G group = groupPersister.read(cursor);
insertItem(childPersister.getContentUri(), group);
}
else
{
insertItem(childPersister.getContentUri());
}
return true;
case MenuUtils.INSERT_GROUP_ID:
insertItem(groupPersister.getContentUri());
return true;
}
if (MenuUtils.checkCommonItemsSelected(item, this, getListConfig().getCurrentViewMenuId())) return true;
return super.onOptionsItemSelected(item);
}
@Override
public final void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
ExpandableListView.ExpandableListContextMenuInfo info;
try {
info = (ExpandableListView.ExpandableListContextMenuInfo) menuInfo;
} catch (ClassCastException e) {
Ln.e(e, "bad menuInfo");
return;
}
long packedPosition = info.packedPosition;
int groupPosition = ExpandableListView.getPackedPositionGroup(packedPosition);
int childPosition = ExpandableListView.getPackedPositionChild(packedPosition);
boolean isChild = isChild(packedPosition);
Cursor cursor;
if (isChild) {
cursor = (Cursor)(getExpandableListAdapter().getChild(groupPosition, childPosition));
} else {
cursor = (Cursor)(getExpandableListAdapter().getGroup(groupPosition));
}
if (cursor == null) {
// For some reason the requested item isn't available, do nothing
return;
}
// Setup the menu header
menu.setHeaderTitle(cursor.getString(1));
if (isChild)
{
long childId = getExpandableListAdapter().getChildId(groupPosition, childPosition);
Uri selectedUri = ContentUris.withAppendedId(getListConfig().getChildPersister().getContentUri(), childId);
MenuUtils.addSelectedAlternativeMenuItems(menu, selectedUri, false);
Cursor c = (Cursor)getExpandableListAdapter().getChild(groupPosition, childPosition);
Task task = getListConfig().getChildPersister().read(c);
MenuUtils.addCompleteMenuItem(menu, task.isComplete());
MenuUtils.addDeleteMenuItem(menu, task.isDeleted());
onCreateChildContextMenu(menu, groupPosition, childPosition, task);
}
else
{
long groupId = getExpandableListAdapter().getGroupId(groupPosition);
Uri selectedUri = ContentUris.withAppendedId(getListConfig().getGroupPersister().getContentUri(), groupId);
MenuUtils.addSelectedAlternativeMenuItems(menu, selectedUri, false);
Cursor c = (Cursor)getExpandableListAdapter().getGroup(groupPosition);
G group = getListConfig().getGroupPersister().read(c);
MenuUtils.addInsertMenuItems(menu, getListConfig().getChildName(this), true, this);
MenuUtils.addDeleteMenuItem(menu, group.isDeleted());
onCreateGroupContextMenu(menu, groupPosition, group);
}
}
protected void onCreateChildContextMenu(ContextMenu menu, int groupPosition, int childPosition, Task task) {
}
protected void onCreateGroupContextMenu(ContextMenu menu, int groupPosition, G group) {
}
@Override
public boolean onContextItemSelected(MenuItem item) {
ExpandableListView.ExpandableListContextMenuInfo info;
try {
info = (ExpandableListView.ExpandableListContextMenuInfo) item.getMenuInfo();
} catch (ClassCastException e) {
Ln.e(e, "bad menuInfo");
return false;
}
switch (item.getItemId()) {
case MenuUtils.COMPLETE_ID:
toggleComplete(info.packedPosition, info.id);
return true;
case MenuUtils.DELETE_ID:
// Delete the item that the context menu is for
deleteItem(info.packedPosition);
return true;
case MenuUtils.INSERT_ID:
int groupPosition = ExpandableListView.getPackedPositionGroup(info.packedPosition);
final Uri childContentUri = getListConfig().getChildPersister().getContentUri();
if (groupPosition > -1)
{
Cursor cursor = (Cursor) getExpandableListAdapter().getGroup(groupPosition);
G group = getListConfig().getGroupPersister().read(cursor);
insertItem(childContentUri, group);
}
else
{
insertItem(childContentUri);
}
return true;
}
return false;
}
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
Uri url = ContentUris.withAppendedId(getListConfig().getChildPersister().getContentUri(), id);
// Launch activity to view/edit the currently selected item
startActivity(getClickIntent(url));
return true;
}
public class MyExpandableListAdapter extends SimpleCursorTreeAdapter {
public MyExpandableListAdapter(Context context, Cursor cursor, int groupLayout,
int childLayout, String[] groupFrom, int[] groupTo, String[] childrenFrom,
int[] childrenTo) {
super(context, cursor, groupLayout, groupFrom, groupTo, childLayout, childrenFrom,
childrenTo);
}
@Override
protected Cursor getChildrenCursor(Cursor groupCursor) {
long groupId = groupCursor.getLong(getGroupIdColumnIndex());
Ln.d("getChildrenCursor for groupId %s", groupId);
return createChildQuery(groupId);
}
}
public void onListItemSwiped(int position) {
long packedPosition = getExpandableListView().getExpandableListPosition(position);
if (isChild(packedPosition)) {
int groupPosition = ExpandableListView.getPackedPositionGroup(packedPosition);
int childPosition = ExpandableListView.getPackedPositionChild(packedPosition);
long id = getExpandableListAdapter().getChildId(groupPosition, childPosition);
toggleComplete(packedPosition, id);
}
}
protected final void toggleComplete(long packedPosition, long id) {
int groupPosition = ExpandableListView.getPackedPositionGroup(packedPosition);
int childPosition = ExpandableListView.getPackedPositionChild(packedPosition);
Cursor c = (Cursor) getExpandableListAdapter().getChild(groupPosition, childPosition);
Task task = getListConfig().getChildPersister().read(c);
getListConfig().getChildPersister().updateCompleteFlag(task.getLocalId(), !task.isComplete());
}
protected Boolean isChildSelected() {
long packed = this.getSelectedPosition();
return isChild(packed);
}
protected Boolean isChild(long packedPosition) {
int type = ExpandableListView.getPackedPositionType(packedPosition);
Boolean isChild = null;
switch (type) {
case ExpandableListView.PACKED_POSITION_TYPE_CHILD:
isChild = Boolean.TRUE;
break;
case ExpandableListView.PACKED_POSITION_TYPE_GROUP:
isChild = Boolean.FALSE;
}
return isChild;
}
protected Uri getSelectedContentUri() {
Uri selectedUri = null;
Boolean childSelected = isChildSelected();
if (childSelected != null) {
selectedUri = childSelected ? getListConfig().getChildPersister().getContentUri() : getListConfig().getGroupPersister().getContentUri();
}
return selectedUri;
}
protected void onAddItem( @Observes ButtonBar.AddItemButtonClickEvent event ) {
insertItem(getListConfig().getChildPersister().getContentUri());
}
protected void onOther( @Observes ButtonBar.OtherButtonClickEvent event ) {
insertItem(getListConfig().getGroupPersister().getContentUri());
}
protected void onFilter( @Observes ButtonBar.FilterButtonClickEvent event ) {
Intent intent = new Intent(this, ListPreferenceActivity.class);
getListConfig().getListPreferenceSettings().addToIntent(intent);
startActivityForResult(intent, FILTER_CONFIG);
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
Ln.d("Got resultCode %s with data %s", resultCode, data);
switch (requestCode) {
case FILTER_CONFIG:
Ln.d("Got result ", resultCode);
updateCursor();
break;
default:
Ln.e("Unknown requestCode: ", requestCode);
}
}
protected void updateCursor() {
SimpleCursorTreeAdapter adapter = (SimpleCursorTreeAdapter)getExpandableListAdapter();
Cursor oldCursor = adapter.getCursor();
if (oldCursor != null) {
// changeCursor always closes the cursor,
// so need to stop managing the old one first
stopManagingCursor(oldCursor);
oldCursor.close();
}
Cursor cursor = createGroupQuery();
adapter.changeCursor(cursor);
}
/**
* Return the intent generated when a list item is clicked.
*
* @param uri type of data selected
*/
protected Intent getClickIntent(Uri uri) {
return new Intent(Intent.ACTION_VIEW, uri);
}
/**
* Permanently delete the selected item.
*/
protected final void deleteItem() {
deleteItem(getSelectedPosition());
}
protected final void deleteItem(final long packedPosition) {
final int type = ExpandableListView.getPackedPositionType(packedPosition);
final int childPosition = ExpandableListView.getPackedPositionChild(packedPosition);
final int groupPosition = ExpandableListView.getPackedPositionGroup(packedPosition);
final EntityPersister<G> groupPersister = getListConfig().getGroupPersister();
final TaskPersister childPersister = getListConfig().getChildPersister();
switch (type) {
case ExpandableListView.PACKED_POSITION_TYPE_CHILD:
Ln.d("Toggling delete flag for child at position %s, %s", groupPosition, childPosition);
Cursor childCursor = (Cursor) getExpandableListAdapter().getChild(groupPosition, childPosition);
Task task = childPersister.read(childCursor);
Ln.i("Setting delete flag to %s for child id %s", !task.isDeleted(), task.getLocalId());
childPersister.updateDeletedFlag(task.getLocalId(), !task.isDeleted());
if (!task.isDeleted()) {
showItemsDeletedToast(false);
}
refreshChildCount();
getExpandableListView().invalidate();
break;
case ExpandableListView.PACKED_POSITION_TYPE_GROUP:
Ln.d("Toggling delete on parent at position ", groupPosition);
// first check if there's any children...
Cursor groupCursor = (Cursor)getExpandableListAdapter().getGroup(groupPosition);
final G group = groupPersister.read(groupCursor);
int childCount = getExpandableListAdapter().getChildrenCount(groupPosition);
if (group.isDeleted() || childCount == 0) {
Ln.i("Setting group %s delete flag to %s at position %s",
group.getLocalId(), !group.isDeleted(), groupPosition);
groupPersister.updateDeletedFlag(group.getLocalId(), !group.isDeleted());
if (!group.isDeleted()) showItemsDeletedToast(true);
} else {
OnClickListener buttonListener = new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON1) {
Ln.i("Deleting group id ", group.getLocalId());
groupPersister.updateDeletedFlag(group.getLocalId(), true);
showItemsDeletedToast(true);
} else {
Ln.d("Hit Cancel button. Do nothing.");
}
}
};
AlertUtils.showDeleteGroupWarning(this, getListConfig().getGroupName(this),
getListConfig().getChildName(this), childCount, buttonListener);
}
break;
}
}
private final void showItemsDeletedToast(boolean isGroup) {
String name = isGroup ? getListConfig().getGroupName(this)
: getListConfig().getChildName(this);
String text = getResources().getString(
R.string.itemDeletedToast, name );
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
private final void insertItem(Uri uri, G group) {
Intent intent = new Intent(Intent.ACTION_INSERT, uri);
Bundle extras = intent.getExtras();
if (extras == null) extras = new Bundle();
updateInsertExtras(extras, group);
intent.putExtras(extras);
startActivity(intent);
}
private final void insertItem(Uri uri) {
// Launch activity to insert a new item
Intent intent = new Intent(Intent.ACTION_INSERT, uri);
startActivity(intent);
}
abstract protected void updateInsertExtras(Bundle extras, G group);
abstract void refreshChildCount();
abstract ExpandableListAdapter createExpandableListAdapter(Cursor cursor);
/**
* @return a cursor selecting the child items to display for a selected top level group item.
*/
abstract Cursor createChildQuery(long groupId);
/**
* @return a cursor selecting the top levels items to display in the list.
*/
abstract Cursor createGroupQuery();
/**
* @return index of group id column in group cursor
*/
abstract int getGroupIdColumnIndex();
/**
* @return index of child id column in group cursor
*/
abstract int getChildIdColumnIndex();
// custom helper methods
abstract protected ExpandableListConfig<G,E> getListConfig();
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/activity/expandable/AbstractExpandableActivity.java | Java | asf20 | 20,620 |
/*
* 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.activity.expandable;
import java.util.Arrays;
import org.dodgybits.shuffle.android.core.model.Context;
import org.dodgybits.shuffle.android.core.model.Id;
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.TaskSelector;
import org.dodgybits.shuffle.android.list.config.ContextExpandableListConfig;
import org.dodgybits.shuffle.android.list.config.ExpandableListConfig;
import org.dodgybits.shuffle.android.list.view.ContextView;
import org.dodgybits.shuffle.android.list.view.ExpandableContextView;
import org.dodgybits.shuffle.android.list.view.ExpandableTaskView;
import org.dodgybits.shuffle.android.list.view.TaskView;
import org.dodgybits.shuffle.android.persistence.provider.ContextProvider;
import org.dodgybits.shuffle.android.persistence.provider.TaskProvider;
import android.database.Cursor;
import android.os.Bundle;
import android.util.SparseIntArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListAdapter;
import com.google.inject.Inject;
import com.google.inject.Provider;
public class ExpandableContextsActivity extends AbstractExpandableActivity<Context,ContextSelector> {
private int mChildIdColumnIndex;
private int mGroupIdColumnIndex;
private SparseIntArray mTaskCountArray;
@Inject ContextExpandableListConfig mListConfig;
@Inject Provider<ExpandableTaskView> mTaskViewProvider;
@Override
protected ExpandableListConfig<Context,ContextSelector> getListConfig() {
return mListConfig;
}
@Override
protected void refreshChildCount() {
TaskSelector selector = getListConfig().getChildSelector().builderFrom()
.applyListPreferences(this, getListConfig().getListPreferenceSettings())
.build();
Cursor cursor = getContentResolver().query(
ContextProvider.Contexts.CONTEXT_TASKS_CONTENT_URI,
ContextProvider.Contexts.FULL_TASK_PROJECTION,
selector.getSelection(this),
selector.getSelectionArgs(),
selector.getSortOrder());
mTaskCountArray = getListConfig().getChildPersister().readCountArray(cursor);
cursor.close();
}
@Override
protected Cursor createGroupQuery() {
ContextSelector selector = getListConfig().getGroupSelector().builderFrom().
applyListPreferences(this, getListConfig().getListPreferenceSettings()).build();
Cursor cursor = managedQuery(
selector.getContentUri(),
ContextProvider.Contexts.FULL_PROJECTION,
selector.getSelection(this),
selector.getSelectionArgs(),
selector.getSortOrder());
mGroupIdColumnIndex = cursor.getColumnIndex(ContextProvider.Contexts._ID);
return cursor;
}
@Override
protected int getGroupIdColumnIndex() {
return mGroupIdColumnIndex;
}
@Override
protected int getChildIdColumnIndex() {
return mChildIdColumnIndex;
}
@Override
protected Cursor createChildQuery(long groupId) {
TaskSelector selector = getListConfig().getChildSelector().builderFrom()
.setContexts(Arrays.asList(new Id[]{Id.create(groupId)}))
.applyListPreferences(this, getListConfig().getListPreferenceSettings())
.build();
Cursor cursor = managedQuery(
selector.getContentUri(),
TaskProvider.Tasks.FULL_PROJECTION,
selector.getSelection(this),
selector.getSelectionArgs(),
selector.getSortOrder());
mChildIdColumnIndex = cursor.getColumnIndex(TaskProvider.Tasks._ID);
return cursor;
}
@Override
protected void updateInsertExtras(Bundle extras, Context context) {
extras.putLong(TaskProvider.Tasks.CONTEXT_ID, context.getLocalId().getId());
}
@Override
protected ExpandableListAdapter createExpandableListAdapter(Cursor cursor) {
return new MyExpandableListAdapter(this,
cursor,
android.R.layout.simple_expandable_list_item_1,
android.R.layout.simple_expandable_list_item_1,
new String[] {ContextProvider.Contexts.NAME},
new int[] {android.R.id.text1},
new String[] {TaskProvider.Tasks.DESCRIPTION},
new int[] {android.R.id.text1}) {
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
Cursor cursor = (Cursor) getChild(groupPosition, childPosition);
Task task = getListConfig().getChildPersister().read(cursor);
TaskView taskView;
if (convertView instanceof ExpandableTaskView) {
taskView = (ExpandableTaskView) convertView;
} else {
taskView = mTaskViewProvider.get();
}
taskView.setShowContext(false);
taskView.setShowProject(true);
taskView.updateView(task);
return taskView;
}
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
Cursor cursor = (Cursor) getGroup(groupPosition);
Context context = getListConfig().getGroupPersister().read(cursor);
ContextView contextView;
if (convertView instanceof ExpandableContextView) {
contextView = (ExpandableContextView) convertView;
} else {
contextView = new ExpandableContextView(parent.getContext());
}
contextView.setTaskCountArray(mTaskCountArray);
contextView.updateView(context);
return contextView;
}
};
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/activity/expandable/ExpandableContextsActivity.java | Java | asf20 | 6,349 |
/*
* 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.activity.expandable;
import java.util.Arrays;
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.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.config.ExpandableListConfig;
import org.dodgybits.shuffle.android.list.config.ProjectExpandableListConfig;
import org.dodgybits.shuffle.android.list.view.ExpandableProjectView;
import org.dodgybits.shuffle.android.list.view.ExpandableTaskView;
import org.dodgybits.shuffle.android.list.view.ProjectView;
import org.dodgybits.shuffle.android.list.view.TaskView;
import org.dodgybits.shuffle.android.persistence.provider.ProjectProvider;
import org.dodgybits.shuffle.android.persistence.provider.TaskProvider;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import com.google.inject.Inject;
import com.google.inject.Provider;
public class ExpandableProjectsActivity extends AbstractExpandableActivity<Project,ProjectSelector> {
private static final String cTag = "ExpandableProjectsActivity";
private int mChildIdColumnIndex;
private int mGroupIdColumnIndex;
private SparseIntArray mTaskCountArray;
@Inject ProjectExpandableListConfig mListConfig;
@Inject Provider<ExpandableTaskView> mTaskViewProvider;
@Override
protected ExpandableListConfig<Project,ProjectSelector> getListConfig() {
return mListConfig;
}
@Override
protected void refreshChildCount() {
TaskSelector selector = getListConfig().getChildSelector().builderFrom()
.applyListPreferences(this, getListConfig().getListPreferenceSettings())
.build();
Cursor cursor = getContentResolver().query(
ProjectProvider.Projects.PROJECT_TASKS_CONTENT_URI,
ProjectProvider.Projects.FULL_TASK_PROJECTION,
selector.getSelection(this),
selector.getSelectionArgs(),
selector.getSortOrder());
mTaskCountArray = getListConfig().getChildPersister().readCountArray(cursor);
cursor.close();
}
@Override
protected Cursor createGroupQuery() {
ProjectSelector selector = getListConfig().getGroupSelector().builderFrom().
applyListPreferences(this, getListConfig().getListPreferenceSettings()).build();
Cursor cursor = managedQuery(
selector.getContentUri(),
ProjectProvider.Projects.FULL_PROJECTION,
selector.getSelection(this),
selector.getSelectionArgs(),
selector.getSortOrder());
mGroupIdColumnIndex = cursor.getColumnIndex(ProjectProvider.Projects._ID);
return cursor;
}
@Override
protected int getGroupIdColumnIndex() {
return mGroupIdColumnIndex;
}
@Override
protected int getChildIdColumnIndex() {
return mChildIdColumnIndex;
}
@Override
protected Cursor createChildQuery(long groupId) {
TaskSelector selector = getListConfig().getChildSelector().builderFrom()
.setProjects(Arrays.asList(new Id[]{Id.create(groupId)}))
.applyListPreferences(this, getListConfig().getListPreferenceSettings())
.build();
Cursor cursor = managedQuery(
selector.getContentUri(),
TaskProvider.Tasks.FULL_PROJECTION,
selector.getSelection(this),
selector.getSelectionArgs(),
selector.getSortOrder());
mChildIdColumnIndex = cursor.getColumnIndex(TaskProvider.Tasks._ID);
return cursor;
}
@Override
protected void updateInsertExtras(Bundle extras, Project project) {
extras.putLong(TaskProvider.Tasks.PROJECT_ID, project.getLocalId().getId());
final Id defaultContextId = project.getDefaultContextId();
if (defaultContextId.isInitialised()) {
extras.putLong(TaskProvider.Tasks.CONTEXT_ID, defaultContextId.getId());
}
}
@Override
protected ExpandableListAdapter createExpandableListAdapter(Cursor cursor) {
return new MyExpandableListAdapter(this,
cursor,
android.R.layout.simple_expandable_list_item_1,
android.R.layout.simple_expandable_list_item_1,
new String[] {ProjectProvider.Projects.NAME},
new int[] {android.R.id.text1},
new String[] {TaskProvider.Tasks.DESCRIPTION},
new int[] {android.R.id.text1}) {
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
Cursor cursor = (Cursor) getChild(groupPosition, childPosition);
Task task = getListConfig().getChildPersister().read(cursor);
TaskView taskView;
if (convertView instanceof ExpandableTaskView) {
taskView = (ExpandableTaskView) convertView;
} else {
taskView = mTaskViewProvider.get();
}
taskView.setShowContext(true);
taskView.setShowProject(false);
taskView.updateView(task);
return taskView;
}
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
Cursor cursor = (Cursor) getGroup(groupPosition);
Project project = getListConfig().getGroupPersister().read(cursor);
ProjectView projectView;
if (convertView instanceof ExpandableProjectView) {
projectView = (ExpandableProjectView) convertView;
} else {
projectView = new ExpandableProjectView(parent.getContext());
}
projectView.setTaskCountArray(mTaskCountArray);
projectView.updateView(project);
return projectView;
}
};
}
@Override
protected void onCreateChildContextMenu(ContextMenu menu, int groupPosition, int childPosition, Task task) {
MenuUtils.addMoveMenuItems(menu,
moveUpPermitted(groupPosition, childPosition),
moveDownPermitted(groupPosition, childPosition));
}
@Override
public boolean onContextItemSelected(MenuItem item) {
ExpandableListView.ExpandableListContextMenuInfo info;
try {
info = (ExpandableListView.ExpandableListContextMenuInfo) item.getMenuInfo();
} catch (ClassCastException e) {
Log.e(cTag, "bad menuInfo", e);
return false;
}
switch (item.getItemId()) {
case MenuUtils.MOVE_UP_ID:
moveUp(info.packedPosition);
return true;
case MenuUtils.MOVE_DOWN_ID:
moveDown(info.packedPosition);
return true;
}
return super.onContextItemSelected(item);
}
private boolean moveUpPermitted(int groupPosition,int childPosition) {
return childPosition > 0;
}
private boolean moveDownPermitted(int groupPosition,int childPosition) {
int childCount = getExpandableListAdapter().getChildrenCount(groupPosition);
return childPosition < childCount - 1;
}
protected final void moveUp(long packedPosition) {
int groupPosition = ExpandableListView.getPackedPositionGroup(packedPosition);
int childPosition = ExpandableListView.getPackedPositionChild(packedPosition);
if (moveUpPermitted(groupPosition, childPosition)) {
Cursor cursor = (Cursor) getExpandableListAdapter().getChild(
groupPosition, childPosition);
getListConfig().getChildPersister().swapTaskPositions(cursor, childPosition - 1, childPosition);
}
}
protected final void moveDown(long packedPosition) {
int groupPosition = ExpandableListView.getPackedPositionGroup(packedPosition);
int childPosition = ExpandableListView.getPackedPositionChild(packedPosition);
if (moveDownPermitted(groupPosition, childPosition)) {
Cursor cursor = (Cursor) getExpandableListAdapter().getChild(
groupPosition, childPosition);
getListConfig().getChildPersister().swapTaskPositions(cursor, childPosition, childPosition + 1);
}
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/activity/expandable/ExpandableProjectsActivity.java | Java | asf20 | 9,094 |
/*
* 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.activity;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledListActivity;
import org.dodgybits.shuffle.android.core.model.Entity;
import org.dodgybits.shuffle.android.core.model.persistence.selector.EntitySelector;
import org.dodgybits.shuffle.android.core.view.MenuUtils;
import org.dodgybits.shuffle.android.list.config.ListConfig;
import org.dodgybits.shuffle.android.list.view.ButtonBar;
import org.dodgybits.shuffle.android.preference.model.Preferences;
import roboguice.event.Observes;
import roboguice.inject.InjectView;
import android.app.Activity;
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.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public abstract class AbstractListActivity<T extends Entity, E extends EntitySelector<E>> extends FlurryEnabledListActivity {
public static final String cSelectedItem = "SELECTED_ITEM";
private static final String cTag = "AbstractListActivity";
protected final int NEW_ITEM = 1;
protected static final int FILTER_CONFIG = 600;
// after a new item is added, select it
private Long mItemIdToSelect = null;
private ListConfig<T,E> mConfig;
@InjectView(R.id.button_bar)
protected ButtonBar mButtonBar;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mConfig = createListConfig();
setContentView(getListConfig().getContentViewResId());
setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);
// If no data was given in the intent (because we were started
// as a MAIN activity), then use our default content provider.
Intent intent = getIntent();
if (intent.getData() == null) {
intent.setData(getListConfig().getPersister().getContentUri());
}
// Inform the view we provide context menus for items
getListView().setOnCreateContextMenuListener(this);
Cursor cursor = getListConfig().createQuery(this);
setListAdapter(createListAdapter(cursor));
}
@Override
protected void onResume() {
super.onResume();
setTitle(getListConfig().createTitle(this));
// attempt to select newly created item (if any)
if (mItemIdToSelect != null) {
Log.d(cTag, "New item id = " + mItemIdToSelect);
// see if list contains the new item
int count = getItemCount();
CursorAdapter adapter = (CursorAdapter) getListAdapter();
for (int i = 0; i < count; i++) {
long currentItemId = adapter.getItemId(i);
Log.d(cTag, "Current id=" + currentItemId + " pos=" + i);
if (currentItemId == mItemIdToSelect) {
Log.d(cTag, "Found new item - selecting");
setSelection(i);
break;
}
}
mItemIdToSelect = null;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
Log.d(cTag, "Got resultCode " + resultCode + " with data " + data);
switch (requestCode) {
case NEW_ITEM:
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
String selectedItem = data.getStringExtra(cSelectedItem);
if (selectedItem != null) {
Uri uri = Uri.parse(selectedItem);
mItemIdToSelect = ContentUris.parseId(uri);
// need to do the actual checking and selecting
// in onResume, otherwise getItemId(i) is always 0
// and setSelection(i) does nothing
}
}
}
break;
case FILTER_CONFIG:
Log.d(cTag, "Got result " + resultCode);
updateCursor();
break;
default:
Log.e(cTag, "Unknown requestCode: " + requestCode);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_N:
// go to previous view
int prevView = getListConfig().getCurrentViewMenuId() - 1;
if (prevView < MenuUtils.INBOX_ID) {
prevView = MenuUtils.CONTEXT_ID;
}
MenuUtils.checkCommonItemsSelected(prevView, this,
getListConfig().getCurrentViewMenuId());
return true;
case KeyEvent.KEYCODE_M:
// go to previous view
int nextView = getListConfig().getCurrentViewMenuId() + 1;
if (nextView > MenuUtils.CONTEXT_ID) {
nextView = MenuUtils.INBOX_ID;
}
MenuUtils.checkCommonItemsSelected(nextView, this,
getListConfig().getCurrentViewMenuId());
return true;
}
return super.onKeyDown(keyCode, event);
}
@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.addInsertMenuItems(menu, getListConfig().getItemName(this), getListConfig().isTaskList(), this);
MenuUtils.addViewMenuItems(menu, getListConfig().getCurrentViewMenuId());
MenuUtils.addPrefsHelpMenuItems(this, menu);
MenuUtils.addSearchMenuItem(this, menu);
return true;
}
@Override
public final void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info;
try {
info = (AdapterView.AdapterContextMenuInfo) menuInfo;
} catch (ClassCastException e) {
Log.e(cTag, "bad menuInfo", e);
return;
}
Cursor cursor = (Cursor) getListAdapter().getItem(info.position);
if (cursor == null) {
// For some reason the requested item isn't available, do nothing
return;
}
T entity = getListConfig().getPersister().read(cursor);
// Setup the menu header
menu.setHeaderTitle(entity.getLocalName());
Uri selectedUri = ContentUris.withAppendedId(getListConfig().getPersister().getContentUri(), info.id);
MenuUtils.addSelectedAlternativeMenuItems(menu, selectedUri, false);
// ... and ends with the delete command.
MenuUtils.addDeleteMenuItem(menu, entity.isDeleted());
onCreateEntityContextMenu(menu, info.position, entity);
}
protected void onCreateEntityContextMenu(ContextMenu menu, int position, T entity) {
}
@Override
public final boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info;
try {
info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
} catch (ClassCastException e) {
Log.e(cTag, "bad menuInfo", e);
return false;
}
Cursor cursor = (Cursor) getListAdapter().getItem(info.position);
if (cursor == null) {
// For some reason the requested item isn't available, do nothing
return false;
}
T entity = getListConfig().getPersister().read(cursor);
switch (item.getItemId()) {
case MenuUtils.DELETE_ID: {
// Delete the item that the context menu is for
toggleDeleted(entity);
return true;
}
}
return onContextEntitySelected(item, info.position, entity);
}
protected boolean onContextEntitySelected(MenuItem item, int position, T entity) {
return false;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MenuUtils.INSERT_ID:
// Launch activity to insert a new item
startActivityForResult(getInsertIntent(), NEW_ITEM);
return true;
}
if (MenuUtils.checkCommonItemsSelected(item, this,
getListConfig().getCurrentViewMenuId())) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Uri url = ContentUris.withAppendedId(getListConfig().getPersister().getContentUri(), id);
String action = getIntent().getAction();
if (Intent.ACTION_PICK.equals(action)
|| Intent.ACTION_GET_CONTENT.equals(action)) {
// The caller is waiting for us to return a task selected by
// the user. They have clicked on one, so return it now.
Bundle bundle = new Bundle();
bundle.putString(cSelectedItem, url.toString());
Intent mIntent = new Intent();
mIntent.putExtras(bundle);
setResult(RESULT_OK, mIntent);
} else {
// Launch activity to view/edit the currently selected item
startActivity(getClickIntent(url));
}
}
abstract protected ListConfig<T, E> createListConfig();
abstract protected ListAdapter createListAdapter(Cursor cursor);
// custom helper methods
protected final ListConfig<T,E> getListConfig()
{
return mConfig;
}
protected void updateCursor() {
SimpleCursorAdapter adapter = (SimpleCursorAdapter)getListAdapter();
Cursor oldCursor = adapter.getCursor();
if (oldCursor != null) {
// changeCursor always closes the cursor,
// so need to stop managing the old one first
stopManagingCursor(oldCursor);
oldCursor.close();
}
Cursor cursor = getListConfig().createQuery(this);
adapter.changeCursor(cursor);
setTitle(getListConfig().createTitle(this));
}
/**
* Make the given item as deleted
*/
protected void toggleDeleted(T entity) {
getListConfig().getPersister().updateDeletedFlag(entity.getLocalId(), !entity.isDeleted()) ;
if (!entity.isDeleted()) {
String text = getResources().getString(
R.string.itemDeletedToast, getListConfig().getItemName(this));
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
}
/**
* @return Number of items in the list.
*/
protected final int getItemCount() {
return getListAdapter().getCount();
}
/**
* The intent to insert a new item in this list. Default to an insert action
* on the list type which is all you need most of the time.
*/
protected Intent getInsertIntent() {
return new Intent(Intent.ACTION_INSERT, getListConfig().getPersister().getContentUri());
}
/**
* Return the intent generated when a list item is clicked.
*
* @param uri
* type of data selected
*/
protected Intent getClickIntent(Uri uri) {
return new Intent(Intent.ACTION_EDIT, uri);
}
protected void onAddItem( @Observes ButtonBar.AddItemButtonClickEvent event ) {
startActivityForResult(getInsertIntent(), NEW_ITEM);
}
protected void onOther( @Observes ButtonBar.OtherButtonClickEvent event ) {
}
protected void onFilter( @Observes ButtonBar.FilterButtonClickEvent event ) {
Intent intent = new Intent(this, ListPreferenceActivity.class);
getListConfig().getListPreferenceSettings().addToIntent(intent);
startActivityForResult(intent, FILTER_CONFIG);
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/activity/AbstractListActivity.java | Java | asf20 | 11,959 |
/*
* 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.activity.task;
import org.dodgybits.shuffle.android.core.model.Task;
import org.dodgybits.shuffle.android.core.model.persistence.selector.TaskSelector;
import org.dodgybits.shuffle.android.list.annotation.TopTasks;
import org.dodgybits.shuffle.android.list.config.ListConfig;
import org.dodgybits.shuffle.android.list.config.TaskListConfig;
import android.os.Bundle;
import com.google.inject.Inject;
public class TopTasksActivity extends AbstractTaskListActivity {
@Inject @TopTasks
private TaskListConfig mTaskListConfig;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
}
protected ListConfig<Task, TaskSelector> createListConfig()
{
return mTaskListConfig;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/activity/task/TopTasksActivity.java | Java | asf20 | 1,402 |
/*
* 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.activity.task;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.model.Task;
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.Inbox;
import org.dodgybits.shuffle.android.list.config.ListConfig;
import org.dodgybits.shuffle.android.list.config.TaskListConfig;
import org.dodgybits.shuffle.android.list.view.ButtonBar;
import org.dodgybits.shuffle.android.preference.model.Preferences;
import roboguice.event.Observes;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.google.inject.Inject;
public class InboxActivity extends AbstractTaskListActivity {
@Inject @Inbox
private TaskListConfig mTaskListConfig;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mButtonBar.getOtherButton().setText(R.string.clean_inbox_button_title);
Drawable cleanIcon = getResources().getDrawable(R.drawable.edit_clear);
cleanIcon.setBounds(0, 0, 24, 24);
mButtonBar.getOtherButton().setCompoundDrawables(cleanIcon, null, null, null);
mButtonBar.getOtherButton().setVisibility(View.VISIBLE);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuUtils.addCleanInboxMenuItem(menu);
super.onCreateOptionsMenu(menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MenuUtils.CLEAN_INBOX_ID:
doCleanup();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected ListConfig<Task,TaskSelector> createListConfig()
{
return mTaskListConfig;
}
@Override
protected void onOther( @Observes ButtonBar.OtherButtonClickEvent event ) {
doCleanup();
}
private void doCleanup() {
Preferences.cleanUpInbox(this);
Toast.makeText(this, R.string.clean_inbox_message, Toast.LENGTH_SHORT).show();
// need to restart the activity since the query has changed
// mCursor.requery() not enough
startActivity(new Intent(this, InboxActivity.class));
finish();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/activity/task/InboxActivity.java | Java | asf20 | 3,038 |
/*
* 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.activity.task;
import org.dodgybits.shuffle.android.core.model.Context;
import org.dodgybits.shuffle.android.core.model.Id;
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.selector.TaskSelector;
import org.dodgybits.shuffle.android.list.annotation.ContextTasks;
import org.dodgybits.shuffle.android.list.config.ContextTasksListConfig;
import org.dodgybits.shuffle.android.list.config.ListConfig;
import org.dodgybits.shuffle.android.persistence.provider.ContextProvider;
import org.dodgybits.shuffle.android.persistence.provider.TaskProvider;
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 com.google.inject.Inject;
public class ContextTasksActivity extends AbstractTaskListActivity {
private static final String cTag = "ContextTasksActivity";
private Id mContextId;
private Context mContext;
@Inject private EntityPersister<Context> mContextPersister;
@Inject @ContextTasks
private ContextTasksListConfig mTaskListConfig;
@Override
public void onCreate(Bundle icicle) {
Uri contextUri = getIntent().getData();
mContextId = Id.create(ContentUris.parseId(contextUri));
super.onCreate(icicle);
}
@Override
protected ListConfig<Task,TaskSelector> createListConfig()
{
mTaskListConfig.setContextId(mContextId);
return mTaskListConfig;
}
@Override
protected void onResume() {
Log.d(cTag, "Fetching context " + mContextId);
Cursor cursor = getContentResolver().query(ContextProvider.Contexts.CONTENT_URI, ContextProvider.Contexts.FULL_PROJECTION,
ContextProvider.Contexts._ID + " = ? ", new String[] {String.valueOf(mContextId)}, null);
if (cursor.moveToNext()) {
mContext = mContextPersister.read(cursor);
mTaskListConfig.setContext(mContext);
}
cursor.close();
super.onResume();
}
/**
* Return the intent generated when a list item is clicked.
*
* @param uri type of data selected
*/
@Override
protected Intent getClickIntent(Uri uri) {
long taskId = ContentUris.parseId(uri);
Uri taskURI = ContentUris.withAppendedId(TaskProvider.Tasks.CONTENT_URI, taskId);
return new Intent(Intent.ACTION_VIEW, taskURI);
}
/**
* Add context name to intent extras so it can be pre-filled for the task.
*/
@Override
protected Intent getInsertIntent() {
Intent intent = super.getInsertIntent();
Bundle extras = intent.getExtras();
if (extras == null) extras = new Bundle();
extras.putLong(TaskProvider.Tasks.CONTEXT_ID, mContext.getLocalId().getId());
intent.putExtras(extras);
return intent;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/activity/task/ContextTasksActivity.java | Java | asf20 | 3,546 |
/*
* 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.activity.task;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.model.Task;
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.annotation.DueTasks;
import org.dodgybits.shuffle.android.list.config.DueActionsListConfig;
import org.dodgybits.shuffle.android.list.config.ListConfig;
import roboguice.inject.InjectView;
import android.os.Bundle;
import android.util.Log;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import com.google.inject.Inject;
public class TabbedDueActionsActivity extends AbstractTaskListActivity {
private static final String cTag = "TabbedDueActionsActivity";
@InjectView(android.R.id.tabhost) TabHost mTabHost;
@Inject @DueTasks
private DueActionsListConfig mListConfig;
public static final String DUE_MODE = "mode";
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mTabHost.setup();
mTabHost.addTab(createTabSpec(
R.string.day_button_title,
PredefinedQuery.dueToday.name(),
android.R.drawable.ic_menu_day));
mTabHost.addTab(createTabSpec(
R.string.week_button_title,
PredefinedQuery.dueNextWeek.name(),
android.R.drawable.ic_menu_week));
mTabHost.addTab(createTabSpec(
R.string.month_button_title,
PredefinedQuery.dueNextMonth.name(),
android.R.drawable.ic_menu_month));
mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
public void onTabChanged(String tabId) {
Log.d(cTag, "Switched to tab: " + tabId);
if (tabId == null) tabId = PredefinedQuery.dueToday.name();
mListConfig.setMode(PredefinedQuery.valueOf(tabId));
updateCursor();
}
});
mListConfig.setMode(PredefinedQuery.dueToday);
Bundle extras = getIntent().getExtras();
if (extras != null && extras.containsKey(DUE_MODE)) {
mListConfig.setMode(PredefinedQuery.valueOf(extras.getString(DUE_MODE)));
}
}
@Override
protected void onResume() {
Log.d(cTag, "onResume+");
super.onResume();
// ugh!! If I take the following out, the tab contents does not display
int nextTab = mListConfig.getMode().ordinal() % 3;
int currentTab = mListConfig.getMode().ordinal() - 1;
mTabHost.setCurrentTab(nextTab);
mTabHost.setCurrentTab(currentTab);
}
@Override
protected ListConfig<Task,TaskSelector> createListConfig()
{
return mListConfig;
}
private TabSpec createTabSpec(int tabTitleRes, String tagId, int iconId) {
TabSpec tabSpec = mTabHost.newTabSpec(tagId);
tabSpec.setContent(R.id.task_list);
String tabName = getString(tabTitleRes);
tabSpec.setIndicator(tabName); //, this.getResources().getDrawable(iconId));
return tabSpec;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/activity/task/TabbedDueActionsActivity.java | Java | asf20 | 3,779 |
/*
* 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.activity.task;
import org.dodgybits.shuffle.android.core.model.Task;
import org.dodgybits.shuffle.android.core.model.persistence.selector.TaskSelector;
import org.dodgybits.shuffle.android.list.annotation.Tickler;
import org.dodgybits.shuffle.android.list.config.ListConfig;
import org.dodgybits.shuffle.android.list.config.TaskListConfig;
import android.os.Bundle;
import android.view.Menu;
import com.google.inject.Inject;
public class TicklerActivity extends AbstractTaskListActivity {
@Inject @Tickler
private TaskListConfig mTaskListConfig;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
return true;
}
@Override
protected ListConfig<Task,TaskSelector> createListConfig()
{
return mTaskListConfig;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/activity/task/TicklerActivity.java | Java | asf20 | 1,580 |
/*
* 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.activity.task;
import org.dodgybits.android.shuffle.R;
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;
import org.dodgybits.shuffle.android.core.view.MenuUtils;
import org.dodgybits.shuffle.android.list.activity.AbstractListActivity;
import org.dodgybits.shuffle.android.list.config.TaskListConfig;
import org.dodgybits.shuffle.android.list.view.ButtonBar;
import org.dodgybits.shuffle.android.list.view.SwipeListItemListener;
import org.dodgybits.shuffle.android.list.view.SwipeListItemWrapper;
import org.dodgybits.shuffle.android.list.view.TaskView;
import org.dodgybits.shuffle.android.persistence.provider.TaskProvider;
import roboguice.event.Observes;
import roboguice.inject.ContextScopedProvider;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import com.google.inject.Inject;
public abstract class AbstractTaskListActivity extends AbstractListActivity<Task,TaskSelector>
implements SwipeListItemListener {
private static final String cTag = "AbstractTaskListActivity";
@Inject ContextScopedProvider<TaskView> mTaskViewProvider;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// register self as swipe listener
SwipeListItemWrapper wrapper = (SwipeListItemWrapper) findViewById(R.id.swipe_wrapper);
wrapper.setSwipeListItemListener(this);
}
@Override
protected void onCreateEntityContextMenu(ContextMenu menu, int position, Task task) {
// ... add complete command.
MenuUtils.addCompleteMenuItem(menu, task.isComplete());
}
@Override
protected boolean onContextEntitySelected(MenuItem item, int position, Task task) {
switch (item.getItemId()) {
case MenuUtils.COMPLETE_ID:
toggleComplete(task);
return true;
}
return super.onContextEntitySelected(item, position, task);
}
protected TaskPersister getTaskPersister() {
return getTaskListConfig().getTaskPersister();
}
@Override
protected Intent getClickIntent(Uri uri) {
return new Intent(Intent.ACTION_VIEW, uri);
}
@Override
protected ListAdapter createListAdapter(Cursor cursor) {
ListAdapter adapter = new SimpleCursorAdapter(this,
R.layout.list_task_view, cursor,
new String[] { TaskProvider.Tasks.DESCRIPTION },
new int[] { R.id.description }) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.d(cTag, "getView position=" + position + ". Old view=" + convertView);
Cursor cursor = (Cursor)getItem(position);
Task task = getListConfig().getPersister().read(cursor);
TaskView taskView;
if (convertView instanceof TaskView) {
taskView = (TaskView) convertView;
} else {
taskView = mTaskViewProvider.get(AbstractTaskListActivity.this);
}
taskView.setShowContext(getTaskListConfig().showTaskContext());
taskView.setShowProject(getTaskListConfig().showTaskProject());
taskView.updateView(task);
return taskView;
}
};
return adapter;
}
public void onListItemSwiped(int position) {
toggleComplete(position);
}
protected final void toggleComplete() {
toggleComplete(getSelectedItemPosition());
}
protected final void toggleComplete(int position) {
if (position >= 0 && position < getItemCount())
{
Cursor c = (Cursor) getListAdapter().getItem(position);
Task task = getTaskPersister().read(c);
toggleComplete(task);
}
}
protected final void toggleComplete(Task task) {
if (task != null)
{
getTaskPersister().updateCompleteFlag(task.getLocalId(), !task.isComplete());
}
}
protected TaskListConfig getTaskListConfig() {
return (TaskListConfig)getListConfig();
}
@Override
protected void onOther( @Observes ButtonBar.OtherButtonClickEvent event ) {
int deletedTasks = getTaskPersister().deleteCompletedTasks();
CharSequence message = getString(R.string.clean_task_message, new Object[] {deletedTasks});
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/activity/task/AbstractTaskListActivity.java | Java | asf20 | 5,252 |
/*
* 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.activity.task;
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.core.model.persistence.EntityPersister;
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.ProjectTasks;
import org.dodgybits.shuffle.android.list.config.ListConfig;
import org.dodgybits.shuffle.android.list.config.ProjectTasksListConfig;
import org.dodgybits.shuffle.android.persistence.provider.ProjectProvider;
import org.dodgybits.shuffle.android.persistence.provider.TaskProvider;
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.ContextMenu;
import android.view.MenuItem;
import com.google.inject.Inject;
public class ProjectTasksActivity extends AbstractTaskListActivity {
private static final String cTag = "ProjectTasksActivity";
private Id mProjectId;
private Project mProject;
@Inject @ProjectTasks
private ProjectTasksListConfig mTaskListConfig;
@Inject private EntityPersister<Project> mPersister;
@Override
public void onCreate(Bundle icicle) {
Uri contextURI = getIntent().getData();
mProjectId = Id.create(ContentUris.parseId(contextURI));
super.onCreate(icicle);
}
@Override
protected ListConfig<Task,TaskSelector> createListConfig()
{
mTaskListConfig.setProjectId(mProjectId);
return mTaskListConfig;
}
@Override
protected void onResume() {
Log.d(cTag, "Fetching project " + mProjectId);
Cursor cursor = getContentResolver().query(ProjectProvider.Projects.CONTENT_URI, ProjectProvider.Projects.FULL_PROJECTION,
ProjectProvider.Projects._ID + " = ? ", new String[] {String.valueOf(mProjectId)}, null);
if (cursor.moveToNext()) {
mProject = mPersister.read(cursor);
mTaskListConfig.setProject(mProject);
}
cursor.close();
super.onResume();
}
/**
* Return the intent generated when a list item is clicked.
*
* @param uri type of data selected
*/
protected Intent getClickIntent(Uri uri) {
long taskId = ContentUris.parseId(uri);
Uri taskUri = ContentUris.appendId(TaskProvider.Tasks.CONTENT_URI.buildUpon(), taskId).build();
return new Intent(Intent.ACTION_VIEW, taskUri);
}
/**
* Add project id to intent extras so it can be pre-filled for the task.
*/
protected Intent getInsertIntent() {
Intent intent = super.getInsertIntent();
Bundle extras = intent.getExtras();
if (extras == null) {
extras = new Bundle();
}
extras.putLong(TaskProvider.Tasks.PROJECT_ID, mProject.getLocalId().getId());
final Id defaultContextId = mProject.getDefaultContextId();
if (defaultContextId.isInitialised()) {
extras.putLong(TaskProvider.Tasks.CONTEXT_ID, defaultContextId.getId());
}
intent.putExtras(extras);
return intent;
}
@Override
protected void onCreateEntityContextMenu(ContextMenu menu, int position, Task task) {
MenuUtils.addMoveMenuItems(menu,
moveUpPermitted(position), moveDownPermitted(position));
}
@Override
protected boolean onContextEntitySelected(MenuItem item, int position, Task task) {
switch (item.getItemId()) {
case MenuUtils.MOVE_UP_ID:
moveUp(position);
return true;
case MenuUtils.MOVE_DOWN_ID:
moveDown(position);
return true;
}
return super.onContextEntitySelected(item, position, task);
}
private boolean moveUpPermitted(int selection) {
return selection > 0;
}
private boolean moveDownPermitted(int selection) {
return selection < getItemCount() - 1;
}
protected final void moveUp(int selection) {
if (moveUpPermitted(selection)) {
Cursor cursor = (Cursor) getListAdapter().getItem(selection);
getTaskPersister().swapTaskPositions(cursor, selection - 1, selection);
}
}
protected final void moveDown(int selection) {
if (moveDownPermitted(selection)) {
Cursor cursor = (Cursor) getListAdapter().getItem(selection);
getTaskPersister().swapTaskPositions(cursor, selection, selection + 1);
}
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/list/activity/task/ProjectTasksActivity.java | Java | asf20 | 5,210 |
package org.dodgybits.shuffle.android.preference.view;
public class Progress {
private int mProgressPercent;
private String mDetails;
private boolean mIsError;
private Runnable mErrorUIAction;
public static Progress createProgress(int progressPercent, String details) {
return new Progress(progressPercent, details, false, null);
}
public static Progress createErrorProgress(String errorMessage) {
return new Progress(0, errorMessage, true, null);
}
public static Progress createErrorProgress(String errorMessage, Runnable errorUIAction) {
return new Progress(0, errorMessage, true, errorUIAction);
}
private Progress(int progressPercent, String details, boolean isError, Runnable errorUIAction) {
mProgressPercent = progressPercent;
mDetails = details;
mIsError = isError;
mErrorUIAction = errorUIAction;
}
public final int getProgressPercent() {
return mProgressPercent;
}
public final String getDetails() {
return mDetails;
}
public final boolean isError() {
return mIsError;
}
public final Runnable getErrorUIAction() {
return mErrorUIAction;
}
public final boolean isComplete() {
return mProgressPercent == 100;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/preference/view/Progress.java | Java | asf20 | 1,181 |
package org.dodgybits.shuffle.android.preference.model;
import org.dodgybits.shuffle.android.core.model.persistence.selector.Flag;
import roboguice.util.Ln;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
public class ListPreferenceSettings {
public static final String LIST_PREFERENCES_UPDATED = "org.dodgybits.shuffle.android.LIST_PREFERENCES_UPDATE";
public static final String LIST_FILTER_ACTIVE = ".list_active";
public static final String LIST_FILTER_COMPLETED = ".list_completed";
public static final String LIST_FILTER_DELETED = ".list_deleted";
public static final String LIST_FILTER_PENDING = ".list_pending";
private static final String PREFIX = "mPrefix";
private static final String BUNDLE = "list-preference-settings";
private static final String DEFAULT_COMPLETED = "defaultCompleted";
private static final String DEFAULT_PENDING = "defaultPending";
private static final String DEFAULT_DELETED = "defaultDeleted";
private static final String DEFAULT_ACTIVE = "defaultActive";
private static final String COMPLETED_ENABLED = "completedEnabled";
private static final String PENDING_ENABLED = "pendingEnabled";
private static final String DELETED_ENABLED = "deletedEnabled";
private static final String ACTIVE_ENABLED = "activeEnabled";
private String mPrefix;
private Flag mDefaultCompleted = Flag.ignored;
private Flag mDefaultPending = Flag.ignored;
private Flag mDefaultDeleted = Flag.no;
private Flag mDefaultActive = Flag.yes;
private boolean mCompletedEnabled = true;
private boolean mPendingEnabled = true;
private boolean mDeletedEnabled = true;
private boolean mActiveEnabled = true;
public ListPreferenceSettings(String prefix) {
this.mPrefix = prefix;
}
public void addToIntent(Intent intent) {
Bundle bundle = new Bundle();
bundle.putString(PREFIX, mPrefix);
bundle.putString(DEFAULT_COMPLETED, mDefaultCompleted.name());
bundle.putString(DEFAULT_PENDING, mDefaultPending.name());
bundle.putString(DEFAULT_DELETED, mDefaultDeleted.name());
bundle.putString(DEFAULT_ACTIVE, mDefaultActive.name());
bundle.putBoolean(COMPLETED_ENABLED, mCompletedEnabled);
bundle.putBoolean(PENDING_ENABLED, mPendingEnabled);
bundle.putBoolean(DELETED_ENABLED, mDeletedEnabled);
bundle.putBoolean(ACTIVE_ENABLED, mActiveEnabled);
intent.putExtra(BUNDLE, bundle);
}
public static ListPreferenceSettings fromIntent(Intent intent) {
Bundle bundle = intent.getBundleExtra(BUNDLE);
ListPreferenceSettings settings = new ListPreferenceSettings(bundle.getString(PREFIX));
settings.mDefaultCompleted = Flag.valueOf(bundle.getString(DEFAULT_COMPLETED));
settings.mDefaultPending = Flag.valueOf(bundle.getString(DEFAULT_PENDING));
settings.mDefaultDeleted = Flag.valueOf(bundle.getString(DEFAULT_DELETED));
settings.mDefaultActive = Flag.valueOf(bundle.getString(DEFAULT_ACTIVE));
settings.mCompletedEnabled = bundle.getBoolean(COMPLETED_ENABLED, true);
settings.mPendingEnabled = bundle.getBoolean(PENDING_ENABLED, true);
settings.mDeletedEnabled = bundle.getBoolean(DELETED_ENABLED, true);
settings.mActiveEnabled = bundle.getBoolean(ACTIVE_ENABLED, true);
return settings;
}
public String getPrefix() {
return mPrefix;
}
private static SharedPreferences getSharedPreferences(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context);
}
public Flag getDefaultCompleted() {
return mDefaultCompleted;
}
public Flag getDefaultPending() {
return mDefaultPending;
}
public Flag getDefaultDeleted() {
return mDefaultDeleted;
}
public Flag getDefaultActive() {
return mDefaultActive;
}
public ListPreferenceSettings setDefaultCompleted(Flag value) {
mDefaultCompleted = value;
return this;
}
public ListPreferenceSettings setDefaultPending(Flag value) {
mDefaultPending = value;
return this;
}
public ListPreferenceSettings setDefaultDeleted(Flag value) {
mDefaultDeleted = value;
return this;
}
public ListPreferenceSettings setDefaultActive(Flag value) {
mDefaultActive = value;
return this;
}
public boolean isCompletedEnabled() {
return mCompletedEnabled;
}
public ListPreferenceSettings disableCompleted() {
mCompletedEnabled = false;
return this;
}
public boolean isPendingEnabled() {
return mPendingEnabled;
}
public ListPreferenceSettings disablePending() {
mPendingEnabled = false;
return this;
}
public boolean isDeletedEnabled() {
return mDeletedEnabled;
}
public ListPreferenceSettings disableDeleted() {
mDeletedEnabled = false;
return this;
}
public boolean isActiveEnabled() {
return mActiveEnabled;
}
public ListPreferenceSettings disableActive() {
mActiveEnabled = false;
return this;
}
public Flag getActive(Context context) {
return getValue(context, LIST_FILTER_ACTIVE, mDefaultActive);
}
public Flag getCompleted(Context context) {
return getValue(context, LIST_FILTER_COMPLETED, mDefaultCompleted);
}
public Flag getDeleted(Context context) {
return getValue(context, LIST_FILTER_DELETED, mDefaultDeleted);
}
public Flag getPending(Context context) {
return getValue(context, LIST_FILTER_PENDING, mDefaultPending);
}
private Flag getValue(Context context, String setting, Flag defaultValue) {
String valueStr = getSharedPreferences(context).getString(mPrefix + setting, defaultValue.name());
Flag value = defaultValue;
try {
value = Flag.valueOf(valueStr);
} catch (IllegalArgumentException e) {
Ln.e("Unrecognized flag setting %s for settings %s using default %s", valueStr, setting, defaultValue);
}
Ln.d("Got value %s for settings %s%s with default %s", value, mPrefix, setting, defaultValue);
return value;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/preference/model/ListPreferenceSettings.java | Java | asf20 | 6,423 |
/*
* 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.preference.model;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
public class Preferences {
private static final String cTag = "Preferences";
public static final String FIRST_TIME = "first_time";
public static final String ANALYTICS_ENABLED = "send_analytics";
public static final String SCREEN_KEY = "screen";
public static final String DELETE_COMPLETED_PERIOD_KEY = "delete_complete_period_str";
public static final String LAST_DELETE_COMPLETED_KEY = "last_delete_completed";
public static final String LAST_INBOX_CLEAN_KEY = "last_inbox_clean";
public static final String LAST_VERSION = "last_version";
public static final String DISPLAY_CONTEXT_ICON_KEY = "display_context_icon";
public static final String DISPLAY_CONTEXT_NAME_KEY = "display_context_name";
public static final String DISPLAY_PROJECT_KEY = "display_project";
public static final String DISPLAY_DETAILS_KEY = "display_details";
public static final String DISPLAY_DUE_DATE_KEY = "display_due_date";
public static final String PROJECT_VIEW_KEY = "project_view";
public static final String CONTEXT_VIEW_KEY = "context_view";
public static final String TOP_LEVEL_COUNTS_KEY = "top_level_counts";
public static final String CALENDAR_ID_KEY = "calendar_id";
public static final String DEFAULT_REMINDER_KEY = "default_reminder";
public static final String KEY_DEFAULT_REMINDER = "default_reminder";
public static final String TRACKS_URL = "tracks_url";
public static final String TRACKS_USER = "tracks_user";
public static final String TRACKS_PASSWORD = "tracks_password";
public static final String TRACKS_SELF_SIGNED_CERT = "tracks_self_signed_cert";
public static final String TRACKS_INTERVAL = "tracks_interval";
public static final String GOOGLE_AUTH_COOKIE = "authCookie";
public static final String GOOGLE_ACCOUNT_NAME = "accountName";
public static final String GOOGLE_DEVICE_REGISTRATION_ID = "deviceRegistrationID";
public static final String NOTIFICATION_ID = "notificationId";
public static final String WIDGET_QUERY_PREFIX = "widget_query_";
public static final String CLEAN_INBOX_INTENT = "org.dodgybits.shuffle.android.CLEAN_INBOX";
public static boolean validateTracksSettings(Context context) {
String url = getTracksUrl(context);
String password = getTracksPassword(context);
String user = getTracksUser(context);
return user.length() != 0 && password.length() != 0 && url.length() != 0;
}
public static int getTracksInterval(Context context) {
return getSharedPreferences(context).getInt(TRACKS_INTERVAL, 0);
}
public static int getLastVersion(Context context) {
return getSharedPreferences(context).getInt(LAST_VERSION, 0);
}
public enum DeleteCompletedPeriod {
hourly, daily, weekly, never
}
private static SharedPreferences getSharedPreferences(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context);
}
public static boolean isFirstTime(Context context) {
return getSharedPreferences(context).getBoolean(FIRST_TIME, true);
}
public static boolean isAnalyticsEnabled(Context context) {
return getSharedPreferences(context).getBoolean(ANALYTICS_ENABLED, true);
}
public static String getTracksUrl(Context context) {
return getSharedPreferences(context).getString(TRACKS_URL,
context.getString(org.dodgybits.android.shuffle.R.string.tracks_url_settings));
}
public static String getTracksUser(Context context) {
return getSharedPreferences(context).getString(TRACKS_USER, "");
}
public static String getTracksPassword(Context context) {
return getSharedPreferences(context).getString(TRACKS_PASSWORD, "");
}
public static int getNotificationId(Context context) {
return getSharedPreferences(context).getInt(NOTIFICATION_ID, 0);
}
public static void incrementNotificationId(Context context) {
int notificationId = getNotificationId(context);
SharedPreferences.Editor editor = getSharedPreferences(context).edit();
editor.putInt(NOTIFICATION_ID, ++notificationId % 32);
editor.commit();
}
public static String getGoogleAuthCookie(Context context) {
return getSharedPreferences(context).getString(GOOGLE_AUTH_COOKIE, null);
}
public static String getGoogleAccountName(Context context) {
return getSharedPreferences(context).getString(GOOGLE_ACCOUNT_NAME, null);
}
public static String getGooglDeviceRegistrationId(Context context) {
return getSharedPreferences(context).getString(GOOGLE_DEVICE_REGISTRATION_ID, null);
}
public static Boolean isTracksSelfSignedCert(Context context) {
return getSharedPreferences(context).getBoolean(TRACKS_SELF_SIGNED_CERT, false);
}
public static String getDeleteCompletedPeriod(Context context) {
return getSharedPreferences(context).getString(DELETE_COMPLETED_PERIOD_KEY, DeleteCompletedPeriod.never.name());
}
public static long getLastDeleteCompleted(Context context) {
return getSharedPreferences(context).getLong(LAST_DELETE_COMPLETED_KEY, 0L);
}
public static long getLastInboxClean(Context context) {
return getSharedPreferences(context).getLong(LAST_INBOX_CLEAN_KEY, 0L);
}
public static int getDefaultReminderMinutes(Context context) {
String durationString =
getSharedPreferences(context).getString(Preferences.DEFAULT_REMINDER_KEY, "0");
return Integer.parseInt(durationString);
}
public static Boolean isProjectViewExpandable(Context context) {
return !getSharedPreferences(context).getBoolean(PROJECT_VIEW_KEY, false);
}
public static Boolean isContextViewExpandable(Context context) {
return !getSharedPreferences(context).getBoolean(CONTEXT_VIEW_KEY, true);
}
public static boolean displayContextIcon(Context context) {
return getSharedPreferences(context).getBoolean(DISPLAY_CONTEXT_ICON_KEY, true);
}
public static boolean displayContextName(Context context) {
return getSharedPreferences(context).getBoolean(DISPLAY_CONTEXT_NAME_KEY, true);
}
public static boolean displayDueDate(Context context) {
return getSharedPreferences(context).getBoolean(DISPLAY_DUE_DATE_KEY, true);
}
public static boolean displayProject(Context context) {
return getSharedPreferences(context).getBoolean(DISPLAY_PROJECT_KEY, true);
}
public static boolean displayDetails(Context context) {
return getSharedPreferences(context).getBoolean(DISPLAY_DETAILS_KEY, true);
}
public static int[] getTopLevelCounts(Context context) {
String countString = getSharedPreferences(context).getString(Preferences.TOP_LEVEL_COUNTS_KEY, null);
int[] result = null;
if (countString != null) {
String[] counts = countString.split(",");
result = new int[counts.length];
for(int i = 0; i < counts.length; i++) {
result[i] = Integer.parseInt(counts[i]);
}
}
return result;
}
public static int getCalendarId(Context context) {
int id = 1;
String calendarIdStr = getSharedPreferences(context).getString(CALENDAR_ID_KEY, null);
if (calendarIdStr != null) {
try {
id = Integer.parseInt(calendarIdStr, 10);
} catch (NumberFormatException e) {
Log.e(cTag, "Failed to parse calendar id: " + e.getMessage());
}
}
return id;
}
public static String getWidgetQueryKey(int widgetId) {
return WIDGET_QUERY_PREFIX + widgetId;
}
public static String getWidgetQuery(Context context, String key) {
return getSharedPreferences(context).getString(key, null);
}
public static SharedPreferences.Editor getEditor(Context context) {
return getSharedPreferences(context).edit();
}
public static void cleanUpInbox(Context context) {
SharedPreferences.Editor ed = getEditor(context);
ed.putLong(LAST_INBOX_CLEAN_KEY, System.currentTimeMillis());
ed.commit();
context.sendBroadcast(new Intent(CLEAN_INBOX_INTENT));
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/preference/model/Preferences.java | Java | asf20 | 8,870 |
package org.dodgybits.shuffle.android.preference.activity;
import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity;
import org.dodgybits.shuffle.android.synchronisation.gae.AccountsActivity;
import android.content.Intent;
import android.os.Bundle;
public class PreferencesAppEngineSynchronizationActivity extends FlurryEnabledActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startActivity(new Intent(this, AccountsActivity.class));
finish();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/preference/activity/PreferencesAppEngineSynchronizationActivity.java | Java | asf20 | 581 |
/*
* 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.preference.activity;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.model.persistence.TaskPersister;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.inject.Inject;
public class PreferencesDeleteCompletedActivity extends PreferencesDeleteActivity {
private static final String cTag = "PreferencesDeleteCompletedActivity";
@Inject TaskPersister mTaskPersister;
@Override
protected void onCreate(Bundle icicle) {
Log.d(cTag, "onCreate+");
super.onCreate(icicle);
mDeleteButton.setText(R.string.delete_completed_button_title);
mText.setText(R.string.delete_completed_warning);
}
@Override
protected void onDelete() {
int deletedTasks = mTaskPersister.deleteCompletedTasks();
CharSequence message = getString(R.string.clean_task_message, new Object[] {deletedTasks});
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
finish();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/preference/activity/PreferencesDeleteCompletedActivity.java | Java | asf20 | 1,680 |
/*
* 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.preference.activity;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.model.persistence.ContextPersister;
import org.dodgybits.shuffle.android.core.model.persistence.ProjectPersister;
import org.dodgybits.shuffle.android.core.model.persistence.TaskPersister;
import roboguice.util.Ln;
import android.os.Bundle;
import android.widget.Toast;
import com.google.inject.Inject;
public class PreferencesPermanentlyDeleteActivity extends PreferencesDeleteActivity {
@Inject private TaskPersister mTaskPersister;
@Inject private ProjectPersister mProjectPersister;
@Inject private ContextPersister mContextPersister;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setProgressBarIndeterminate(true);
mDeleteButton.setText(R.string.menu_delete);
mText.setText(R.string.warning_empty_trash);
}
@Override
protected void onDelete() {
int taskCount = mTaskPersister.emptyTrash();
int projectCount = mProjectPersister.emptyTrash();
int contextCount = mContextPersister.emptyTrash();
Ln.i("Permanently deleted %s tasks, %s contexts and %s projects", taskCount, contextCount, projectCount);
CharSequence message = getString(R.string.toast_empty_trash, new Object[] {taskCount, contextCount, projectCount});
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
finish();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/preference/activity/PreferencesPermanentlyDeleteActivity.java | Java | asf20 | 2,129 |
/*
* 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.preference.activity;
import static org.dodgybits.shuffle.android.preference.model.Preferences.DISPLAY_CONTEXT_ICON_KEY;
import static org.dodgybits.shuffle.android.preference.model.Preferences.DISPLAY_CONTEXT_NAME_KEY;
import static org.dodgybits.shuffle.android.preference.model.Preferences.DISPLAY_DETAILS_KEY;
import static org.dodgybits.shuffle.android.preference.model.Preferences.DISPLAY_DUE_DATE_KEY;
import static org.dodgybits.shuffle.android.preference.model.Preferences.DISPLAY_PROJECT_KEY;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity;
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.core.model.persistence.EntityCache;
import org.dodgybits.shuffle.android.core.model.persistence.InitialDataGenerator;
import org.dodgybits.shuffle.android.list.view.TaskView;
import org.dodgybits.shuffle.android.preference.model.Preferences;
import roboguice.inject.InjectView;
import roboguice.util.Ln;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.TableRow.LayoutParams;
import com.google.inject.Inject;
public class PreferencesAppearanceActivity extends FlurryEnabledActivity {
private TaskView mTaskView;
private Task mSampleTask;
private Project mSampleProject;
private Context mSampleContext;
private boolean mSaveChanges;
private boolean mDisplayIcon, mDisplayContext, mDisplayDueDate, mDisplayProject, mDisplayDetails;
@InjectView(R.id.display_icon) CheckBox mDisplayIconCheckbox;
@InjectView(R.id.display_context) CheckBox mDisplayContextCheckbox;
@InjectView(R.id.display_due_date) CheckBox mDisplayDueDateCheckbox;
@InjectView(R.id.display_project) CheckBox mDisplayProjectCheckbox;
@InjectView(R.id.display_details) CheckBox mDisplayDetailsCheckbox;
@Inject InitialDataGenerator mGenerator;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.preferences_appearance);
// need to add task view programatically due to issues adding via XML
setupSampleEntities();
EntityCache<Context> contentCache = new EntityCache<Context>() {
@Override
public Context findById(Id localId) {
return mSampleContext;
}
};
EntityCache<Project> projectCache = new EntityCache<Project>() {
@Override
public Project findById(Id localId) {
return mSampleProject;
}
};
mTaskView = new TaskView(this, contentCache, projectCache);
mTaskView.updateView(mSampleTask); // todo pass in project and context
LayoutParams taskLayout = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT );
LinearLayout layout = (LinearLayout)findViewById(R.id.appearance_layout);
layout.addView(mTaskView, 0, taskLayout);
// currently no cancel button
mSaveChanges = true;
OnCheckedChangeListener listener = new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
savePrefs();
mTaskView.updateView(mSampleTask);
}
};
mDisplayIconCheckbox.setOnCheckedChangeListener(listener);
mDisplayContextCheckbox.setOnCheckedChangeListener(listener);
mDisplayDueDateCheckbox.setOnCheckedChangeListener(listener);
mDisplayProjectCheckbox.setOnCheckedChangeListener(listener);
mDisplayDetailsCheckbox.setOnCheckedChangeListener(listener);
}
private void setupSampleEntities() {
long now = System.currentTimeMillis();
mSampleProject = Project.newBuilder().setName("Sample project").build();
mSampleContext = mGenerator.getSampleContext();
mSampleTask = Task.newBuilder()
.setDescription("Sample action")
.setDetails("Additional action details")
.setCreatedDate(now)
.setModifiedDate(now)
.setStartDate(now + DateUtils.DAY_IN_MILLIS * 2)
.setDueDate(now + DateUtils.DAY_IN_MILLIS * 7)
.setAllDay(true)
.build();
}
@Override
protected void onResume() {
super.onResume();
readPrefs();
}
@Override
protected void onPause() {
super.onPause();
if (!mSaveChanges) {
revertPrefs();
}
}
private void readPrefs() {
Ln.d("Settings prefs controls");
mDisplayIcon = Preferences.displayContextIcon(this);
mDisplayContext = Preferences.displayContextName(this);
mDisplayDueDate = Preferences.displayDueDate(this);
mDisplayProject = Preferences.displayProject(this);
mDisplayDetails = Preferences.displayDetails(this);
mDisplayIconCheckbox.setChecked(mDisplayIcon);
mDisplayContextCheckbox.setChecked(mDisplayContext);
mDisplayDueDateCheckbox.setChecked(mDisplayDueDate);
mDisplayProjectCheckbox.setChecked(mDisplayProject);
mDisplayDetailsCheckbox.setChecked(mDisplayDetails);
}
private void revertPrefs() {
Ln.d("Reverting prefs");
SharedPreferences.Editor ed = Preferences.getEditor(this);
ed.putBoolean(DISPLAY_CONTEXT_ICON_KEY, mDisplayIcon);
ed.putBoolean(DISPLAY_CONTEXT_NAME_KEY, mDisplayContext);
ed.putBoolean(DISPLAY_DUE_DATE_KEY, mDisplayDueDate);
ed.putBoolean(DISPLAY_PROJECT_KEY, mDisplayProject);
ed.putBoolean(DISPLAY_DETAILS_KEY, mDisplayDetails);
ed.commit();
}
private void savePrefs() {
Ln.d("Saving prefs");
SharedPreferences.Editor ed = Preferences.getEditor(this);
ed.putBoolean(DISPLAY_CONTEXT_ICON_KEY, mDisplayIconCheckbox.isChecked());
ed.putBoolean(DISPLAY_CONTEXT_NAME_KEY, mDisplayContextCheckbox.isChecked());
ed.putBoolean(DISPLAY_DUE_DATE_KEY, mDisplayDueDateCheckbox.isChecked());
ed.putBoolean(DISPLAY_PROJECT_KEY, mDisplayProjectCheckbox.isChecked());
ed.putBoolean(DISPLAY_DETAILS_KEY, mDisplayDetailsCheckbox.isChecked());
ed.commit();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/preference/activity/PreferencesAppearanceActivity.java | Java | asf20 | 7,054 |
package org.dodgybits.shuffle.android.preference.activity;
import static org.dodgybits.shuffle.android.preference.model.Preferences.TRACKS_INTERVAL;
import static org.dodgybits.shuffle.android.preference.model.Preferences.TRACKS_PASSWORD;
import static org.dodgybits.shuffle.android.preference.model.Preferences.TRACKS_SELF_SIGNED_CERT;
import static org.dodgybits.shuffle.android.preference.model.Preferences.TRACKS_URL;
import static org.dodgybits.shuffle.android.preference.model.Preferences.TRACKS_USER;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpStatus;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity;
import org.dodgybits.shuffle.android.preference.model.Preferences;
import org.dodgybits.shuffle.android.synchronisation.tracks.ApiException;
import org.dodgybits.shuffle.android.synchronisation.tracks.WebClient;
import org.dodgybits.shuffle.android.synchronisation.tracks.WebResult;
import roboguice.inject.InjectView;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
/**
* Activity that changes the options set for synchronization
*/
public class PreferencesTracksSynchronizationActivity extends FlurryEnabledActivity {
@InjectView(R.id.url) EditText mUrlTextbox;
@InjectView(R.id.user) EditText mUserTextbox;
@InjectView(R.id.pass) EditText mPassTextbox;
@InjectView(R.id.checkSettings) Button mCheckSettings;
@InjectView(R.id.sync_interval) Spinner mInterval;
@InjectView(R.id.tracks_self_signed_cert) CheckBox mSelfSignedCertCheckBox;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.synchronize_settings);
String[] options = new String[] {
getText(R.string.sync_interval_none).toString(),
getText(R.string.sync_interval_30min).toString(),
getText(R.string.sync_interval_1h).toString(),
getText(R.string.sync_interval_2h).toString(),
getText(R.string.sync_interval_3h).toString() };
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(
this, android.R.layout.simple_list_item_1, options);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mInterval.setAdapter(adapter);
mInterval.setSelection(Preferences.getTracksInterval(this));
String tracksUrl = Preferences.getTracksUrl(this);
mUrlTextbox.setText(tracksUrl);
// select server portion of URL
int startIndex = 0;
int index = tracksUrl.indexOf("://");
if (index > 0) {
startIndex = index + 3;
}
mUrlTextbox.setSelection(startIndex, tracksUrl.length());
mUserTextbox.setText(Preferences.getTracksUser(this));
mPassTextbox.setText(Preferences.getTracksPassword(this));
mSelfSignedCertCheckBox.setChecked(Preferences.isTracksSelfSignedCert(this));
CompoundButton.OnClickListener checkSettings = new CompoundButton.OnClickListener() {
@Override
public void onClick(View view) {
if(checkSettings()){
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(),
R.string.tracks_settings_valid, duration);
toast.show();
} else {
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(),
R.string.tracks_failed_to_check_url, duration);
toast.show();
}
}
};
CompoundButton.OnClickListener saveClick = new CompoundButton.OnClickListener() {
@Override
public void onClick(View view) {
savePrefs();
finish();
}
};
CompoundButton.OnClickListener cancelClick = new CompoundButton.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
};
final int color = mUrlTextbox.getCurrentTextColor();
verifyUrl(color);
// Setup the bottom buttons
View view = findViewById(R.id.saveButton);
view.setOnClickListener(saveClick);
view = findViewById(R.id.discardButton);
view.setOnClickListener(cancelClick);
view = findViewById(R.id.checkSettings);
view.setOnClickListener(checkSettings);
View url = findViewById(R.id.url);
url.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
verifyUrl(color);
return false;
}
});
}
private boolean verifyUrl(int color) {
try {
new URI(mUrlTextbox.getText().toString());
mUrlTextbox.setTextColor(color);
return true;
} catch (URISyntaxException e) {
mUrlTextbox.setTextColor(Color.RED);
return false;
}
}
private boolean savePrefs() {
SharedPreferences.Editor ed = Preferences.getEditor(this);
URI uri = null;
try {
uri = new URI(mUrlTextbox.getText().toString());
} catch (URISyntaxException ignored) {
}
ed.putString(TRACKS_URL, uri.toString());
ed.putInt(TRACKS_INTERVAL, mInterval.getSelectedItemPosition());
ed.putString(TRACKS_USER, mUserTextbox.getText().toString());
ed.putString(TRACKS_PASSWORD, mPassTextbox.getText().toString());
ed.putBoolean(TRACKS_SELF_SIGNED_CERT, mSelfSignedCertCheckBox.isChecked());
ed.commit();
return true;
}
private boolean checkSettings() {
URI uri = null;
try {
uri = new URI(mUrlTextbox.getText().toString());
} catch (URISyntaxException ignored) {
}
try {
WebClient client = new WebClient(this, mUserTextbox.getText()
.toString(), mPassTextbox.getText().toString(), mSelfSignedCertCheckBox.isChecked());
if (uri != null && uri.isAbsolute()) {
WebResult result = client.getUrlContent(uri.toString() + "/contexts.xml");
if(result.getStatus().getStatusCode() != HttpStatus.SC_OK)
return false;
}
} catch (ApiException e) {
return false;
}
return true;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/preference/activity/PreferencesTracksSynchronizationActivity.java | Java | asf20 | 6,995 |
package org.dodgybits.shuffle.android.preference.activity;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity;
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.persistence.EntityPersister;
import org.dodgybits.shuffle.android.core.model.protocol.ContextProtocolTranslator;
import org.dodgybits.shuffle.android.core.model.protocol.ProjectProtocolTranslator;
import org.dodgybits.shuffle.android.core.model.protocol.TaskProtocolTranslator;
import org.dodgybits.shuffle.android.core.view.AlertUtils;
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 org.dodgybits.shuffle.android.preference.view.Progress;
import org.dodgybits.shuffle.dto.ShuffleProtos.Catalogue;
import org.dodgybits.shuffle.dto.ShuffleProtos.Catalogue.Builder;
import roboguice.inject.InjectView;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.inject.Inject;
public class PreferencesCreateBackupActivity extends FlurryEnabledActivity
implements View.OnClickListener {
private static final String CREATE_BACKUP_STATE = "createBackupState";
private static final String cTag = "PreferencesCreateBackupActivity";
private enum State {EDITING, IN_PROGRESS, COMPLETE, ERROR};
private State mState = State.EDITING;
@InjectView(R.id.filename) EditText mFilenameWidget;
@InjectView(R.id.saveButton) Button mSaveButton;
@InjectView(R.id.discardButton) Button mCancelButton;
@InjectView(R.id.progress_horizontal) ProgressBar mProgressBar;
@InjectView(R.id.progress_label) TextView mProgressText;
@Inject EntityPersister<Context> mContextPersister;
@Inject EntityPersister<Project> mProjectPersister;
@Inject EntityPersister<Task> mTaskPersister;
private AsyncTask<?, ?, ?> mTask;
@Override
protected void onCreate(Bundle icicle) {
Log.d(cTag, "onCreate+");
super.onCreate(icicle);
setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);
setContentView(R.layout.backup_create);
findViewsAndAddListeners();
onUpdateState();
}
private void findViewsAndAddListeners() {
mSaveButton.setOnClickListener(this);
mCancelButton.setOnClickListener(this);
// save progress text when we switch orientation
mProgressText.setFreezesText(true);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.saveButton:
setState(State.IN_PROGRESS);
createBackup();
break;
case R.id.discardButton:
finish();
break;
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(CREATE_BACKUP_STATE, mState.name());
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
String stateName = savedInstanceState.getString(CREATE_BACKUP_STATE);
if (stateName == null) {
stateName = State.EDITING.name();
}
setState(State.valueOf(stateName));
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mTask != null && mTask.getStatus() != AsyncTask.Status.RUNNING) {
mTask.cancel(true);
}
}
private void setState(State value) {
if (mState != value) {
mState = value;
onUpdateState();
}
}
private void onUpdateState() {
switch (mState) {
case EDITING:
setButtonsEnabled(true);
if (TextUtils.isEmpty(mFilenameWidget.getText())) {
Date today = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
String defaultText = "shuffle-" + formatter.format(today) + ".bak";
mFilenameWidget.setText(defaultText);
mFilenameWidget.setSelection(0, defaultText.length() - 4);
}
mFilenameWidget.setEnabled(true);
mProgressBar.setVisibility(View.INVISIBLE);
mProgressText.setVisibility(View.INVISIBLE);
mCancelButton.setText(R.string.cancel_button_title);
break;
case IN_PROGRESS:
setButtonsEnabled(false);
mFilenameWidget.setSelection(0, 0);
mFilenameWidget.setEnabled(false);
mProgressBar.setProgress(0);
mProgressBar.setVisibility(View.VISIBLE);
mProgressText.setVisibility(View.VISIBLE);
break;
case COMPLETE:
setButtonsEnabled(true);
mFilenameWidget.setEnabled(false);
mProgressBar.setVisibility(View.VISIBLE);
mProgressText.setVisibility(View.VISIBLE);
mSaveButton.setVisibility(View.GONE);
mCancelButton.setText(R.string.ok_button_title);
break;
case ERROR:
setButtonsEnabled(true);
mFilenameWidget.setEnabled(true);
mProgressBar.setVisibility(View.VISIBLE);
mProgressText.setVisibility(View.VISIBLE);
mSaveButton.setVisibility(View.VISIBLE);
mCancelButton.setText(R.string.cancel_button_title);
break;
}
}
private void setButtonsEnabled(boolean enabled) {
mSaveButton.setEnabled(enabled);
mCancelButton.setEnabled(enabled);
}
private void createBackup() {
String filename = mFilenameWidget.getText().toString();
if (TextUtils.isEmpty(filename)) {
String message = getString(R.string.warning_filename_empty);
Log.e(cTag, message);
AlertUtils.showWarning(this, message);
setState(State.EDITING);
} else {
mTask = new CreateBackupTask().execute(filename);
}
}
private class CreateBackupTask extends AsyncTask<String, Progress, Void> {
public Void doInBackground(String... filename) {
try {
String message = getString(R.string.status_checking_media);
Log.d(cTag, message);
publishProgress(Progress.createProgress(0, message));
String storage_state = Environment.getExternalStorageState();
if (! Environment.MEDIA_MOUNTED.equals(storage_state)) {
message = getString(R.string.warning_media_not_mounted, storage_state);
reportError(message);
} else {
File dir = Environment.getExternalStorageDirectory();
final File backupFile = new File(dir, filename[0]);
message = getString(R.string.status_creating_backup);
Log.d(cTag, message);
publishProgress(Progress.createProgress(5, message));
if (backupFile.exists()) {
publishProgress(Progress.createErrorProgress("", new Runnable() {
@Override
public void run() {
showFileExistsWarning(backupFile);
}
}));
} else {
backupFile.createNewFile();
FileOutputStream out = new FileOutputStream(backupFile);
writeBackup(out);
}
}
} catch (Exception e) {
String message = getString(R.string.warning_backup_failed, e.getMessage());
reportError(message);
}
return null;
}
private void showFileExistsWarning(final File backupFile) {
OnClickListener buttonListener = new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON1) {
Log.i(cTag, "Overwriting file " + backupFile.getName());
try {
FileOutputStream out = new FileOutputStream(backupFile);
writeBackup(out);
} catch (Exception e) {
String message = getString(R.string.warning_backup_failed, e.getMessage());
reportError(message);
}
} else {
Log.d(cTag, "Hit Cancel button.");
setState(State.EDITING);
}
}
};
OnCancelListener cancelListener = new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
Log.d(cTag, "Hit Cancel button.");
setState(State.EDITING);
}
};
AlertUtils.showFileExistsWarning(PreferencesCreateBackupActivity.this,
backupFile.getName(), buttonListener, cancelListener);
}
private void writeBackup(OutputStream out) throws IOException {
Builder builder = Catalogue.newBuilder();
writeContexts(builder, 10, 20);
writeProjects(builder, 20, 30);
writeTasks(builder, 30, 100);
builder.build().writeTo(out);
out.close();
String message = getString(R.string.status_backup_complete);
Progress progress = Progress.createProgress(100, message);
publishProgress(progress);
}
private void writeContexts(Builder builder, int progressStart, int progressEnd)
{
Log.d(cTag, "Writing contexts");
Cursor cursor = getContentResolver().query(
ContextProvider.Contexts.CONTENT_URI, ContextProvider.Contexts.FULL_PROJECTION,
null, null, null);
int i = 0;
int total = cursor.getCount();
String type = getString(R.string.context_name);
ContextProtocolTranslator translator = new ContextProtocolTranslator();
while (cursor.moveToNext()) {
Context context = mContextPersister.read(cursor);
builder.addContext(translator.toMessage(context));
String text = getString(R.string.backup_progress, type, context.getName());
int percent = calculatePercent(progressStart, progressEnd, ++i, total);
publishProgress(Progress.createProgress(percent, text));
}
cursor.close();
}
private void writeProjects(Builder builder, int progressStart, int progressEnd)
{
Log.d(cTag, "Writing projects");
Cursor cursor = getContentResolver().query(
ProjectProvider.Projects.CONTENT_URI, ProjectProvider.Projects.FULL_PROJECTION,
null, null, null);
int i = 0;
int total = cursor.getCount();
String type = getString(R.string.project_name);
ProjectProtocolTranslator translator = new ProjectProtocolTranslator(null);
while (cursor.moveToNext()) {
Project project = mProjectPersister.read(cursor);
builder.addProject(translator.toMessage(project));
String text = getString(R.string.backup_progress, type, project.getName());
int percent = calculatePercent(progressStart, progressEnd, ++i, total);
publishProgress(Progress.createProgress(percent, text));
}
cursor.close();
}
private void writeTasks(Builder builder, int progressStart, int progressEnd)
{
Log.d(cTag, "Writing tasks");
Cursor cursor = getContentResolver().query(
TaskProvider.Tasks.CONTENT_URI, TaskProvider.Tasks.FULL_PROJECTION,
null, null, null);
int i = 0;
int total = cursor.getCount();
String type = getString(R.string.task_name);
TaskProtocolTranslator translator = new TaskProtocolTranslator(null, null);
while (cursor.moveToNext()) {
Task task = mTaskPersister.read(cursor);
builder.addTask(translator.toMessage(task));
String text = getString(R.string.backup_progress, type, task.getDescription());
int percent = calculatePercent(progressStart, progressEnd, ++i, total);
publishProgress(Progress.createProgress(percent, text));
}
cursor.close();
}
private int calculatePercent(int start, int end, int current, int total) {
return start + (end - start) * current / total;
}
private void reportError(String message) {
Log.e(cTag, message);
publishProgress(Progress.createErrorProgress(message));
}
@Override
public void onProgressUpdate (Progress... progresses) {
Progress progress = progresses[0];
String details = progress.getDetails();
mProgressBar.setProgress(progress.getProgressPercent());
mProgressText.setText(details);
if (progress.isError()) {
if (!TextUtils.isEmpty(details)) {
AlertUtils.showWarning(PreferencesCreateBackupActivity.this, details);
}
Runnable action = progress.getErrorUIAction();
if (action != null) {
action.run();
} else {
setState(State.ERROR);
}
} else if (progress.isComplete()) {
setState(State.COMPLETE);
}
}
@SuppressWarnings("unused")
public void onPostExecute() {
mTask = null;
}
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/preference/activity/PreferencesCreateBackupActivity.java | Java | asf20 | 14,193 |
/*
* 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.preference.activity;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.model.persistence.InitialDataGenerator;
import com.google.inject.Inject;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class PreferencesDeleteAllActivity extends PreferencesDeleteActivity {
private static final String cTag = "PreferencesDeleteAllActivity";
@Inject InitialDataGenerator mGenerator;
@Override
protected void onCreate(Bundle icicle) {
Log.d(cTag, "onCreate+");
super.onCreate(icicle);
setProgressBarIndeterminate(true);
mDeleteButton.setText(R.string.clean_slate_button_title);
mText.setText(R.string.clean_slate_warning);
}
@Override
protected void onDelete() {
Log.i(cTag, "Cleaning the slate");
mGenerator.cleanSlate(null);
Toast.makeText(this, R.string.clean_slate_message, Toast.LENGTH_SHORT).show();
finish();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/preference/activity/PreferencesDeleteAllActivity.java | Java | asf20 | 1,663 |
/*
* 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.preference.activity;
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.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public abstract class PreferencesDeleteActivity extends FlurryEnabledActivity {
private static final String cTag = "PreferencesDeleteActivity";
@InjectView(R.id.text) TextView mText;
@InjectView(R.id.delete_button) Button mDeleteButton;
@InjectView(R.id.cancel_button) Button mCancelButton;
@Override
protected void onCreate(Bundle icicle) {
Log.d(cTag, "onCreate+");
super.onCreate(icicle);
setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);
setContentView(R.layout.delete_dialog);
mDeleteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onDelete();
}
});
mCancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
abstract protected void onDelete();
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/preference/activity/PreferencesDeleteActivity.java | Java | asf20 | 1,942 |
/*
* 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.preference.activity;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledPreferenceActivity;
import org.dodgybits.shuffle.android.core.util.CalendarUtils;
import org.dodgybits.shuffle.android.preference.model.Preferences;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.ListPreference;
import android.util.Log;
public class PreferencesActivity extends FlurryEnabledPreferenceActivity {
private static final String cTag = "PreferencesActivity";
private static final String[] CALENDARS_PROJECTION = new String[] {
"_id", // Calendars._ID,
"displayName" //Calendars.DISPLAY_NAME
};
// only show calendars that the user can modify and that are synced
private static final String CALENDARS_WHERE =
"access_level>=500 AND sync_events=1";
// Calendars.ACCESS_LEVEL + ">=" +
// Calendars.CONTRIBUTOR_ACCESS + " AND " + Calendars.SYNC_EVENTS + "=1";
private static final String CALENDARS_SORT = "displayName ASC";
private AsyncQueryHandler mQueryHandler;
private ListPreference mPreference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
setCalendarPreferenceEntries();
}
private void setCalendarPreferenceEntries() {
mPreference = (ListPreference)findPreference(Preferences.CALENDAR_ID_KEY);
// disable the pref until we load the values (if at all)
mPreference.setEnabled(false);
// Start a query in the background to read the list of calendars
mQueryHandler = new QueryHandler(getContentResolver());
mQueryHandler.startQuery(0, null, CalendarUtils.getCalendarContentUri(), CALENDARS_PROJECTION,
CALENDARS_WHERE, null /* selection args */, CALENDARS_SORT);
}
private class QueryHandler extends AsyncQueryHandler {
public QueryHandler(ContentResolver cr) {
super(cr);
}
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
if (cursor != null) {
int selectedIndex = -1;
final String currentValue = String.valueOf(
Preferences.getCalendarId(PreferencesActivity.this));
final int numCalendars = cursor.getCount();
final String[] values = new String[numCalendars];
final String[] names = new String[numCalendars];
for(int i = 0; i < numCalendars; i++) {
cursor.moveToPosition(i);
values[i] = cursor.getString(0);
names[i] = cursor.getString(1);
if (currentValue.equals(values[i])) {
selectedIndex = i;
}
}
cursor.close();
mPreference.setEntryValues(values);
mPreference.setEntries(names);
if (selectedIndex >= 0) {
mPreference.setValueIndex(selectedIndex);
}
mPreference.setEnabled(true);
} else {
Log.e(cTag, "Failed to fetch calendars - setting disabled.");
}
}
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/preference/activity/PreferencesActivity.java | Java | asf20 | 4,220 |
package org.dodgybits.shuffle.android.preference.activity;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity;
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.core.model.persistence.EntityPersister;
import org.dodgybits.shuffle.android.core.model.protocol.ContextProtocolTranslator;
import org.dodgybits.shuffle.android.core.model.protocol.EntityDirectory;
import org.dodgybits.shuffle.android.core.model.protocol.HashEntityDirectory;
import org.dodgybits.shuffle.android.core.model.protocol.ProjectProtocolTranslator;
import org.dodgybits.shuffle.android.core.model.protocol.TaskProtocolTranslator;
import org.dodgybits.shuffle.android.core.util.StringUtils;
import org.dodgybits.shuffle.android.core.view.AlertUtils;
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.dto.ShuffleProtos.Catalogue;
import roboguice.inject.InjectView;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import com.google.inject.Inject;
public class PreferencesRestoreBackupActivity extends FlurryEnabledActivity
implements View.OnClickListener {
private static final String RESTORE_BACKUP_STATE = "restoreBackupState";
private static final String cTag = "PrefRestoreBackup";
private enum State {SELECTING, IN_PROGRESS, COMPLETE, ERROR};
private State mState = State.SELECTING;
@InjectView(R.id.filename) Spinner mFileSpinner;
@InjectView(R.id.saveButton) Button mRestoreButton;
@InjectView(R.id.discardButton) Button mCancelButton;
@InjectView(R.id.progress_horizontal) ProgressBar mProgressBar;
@InjectView(R.id.progress_label) TextView mProgressText;
@Inject EntityPersister<Context> mContextPersister;
@Inject EntityPersister<Project> mProjectPersister;
@Inject EntityPersister<Task> mTaskPersister;
private AsyncTask<?, ?, ?> mTask;
@Override
protected void onCreate(Bundle icicle) {
Log.d(cTag, "onCreate+");
super.onCreate(icicle);
setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);
setContentView(R.layout.backup_restore);
findViewsAndAddListeners();
onUpdateState();
}
@Override
protected void onResume() {
super.onResume();
setupFileSpinner();
}
private void findViewsAndAddListeners() {
mRestoreButton.setText(R.string.restore_button_title);
mRestoreButton.setOnClickListener(this);
mCancelButton.setOnClickListener(this);
// save progress text when we switch orientation
mProgressText.setFreezesText(true);
}
private void setupFileSpinner() {
String storage_state = Environment.getExternalStorageState();
if (! Environment.MEDIA_MOUNTED.equals(storage_state)) {
String message = getString(R.string.warning_media_not_mounted, storage_state);
Log.e(cTag, message);
AlertUtils.showWarning(this, message);
setState(State.COMPLETE);
return;
}
File dir = Environment.getExternalStorageDirectory();
String[] files = dir.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
// don't show hidden files
return !filename.startsWith(".");
}
});
if (files == null || files.length == 0) {
String message = getString(R.string.warning_no_files, storage_state);
Log.e(cTag, message);
AlertUtils.showWarning(this, message);
setState(State.COMPLETE);
return;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, files);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mFileSpinner.setAdapter(adapter);
// select most recent file ending in .bak
int selectedIndex = 0;
long lastModified = Long.MIN_VALUE;
for (int i = 0; i < files.length; i++) {
String filename = files[i];
File f = new File(dir, filename);
if (f.getName().endsWith(".bak") &&
f.lastModified() > lastModified) {
selectedIndex = i;
lastModified = f.lastModified();
}
}
mFileSpinner.setSelection(selectedIndex);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.saveButton:
setState(State.IN_PROGRESS);
restoreBackup();
break;
case R.id.discardButton:
finish();
break;
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(RESTORE_BACKUP_STATE, mState.name());
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
String stateName = savedInstanceState.getString(RESTORE_BACKUP_STATE);
if (stateName == null) {
stateName = State.SELECTING.name();
}
setState(State.valueOf(stateName));
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mTask != null && mTask.getStatus() != AsyncTask.Status.RUNNING) {
mTask.cancel(true);
}
}
private void setState(State value) {
if (mState != value) {
mState = value;
onUpdateState();
}
}
private void onUpdateState() {
switch (mState) {
case SELECTING:
setButtonsEnabled(true);
mFileSpinner.setEnabled(true);
mProgressBar.setVisibility(View.INVISIBLE);
mProgressText.setVisibility(View.INVISIBLE);
mCancelButton.setText(R.string.cancel_button_title);
break;
case IN_PROGRESS:
setButtonsEnabled(false);
mFileSpinner.setEnabled(false);
mProgressBar.setProgress(0);
mProgressBar.setVisibility(View.VISIBLE);
mProgressText.setVisibility(View.VISIBLE);
break;
case COMPLETE:
setButtonsEnabled(true);
mFileSpinner.setEnabled(false);
mProgressBar.setVisibility(View.VISIBLE);
mProgressText.setVisibility(View.VISIBLE);
mRestoreButton.setVisibility(View.GONE);
mCancelButton.setText(R.string.ok_button_title);
break;
case ERROR:
setButtonsEnabled(true);
mFileSpinner.setEnabled(true);
mProgressBar.setVisibility(View.VISIBLE);
mProgressText.setVisibility(View.VISIBLE);
mRestoreButton.setVisibility(View.VISIBLE);
mCancelButton.setText(R.string.cancel_button_title);
break;
}
}
private void setButtonsEnabled(boolean enabled) {
mRestoreButton.setEnabled(enabled);
mCancelButton.setEnabled(enabled);
}
private void restoreBackup() {
String filename = mFileSpinner.getSelectedItem().toString();
mTask = new RestoreBackupTask().execute(filename);
}
private class RestoreBackupTask extends AsyncTask<String, Progress, Void> {
public Void doInBackground(String... filename) {
try {
String message = getString(R.string.status_reading_backup);
Log.d(cTag, message);
publishProgress(Progress.createProgress(5, message));
File dir = Environment.getExternalStorageDirectory();
File backupFile = new File(dir, filename[0]);
FileInputStream in = new FileInputStream(backupFile);
Catalogue catalogue = Catalogue.parseFrom(in);
in.close();
if (Log.isLoggable(cTag, Log.DEBUG)) {
Log.d(cTag, catalogue.toString());
}
EntityDirectory<Context> contextLocator = addContexts(catalogue.getContextList(), 10, 20);
EntityDirectory<Project> projectLocator = addProjects(catalogue.getProjectList(), contextLocator, 20, 30);
addTasks(catalogue.getTaskList(), contextLocator, projectLocator, 30, 100);
message = getString(R.string.status_restore_complete);
publishProgress(Progress.createProgress(100, message));
} catch (Exception e) {
String message = getString(R.string.warning_restore_failed, e.getMessage());
reportError(message);
}
return null;
}
private EntityDirectory<Context> addContexts(
List<org.dodgybits.shuffle.dto.ShuffleProtos.Context> protoContexts,
int progressStart, int progressEnd) {
ContextProtocolTranslator translator = new ContextProtocolTranslator();
Set<String> allContextNames = new HashSet<String>();
for (org.dodgybits.shuffle.dto.ShuffleProtos.Context protoContext : protoContexts)
{
allContextNames.add(protoContext.getName());
}
Map<String,Context> existingContexts = fetchContextsByName(allContextNames);
// build up the locator and list of new contacts
HashEntityDirectory<Context> contextLocator = new HashEntityDirectory<Context>();
List<Context> newContexts = new ArrayList<Context>();
Set<String> newContextNames = new HashSet<String>();
int i = 0;
int total = protoContexts.size();
String type = getString(R.string.context_name);
for (org.dodgybits.shuffle.dto.ShuffleProtos.Context protoContext : protoContexts)
{
String contextName = protoContext.getName();
Context context = existingContexts.get(contextName);
if (context != null) {
Log.d(cTag, "Context " + contextName + " already exists - skipping.");
} else {
Log.d(cTag, "Context " + contextName + " new - adding.");
context = translator.fromMessage(protoContext);
newContexts.add(context);
newContextNames.add(contextName);
}
Id contextId = Id.create(protoContext.getId());
contextLocator.addItem(contextId, contextName, context);
String text = getString(R.string.restore_progress, type, contextName);
int percent = calculatePercent(progressStart, progressEnd, ++i, total);
publishProgress(Progress.createProgress(percent, text));
}
mContextPersister.bulkInsert(newContexts);
// we need to fetch all the newly created contexts to retrieve their new ids
// and update the locator accordingly
Map<String,Context> savedContexts = fetchContextsByName(newContextNames);
for (String contextName : newContextNames) {
Context savedContext = savedContexts.get(contextName);
Context restoredContext = contextLocator.findByName(contextName);
contextLocator.addItem(restoredContext.getLocalId(), contextName, savedContext);
}
return contextLocator;
}
/**
* Attempts to match existing contexts against a list of context names.
*
* @param names names to match
* @return any matching contexts in a Map, keyed on the context name
*/
private Map<String,Context> fetchContextsByName(Collection<String> names) {
Map<String,Context> contexts = new HashMap<String,Context>();
if (names.size() > 0)
{
String params = StringUtils.repeat(names.size(), "?", ",");
String[] paramValues = names.toArray(new String[0]);
Cursor cursor = getContentResolver().query(
ContextProvider.Contexts.CONTENT_URI,
ContextProvider.Contexts.FULL_PROJECTION,
ContextProvider.Contexts.NAME + " IN (" + params + ")",
paramValues, ContextProvider.Contexts.NAME + " ASC");
while (cursor.moveToNext()) {
Context context = mContextPersister.read(cursor);
contexts.put(context.getName(), context);
}
cursor.close();
}
return contexts;
}
private EntityDirectory<Project> addProjects(
List<org.dodgybits.shuffle.dto.ShuffleProtos.Project> protoProjects,
EntityDirectory<Context> contextLocator,
int progressStart, int progressEnd) {
ProjectProtocolTranslator translator = new ProjectProtocolTranslator(contextLocator);
Set<String> allProjectNames = new HashSet<String>();
for (org.dodgybits.shuffle.dto.ShuffleProtos.Project protoProject : protoProjects)
{
allProjectNames.add(protoProject.getName());
}
Map<String,Project> existingProjects = fetchProjectsByName(allProjectNames);
// build up the locator and list of new projects
HashEntityDirectory<Project> projectLocator = new HashEntityDirectory<Project>();
List<Project> newProjects = new ArrayList<Project>();
Set<String> newProjectNames = new HashSet<String>();
int i = 0;
int total = protoProjects.size();
String type = getString(R.string.project_name);
for (org.dodgybits.shuffle.dto.ShuffleProtos.Project protoProject : protoProjects)
{
String projectName = protoProject.getName();
Project project = existingProjects.get(projectName);
if (project != null) {
Log.d(cTag, "Project " + projectName + " already exists - skipping.");
} else {
Log.d(cTag, "Project " + projectName + " new - adding.");
project = translator.fromMessage(protoProject);
newProjects.add(project);
newProjectNames.add(projectName);
}
Id projectId = Id.create(protoProject.getId());
projectLocator.addItem(projectId, projectName, project);
String text = getString(R.string.restore_progress, type, projectName);
int percent = calculatePercent(progressStart, progressEnd, ++i, total);
publishProgress(Progress.createProgress(percent, text));
}
mProjectPersister.bulkInsert(newProjects);
// we need to fetch all the newly created contexts to retrieve their new ids
// and update the locator accordingly
Map<String,Project> savedProjects = fetchProjectsByName(newProjectNames);
for (String projectName : newProjectNames) {
Project savedProject = savedProjects.get(projectName);
Project restoredProject = projectLocator.findByName(projectName);
projectLocator.addItem(restoredProject.getLocalId(), projectName, savedProject);
}
return projectLocator;
}
/**
* Attempts to match existing contexts against a list of context names.
*
* @return any matching contexts in a Map, keyed on the context name
*/
private Map<String,Project> fetchProjectsByName(Collection<String> names) {
Map<String,Project> projects = new HashMap<String,Project>();
if (names.size() > 0)
{
String params = StringUtils.repeat(names.size(), "?", ",");
String[] paramValues = names.toArray(new String[0]);
Cursor cursor = getContentResolver().query(
ProjectProvider.Projects.CONTENT_URI,
ProjectProvider.Projects.FULL_PROJECTION,
ProjectProvider.Projects.NAME + " IN (" + params + ")",
paramValues, ProjectProvider.Projects.NAME + " ASC");
while (cursor.moveToNext()) {
Project project = mProjectPersister.read(cursor);
projects.put(project.getName(), project);
}
cursor.close();
}
return projects;
}
private void addTasks(
List<org.dodgybits.shuffle.dto.ShuffleProtos.Task> protoTasks,
EntityDirectory<Context> contextLocator,
EntityDirectory<Project> projectLocator,
int progressStart, int progressEnd) {
TaskProtocolTranslator translator = new TaskProtocolTranslator(contextLocator, projectLocator);
// add all tasks back, even if they're duplicates
String type = getString(R.string.task_name);
List<Task> newTasks = new ArrayList<Task>();
int i = 0;
int total = protoTasks.size();
for (org.dodgybits.shuffle.dto.ShuffleProtos.Task protoTask : protoTasks)
{
Task task = translator.fromMessage(protoTask);
newTasks.add(task);
Log.d(cTag, "Adding task " + task.getDescription());
String text = getString(R.string.restore_progress, type, task.getDescription());
int percent = calculatePercent(progressStart, progressEnd, ++i, total);
publishProgress(Progress.createProgress(percent, text));
}
mTaskPersister.bulkInsert(newTasks);
}
private int calculatePercent(int start, int end, int current, int total) {
return start + (end - start) * current / total;
}
private void reportError(String message) {
Log.e(cTag, message);
publishProgress(Progress.createErrorProgress(message));
}
@Override
public void onProgressUpdate (Progress... progresses) {
Progress progress = progresses[0];
String details = progress.getDetails();
mProgressBar.setProgress(progress.getProgressPercent());
mProgressText.setText(details);
if (progress.isError()) {
if (!TextUtils.isEmpty(details)) {
AlertUtils.showWarning(PreferencesRestoreBackupActivity.this, details);
}
Runnable action = progress.getErrorUIAction();
if (action != null) {
action.run();
} else {
setState(State.ERROR);
}
} else if (progress.isComplete()) {
setState(State.COMPLETE);
}
}
@SuppressWarnings("unused")
public void onPostExecute() {
mTask = null;
}
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/preference/activity/PreferencesRestoreBackupActivity.java | Java | asf20 | 18,708 |
package org.dodgybits.shuffle.android.persistence.migrations;
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 android.database.sqlite.SQLiteDatabase;
public class V15Migration implements Migration {
@Override
public void migrate(SQLiteDatabase db) {
db.execSQL("ALTER TABLE " + TaskProvider.TASK_TABLE_NAME
+ " ADD COLUMN active INTEGER NOT NULL DEFAULT 1;");
db.execSQL("ALTER TABLE " + ContextProvider.CONTEXT_TABLE_NAME
+ " ADD COLUMN active INTEGER NOT NULL DEFAULT 1;");
db.execSQL("ALTER TABLE " + ProjectProvider.PROJECT_TABLE_NAME
+ " ADD COLUMN active INTEGER NOT NULL DEFAULT 1;");
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/persistence/migrations/V15Migration.java | Java | asf20 | 882 |
package org.dodgybits.shuffle.android.persistence.migrations;
import android.database.sqlite.SQLiteDatabase;
public interface Migration {
public void migrate(SQLiteDatabase db);
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/persistence/migrations/Migration.java | Java | asf20 | 190 |
package org.dodgybits.shuffle.android.persistence.migrations;
import org.dodgybits.shuffle.android.persistence.provider.ReminderProvider;
import org.dodgybits.shuffle.android.persistence.provider.TaskProvider;
import android.database.sqlite.SQLiteDatabase;
public class V11Migration implements Migration {
@Override
public void migrate(SQLiteDatabase db) {
// Shuffle v1.1.1 (2nd release)
db.execSQL("ALTER TABLE " + TaskProvider.TASK_TABLE_NAME
+ " ADD COLUMN start INTEGER;");
db.execSQL("ALTER TABLE " + TaskProvider.TASK_TABLE_NAME
+ " ADD COLUMN timezone TEXT;");
db.execSQL("ALTER TABLE " + TaskProvider.TASK_TABLE_NAME
+ " ADD COLUMN allDay INTEGER NOT NULL DEFAULT 0;");
db.execSQL("ALTER TABLE " + TaskProvider.TASK_TABLE_NAME
+ " ADD COLUMN hasAlarm INTEGER NOT NULL DEFAULT 0;");
db.execSQL("ALTER TABLE " + TaskProvider.TASK_TABLE_NAME
+ " ADD COLUMN calEventId INTEGER;");
db.execSQL("UPDATE " + TaskProvider.TASK_TABLE_NAME + " SET start = due;");
db.execSQL("UPDATE " + TaskProvider.TASK_TABLE_NAME + " SET allDay = 1 " +
"WHERE due > 0;");
createRemindersTable(db);
createRemindersEventIdIndex(db);
createTaskCleanupTrigger(db);
// no break since we want it to fall through
}
private void createRemindersTable(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + ReminderProvider.cReminderTableName);
db.execSQL("CREATE TABLE " + ReminderProvider.cReminderTableName + " (" + "_id INTEGER PRIMARY KEY,"
+ "taskId INTEGER," + "minutes INTEGER,"
+ "method INTEGER NOT NULL" + " DEFAULT "
+ ReminderProvider.Reminders.METHOD_DEFAULT + ");");
}
private void createRemindersEventIdIndex(SQLiteDatabase db) {
db.execSQL("DROP INDEX IF EXISTS remindersEventIdIndex");
db.execSQL("CREATE INDEX remindersEventIdIndex ON " + ReminderProvider.cReminderTableName + " ("
+ ReminderProvider.Reminders.TASK_ID + ");");
}
private void createTaskCleanupTrigger(SQLiteDatabase db) {
// Trigger to remove data tied to a task when we delete that task
db.execSQL("DROP TRIGGER IF EXISTS tasks_cleanup_delete");
db.execSQL("CREATE TRIGGER tasks_cleanup_delete DELETE ON " + TaskProvider.TASK_TABLE_NAME
+ " BEGIN "
+ "DELETE FROM " + ReminderProvider.cReminderTableName + " WHERE taskId = old._id;"
+ "END");
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/persistence/migrations/V11Migration.java | Java | asf20 | 2,391 |
package org.dodgybits.shuffle.android.persistence.migrations;
import static org.dodgybits.shuffle.android.persistence.provider.ContextProvider.CONTEXT_TABLE_NAME;
import android.database.sqlite.SQLiteDatabase;
public class V9Migration implements Migration {
@Override
public void migrate(SQLiteDatabase db) {
createContextTable(db);
}
private void createContextTable(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + CONTEXT_TABLE_NAME);
db.execSQL("CREATE TABLE "
+ CONTEXT_TABLE_NAME
+ " ("
+ "_id INTEGER PRIMARY KEY,"
+ "name TEXT,"
+ "colour INTEGER,"
+ "iconName TEXT"
+ ");");
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/persistence/migrations/V9Migration.java | Java | asf20 | 681 |
package org.dodgybits.shuffle.android.persistence.migrations;
import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.DISPLAY_ORDER;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import roboguice.util.Ln;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.provider.BaseColumns;
public class V16Migration implements Migration {
@Override
public void migrate(SQLiteDatabase db) {
// clean up task ordering - previous schema may have allowed
// two tasks in the same project to share the same order id
Map<String,Integer> updatedValues = findTasksToUpdate(db);
applyUpdates(db, updatedValues);
}
private Map<String,Integer> findTasksToUpdate(SQLiteDatabase db) {
Cursor c = db.query("task",
new String[] {"_id","projectId","displayOrder"},
"projectId not null", null,
null, null,
"projectId ASC, due ASC, displayOrder ASC");
long currentProjectId = 0L;
int newOrder = 0;
Map<String,Integer> updatedValues = new HashMap<String,Integer>();
while (c.moveToNext()) {
long id = c.getLong(0);
long projectId = c.getLong(1);
int displayOrder = c.getInt(2);
if (projectId == currentProjectId) {
newOrder++;
} else {
newOrder = 0;
currentProjectId = projectId;
}
if (newOrder != displayOrder) {
Ln.d("Updating task %1$d displayOrder from %2$d to %3$d", id, displayOrder, newOrder);
updatedValues.put(String.valueOf(id), newOrder);
}
}
c.close();
return updatedValues;
}
private void applyUpdates(SQLiteDatabase db, Map<String,Integer> updatedValues) {
ContentValues values = new ContentValues();
Set<String> ids = updatedValues.keySet();
for (String id : ids) {
values.clear();
values.put(DISPLAY_ORDER, updatedValues.get(id));
db.update("task", values, BaseColumns._ID + " = ?", new String[] {id});
}
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/persistence/migrations/V16Migration.java | Java | asf20 | 2,333 |
package org.dodgybits.shuffle.android.persistence.migrations;
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 android.database.sqlite.SQLiteDatabase;
public class V12Migration implements Migration {
@Override
public void migrate(SQLiteDatabase db) {
// Shuffle v1.2.0
db.execSQL("ALTER TABLE " + TaskProvider.TASK_TABLE_NAME
+ " ADD COLUMN tracks_id INTEGER;");
db.execSQL("ALTER TABLE " + ContextProvider.CONTEXT_TABLE_NAME
+ " ADD COLUMN tracks_id INTEGER;");
db.execSQL("ALTER TABLE " + ContextProvider.CONTEXT_TABLE_NAME
+ " ADD COLUMN modified INTEGER;");
db.execSQL("ALTER TABLE " + ProjectProvider.PROJECT_TABLE_NAME
+ " ADD COLUMN tracks_id INTEGER;");
db.execSQL("ALTER TABLE " + ProjectProvider.PROJECT_TABLE_NAME
+ " ADD COLUMN modified INTEGER;");
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/persistence/migrations/V12Migration.java | Java | asf20 | 1,054 |
package org.dodgybits.shuffle.android.persistence.migrations;
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 android.database.sqlite.SQLiteDatabase;
public class V14Migration implements Migration {
@Override
public void migrate(SQLiteDatabase db) {
db.execSQL("ALTER TABLE " + TaskProvider.TASK_TABLE_NAME
+ " ADD COLUMN deleted INTEGER NOT NULL DEFAULT 0;");
db.execSQL("ALTER TABLE " + ContextProvider.CONTEXT_TABLE_NAME
+ " ADD COLUMN deleted INTEGER NOT NULL DEFAULT 0;");
db.execSQL("ALTER TABLE " + ProjectProvider.PROJECT_TABLE_NAME
+ " ADD COLUMN deleted INTEGER NOT NULL DEFAULT 0;");
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/persistence/migrations/V14Migration.java | Java | asf20 | 885 |
package org.dodgybits.shuffle.android.persistence.migrations;
import org.dodgybits.shuffle.android.persistence.provider.ProjectProvider;
import android.database.sqlite.SQLiteDatabase;
public class V13Migration implements Migration {
@Override
public void migrate(SQLiteDatabase db) {
// Shuffle v1.4.0
db.execSQL("ALTER TABLE " + ProjectProvider.PROJECT_TABLE_NAME
+ " ADD COLUMN parallel INTEGER NOT NULL DEFAULT 0;");
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/persistence/migrations/V13Migration.java | Java | asf20 | 477 |