code
stringlengths
3
1.18M
language
stringclasses
1 value
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 { }
Java
package org.dodgybits.shuffle.android.list.annotation; import com.google.inject.BindingAnnotation; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; @BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) public @interface ExpandableProjects { }
Java
package org.dodgybits.shuffle.android.list.annotation; import com.google.inject.BindingAnnotation; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; @BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) public @interface ExpandableContexts { }
Java
package org.dodgybits.shuffle.android.list.annotation; import com.google.inject.BindingAnnotation; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; @BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) public @interface DueTasks { }
Java
package org.dodgybits.shuffle.android.list.annotation; import com.google.inject.BindingAnnotation; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; @BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) public @interface Projects { }
Java
package org.dodgybits.shuffle.android.list.annotation; import com.google.inject.BindingAnnotation; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; @BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) public @interface ContextTasks { }
Java
package org.dodgybits.shuffle.android.list.annotation; import com.google.inject.BindingAnnotation; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; @BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) public @interface Inbox { }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.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); } }
Java
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 {}; }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.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; } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.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); }
Java
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); } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.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; } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.view; public interface SwipeListItemListener { public void onListItemSwiped(int position); }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.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); } } } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.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); } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.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); } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.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; } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.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); } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.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(); }
Java
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; } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.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 } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.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; } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.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; } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.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(); }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.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; } }; } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.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); } } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.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); } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.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; } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.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(); } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.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; } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.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; } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.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; } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.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(); } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.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); } } }
Java
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; } }
Java
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; } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.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)); } }
Java
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(); } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.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(); } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.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(); } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.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(); } }
Java
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; } }
Java
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; } } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.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(); } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.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(); }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.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."); } } } }
Java
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; } } }
Java
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;"); } }
Java
package org.dodgybits.shuffle.android.persistence.migrations; import android.database.sqlite.SQLiteDatabase; public interface Migration { public void migrate(SQLiteDatabase db); }
Java
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"); } }
Java
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" + ");"); } }
Java
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}); } } }
Java
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;"); } }
Java
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;"); } }
Java
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;"); } }
Java
package org.dodgybits.shuffle.android.persistence.migrations; import org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider; import org.dodgybits.shuffle.android.persistence.provider.ProjectProvider; import org.dodgybits.shuffle.android.persistence.provider.TaskProvider; import android.database.sqlite.SQLiteDatabase; import android.util.Log; public class V1Migration implements Migration { @Override public void migrate(SQLiteDatabase db) { createProjectTable(db); createTaskTable(db); } private void createProjectTable(SQLiteDatabase db) { Log.w(AbstractCollectionProvider.cTag, "Destroying all old data"); db.execSQL("DROP TABLE IF EXISTS " + ProjectProvider.PROJECT_TABLE_NAME); db.execSQL("CREATE TABLE " + ProjectProvider.PROJECT_TABLE_NAME + " (" + "_id INTEGER PRIMARY KEY," + "name TEXT," + "archived INTEGER," + "defaultContextId INTEGER" + ");"); } private void createTaskTable(SQLiteDatabase db) { db.execSQL("DROP TABLE IF EXISTS " + TaskProvider.TASK_TABLE_NAME); db.execSQL("CREATE TABLE " + TaskProvider.TASK_TABLE_NAME + " (" + "_id INTEGER PRIMARY KEY," + "description TEXT," + "details TEXT," + "contextId INTEGER," + "projectId INTEGER," + "created INTEGER," + "modified INTEGER," + "due INTEGER," + "displayOrder INTEGER," + "complete INTEGER" + ");"); } }
Java
package org.dodgybits.shuffle.android.persistence.migrations; import org.dodgybits.shuffle.android.persistence.provider.TaskProvider; import android.database.sqlite.SQLiteDatabase; public class V10Migration implements Migration { @Override public void migrate(SQLiteDatabase db) { // Shuffle v1.1 (1st release) createTaskProjectIdIndex(db); createTaskContextIdIndex(db); // no break since we want it to fall through } private void createTaskProjectIdIndex(SQLiteDatabase db) { db.execSQL("DROP INDEX IF EXISTS taskProjectIdIndex"); db.execSQL("CREATE INDEX taskProjectIdIndex ON " + TaskProvider.TASK_TABLE_NAME + " (" + TaskProvider.Tasks.PROJECT_ID + ");"); } private void createTaskContextIdIndex(SQLiteDatabase db) { db.execSQL("DROP INDEX IF EXISTS taskContextIdIndex"); db.execSQL("CREATE INDEX taskContextIdIndex ON " + TaskProvider.TASK_TABLE_NAME + " (" + TaskProvider.Tasks.CONTEXT_ID + ");"); } }
Java
package org.dodgybits.shuffle.android.persistence.provider; import android.net.Uri; public class ReminderProvider extends AbstractCollectionProvider { private static final String AUTHORITY = Shuffle.PACKAGE+".reminderprovider"; public static final String cUpdateIntent = "org.dodgybits.shuffle.android.REMINDER_UPDATE"; /** * Reminders table */ public static final class Reminders implements ShuffleTable { /** * The content:// style URL for this table */ public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/reminders"); /** * The default sort order for this table */ public static final String DEFAULT_SORT_ORDER = "minutes DESC"; /** * The task the reminder belongs to * <P> * Type: INTEGER (foreign key to the task table) * </P> */ public static final String TASK_ID = "taskId"; /** * The minutes prior to the event that the alarm should ring. -1 * specifies that we should use the default value for the system. * <P> * Type: INTEGER * </P> */ public static final String MINUTES = "minutes"; public static final int MINUTES_DEFAULT = -1; /** * The alarm method. */ public static final String METHOD = "method"; public static final int METHOD_DEFAULT = 0; public static final int METHOD_ALERT = 1; /** * Projection for all the columns of a context. */ public static final String[] cFullProjection = new String[] { _ID, MINUTES, METHOD, }; public static final int MINUTES_INDEX = 1; public static final int METHOD_INDEX = 2; } public static final String cReminderTableName = "Reminder"; public ReminderProvider() { super( AUTHORITY, "reminders", cReminderTableName, cUpdateIntent, Reminders.METHOD, Reminders._ID, Reminders.CONTENT_URI, Reminders._ID,Reminders.TASK_ID,Reminders.MINUTES, Reminders.METHOD ); setDefaultSortOrder(Reminders.DEFAULT_SORT_ORDER); } }
Java
package org.dodgybits.shuffle.android.persistence.provider; import android.net.Uri; import android.provider.BaseColumns; public class ContextProvider extends AbstractCollectionProvider { public static final String CONTEXT_TABLE_NAME = "context"; public static final String UPDATE_INTENT = "org.dodgybits.shuffle.android.CONTEXT_UPDATE"; private static final String AUTHORITY = Shuffle.PACKAGE + ".contextprovider"; static final int CONTEXT_TASKS = 103; private static final String URL_COLLECTION_NAME = "contexts"; public ContextProvider() { super( AUTHORITY, // authority URL_COLLECTION_NAME, // collectionNamePlural CONTEXT_TABLE_NAME, // tableName UPDATE_INTENT, // update intent action Contexts.NAME, // primary key BaseColumns._ID, // id field Contexts.CONTENT_URI,// content URI BaseColumns._ID, // fields... Contexts.NAME, Contexts.COLOUR, Contexts.ICON, ShuffleTable.TRACKS_ID, ShuffleTable.MODIFIED_DATE, ShuffleTable.DELETED, ShuffleTable.ACTIVE ); uriMatcher.addURI(AUTHORITY, "contextTasks", CONTEXT_TASKS); restrictionBuilders.put(CONTEXT_TASKS, new CustomElementFilterRestrictionBuilder( "context, task", "task.contextId = context._id", "context._id")); groupByBuilders.put(CONTEXT_TASKS, new StandardGroupByBuilder("context._id")); elementInserters.put(COLLECTION_MATCH_ID, new ContextInserter()); setDefaultSortOrder(Contexts.DEFAULT_SORT_ORDER); } /** * Contexts table */ public static final class Contexts implements ShuffleTable { /** * The content:// style URL for this table */ public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/contexts"); public static final Uri CONTEXT_TASKS_CONTENT_URI = Uri .parse("content://" + AUTHORITY + "/contextTasks"); public static final Uri ACTIVE_CONTEXTS = Uri .parse("content://" + AUTHORITY + "/activeContexts"); /** * The default sort order for this table */ public static final String DEFAULT_SORT_ORDER = "name DESC"; public static final String NAME = "name"; public static final String COLOUR = "colour"; public static final String ICON = "iconName"; /** * Projection for all the columns of a context. */ public static final String[] FULL_PROJECTION = new String[] { _ID, NAME, COLOUR, ICON, TRACKS_ID, MODIFIED_DATE, DELETED, ACTIVE }; public static final String TASK_COUNT = "count"; /** * Projection for fetching the task count for each context. */ public static final String[] FULL_TASK_PROJECTION = new String[] { _ID, TASK_COUNT, }; } private class ContextInserter extends ElementInserterImpl { public ContextInserter() { super(Contexts.NAME); } } }
Java
package org.dodgybits.shuffle.android.persistence.provider; import android.content.ContentValues; import android.net.Uri; import android.provider.BaseColumns; public class TaskProvider extends AbstractCollectionProvider { public static final String TASK_TABLE_NAME = "task"; public static final String UPDATE_INTENT = "org.dodgybits.shuffle.android.TASK_UPDATE"; private static final String URL_COLLECTION_NAME = "tasks"; public TaskProvider() { super( AUTHORITY, // authority URL_COLLECTION_NAME, // collectionNamePlural TASK_TABLE_NAME, // tableName UPDATE_INTENT, // update intent action Tasks.DESCRIPTION, // primary key BaseColumns._ID, // id field Tasks.CONTENT_URI, // content URI BaseColumns._ID, // fields... Tasks.DESCRIPTION, Tasks.DETAILS, Tasks.CONTEXT_ID, Tasks.PROJECT_ID, Tasks.CREATED_DATE, Tasks.START_DATE, Tasks.DUE_DATE, Tasks.TIMEZONE, Tasks.CAL_EVENT_ID, Tasks.DISPLAY_ORDER, Tasks.COMPLETE, Tasks.ALL_DAY, Tasks.HAS_ALARM, ShuffleTable.TRACKS_ID, ShuffleTable.MODIFIED_DATE, ShuffleTable.DELETED, ShuffleTable.ACTIVE ); makeSearchable(Tasks._ID, Tasks.DESCRIPTION, Tasks.DETAILS, Tasks.DESCRIPTION, Tasks.DETAILS); elementInserters.put(COLLECTION_MATCH_ID, new TaskInserter()); setDefaultSortOrder(Tasks.DEFAULT_SORT_ORDER); } public static final String AUTHORITY = Shuffle.PACKAGE + ".taskprovider"; /** * Tasks table */ public static final class Tasks implements ShuffleTable { /** * The content:// style URL for this table */ public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY+"/tasks"); /** * The default sort order for this table */ public static final String DEFAULT_SORT_ORDER = "due ASC, created ASC"; public static final String DESCRIPTION = "description"; public static final String DETAILS = "details"; public static final String CONTEXT_ID = "contextId"; public static final String PROJECT_ID = "projectId"; public static final String CREATED_DATE = "created"; public static final String START_DATE = "start"; public static final String DUE_DATE = "due"; public static final String TIMEZONE = "timezone"; public static final String CAL_EVENT_ID = "calEventId"; public static final String DISPLAY_ORDER = "displayOrder"; public static final String COMPLETE = "complete"; public static final String ALL_DAY = "allDay"; public static final String HAS_ALARM = "hasAlarm"; /** * Projection for all the columns of a task. */ public static final String[] FULL_PROJECTION = new String[] { _ID, DESCRIPTION, DETAILS, PROJECT_ID, CONTEXT_ID, CREATED_DATE, MODIFIED_DATE, START_DATE, DUE_DATE, TIMEZONE, CAL_EVENT_ID, DISPLAY_ORDER, COMPLETE, ALL_DAY, HAS_ALARM, TRACKS_ID, DELETED, ACTIVE }; } private class TaskInserter extends ElementInserterImpl { public TaskInserter() { super(Tasks.DESCRIPTION); } @Override protected void addDefaultValues(ContentValues values) { super.addDefaultValues(values); // Make sure that the fields are all set Long now = System.currentTimeMillis(); if (!values.containsKey(Tasks.CREATED_DATE)) { values.put(Tasks.CREATED_DATE, now); } if (!values.containsKey(Tasks.DETAILS)) { values.put(Tasks.DETAILS, ""); } if (!values.containsKey(Tasks.DISPLAY_ORDER)) { values.put(Tasks.DISPLAY_ORDER, 0); } if (!values.containsKey(Tasks.COMPLETE)) { values.put(Tasks.COMPLETE, 0); } } } }
Java
/** * */ package org.dodgybits.shuffle.android.persistence.provider; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import org.dodgybits.shuffle.android.persistence.migrations.*; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; class DatabaseHelper extends SQLiteOpenHelper { private static final SortedMap<Integer, Migration> ALL_MIGRATIONS = new TreeMap<Integer, Migration>(); static { ALL_MIGRATIONS.put(1, new V1Migration()); ALL_MIGRATIONS.put(9, new V9Migration()); ALL_MIGRATIONS.put(10, new V10Migration()); ALL_MIGRATIONS.put(11, new V11Migration()); ALL_MIGRATIONS.put(12, new V12Migration()); ALL_MIGRATIONS.put(13, new V13Migration()); ALL_MIGRATIONS.put(14, new V14Migration()); ALL_MIGRATIONS.put(15, new V15Migration()); ALL_MIGRATIONS.put(16, new V16Migration()); } DatabaseHelper(Context context) { super(context, AbstractCollectionProvider.cDatabaseName, null, AbstractCollectionProvider.cDatabaseVersion); } @Override public void onCreate(SQLiteDatabase db) { Log.i(AbstractCollectionProvider.cTag, "Creating shuffle DB"); executeMigrations(db, ALL_MIGRATIONS.keySet()); } private void executeMigrations(SQLiteDatabase db, Set<Integer> migrationVersions) { for (Integer version : migrationVersions) { Log.i(AbstractCollectionProvider.cTag, "Migrating to version " + version); ALL_MIGRATIONS.get(version).migrate(db); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.i(AbstractCollectionProvider.cTag, "Upgrading database from version " + oldVersion + " to " + newVersion); SortedMap<Integer, Migration> migrations = ALL_MIGRATIONS.subMap(oldVersion, newVersion); executeMigrations(db, migrations.keySet()); } }
Java
package org.dodgybits.shuffle.android.persistence.provider; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import android.app.SearchManager; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.Intent; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.provider.BaseColumns; import android.text.TextUtils; import android.util.Log; public abstract class AbstractCollectionProvider extends ContentProvider { public static final String cDatabaseName = "shuffle.db"; static final int cDatabaseVersion = 17; public static final String cTag = "ShuffleProvider"; public static interface ShuffleTable extends BaseColumns { static final String CONTENT_TYPE_PATH = "vnd.dodgybits"; static final String CONTENT_TYPE_PRE_PREFIX = "vnd.android.cursor.dir/"; static final String CONTENT_ITEM_TYPE_PRE_PREFIX = "vnd.android.cursor.item/"; static final String CONTENT_TYPE_PREFIX = CONTENT_TYPE_PRE_PREFIX+CONTENT_TYPE_PATH; static final String CONTENT_ITEM_TYPE_PREFIX = CONTENT_ITEM_TYPE_PRE_PREFIX+CONTENT_TYPE_PATH; public static final String MODIFIED_DATE = "modified"; public static final String TRACKS_ID = "tracks_id"; public static final String DELETED = "deleted"; public static final String ACTIVE = "active"; } protected static final int SEARCH = 3; protected static final int COLLECTION_MATCH_ID = 1; protected static final int ELEMENT_MATCH_ID = 2; protected static Map<String, String> createSuggestionsMap(String idField, String column1Field, String column2Field) { HashMap<String, String> sSuggestionProjectionMap = new HashMap<String, String>(); sSuggestionProjectionMap.put(SearchManager.SUGGEST_COLUMN_TEXT_1, column1Field + " AS " + SearchManager.SUGGEST_COLUMN_TEXT_1); sSuggestionProjectionMap.put(SearchManager.SUGGEST_COLUMN_TEXT_2, column2Field + " AS " + SearchManager.SUGGEST_COLUMN_TEXT_2); sSuggestionProjectionMap.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID, idField + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID); sSuggestionProjectionMap.put(idField, idField); return sSuggestionProjectionMap; } protected static Map<String, String> createTableMap(String tableName, String... fieldNames) { HashMap<String, String> fieldNameMap = new HashMap<String, String>(); for (String fieldName : fieldNames) { fieldNameMap.put(fieldName, tableName + "."+fieldName); } return fieldNameMap; } private final String authority; protected DatabaseHelper mOpenHelper; protected Map<String, String> suggestionProjectionMap; protected final Map<Integer, RestrictionBuilder> restrictionBuilders; protected final Map<Integer, GroupByBuilder> groupByBuilders; protected final Map<Integer, CollectionUpdater> collectionUpdaters; protected final Map<Integer, ElementInserter> elementInserters; protected final Map<Integer, ElementDeleter> elementDeleters; private final String tableName; private final String updateIntentAction; private final Map<String, String> elementsMap; protected final Map<Integer,String> mimeTypes; protected final Uri contentUri; private String defaultSortOrder = null; protected void setDefaultSortOrder(String defaultSortOrder) { this.defaultSortOrder = defaultSortOrder; } protected String getTableName() { return tableName; } protected Map<String,String> getElementsMap() { return elementsMap; } private void notifyOnChange(Uri uri) { getContext().getContentResolver().notifyChange(uri, null); getContext().sendBroadcast(new Intent(updateIntentAction)); } public static interface RestrictionBuilder { void addRestrictions(Uri uri, SQLiteQueryBuilder qb); } private class EntireCollectionRestrictionBuilder implements RestrictionBuilder { @Override public void addRestrictions(Uri uri, SQLiteQueryBuilder qb) { qb.setTables(getTableName()); qb.setProjectionMap(getElementsMap()); } } private class ElementByIdRestrictionBuilder implements RestrictionBuilder { @Override public void addRestrictions(Uri uri, SQLiteQueryBuilder qb) { qb.setTables(getTableName()); qb.appendWhere("_id=" + uri.getPathSegments().get(1)); } } private class SearchRestrictionBuilder implements RestrictionBuilder { private final String[] searchFields; public SearchRestrictionBuilder(String[] searchFields) { super(); this.searchFields = searchFields; } @Override public void addRestrictions(Uri uri, SQLiteQueryBuilder qb) { qb.setTables(getTableName()); String query = uri.getLastPathSegment(); if (!TextUtils.isEmpty(query)) { for (int i = 0; i < searchFields.length; i++) { String field = searchFields[i]; qb.appendWhere(field + " LIKE "); qb.appendWhereEscapeString('%' + query + '%'); if (i < searchFields.length - 1) qb.appendWhere(" OR "); } } qb.setProjectionMap(suggestionProjectionMap); } } protected class CustomElementFilterRestrictionBuilder implements RestrictionBuilder { private final String tables; private final String restrictions; private final String idField; public CustomElementFilterRestrictionBuilder(String tables, String restrictions, String idField) { super(); this.tables = tables; this.restrictions = restrictions; this.idField = idField; } @Override public void addRestrictions(Uri uri, SQLiteQueryBuilder qb) { Map<String, String> projectionMap = new HashMap<String, String>(); projectionMap.put("_id", idField); projectionMap.put("count", "count(*)"); qb.setProjectionMap(projectionMap); qb.setTables(tables); qb.appendWhere(restrictions); } } public static interface GroupByBuilder { String getGroupBy(Uri uri); } protected class StandardGroupByBuilder implements GroupByBuilder { private String mGroupBy; public StandardGroupByBuilder(String groupBy) { mGroupBy = groupBy; } @Override public String getGroupBy(Uri uri) { return mGroupBy; } } protected final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); public AbstractCollectionProvider(String authority, String collectionNamePlural, String tableName, String updateIntentAction, String primaryKey, String idField,Uri contentUri, String... fields) { this.authority = authority; this.contentUri = contentUri; registerCollectionUrls(collectionNamePlural); this.restrictionBuilders = new HashMap<Integer, RestrictionBuilder>(); this.restrictionBuilders.put(COLLECTION_MATCH_ID, new EntireCollectionRestrictionBuilder()); this.restrictionBuilders.put(ELEMENT_MATCH_ID, new ElementByIdRestrictionBuilder()); this.tableName = tableName; this.updateIntentAction = updateIntentAction; this.elementsMap = createTableMap(tableName, fields); this.mimeTypes = new HashMap<Integer, String>(); this.mimeTypes.put(COLLECTION_MATCH_ID, getContentType()); this.mimeTypes.put(ELEMENT_MATCH_ID, getContentItemType()); this.collectionUpdaters = new HashMap<Integer, CollectionUpdater>(); this.collectionUpdaters.put(COLLECTION_MATCH_ID, new EntireCollectionUpdater()); this.collectionUpdaters.put(ELEMENT_MATCH_ID, new SingleElementUpdater()); this.elementInserters = new HashMap<Integer, ElementInserter>(); this.elementInserters.put(COLLECTION_MATCH_ID, new ElementInserterImpl(primaryKey)); this.elementDeleters = new HashMap<Integer, ElementDeleter>(); this.elementDeleters.put(COLLECTION_MATCH_ID, new EntireCollectionDeleter()); this.elementDeleters.put(ELEMENT_MATCH_ID, new ElementDeleterImpl(idField)); this.groupByBuilders = new HashMap<Integer, GroupByBuilder>(); } @Override public String getType(Uri uri) { String mimeType = mimeTypes.get(match(uri)); if (mimeType == null) throw new IllegalArgumentException("Unknown Uri " + uri); return mimeType; } SQLiteQueryBuilder createQueryBuilder() { return new SQLiteQueryBuilder(); } @Override public int delete(Uri uri, String where, String[] whereArgs) { SQLiteDatabase db = getWriteableDatabase(); int count = doDelete(uri, where, whereArgs, db); notifyOnChange(uri); return count; } SQLiteDatabase getReadableDatabase() { return mOpenHelper.getReadableDatabase(); } protected String getSortOrder(Uri uri, String sort) { if (defaultSortOrder != null && TextUtils.isEmpty(sort)) { return defaultSortOrder; } return sort; } protected SQLiteDatabase getWriteableDatabase() { return mOpenHelper.getWritableDatabase(); } @Override public Uri insert(Uri url, ContentValues initialValues) { ContentValues values; if (initialValues != null) { values = new ContentValues(initialValues); } else { values = new ContentValues(); } SQLiteDatabase db = getWriteableDatabase(); return doInsert(url, values, db); } protected void makeSearchable(String idField, String descriptionField, String detailsField, String...searchFields) { uriMatcher.addURI(authority, SearchManager.SUGGEST_URI_PATH_QUERY, SEARCH); uriMatcher.addURI(authority, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", SEARCH); suggestionProjectionMap = createSuggestionsMap(idField,descriptionField,detailsField); restrictionBuilders.put(SEARCH, new SearchRestrictionBuilder(searchFields)); } public int match(Uri uri) { return uriMatcher.match(uri); } @Override public boolean onCreate() { Log.i(cTag, "+onCreate"); mOpenHelper = new DatabaseHelper(getContext()); return true; } protected int doUpdate(Uri uri, ContentValues values, String where, String[] whereArgs, SQLiteDatabase db) { CollectionUpdater updater = collectionUpdaters.get(match(uri)); if (updater == null) throw new IllegalArgumentException("Unknown URL " + uri); return updater.update(uri, values, where, whereArgs, db); } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sort) { SQLiteQueryBuilder qb = createQueryBuilder(); SQLiteDatabase db = getReadableDatabase(); addRestrictions(uri, qb); String orderBy = getSortOrder(uri, sort); String groupBy = getGroupBy(uri); if (Log.isLoggable(cTag, Log.DEBUG)) { Log.d(cTag, "Executing " + selection + " with args " + Arrays.toString(selectionArgs) + " ORDER BY " + orderBy); } Cursor c = qb.query(db, projection, selection, selectionArgs, groupBy, null, orderBy); c.setNotificationUri(getContext().getContentResolver(), uri); return c; } protected String getGroupBy(Uri uri) { String groupBy = null; GroupByBuilder builder = groupByBuilders.get(match(uri)); if (builder != null) { groupBy = builder.getGroupBy(uri); } return groupBy; } protected void registerCollectionUrls(String collectionName) { uriMatcher.addURI(authority, collectionName, COLLECTION_MATCH_ID); uriMatcher.addURI(authority, collectionName+"/#", ELEMENT_MATCH_ID); } protected String getContentType() { return ShuffleTable.CONTENT_TYPE_PREFIX+"."+getTableName(); } public String getContentItemType() { return ShuffleTable.CONTENT_ITEM_TYPE_PREFIX+"."+getTableName(); } @Override public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { int count = 0; SQLiteDatabase db = getWriteableDatabase(); count = doUpdate(uri, values, where, whereArgs, db); notifyOnChange(uri); return count; } protected void addRestrictions(Uri uri, SQLiteQueryBuilder qb) { RestrictionBuilder restrictionBuilder = restrictionBuilders.get(match(uri)); if (restrictionBuilder == null) throw new IllegalArgumentException("Unknown URL " + uri); restrictionBuilder.addRestrictions(uri, qb); } public interface CollectionUpdater { int update(Uri uri, ContentValues values, String where, String[] whereArgs, SQLiteDatabase db); } private class EntireCollectionUpdater implements CollectionUpdater { @Override public int update(Uri uri, ContentValues values, String where, String[] whereArgs, SQLiteDatabase db) { return db.update(getTableName(), values, where, whereArgs); } } private class SingleElementUpdater implements CollectionUpdater { @Override public int update(Uri uri, ContentValues values, String where, String[] whereArgs, SQLiteDatabase db) { String segment = uri.getPathSegments().get(1); return db.update(getTableName(), values, "_id=" + segment + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs); } } public interface ElementInserter { Uri insert(Uri url, ContentValues values, SQLiteDatabase db); } protected class ElementInserterImpl implements ElementInserter { private final String primaryKey; public ElementInserterImpl(String primaryKey) { super(); this.primaryKey = primaryKey; } @Override public Uri insert(Uri url, ContentValues values, SQLiteDatabase db) { addDefaultValues(values); long rowID = db.insert(getTableName(), getElementsMap() .get(primaryKey), values); if (rowID > 0) { Uri uri = ContentUris.withAppendedId(contentUri, rowID); notifyOnChange(uri); return uri; } throw new SQLException("Failed to insert row into " + url); } protected void addDefaultValues(ContentValues values) { Long now = System.currentTimeMillis(); if (!values.containsKey(ShuffleTable.MODIFIED_DATE)) { values.put(ShuffleTable.MODIFIED_DATE, now); } if (!values.containsKey(ShuffleTable.DELETED)) { values.put(ShuffleTable.DELETED, 0); } if (!values.containsKey(ShuffleTable.ACTIVE)) { values.put(ShuffleTable.ACTIVE, 1); } if (!values.containsKey(primaryKey)) { values.put(primaryKey, ""); } } } protected Uri doInsert(Uri url, ContentValues values, SQLiteDatabase db) { ElementInserter elementInserter = elementInserters.get(match(url)); if (elementInserter == null) throw new IllegalArgumentException("Unknown URL " + url); return elementInserter.insert(url, values, db); } public static interface ElementDeleter { int delete(Uri uri, String where, String[] whereArgs, SQLiteDatabase db); } private class ElementDeleterImpl implements ElementDeleter { private final String idField; public ElementDeleterImpl(String idField) { super(); this.idField = idField; } @Override public int delete(Uri uri, String where, String[] whereArgs, SQLiteDatabase db) { String id = uri.getPathSegments().get(1); int rowsUpdated = db.delete(getTableName(), idField + "=" + id + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs); notifyOnChange(uri); return rowsUpdated; } } private class EntireCollectionDeleter implements ElementDeleter { @Override public int delete(Uri uri, String where, String[] whereArgs, SQLiteDatabase db) { int rowsUpdated = db.delete(getTableName(), where, whereArgs); notifyOnChange(uri); return rowsUpdated; } } protected int doDelete(Uri uri, String where, String[] whereArgs, SQLiteDatabase db) { ElementDeleter elementDeleter = elementDeleters.get(match(uri)); if (elementDeleter == null) throw new IllegalArgumentException("Unknown uri " + uri); return elementDeleter.delete(uri, where, whereArgs, db); } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.persistence.provider; public class Shuffle { public static final String PACKAGE = "org.dodgybits.android.shuffle.provider"; }
Java
package org.dodgybits.shuffle.android.persistence.provider; import android.net.Uri; import android.provider.BaseColumns; public class ProjectProvider extends AbstractCollectionProvider { public static final String PROJECT_TABLE_NAME = "project"; public static final String UPDATE_INTENT = "org.dodgybits.shuffle.android.PROJECT_UPDATE"; private static final String AUTHORITY = Shuffle.PACKAGE+".projectprovider"; static final int PROJECT_TASKS = 203; private static final String URL_COLLECTION_NAME = "projects"; public ProjectProvider() { super( AUTHORITY, // authority URL_COLLECTION_NAME, // collectionNamePlural PROJECT_TABLE_NAME, // tableName UPDATE_INTENT, // update intent action Projects.NAME, // primary key BaseColumns._ID, // id field Projects.CONTENT_URI,// content URI BaseColumns._ID, // fields... Projects.NAME, Projects.DEFAULT_CONTEXT_ID, Projects.PARALLEL, Projects.ARCHIVED, ShuffleTable.TRACKS_ID, ShuffleTable.MODIFIED_DATE, ShuffleTable.DELETED, ShuffleTable.ACTIVE ); makeSearchable(Projects._ID, Projects.NAME, Projects.NAME, Projects.NAME); uriMatcher.addURI(AUTHORITY, "projectTasks", PROJECT_TASKS); String idField = "project._id"; String tables = "project, task"; String restrictions = "task.projectId = project._id"; restrictionBuilders.put(PROJECT_TASKS, new CustomElementFilterRestrictionBuilder( tables, restrictions, idField)); groupByBuilders.put(PROJECT_TASKS, new StandardGroupByBuilder("project._id")); elementInserters.put(COLLECTION_MATCH_ID, new ProjectInserter()); setDefaultSortOrder(Projects.DEFAULT_SORT_ORDER); } /** * Projects table */ public static final class Projects implements ShuffleTable { public static final String ARCHIVED = "archived"; /** * The content:// style URL for this table */ public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + URL_COLLECTION_NAME); public static final Uri PROJECT_TASKS_CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/projectTasks"); public static final String DEFAULT_CONTEXT_ID = "defaultContextId"; /** * The default sort order for this table */ public static final String DEFAULT_SORT_ORDER = "name DESC"; public static final String NAME = "name"; public static final String PARALLEL = "parallel"; public static final String TASK_COUNT = "count"; /** * Projection for all the columns of a project. */ public static final String[] FULL_PROJECTION = new String[] { _ID, NAME, DEFAULT_CONTEXT_ID, TRACKS_ID, MODIFIED_DATE, PARALLEL, ARCHIVED, DELETED, ACTIVE }; /** * Projection for fetching the task count for each project. */ public static final String[] FULL_TASK_PROJECTION = new String[] { _ID, TASK_COUNT, }; } private class ProjectInserter extends ElementInserterImpl { public ProjectInserter() { super(Projects.NAME); } } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.persistence; import java.util.Arrays; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.util.Log; import android.widget.SimpleCursorAdapter; /** * A database cursor adaptor that can be used for an AutoCompleteTextField. * */ public class AutoCompleteCursorAdapter extends SimpleCursorAdapter { private static final String cTag = "AutoCompleteCursorAdapter"; private Context mContext; private String[] mProjection; private Uri mContentUri; public AutoCompleteCursorAdapter(Context context, Cursor c, String[] from, Uri contentUri) { super(context, android.R.layout.simple_list_item_1, c, from, new int[] { android.R.id.text1 }); mContext = context; mProjection = from; mContentUri = contentUri; } @Override public Cursor runQueryOnBackgroundThread(CharSequence constraint) { if (constraint == null || constraint.length() == 0) { return super.runQueryOnBackgroundThread(constraint); } StringBuilder buffer = null; String[] args = null; if (constraint != null) { buffer = new StringBuilder(); buffer.append(mProjection[0]); buffer.append(" LIKE ?"); args = new String[] { '%' + constraint.toString() + '%'}; } String query = buffer.toString(); Log.d(cTag, "Query '" + query + "' with params: " + Arrays.asList(args)); return mContext.getContentResolver().query(mContentUri, mProjection, query, args, null); } @Override public CharSequence convertToString(Cursor cursor) { // assuming name is first entry in cursor.... return cursor.getString(0); } }
Java
package org.dodgybits.shuffle.android.widget; import android.appwidget.AppWidgetManager; import android.content.Context; import android.content.Intent; import android.os.Bundle; public class RoboAppWidgetProvider extends RoboBroadcastReceiver { @Override protected void handleReceive(Context context, Intent intent) { // Protect against rogue update broadcasts (not really a security issue, // just filter bad broadcasts out so subclasses are less likely to crash). String action = intent.getAction(); if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) { Bundle extras = intent.getExtras(); if (extras != null) { int[] appWidgetIds = extras.getIntArray(AppWidgetManager.EXTRA_APPWIDGET_IDS); if (appWidgetIds != null && appWidgetIds.length > 0) { this.onUpdate(context, AppWidgetManager.getInstance(context), appWidgetIds); } } } else if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) { Bundle extras = intent.getExtras(); if (extras != null && extras.containsKey(AppWidgetManager.EXTRA_APPWIDGET_ID)) { final int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID); this.onDeleted(context, new int[] { appWidgetId }); } } else if (AppWidgetManager.ACTION_APPWIDGET_ENABLED.equals(action)) { this.onEnabled(context); } else if (AppWidgetManager.ACTION_APPWIDGET_DISABLED.equals(action)) { this.onDisabled(context); } } /** * Called in response to the {@link AppWidgetManager#ACTION_APPWIDGET_UPDATE} broadcast when * this AppWidget provider is being asked to provide {@link android.widget.RemoteViews RemoteViews} * for a set of AppWidgets. Override this method to implement your own AppWidget functionality. * * {@more} * * @param context The {@link android.content.Context Context} in which this receiver is * running. * @param appWidgetManager A {@link AppWidgetManager} object you can call {@link * AppWidgetManager#updateAppWidget} on. * @param appWidgetIds The appWidgetIds for which an update is needed. Note that this * may be all of the AppWidget instances for this provider, or just * a subset of them. * * @see AppWidgetManager#ACTION_APPWIDGET_UPDATE */ public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { } /** * Called in response to the {@link AppWidgetManager#ACTION_APPWIDGET_DELETED} broadcast when * one or more AppWidget instances have been deleted. Override this method to implement * your own AppWidget functionality. * * {@more} * * @param context The {@link android.content.Context Context} in which this receiver is * running. * @param appWidgetIds The appWidgetIds that have been deleted from their host. * * @see AppWidgetManager#ACTION_APPWIDGET_DELETED */ public void onDeleted(Context context, int[] appWidgetIds) { } /** * Called in response to the {@link AppWidgetManager#ACTION_APPWIDGET_ENABLED} broadcast when * the a AppWidget for this provider is instantiated. Override this method to implement your * own AppWidget functionality. * * {@more} * When the last AppWidget for this provider is deleted, * {@link AppWidgetManager#ACTION_APPWIDGET_DISABLED} is sent by the AppWidget manager, and * {@link #onDisabled} is called. If after that, an AppWidget for this provider is created * again, onEnabled() will be called again. * * @param context The {@link android.content.Context Context} in which this receiver is * running. * * @see AppWidgetManager#ACTION_APPWIDGET_ENABLED */ public void onEnabled(Context context) { } /** * Called in response to the {@link AppWidgetManager#ACTION_APPWIDGET_DISABLED} broadcast, which * is sent when the last AppWidget instance for this provider is deleted. Override this method * to implement your own AppWidget functionality. * * {@more} * * @param context The {@link android.content.Context Context} in which this receiver is * running. * * @see AppWidgetManager#ACTION_APPWIDGET_DISABLED */ public void onDisabled(Context context) { } }
Java
/* * Copyright (C) 2008 The Android 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.widget; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.view.ContextIcon; import roboguice.inject.ContextSingleton; import android.view.View; import android.widget.RemoteViews; @ContextSingleton /** * A widget provider. We have a string that we pull from a preference in order to show * the configuration settings and the current time when the widget was updated. We also * register a BroadcastReceiver for time-changed and timezone-changed broadcasts, and * update then too. */ public class LightWidgetProvider extends AbstractWidgetProvider { @Override protected int getWidgetLayoutId() { return R.layout.widget; } @Override protected int getTotalEntries() { return 4; } @Override protected int updateContext(android.content.Context androidContext, RemoteViews views, Context context, int taskCount) { int contextIconId = getIdIdentifier(androidContext, "context_icon_" + taskCount); String iconName = context != null ? context.getIconName() : null; ContextIcon icon = ContextIcon.createIcon(iconName, androidContext.getResources()); if (icon != ContextIcon.NONE) { views.setImageViewResource(contextIconId, icon.smallIconId); views.setViewVisibility(contextIconId, View.VISIBLE); } else { views.setViewVisibility(contextIconId, View.INVISIBLE); } return contextIconId; } }
Java
/* * Copyright (C) 2008 The Android 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.widget; import java.util.HashMap; 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.DrawableUtils; import org.dodgybits.shuffle.android.list.config.StandardTaskQueries; import roboguice.inject.ContextSingleton; import android.app.PendingIntent; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.GradientDrawable.Orientation; import android.widget.RelativeLayout; import android.widget.RemoteViews; @ContextSingleton /** * A widget provider. We have a string that we pull from a preference in order to show * the configuration settings and the current time when the widget was updated. We also * register a BroadcastReceiver for time-changed and timezone-changed broadcasts, and * update then too. */ public class DarkWidgetProvider extends AbstractWidgetProvider { private static final Bitmap sEmptyBitmap = Bitmap.createBitmap(8, 40, Bitmap.Config.ARGB_8888); private HashMap<Integer, Bitmap> mGradientCache; private TextColours mColours; @Override protected int getWidgetLayoutId() { return R.layout.widget_dark; } @Override protected int getTotalEntries() { return 7; } @Override public void handleReceive(android.content.Context context, Intent intent) { mColours = TextColours.getInstance(context); mGradientCache = new HashMap<Integer, Bitmap>(mColours.getNumColours()); super.handleReceive(context, intent); } @Override protected void setupFrameClickIntents(android.content.Context androidContext, RemoteViews views, String queryName){ super.setupFrameClickIntents(androidContext, views, queryName); Intent intent = StandardTaskQueries.getActivityIntent(androidContext, queryName); PendingIntent pendingIntent = PendingIntent.getActivity(androidContext, 0, intent, 0); views.setOnClickPendingIntent(R.id.all_tasks, pendingIntent); } @Override protected int updateContext(android.content.Context androidContext, RemoteViews views, Context context, int taskCount) { Bitmap gradientBitmap = null; if (context != null) { int colourIndex = context.getColourIndex(); gradientBitmap = mGradientCache.get(colourIndex); if (gradientBitmap == null) { int colour = mColours.getBackgroundColour(colourIndex); GradientDrawable drawable = DrawableUtils.createGradient(colour, Orientation.TOP_BOTTOM); drawable.setCornerRadius(6.0f); Bitmap bitmap = Bitmap.createBitmap(16, 80, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); RelativeLayout l = new RelativeLayout(androidContext); l.setBackgroundDrawable(drawable); l.layout(0, 0, 16, 80); l.draw(canvas); gradientBitmap = Bitmap.createBitmap(bitmap, 6, 0, 10, 80); mGradientCache.put(colourIndex, gradientBitmap); } } views.setImageViewBitmap(getIdIdentifier(androidContext, "contextColour_" + taskCount), gradientBitmap == null ? sEmptyBitmap : gradientBitmap); return 0; } }
Java
package org.dodgybits.shuffle.android.widget; import java.util.ArrayList; import java.util.List; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.view.IconArrayAdapter; import org.dodgybits.shuffle.android.list.config.StandardTaskQueries; import org.dodgybits.shuffle.android.preference.model.Preferences; import roboguice.activity.RoboListActivity; import roboguice.util.Ln; import android.appwidget.AppWidgetManager; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; /** * The configuration screen for the DarkWidgetProvider widget. */ public class WidgetConfigure extends RoboListActivity { private static final int NEXT_TASKS = 0; private static final int DUE_TODAY = 1; private static final int DUE_NEXT_WEEK = 2; private static final int DUE_NEXT_MONTH = 3; private static final int INBOX = 4; private static final int TICKLER = 5; private int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID; private List<String> mLabels; public WidgetConfigure() { super(); } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); // Set the result to CANCELED. This will cause the widget host to cancel // out of the widget placement if they press the back button. setResult(RESULT_CANCELED); setContentView(R.layout.launcher_shortcut); setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); // Find the widget id from the intent. final Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras != null) { mAppWidgetId = extras.getInt( AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); } // If they gave us an intent without the widget id, just bail. if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) { finish(); } mLabels = new ArrayList<String>(); // TODO figure out a non-retarded way of added padding between text and icon mLabels.add(" " + getString(R.string.title_next_tasks)); mLabels.add(" " + getString(R.string.title_due_today)); mLabels.add(" " + getString(R.string.title_due_next_week)); mLabels.add(" " + getString(R.string.title_due_next_month)); mLabels.add(" " + getString(R.string.title_inbox)); mLabels.add(" " + getString(R.string.title_tickler)); setTitle(R.string.title_widget_picker); Integer[] iconIds = new Integer[6]; iconIds[NEXT_TASKS] = R.drawable.next_actions; iconIds[DUE_TODAY] = R.drawable.due_actions; iconIds[DUE_NEXT_WEEK] = R.drawable.due_actions; iconIds[DUE_NEXT_MONTH] = R.drawable.due_actions; iconIds[INBOX] = R.drawable.inbox; iconIds[TICKLER] = R.drawable.ic_media_pause; 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) { String key = Preferences.getWidgetQueryKey(mAppWidgetId); String queryName = queryValue(position); Preferences.getEditor(this).putString(key, queryName).commit(); Ln.d("Saving query %s under key %s", queryName, key); // let widget update itself (suggested approach of calling updateAppWidget did nothing) Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] {mAppWidgetId}); intent.setPackage(getPackageName()); sendBroadcast(intent); // Make sure we pass back the original appWidgetId Intent resultValue = new Intent(); resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId); setResult(RESULT_OK, resultValue); finish(); } private String queryValue(int position) { String result = null; switch (position) { case INBOX: result = StandardTaskQueries.cInbox; break; case NEXT_TASKS: result = StandardTaskQueries.cNextTasks; break; case DUE_TODAY: result = StandardTaskQueries.cDueToday; break; case DUE_NEXT_WEEK: result = StandardTaskQueries.cDueNextWeek; break; case DUE_NEXT_MONTH: result = StandardTaskQueries.cDueNextMonth; break; case TICKLER: result = StandardTaskQueries.cTickler; break; } return result; } }
Java
package org.dodgybits.shuffle.android.widget; import static org.dodgybits.shuffle.android.core.util.Constants.cIdType; import static org.dodgybits.shuffle.android.core.util.Constants.cPackage; import static org.dodgybits.shuffle.android.core.util.Constants.cStringType; import java.util.Arrays; import java.util.HashMap; 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.ContextPersister; import org.dodgybits.shuffle.android.core.model.persistence.EntityCache; 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.TaskSelector; import org.dodgybits.shuffle.android.list.config.StandardTaskQueries; 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.model.ListPreferenceSettings; import org.dodgybits.shuffle.android.preference.model.Preferences; import roboguice.util.Ln; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.ContentUris; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.view.View; import android.widget.RemoteViews; import com.google.inject.Inject; public abstract class AbstractWidgetProvider extends RoboAppWidgetProvider { private static final HashMap<String,Integer> sIdCache = new HashMap<String,Integer>(); @Inject TaskPersister mTaskPersister; @Inject ProjectPersister mProjectPersister; @Inject EntityCache<Project> mProjectCache; @Inject ContextPersister mContextPersister; @Inject EntityCache<Context> mContextCache; @Override public void handleReceive(android.content.Context context, Intent intent) { super.handleReceive(context, intent); String action = intent.getAction(); if (TaskProvider.UPDATE_INTENT.equals(action) || ProjectProvider.UPDATE_INTENT.equals(action) || ContextProvider.UPDATE_INTENT.equals(action) || Preferences.CLEAN_INBOX_INTENT.equals(action) || ListPreferenceSettings.LIST_PREFERENCES_UPDATED.equals(action)) { AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); // Retrieve the identifiers for each instance of your chosen widget. ComponentName thisWidget = new ComponentName(context, getClass()); int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget); if (appWidgetIds != null && appWidgetIds.length > 0) { this.onUpdate(context, appWidgetManager, appWidgetIds); } } } @Override public void onUpdate(android.content.Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { Ln.d("onUpdate"); ComponentName thisWidget = new ComponentName(context, getClass()); int[] localAppWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget); Arrays.sort(localAppWidgetIds); final int N = appWidgetIds.length; for (int i=0; i<N; i++) { int appWidgetId = appWidgetIds[i]; if (Arrays.binarySearch(localAppWidgetIds, appWidgetId) >= 0) { String prefKey = Preferences.getWidgetQueryKey(appWidgetId); String queryName = Preferences.getWidgetQuery(context, prefKey); Ln.d("App widget %s found query %s for key %s", appWidgetId, queryName, prefKey); updateAppWidget(context, appWidgetManager, appWidgetId, queryName); } else { Ln.d("App widget %s not handled by this provider %s", appWidgetId, getClass()); } } } @Override public void onDeleted(android.content.Context context, int[] appWidgetIds) { Ln.d("onDeleted"); // When the user deletes the widget, delete the preference associated with it. final int N = appWidgetIds.length; SharedPreferences.Editor editor = Preferences.getEditor(context); for (int i=0; i<N; i++) { String prefKey = Preferences.getWidgetQueryKey(appWidgetIds[i]); editor.remove(prefKey); } editor.commit(); } @Override public void onEnabled(android.content.Context context) { } @Override public void onDisabled(android.content.Context context) { } private void updateAppWidget(final android.content.Context androidContext, AppWidgetManager appWidgetManager, int appWidgetId, String queryName) { Ln.d("updateAppWidget appWidgetId=%s queryName=%s provider=%s", appWidgetId, queryName, getClass()); RemoteViews views = new RemoteViews(androidContext.getPackageName(), getWidgetLayoutId()); Cursor taskCursor = createCursor(androidContext, queryName); if (taskCursor == null) return; int titleId = getIdentifier(androidContext, "title_" + queryName, cStringType); views.setTextViewText(R.id.title, androidContext.getString(titleId) + " (" + taskCursor.getCount() + ")"); setupFrameClickIntents(androidContext, views, queryName); int totalEntries = getTotalEntries(); for (int taskCount = 1; taskCount <= totalEntries; taskCount++) { Task task = null; Project project = null; Context context = null; if (taskCursor.moveToNext()) { task = mTaskPersister.read(taskCursor); project = mProjectCache.findById(task.getProjectId()); context = mContextCache.findById(task.getContextId()); } int descriptionViewId = updateDescription(androidContext, views, task, taskCount); int projectViewId = updateProject(androidContext, views, project, taskCount); int contextIconId = updateContext(androidContext, views, context, taskCount); if (task != null) { Uri.Builder builder = TaskProvider.Tasks.CONTENT_URI.buildUpon(); ContentUris.appendId(builder, task.getLocalId().getId()); Uri taskUri = builder.build(); Intent intent = new Intent(Intent.ACTION_VIEW, taskUri); Ln.d("Adding pending event for viewing uri %s", taskUri); int entryId = getIdIdentifier(androidContext, "entry_" + taskCount); PendingIntent pendingIntent = PendingIntent.getActivity(androidContext, 0, intent, 0); views.setOnClickPendingIntent(entryId, pendingIntent); views.setOnClickPendingIntent(descriptionViewId, pendingIntent); views.setOnClickPendingIntent(projectViewId, pendingIntent); if (contextIconId != 0) { views.setOnClickPendingIntent(contextIconId, pendingIntent); } } } taskCursor.close(); appWidgetManager.updateAppWidget(appWidgetId, views); } protected Cursor createCursor(android.content.Context androidContext, String queryName) { TaskSelector query = StandardTaskQueries.getQuery(queryName); if (query == null) return null; String key = StandardTaskQueries.getFilterPrefsKey(queryName); ListPreferenceSettings settings = new ListPreferenceSettings(key); query = query.builderFrom().applyListPreferences(androidContext, settings).build(); return androidContext.getContentResolver().query( TaskProvider.Tasks.CONTENT_URI, TaskProvider.Tasks.FULL_PROJECTION, query.getSelection(androidContext), query.getSelectionArgs(), query.getSortOrder()); } abstract int getWidgetLayoutId(); abstract int getTotalEntries(); protected void setupFrameClickIntents(android.content.Context androidContext, RemoteViews views, String queryName){ Intent intent = StandardTaskQueries.getActivityIntent(androidContext, queryName); PendingIntent pendingIntent = PendingIntent.getActivity(androidContext, 0, intent, 0); views.setOnClickPendingIntent(R.id.title, pendingIntent); intent = new Intent(Intent.ACTION_INSERT, TaskProvider.Tasks.CONTENT_URI); pendingIntent = PendingIntent.getActivity(androidContext, 0, intent, 0); views.setOnClickPendingIntent(R.id.add_task, pendingIntent); } protected int updateDescription(android.content.Context androidContext, RemoteViews views, Task task, int taskCount) { int descriptionViewId = getIdIdentifier(androidContext, "description_" + taskCount); if (descriptionViewId != 0) { views.setTextViewText(descriptionViewId, task != null ? task.getDescription() : ""); } return descriptionViewId; } protected int updateProject(android.content.Context androidContext, RemoteViews views, Project project, int taskCount) { int projectViewId = getIdIdentifier(androidContext, "project_" + taskCount); views.setViewVisibility(projectViewId, project == null ? View.INVISIBLE : View.VISIBLE); views.setTextViewText(projectViewId, project != null ? project.getName() : ""); return projectViewId; } abstract protected int updateContext(android.content.Context androidContext, RemoteViews views, Context context, int taskCount); static int getIdIdentifier(android.content.Context context, String name) { Integer id = sIdCache.get(name); if (id == null) { id = getIdentifier(context, name, cIdType); if (id == 0) return id; sIdCache.put(name, id); } Ln.d("Got id " + id + " for resource " + name); return id; } static int getIdentifier(android.content.Context context, String name, String type) { int id = context.getResources().getIdentifier( name, type, cPackage); Ln.d("Got id " + id + " for resource " + name); return id; } }
Java
package org.dodgybits.shuffle.android.widget; import roboguice.RoboGuice; import roboguice.inject.RoboInjector; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; /** * To ensure proper ContextScope usage, override the handleReceive method * * Replace with robojuice version when following issue is fixed... * http://code.google.com/p/roboguice/issues/detail?id=150 */ public abstract class RoboBroadcastReceiver extends BroadcastReceiver { /** Handles the receive event. This method should not be overridden, instead override * the handleReceive method to ensure that the proper ContextScope is maintained. * @param context * @param intent */ @Override public final void onReceive(Context context, Intent intent) { final RoboInjector injector = RoboGuice.getInjector(context); injector.injectMembers(this); handleReceive(context, intent); } /** * Template method that should be overridden to handle the broadcast event * Using this method ensures that the proper ContextScope is maintained before and after * the execution of the receiver. * @param context * @param intent */ @SuppressWarnings("UnusedParameters") protected void handleReceive(Context context, Intent intent) { // proper template method to handle the receive } }
Java
package org.dodgybits.shuffle.gwt.gin; import com.google.gwt.event.shared.EventBus; import com.google.gwt.inject.client.AsyncProvider; import com.google.gwt.inject.client.GinModules; import com.google.gwt.inject.client.Ginjector; import com.google.inject.Provider; import com.gwtplatform.dispatch.client.gin.DispatchAsyncModule; import com.gwtplatform.mvp.client.proxy.PlaceManager; import org.dodgybits.shuffle.client.ShuffleRequestFactory; import org.dodgybits.shuffle.gwt.core.ErrorPresenter; import org.dodgybits.shuffle.gwt.core.HelpPresenter; import org.dodgybits.shuffle.gwt.core.InboxPresenter; import org.dodgybits.shuffle.gwt.core.LoginPresenter; import org.dodgybits.shuffle.gwt.core.MainPresenter; import org.dodgybits.shuffle.gwt.core.NavigationPresenter; import org.dodgybits.shuffle.gwt.core.EditActionPresenter; import org.dodgybits.shuffle.gwt.core.WelcomePresenter; import org.dodgybits.shuffle.gwt.gin.ClientModule; @GinModules({ DispatchAsyncModule.class, ClientModule.class }) public interface ClientGinjector extends Ginjector { EventBus getEventBus(); PlaceManager getPlaceManager(); Provider<WelcomePresenter> getWelcomePresenter(); AsyncProvider<ErrorPresenter> getErrorPresenter(); Provider<MainPresenter> getMainPresenter(); AsyncProvider<LoginPresenter> getLoginPresenter(); AsyncProvider<HelpPresenter> getHelpPresenter(); AsyncProvider<InboxPresenter> getInboxPresenter(); AsyncProvider<EditActionPresenter> getNewActionPresenter(); Provider<NavigationPresenter> getNavigationPresenter(); ShuffleRequestFactory getRequestFactory(); }
Java
package org.dodgybits.shuffle.gwt.gin; import org.dodgybits.shuffle.client.ShuffleRequestFactory; import org.dodgybits.shuffle.gwt.core.ErrorPresenter; import org.dodgybits.shuffle.gwt.core.ErrorView; import org.dodgybits.shuffle.gwt.core.HelpPresenter; import org.dodgybits.shuffle.gwt.core.HelpView; import org.dodgybits.shuffle.gwt.core.InboxPresenter; import org.dodgybits.shuffle.gwt.core.InboxView; import org.dodgybits.shuffle.gwt.core.LoginPresenter; import org.dodgybits.shuffle.gwt.core.LoginView; import org.dodgybits.shuffle.gwt.core.MainPresenter; import org.dodgybits.shuffle.gwt.core.MainView; import org.dodgybits.shuffle.gwt.core.NavigationPresenter; import org.dodgybits.shuffle.gwt.core.NavigationView; import org.dodgybits.shuffle.gwt.core.EditActionPresenter; import org.dodgybits.shuffle.gwt.core.EditActionView; import org.dodgybits.shuffle.gwt.core.WelcomePresenter; import org.dodgybits.shuffle.gwt.core.WelcomeView; import org.dodgybits.shuffle.gwt.place.ClientPlaceManager; import org.dodgybits.shuffle.gwt.place.DefaultPlace; import org.dodgybits.shuffle.gwt.place.ErrorPlace; import org.dodgybits.shuffle.gwt.place.NameTokens; import org.dodgybits.shuffle.shared.TaskService; import com.google.inject.Provides; import com.google.inject.Singleton; import com.gwtplatform.mvp.client.gin.AbstractPresenterModule; import com.gwtplatform.mvp.client.gin.DefaultModule; public class ClientModule extends AbstractPresenterModule { @Override protected void configure() { install(new DefaultModule(ClientPlaceManager.class)); bindPresenter(WelcomePresenter.class, WelcomePresenter.MyView.class, WelcomeView.class, WelcomePresenter.MyProxy.class); bindConstant().annotatedWith(DefaultPlace.class).to(NameTokens.welcome); bindPresenter(ErrorPresenter.class, ErrorPresenter.MyView.class, ErrorView.class, ErrorPresenter.MyProxy.class); bindConstant().annotatedWith(ErrorPlace.class).to(NameTokens.error); bindPresenter(MainPresenter.class, MainPresenter.MyView.class, MainView.class, MainPresenter.MyProxy.class); bindPresenter(LoginPresenter.class, LoginPresenter.MyView.class, LoginView.class, LoginPresenter.MyProxy.class); bindPresenter(HelpPresenter.class, HelpPresenter.MyView.class, HelpView.class, HelpPresenter.MyProxy.class); bindPresenter(InboxPresenter.class, InboxPresenter.MyView.class, InboxView.class, InboxPresenter.MyProxy.class); bindPresenter(EditActionPresenter.class, EditActionPresenter.MyView.class, EditActionView.class, EditActionPresenter.MyProxy.class); bindPresenterWidget(NavigationPresenter.class, NavigationPresenter.MyView.class, NavigationView.class); bind(ShuffleRequestFactory.class).in(Singleton.class); } @Provides TaskService provideTaskService(ShuffleRequestFactory requestFactory) { return requestFactory.taskService(); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.dodgybits.shuffle.gwt; import java.util.Date; import java.util.List; import org.dodgybits.shuffle.client.ShuffleRequestFactory; import org.dodgybits.shuffle.client.ShuffleRequestFactory.HelloWorldRequest; import org.dodgybits.shuffle.client.ShuffleRequestFactory.MessageRequest; import org.dodgybits.shuffle.gwt.formatter.ActionDateFormatter; import org.dodgybits.shuffle.shared.MessageProxy; import org.dodgybits.shuffle.shared.TaskProxy; import org.dodgybits.shuffle.shared.TaskService; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.DivElement; import com.google.gwt.dom.client.InputElement; import com.google.gwt.dom.client.TextAreaElement; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlexTable; import com.google.gwt.user.client.ui.Widget; import com.google.web.bindery.event.shared.EventBus; import com.google.web.bindery.event.shared.SimpleEventBus; import com.google.web.bindery.requestfactory.shared.Receiver; import com.google.web.bindery.requestfactory.shared.Request; import com.google.web.bindery.requestfactory.shared.ServerFailure; public class ShuffleWidget extends Composite { private static final int STATUS_DELAY = 4000; private static final String STATUS_ERROR = "status error"; private static final String STATUS_NONE = "status none"; private static final String STATUS_SUCCESS = "status success"; interface ShuffleUiBinder extends UiBinder<Widget, ShuffleWidget> { } private static ShuffleUiBinder uiBinder = GWT.create(ShuffleUiBinder.class); private ActionDateFormatter mFormatter; @UiField TextAreaElement messageArea; @UiField InputElement recipientArea; @UiField DivElement status; @UiField Button sayHelloButton; @UiField Button sendMessageButton; @UiField Button fetchTasksButton; @UiField FlexTable table; /** * Timer to clear the UI. */ Timer timer = new Timer() { @Override public void run() { status.setInnerText(""); status.setClassName(STATUS_NONE); recipientArea.setValue(""); messageArea.setValue(""); } }; private void setStatus(String message, boolean error) { status.setInnerText(message); if (error) { status.setClassName(STATUS_ERROR); } else { if (message.length() == 0) { status.setClassName(STATUS_NONE); } else { status.setClassName(STATUS_SUCCESS); } } timer.schedule(STATUS_DELAY); } public ShuffleWidget() { initWidget(uiBinder.createAndBindUi(this)); sayHelloButton.getElement().setClassName("send centerbtn"); sendMessageButton.getElement().setClassName("send"); mFormatter = new ActionDateFormatter(); final EventBus eventBus = new SimpleEventBus(); final ShuffleRequestFactory requestFactory = GWT.create(ShuffleRequestFactory.class); requestFactory.initialize(eventBus); sendMessageButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { String recipient = recipientArea.getValue(); String message = messageArea.getValue(); setStatus("Connecting...", false); sendMessageButton.setEnabled(false); // Send a message using RequestFactory MessageRequest request = requestFactory.messageRequest(); MessageProxy messageProxy = request.create(MessageProxy.class); messageProxy.setRecipient(recipient); messageProxy.setMessage(message); Request<String> sendRequest = request.send().using(messageProxy); sendRequest.fire(new Receiver<String>() { @Override public void onFailure(ServerFailure error) { sendMessageButton.setEnabled(true); setStatus(error.getMessage(), true); } @Override public void onSuccess(String response) { sendMessageButton.setEnabled(true); setStatus(response, response.startsWith("Failure:")); } }); } }); fetchTasksButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { setStatus("Connecting...", false); fetchTasksButton.setEnabled(false); // Send a message using RequestFactory TaskService service = requestFactory.taskService(); Request<List<TaskProxy>> taskListRequest = service.listAll(); taskListRequest.fire(new Receiver<List<TaskProxy>>() { @Override public void onFailure(ServerFailure error) { fetchTasksButton.setEnabled(true); setStatus(error.getMessage(), true); } @Override public void onSuccess(List<TaskProxy> tasks) { fetchTasksButton.setEnabled(true); setStatus("Success - got " + tasks.size(), false); displayActions(tasks); } }); } }); sayHelloButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { sayHelloButton.setEnabled(false); HelloWorldRequest helloWorldRequest = requestFactory.helloWorldRequest(); helloWorldRequest.getMessage().fire(new Receiver<String>() { @Override public void onFailure(ServerFailure error) { sayHelloButton.setEnabled(true); setStatus(error.getMessage(), true); } @Override public void onSuccess(String response) { sayHelloButton.setEnabled(true); setStatus(response, response.startsWith("Failure:")); } }); } }); } private void displayActions(List<TaskProxy> tasks) { int numActions = tasks.size(); for (int i = 0; i < numActions; i++) { TaskProxy taskValue = tasks.get(i); displayAction(taskValue, i); } } private void displayAction(TaskProxy taskValue, int row) { String description = "<div class='actionTitle'>" + escapeHtml(taskValue.getDescription()) + "<span class='actionDetails'> - " + escapeHtml(taskValue.getDetails()) + "</span></div>"; table.setHTML(row, 0, description); table.setText(row, 1, mFormatter.getShortDate(taskValue.getModifiedDate())); table.getCellFormatter().setStyleName( row, 1, isInPast(taskValue.getModifiedDate()) ? "actionDueInPass" : "actionDueInFuture"); } private static String escapeHtml(String maybeHtml) { final Element div = DOM.createDiv(); DOM.setInnerText(div, maybeHtml); return DOM.getInnerHTML(div); } private static boolean isInPast(Date date) { return date != null && date.getTime() < System.currentTimeMillis(); } }
Java
package org.dodgybits.shuffle.gwt.place; import com.google.inject.BindingAnnotation; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.METHOD; import java.lang.annotation.Retention; import static java.lang.annotation.RetentionPolicy.RUNTIME; @BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) public @interface DefaultPlace { }
Java
package org.dodgybits.shuffle.gwt.place; import com.gwtplatform.mvp.client.proxy.PlaceManagerImpl; import com.gwtplatform.mvp.client.proxy.PlaceRequest; import com.google.inject.Inject; import com.google.gwt.event.shared.EventBus; import com.gwtplatform.mvp.client.proxy.TokenFormatter; public class ClientPlaceManager extends PlaceManagerImpl { private final PlaceRequest defaultPlaceRequest; private final PlaceRequest errorPlaceRequest; @Inject public ClientPlaceManager(final EventBus eventBus, final TokenFormatter tokenFormatter, @DefaultPlace final String defaultPlaceNameToken, @ErrorPlace final String errorPlaceNameToken) { super(eventBus, tokenFormatter); this.defaultPlaceRequest = new PlaceRequest(defaultPlaceNameToken); this.errorPlaceRequest = new PlaceRequest(errorPlaceNameToken); } @Override public void revealDefaultPlace() { revealPlace(defaultPlaceRequest, false); } @Override public void revealErrorPlace(String invalidHistoryToken) { revealPlace(errorPlaceRequest, false); } }
Java
package org.dodgybits.shuffle.gwt.place; import com.google.inject.BindingAnnotation; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.METHOD; import java.lang.annotation.Retention; import static java.lang.annotation.RetentionPolicy.RUNTIME; @BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) public @interface ErrorPlace { }
Java
package org.dodgybits.shuffle.gwt.place; public class NameTokens { public static final String welcome = "!welcome"; public static final String error = "!error"; public static final String login = "!login"; public static final String help = "!help"; public static final String inbox = "!inbox"; public static final String dueActions = "!dueActions"; public static final String nextActions = "!nextActions"; public static final String projects = "!projects"; public static final String tickler = "!tickler"; public static final String editAction = "!editAction"; public static String getWelcome() { return welcome; } public static String getError() { return error; } public static String getLogin() { return login; } public static String getHelp() { return help; } public static String getInbox() { return inbox; } public static String getDueActions() { return dueActions; } public static String getNextActions() { return nextActions; } public static String getProjects() { return projects; } public static String getTickler() { return tickler; } public static String getEditAction() { return editAction; } }
Java
package org.dodgybits.shuffle.gwt.formatter; import java.util.Date; import com.google.gwt.i18n.client.DateTimeFormat; public class ActionDateFormatter { private DateTimeFormat dateFormat; public ActionDateFormatter() { dateFormat = DateTimeFormat.getFormat("d MMM"); } public String getShortDate(Date date) { String result = ""; if (date != null) { if (isSameDay(date, new Date())) { // only show time if date is today result = DateTimeFormat.getShortTimeFormat().format(date); } else { result = dateFormat.format(date); } } return result; } @SuppressWarnings("deprecation") private static boolean isSameDay(Date date1, Date date2) { return date1.getYear() == date2.getYear() && date1.getMonth() == date2.getMonth() && date1.getDate() == date2.getDate(); } }
Java
package org.dodgybits.shuffle.gwt; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.FileUpload; import com.google.gwt.user.client.ui.FormPanel; import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent; import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler; import com.google.gwt.user.client.ui.FormPanel.SubmitEvent; import com.google.gwt.user.client.ui.FormPanel.SubmitHandler; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; public class SingleUploadSample implements EntryPoint { public void onModuleLoad() { // Create a FormPanel and point it at a service. final FormPanel form = new FormPanel(); form.setAction("/restoreBackup"); // Because we're going to add a FileUpload widget, we'll need to set the // form to use the POST method, and multipart MIME encoding. form.setEncoding(FormPanel.ENCODING_MULTIPART); form.setMethod(FormPanel.METHOD_POST); // Create a panel to hold all of the form widgets. VerticalPanel panel = new VerticalPanel(); form.setWidget(panel); // Create a TextBox, giving it a name so that it will be submitted. final TextBox tb = new TextBox(); tb.setName("textBoxFormElement"); panel.add(tb); // Create a ListBox, giving it a name and some values to be associated // with // its options. ListBox lb = new ListBox(); lb.setName("listBoxFormElement"); lb.addItem("foo", "fooValue"); lb.addItem("barry", "barValue"); lb.addItem("baz", "bazValue"); panel.add(lb); // Create a FileUpload widget. FileUpload upload = new FileUpload(); upload.setName("uploadFormElement"); panel.add(upload); // Add a 'submit' button. panel.add(new Button("Submit", new ClickHandler() { @Override public void onClick(ClickEvent event) { form.submit(); } })); form.addSubmitCompleteHandler(new SubmitCompleteHandler() { @Override public void onSubmitComplete(SubmitCompleteEvent event) { // When the form submission is successfully completed, this // event is // fired. Assuming the service returned a response of type // text/html, // we can get the result text here (see the FormPanel // documentation for // further explanation). Window.alert(event.getResults()); } }); form.addSubmitHandler(new SubmitHandler() { @Override public void onSubmit(SubmitEvent event) { // This event is fired just before the form is submitted. We can // take // this opportunity to perform validation. if (tb.getText().length() == 0) { Window.alert("The text box must not be empty"); event.cancel(); } } }); RootPanel.get().add(form); RootPanel.get().add(new Button("Submit", new ClickHandler() { @Override public void onClick(ClickEvent event) { form.submit(); } })); } }
Java
package org.dodgybits.shuffle.gwt.core; import java.util.List; import org.dodgybits.shuffle.gwt.place.NameTokens; import org.dodgybits.shuffle.shared.TaskProxy; import org.dodgybits.shuffle.shared.TaskService; import com.google.gwt.core.client.GWT; import com.google.gwt.event.shared.EventBus; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.web.bindery.requestfactory.shared.Receiver; import com.google.web.bindery.requestfactory.shared.Request; import com.google.web.bindery.requestfactory.shared.ServerFailure; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit; import com.gwtplatform.mvp.client.proxy.ProxyPlace; import com.gwtplatform.mvp.client.proxy.RevealContentEvent; public class InboxPresenter extends Presenter<InboxPresenter.MyView, InboxPresenter.MyProxy> { public interface MyView extends View { void displayTasks(List<TaskProxy> tasks); } @ProxyCodeSplit @NameToken(NameTokens.inbox) public interface MyProxy extends ProxyPlace<InboxPresenter> { } private final Provider<TaskService> taskServiceProvider; @Inject public InboxPresenter(final EventBus eventBus, final MyView view, final MyProxy proxy, final Provider<TaskService> taskServiceProvider) { super(eventBus, view, proxy); this.taskServiceProvider = taskServiceProvider; } @Override protected void revealInParent() { RevealContentEvent.fire(this, MainPresenter.MAIN_SLOT, this); } @Override protected void onReset() { super.onReset(); // Send a message using RequestFactory Request<List<TaskProxy>> taskListRequest = taskServiceProvider.get().listAll(); taskListRequest.fire(new Receiver<List<TaskProxy>>() { @Override public void onFailure(ServerFailure error) { GWT.log(error.getMessage()); } @Override public void onSuccess(List<TaskProxy> tasks) { GWT.log("Success - got " + tasks.size() + " tasks"); getView().displayTasks(tasks); } }); } }
Java
package org.dodgybits.shuffle.gwt.core; import com.gwtplatform.mvp.client.ViewImpl; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; public class MainView extends ViewImpl implements MainPresenter.MyView { private final Widget widget; public interface Binder extends UiBinder<Widget, MainView> { } @UiField HTMLPanel mainPanel; @UiField HTMLPanel navigation; @Inject public MainView(final Binder binder) { widget = binder.createAndBindUi(this); } @Override public Widget asWidget() { return widget; } @Override public void setInSlot(Object slot, Widget widget) { if (slot == MainPresenter.MAIN_SLOT) { mainPanel.clear(); mainPanel.add(widget); } else if (slot == MainPresenter.NAVIGATION_SLOT) { navigation.clear(); navigation.add(widget); } } }
Java
package org.dodgybits.shuffle.gwt.core; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit; import com.gwtplatform.mvp.client.annotations.NameToken; import org.dodgybits.shuffle.gwt.place.NameTokens; import com.gwtplatform.mvp.client.proxy.ProxyPlace; import com.google.inject.Inject; import com.google.gwt.event.shared.EventBus; import com.gwtplatform.mvp.client.proxy.RevealContentEvent; import org.dodgybits.shuffle.gwt.core.MainPresenter; public class HelpPresenter extends Presenter<HelpPresenter.MyView, HelpPresenter.MyProxy> { public interface MyView extends View { // TODO Put your view methods here } @ProxyCodeSplit @NameToken(NameTokens.help) public interface MyProxy extends ProxyPlace<HelpPresenter> { } @Inject public HelpPresenter(final EventBus eventBus, final MyView view, final MyProxy proxy) { super(eventBus, view, proxy); } @Override protected void revealInParent() { RevealContentEvent.fire(this, MainPresenter.MAIN_SLOT, this); } }
Java
package org.dodgybits.shuffle.gwt.core; import java.util.Date; import java.util.List; import org.dodgybits.shuffle.gwt.formatter.ActionDateFormatter; import org.dodgybits.shuffle.shared.TaskProxy; import com.google.gwt.cell.client.CheckboxCell; import com.google.gwt.cell.client.EditTextCell; import com.google.gwt.cell.client.TextCell; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.gwt.safehtml.shared.SafeHtmlUtils; import com.google.gwt.text.shared.SafeHtmlRenderer; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.cellview.client.CellTable; import com.google.gwt.user.cellview.client.Column; import com.google.gwt.user.client.ui.Widget; import com.google.gwt.view.client.DefaultSelectionEventManager; import com.google.gwt.view.client.ListDataProvider; import com.google.gwt.view.client.MultiSelectionModel; import com.google.gwt.view.client.ProvidesKey; import com.google.gwt.view.client.SelectionModel; import com.google.inject.Inject; import com.gwtplatform.mvp.client.ViewImpl; public class InboxView extends ViewImpl implements InboxPresenter.MyView { private final Widget widget; public interface Binder extends UiBinder<Widget, InboxView> { } private static final ProvidesKey<TaskProxy> KEY_PROVIDER = new ProvidesKey<TaskProxy>() { @Override public Object getKey(TaskProxy item) { return item.getId(); } }; private ActionDateFormatter mFormatter; @UiField(provided=true) CellTable<TaskProxy> table; /** * The provider that holds the list of contacts in the database. */ private ListDataProvider<TaskProxy> dataProvider = new ListDataProvider<TaskProxy>(); @Inject public InboxView(final Binder binder) { mFormatter = new ActionDateFormatter(); // Create a table. // Set a key provider that provides a unique key for each contact. If key is // used to identify contacts when fields (such as the name and address) // change. table = new CellTable<TaskProxy>(KEY_PROVIDER); table.setWidth("100%", true); // Add a selection model so we can select cells. final SelectionModel<TaskProxy> selectionModel = new MultiSelectionModel<TaskProxy>(KEY_PROVIDER); table.setSelectionModel(selectionModel, DefaultSelectionEventManager.<TaskProxy> createCheckboxManager()); // Initialize the columns. initTableColumns(selectionModel); widget = binder.createAndBindUi(this); } /** * Add the columns to the table. */ private void initTableColumns( final SelectionModel<TaskProxy> selectionModel) { // Checkbox column. This table will uses a checkbox column for selection. // Alternatively, you can call table.setSelectionEnabled(true) to enable // mouse selection. Column<TaskProxy, Boolean> checkColumn = new Column<TaskProxy, Boolean>( new CheckboxCell(true, false)) { @Override public Boolean getValue(TaskProxy object) { // Get the value from the selection model. return selectionModel.isSelected(object); } }; table.addColumn(checkColumn, SafeHtmlUtils.fromSafeConstant("<br/>")); table.setColumnWidth(checkColumn, 40, Unit.PX); // Details. Column<TaskProxy, String> detailsColumn = new Column<TaskProxy, String>( new EditTextCell(new SafeHtmlRenderer<String>() { public SafeHtml render(String object) { return (object == null) ? SafeHtmlUtils.EMPTY_SAFE_HTML : SafeHtmlUtils.fromTrustedString(object); } public void render(String object, SafeHtmlBuilder appendable) { appendable.append(SafeHtmlUtils.fromTrustedString(object)); } })) { @Override public String getValue(TaskProxy taskValue) { String description = "<div class='action-title'>" + SafeHtmlUtils.htmlEscape(taskValue.getDescription()) + "<span class='action-details'> - " + SafeHtmlUtils.htmlEscape(taskValue.getDetails()) + "</span></div>"; return description; } }; table.addColumn(detailsColumn, "Details"); table.setColumnWidth(detailsColumn, 80, Unit.PCT); // Date. Column<TaskProxy, String> dueDateColumn = new Column<TaskProxy, String>( new TextCell()) { @Override public String getValue(TaskProxy taskValue) { return mFormatter.getShortDate(taskValue.getModifiedDate()); } }; dueDateColumn.setSortable(true); table.addColumn(dueDateColumn, "Due"); table.setColumnWidth(dueDateColumn, 60, Unit.PCT); } @Override public Widget asWidget() { return widget; } @Override public void displayTasks(List<TaskProxy> tasks) { dataProvider.setList(tasks); dataProvider.addDataDisplay(table); } // private void displayAction(TaskProxy taskValue, int row) { // String description = "<div class='actionTitle'>" // + escapeHtml(taskValue.getDescription()) // + "<span class='actionDetails'> - " // + escapeHtml(taskValue.getDetails()) + "</span></div>"; // table.setHTML(row, 0, description); // // table.setText(row, 1, // mFormatter.getShortDate(taskValue.getModifiedDate())); // table.getCellFormatter().setStyleName( // row, // 1, // isInPast(taskValue.getModifiedDate()) ? "actionDueInPass" // : "actionDueInFuture"); // } // // private static String escapeHtml(String maybeHtml) { // final Element div = DOM.createDiv(); // DOM.setInnerText(div, maybeHtml); // return DOM.getInnerHTML(div); // } private static boolean isInPast(Date date) { return date != null && date.getTime() < System.currentTimeMillis(); } }
Java
package org.dodgybits.shuffle.gwt.core; import com.gwtplatform.mvp.client.UiHandlers; public interface NavigationUiHandlers extends UiHandlers { void onNewAction(); }
Java
package org.dodgybits.shuffle.gwt.core; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import com.gwtplatform.mvp.client.ViewWithUiHandlers; public class NavigationView extends ViewWithUiHandlers<NavigationUiHandlers> implements NavigationPresenter.MyView, IsWidget { private final Widget widget; public interface Binder extends UiBinder<Widget, NavigationView> { } @UiField Button newAction; @Inject public NavigationView(final Binder binder) { widget = binder.createAndBindUi(this); } @Override public Widget asWidget() { return widget; } @UiHandler("newAction") void onNewActionButtonClicked(ClickEvent event) { if (getUiHandlers() != null) { getUiHandlers().onNewAction(); } } }
Java
package org.dodgybits.shuffle.gwt.core; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.TextArea; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Widget; import com.google.gwt.user.datepicker.client.DateBox; import com.google.inject.Inject; import com.gwtplatform.mvp.client.ViewImpl; import com.gwtplatform.mvp.client.ViewWithUiHandlers; import org.dodgybits.shuffle.shared.TaskProxy; public class EditActionView extends ViewWithUiHandlers<EditEntityUiHandlers> implements EditActionPresenter.MyView { private final Widget widget; public interface Binder extends UiBinder<Widget, EditActionView> { } @UiField Button save; @UiField Button cancel; @UiField TextBox description; @UiField TextBox context; @UiField TextBox project; @UiField TextArea details; @UiField DateBox from; @UiField DateBox due; @Inject public EditActionView(final Binder binder) { widget = binder.createAndBindUi(this); } @Override public Widget asWidget() { return widget; } @Override public void displayTask(TaskProxy task) { description.setText(task.getDescription()); details.setText(task.getDetails()); due.setValue(task.getModifiedDate()); } @UiHandler("save") void onSaveButtonClicked(ClickEvent event) { GWT.log("Saving task"); if (getUiHandlers() != null) { getUiHandlers().save(description.getText(), details.getText()); } } @UiHandler("cancel") void onCancelButtonClicked(ClickEvent event) { GWT.log("Canceling task edit"); if (getUiHandlers() != null) { getUiHandlers().cancel(); } } }
Java
package org.dodgybits.shuffle.gwt.core; import com.gwtplatform.mvp.client.ViewImpl; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; public class LoginView extends ViewImpl implements LoginPresenter.MyView { private final Widget widget; public interface Binder extends UiBinder<Widget, LoginView> { } @Inject public LoginView(final Binder binder) { widget = binder.createAndBindUi(this); } @Override public Widget asWidget() { return widget; } }
Java
package org.dodgybits.shuffle.gwt.core; import org.dodgybits.shuffle.gwt.place.NameTokens; import com.google.gwt.event.shared.EventBus; import com.google.inject.Inject; import com.gwtplatform.mvp.client.HasUiHandlers; import com.gwtplatform.mvp.client.PresenterWidget; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.proxy.PlaceManager; import com.gwtplatform.mvp.client.proxy.PlaceRequest; public class NavigationPresenter extends PresenterWidget<NavigationPresenter.MyView> implements NavigationUiHandlers { public interface MyView extends View, HasUiHandlers<NavigationUiHandlers> { // TODO Put your view methods here } private PlaceManager placeManager; @Inject public NavigationPresenter(final EventBus eventBus, final MyView view, PlaceManager placeManager) { super(eventBus, view); this.placeManager = placeManager; getView().setUiHandlers(this); } public void onNewAction() { PlaceRequest myRequest = new PlaceRequest(NameTokens.editAction); placeManager.revealPlace( myRequest ); } }
Java
package org.dodgybits.shuffle.gwt.core; import com.google.gwt.event.shared.EventBus; import com.google.gwt.event.shared.GwtEvent.Type; import com.google.inject.Inject; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.ContentSlot; import com.gwtplatform.mvp.client.annotations.ProxyStandard; import com.gwtplatform.mvp.client.proxy.Proxy; import com.gwtplatform.mvp.client.proxy.RevealContentHandler; import com.gwtplatform.mvp.client.proxy.RevealRootLayoutContentEvent; public class MainPresenter extends Presenter<MainPresenter.MyView, MainPresenter.MyProxy> { public interface MyView extends View { // TODO Put your view methods here } @ProxyStandard public interface MyProxy extends Proxy<MainPresenter> { } @ContentSlot public static final Type<RevealContentHandler<?>> MAIN_SLOT = new Type<RevealContentHandler<?>>(); @ContentSlot public static final Type<RevealContentHandler<?>> NAVIGATION_SLOT = new Type<RevealContentHandler<?>>(); private final NavigationPresenter navigationPresenter; @Inject public MainPresenter(final EventBus eventBus, final MyView view, final MyProxy proxy, final NavigationPresenter navigationPresenter) { super(eventBus, view, proxy); this.navigationPresenter = navigationPresenter; } @Override protected void revealInParent() { RevealRootLayoutContentEvent.fire(this, this); } @Override protected void onReveal() { setInSlot(NAVIGATION_SLOT, navigationPresenter); } }
Java
package org.dodgybits.shuffle.gwt.core; import org.dodgybits.shuffle.gwt.place.NameTokens; import com.google.gwt.event.shared.EventBus; import com.google.inject.Inject; import com.gwtplatform.dispatch.shared.DispatchAsync; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.ProxyStandard; import com.gwtplatform.mvp.client.proxy.PlaceRequest; import com.gwtplatform.mvp.client.proxy.ProxyPlace; import com.gwtplatform.mvp.client.proxy.RevealRootLayoutContentEvent; public class WelcomePresenter extends Presenter<WelcomePresenter.MyView, WelcomePresenter.MyProxy> { public interface MyView extends View { public void setFormattedDate(String formattedDate); public void setBackgroundColor(String color); } @ProxyStandard @NameToken(NameTokens.welcome) public interface MyProxy extends ProxyPlace<WelcomePresenter> { } private final DispatchAsync dispatcher; @Inject public WelcomePresenter(final EventBus eventBus, final MyView view, final MyProxy proxy, final DispatchAsync dispatcher) { super(eventBus, view, proxy); this.dispatcher = dispatcher; } @Override protected void revealInParent() { RevealRootLayoutContentEvent.fire(this, this); } @Override protected void onReset() { getView().setFormattedDate("Loading..."); // dispatcher.execute(new GetServerDate(), new AsyncCallback<GetServerDateResult>() { // @Override // public void onFailure(Throwable caught) { // getView().setFormattedDate("An error occurred!"); // } // @Override // public void onSuccess(GetServerDateResult result) { // getView().setFormattedDate(result.getFormattedDate()); // } // }); super.onReset(); } @Override public void prepareFromRequest(PlaceRequest request) { // Gets the preferred color from a URL parameter, defaults to lightBlue String color = request.getParameter("col", "lightBlue"); getView().setBackgroundColor(color); } }
Java
package org.dodgybits.shuffle.gwt.core; import com.gwtplatform.mvp.client.ViewImpl; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; public class HelpView extends ViewImpl implements HelpPresenter.MyView { private final Widget widget; public interface Binder extends UiBinder<Widget, HelpView> { } @Inject public HelpView(final Binder binder) { widget = binder.createAndBindUi(this); } @Override public Widget asWidget() { return widget; } }
Java
package org.dodgybits.shuffle.gwt.core; import com.gwtplatform.mvp.client.HasUiHandlers; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit; import com.gwtplatform.mvp.client.annotations.NameToken; import org.dodgybits.shuffle.gwt.place.NameTokens; import com.gwtplatform.mvp.client.proxy.PlaceManager; import com.gwtplatform.mvp.client.proxy.PlaceRequest; import com.gwtplatform.mvp.client.proxy.ProxyPlace; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.web.bindery.requestfactory.shared.Receiver; import com.google.web.bindery.requestfactory.shared.Request; import com.google.web.bindery.requestfactory.shared.ServerFailure; import com.google.gwt.core.client.GWT; import com.google.gwt.event.shared.EventBus; import com.gwtplatform.mvp.client.proxy.RevealContentEvent; import org.dodgybits.shuffle.shared.TaskProxy; import org.dodgybits.shuffle.shared.TaskService; public class EditActionPresenter extends Presenter<EditActionPresenter.MyView, EditActionPresenter.MyProxy> implements EditEntityUiHandlers { private enum Action { NEW, EDIT } public interface MyView extends View, HasUiHandlers<EditEntityUiHandlers> { void displayTask(TaskProxy task); } @ProxyCodeSplit @NameToken(NameTokens.editAction) public interface MyProxy extends ProxyPlace<EditActionPresenter> { } private final TaskService mTaskService; private PlaceManager placeManager; private Action mAction; private TaskProxy mTask = null; @Inject public EditActionPresenter(final EventBus eventBus, final MyView view, final MyProxy proxy, final PlaceManager placeManager, final Provider<TaskService> taskServiceProvider) { super(eventBus, view, proxy); this.placeManager = placeManager; this.mTaskService = taskServiceProvider.get(); getView().setUiHandlers(this); } @Override public void prepareFromRequest(PlaceRequest placeRequest) { super.prepareFromRequest(placeRequest); // In the next call, "view" is the default value, // returned if "action" is not found on the URL. String actionString = placeRequest.getParameter("action", "new"); mAction = Action.NEW; if ("edit".equals(actionString)) { Long taskId = null; mAction = Action.EDIT; try { taskId = Long.valueOf(placeRequest.getParameter("taskId", null)); } catch (NumberFormatException e) { } if (taskId == null) { placeManager.revealErrorPlace(placeRequest.getNameToken()); return; } load(taskId); } } @Override protected void revealInParent() { RevealContentEvent.fire(this, MainPresenter.MAIN_SLOT, this); } private void load(Long taskId) { // Send a message using RequestFactory Request<TaskProxy> taskListRequest = mTaskService.findById(taskId); taskListRequest.fire(new Receiver<TaskProxy>() { @Override public void onFailure(ServerFailure error) { GWT.log(error.getMessage()); } @Override public void onSuccess(TaskProxy task) { mTask = task; GWT.log("Success - got " + task); getView().displayTask(task); } }); } @Override public void save(String description, String details) { if (mAction == Action.NEW) { mTask = mTaskService.create(TaskProxy.class); } mTask.setDescription(description); mTask.setDetails(details); Request<Void> saveRequest = mTaskService.save(mTask); saveRequest.fire(new Receiver<Void>() { @Override public void onFailure(ServerFailure error) { GWT.log(error.getMessage()); } @Override public void onSuccess(Void response) { GWT.log("Success"); goBack(); } }); } @Override public void cancel() { goBack(); } private void goBack() { // TODO - go back to previous page } }
Java
package org.dodgybits.shuffle.gwt.core; import com.gwtplatform.mvp.client.ViewImpl; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; public class ErrorView extends ViewImpl implements ErrorPresenter.MyView { private final Widget widget; public interface Binder extends UiBinder<Widget, ErrorView> { } @Inject public ErrorView(final Binder binder) { widget = binder.createAndBindUi(this); } @Override public Widget asWidget() { return widget; } }
Java
package org.dodgybits.shuffle.gwt.core; import com.gwtplatform.mvp.client.UiHandlers; import org.dodgybits.shuffle.shared.TaskProxy; public interface EditEntityUiHandlers extends UiHandlers { void save(String description, String details); void cancel(); }
Java
package org.dodgybits.shuffle.gwt.core; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit; import com.gwtplatform.mvp.client.annotations.NameToken; import org.dodgybits.shuffle.gwt.place.NameTokens; import com.gwtplatform.mvp.client.proxy.ProxyPlace; import com.google.inject.Inject; import com.google.gwt.event.shared.EventBus; import com.gwtplatform.mvp.client.proxy.RevealContentEvent; import org.dodgybits.shuffle.gwt.core.MainPresenter; public class LoginPresenter extends Presenter<LoginPresenter.MyView, LoginPresenter.MyProxy> { public interface MyView extends View { // TODO Put your view methods here } @ProxyCodeSplit @NameToken(NameTokens.login) public interface MyProxy extends ProxyPlace<LoginPresenter> { } @Inject public LoginPresenter(final EventBus eventBus, final MyView view, final MyProxy proxy) { super(eventBus, view, proxy); } @Override protected void revealInParent() { RevealContentEvent.fire(this, MainPresenter.MAIN_SLOT, this); } }
Java
package org.dodgybits.shuffle.gwt.core; import com.google.gwt.event.shared.EventBus; import com.google.inject.Inject; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit; import com.gwtplatform.mvp.client.proxy.ProxyPlace; import com.gwtplatform.mvp.client.proxy.RevealRootLayoutContentEvent; import org.dodgybits.shuffle.gwt.place.NameTokens; public class ErrorPresenter extends Presenter<ErrorPresenter.MyView, ErrorPresenter.MyProxy> { public interface MyView extends View { // TODO Put your view methods here } @ProxyCodeSplit @NameToken(NameTokens.error) public interface MyProxy extends ProxyPlace<ErrorPresenter> { } @Inject public ErrorPresenter(final EventBus eventBus, final MyView view, final MyProxy proxy) { super(eventBus, view, proxy); } @Override protected void revealInParent() { RevealRootLayoutContentEvent.fire(this, this); } }
Java
package org.dodgybits.shuffle.gwt.core; import com.gwtplatform.mvp.client.ViewImpl; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; public class WelcomeView extends ViewImpl implements WelcomePresenter.MyView { private final Widget widget; public interface Binder extends UiBinder<Widget, WelcomeView> { } @UiField HTMLPanel mainPanel; @UiField HTML dateField; @Inject public WelcomeView(final Binder binder) { widget = binder.createAndBindUi(this); } @Override public Widget asWidget() { return widget; } @Override public void setFormattedDate(String formattedDate) { dateField.setText(formattedDate); } @Override public void setBackgroundColor(String color) { mainPanel.getElement().getStyle().setBackgroundColor(color); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.dodgybits.shuffle.gwt; import org.dodgybits.shuffle.gwt.gin.ClientGinjector; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.resources.client.ClientBundle; import com.google.gwt.resources.client.CssResource; import com.google.gwt.resources.client.CssResource.NotStrict; import com.gwtplatform.mvp.client.DelayedBindRegistry; /** * Entry point classes define <code>onModuleLoad()</code>. */ public class Shuffle implements EntryPoint { interface GlobalResources extends ClientBundle { @NotStrict @Source("../../../../../resources/org/dodgybits/shuffle/gwt/global.css") CssResource css(); } private final ClientGinjector ginjector = GWT.create(ClientGinjector.class); /** * This is the entry point method. */ public void onModuleLoad() { // Wire the request factory and the event bus ginjector.getRequestFactory().initialize(ginjector.getEventBus()); // Inject global styles. GWT.<GlobalResources> create(GlobalResources.class).css() .ensureInjected(); // This is required for Gwt-Platform proxy's generator DelayedBindRegistry.bind(ginjector); ginjector.getPlaceManager().revealCurrentPlace(); } }
Java