code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.editor.activity; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity; import org.dodgybits.shuffle.android.core.model.Entity; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.encoding.EntityEncoder; import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister; import org.dodgybits.shuffle.android.core.view.MenuUtils; import org.dodgybits.shuffle.android.list.activity.State; import org.dodgybits.shuffle.android.preference.model.Preferences; import android.content.ContentUris; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; /** * A generic activity for editing an item in a database. This can be used either * to simply view an item (Intent.VIEW_ACTION), view and edit an item * (Intent.EDIT_ACTION), or create a new item (Intent.INSERT_ACTION). */ public abstract class AbstractEditorActivity<E extends Entity> extends FlurryEnabledActivity implements View.OnClickListener, View.OnFocusChangeListener { private static final String cTag = "AbstractEditorActivity"; protected int mState; protected Uri mUri; protected Cursor mCursor; protected E mOriginalItem; protected Intent mNextIntent; @Override protected void onCreate(Bundle icicle) { Log.d(cTag, "onCreate+"); super.onCreate(icicle); processIntent(); setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); setContentView(getContentViewResId()); addSavePanelListeners(); Log.d(cTag, "onCreate-"); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: doSaveAction(); break; } return super.onKeyDown(keyCode, event); } @Override public void finish() { if (mNextIntent != null) { startActivity(mNextIntent); } super.finish(); } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); MenuItem item = menu.findItem(MenuUtils.SYNC_ID); if (item != null) { item.setVisible(Preferences.validateTracksSettings(this)); } return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuUtils.addEditorMenuItems(menu, mState); MenuUtils.addPrefsHelpMenuItems(this, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle all of the possible menu actions. switch (item.getItemId()) { case MenuUtils.SAVE_ID: doSaveAction(); break; case MenuUtils.SAVE_AND_ADD_ID: // create an Intent for the new item based on the current item startActivity(getInsertIntent()); doSaveAction(); break; case MenuUtils.DELETE_ID: doDeleteAction(); finish(); break; case MenuUtils.DISCARD_ID: doRevertAction(); break; case MenuUtils.REVERT_ID: doRevertAction(); break; } if (MenuUtils.checkCommonItemsSelected(item, this, MenuUtils.INBOX_ID)) { return true; } return super.onOptionsItemSelected(item); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); E item = createItemFromUI(false); saveItem(outState, item); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); E item = restoreItem(savedInstanceState); updateUIFromItem(item); } @Override public void onFocusChange(View v, boolean hasFocus) { // Because we're emulating a ListView, we need to setSelected() for // views as they are focused. v.setSelected(hasFocus); } public void onClick(View v) { switch (v.getId()) { case R.id.saveButton: doSaveAction(); break; case R.id.discardButton: doRevertAction(); break; } } protected void doSaveAction() { // Save or create the contact if needed Uri result = null; switch (mState) { case State.STATE_EDIT: result = save(); break; case State.STATE_INSERT: result = create(); break; default: Log.e(cTag, "Unknown state in doSaveAction: " + mState); break; } if (result == null) { setResult(RESULT_CANCELED); } else { setResult(RESULT_OK, new Intent().setData(result)); } finish(); } /** * Take care of canceling work on a item. Deletes the item if we had created * it, otherwise reverts to the original text. */ protected void doRevertAction() { if (mCursor != null) { if (mState == State.STATE_EDIT) { // Put the original item back into the database mCursor.close(); mCursor = null; getPersister().update(mOriginalItem); } else if (mState == State.STATE_INSERT) { // if inserting, there's nothing to delete } } setResult(RESULT_CANCELED); finish(); } /** * Take care of deleting a item. Simply deletes the entry. */ protected void doDeleteAction() { // if inserting, there's nothing to delete if (mState == State.STATE_EDIT && mCursor != null) { mCursor.close(); mCursor = null; Id id = Id.create(ContentUris.parseId(mUri)); getPersister().updateDeletedFlag(id, true); } } protected final void showSaveToast() { String text; if (mState == State.STATE_EDIT) { text = getResources().getString(R.string.itemSavedToast, getItemName()); } else { text = getResources().getString(R.string.itemCreatedToast, getItemName()); } Toast.makeText(this, text, Toast.LENGTH_SHORT).show(); } protected boolean isValid() { return true; } protected Uri create() { Uri uri = null; if (isValid()) { E item = createItemFromUI(true); uri = getPersister().insert(item); showSaveToast(); } return uri; } protected Uri save() { Uri uri = null; if (isValid()) { E item = createItemFromUI(true); getPersister().update(item); showSaveToast(); uri = mUri; } return uri; } protected final E restoreItem(Bundle icicle) { return getEncoder().restore(icicle); } protected final void saveItem(Bundle outState, E item) { getEncoder().save(outState, item); } /** * @return id of layout for this view */ abstract protected int getContentViewResId(); abstract protected E createItemFromUI(boolean commitValues); abstract protected void updateUIFromItem(E item); abstract protected void updateUIFromExtras(Bundle extras); abstract protected EntityPersister<E> getPersister(); abstract protected EntityEncoder<E> getEncoder(); abstract protected Intent getInsertIntent(); abstract protected CharSequence getItemName(); private void processIntent() { final Intent intent = getIntent(); // Do some setup based on the action being performed. final String action = intent.getAction(); mUri = intent.getData(); if (action.equals(Intent.ACTION_EDIT)) { // Requested to edit: set that state, and the data being edited. mState = State.STATE_EDIT; } else if (action.equals(Intent.ACTION_INSERT)) { // Requested to insert: set that state, and create a new entry // in the container. mState = State.STATE_INSERT; } else { // Whoops, unknown action! Bail. Log.e(cTag, "Unknown action " + action + ", exiting"); finish(); return; } } private void addSavePanelListeners() { // Setup the bottom buttons View view = findViewById(R.id.saveButton); view.setOnClickListener(this); view = findViewById(R.id.discardButton); view.setOnClickListener(this); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/editor/activity/AbstractEditorActivity.java
Java
asf20
8,288
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.editor.activity; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.android.core.model.Project.Builder; import org.dodgybits.shuffle.android.core.model.encoding.EntityEncoder; import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister; import org.dodgybits.shuffle.android.list.activity.State; import org.dodgybits.shuffle.android.persistence.provider.ContextProvider; import org.dodgybits.shuffle.android.persistence.provider.ProjectProvider; import roboguice.inject.InjectView; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import com.google.inject.Inject; public class ProjectEditorActivity extends AbstractEditorActivity<Project> { private static final String cTag = "ProjectEditorActivity"; @InjectView(R.id.name) EditText mNameWidget; @InjectView(R.id.default_context) Spinner mDefaultContextSpinner; @InjectView(R.id.parallel_entry) RelativeLayout mParallelEntry; @InjectView(R.id.parallel_label) TextView mParallelLabel; @InjectView(R.id.parallel_icon) ImageView mParallelButton; private @InjectView(R.id.active_entry) View mActiveEntry; private @InjectView(R.id.active_entry_checkbox) CheckBox mActiveCheckBox; private @InjectView(R.id.deleted_entry) View mDeletedEntry; private CheckBox mDeletedCheckBox; @Inject private EntityPersister<Project> mPersister; @Inject private EntityEncoder<Project> mEncoder; private String[] mContextNames; private long[] mContextIds; private boolean isParallel; @Override protected void onCreate(Bundle icicle) { Log.d(cTag, "onCreate+"); super.onCreate(icicle); loadCursor(); findViewsAndAddListeners(); if (mState == State.STATE_EDIT) { // Make sure we are at the one and only row in the cursor. mCursor.moveToFirst(); setTitle(R.string.title_edit_project); mOriginalItem = mPersister.read(mCursor); updateUIFromItem(mOriginalItem); } else if (mState == State.STATE_INSERT) { isParallel = false; setTitle(R.string.title_new_project); mDeletedEntry.setVisibility(View.GONE); mDeletedCheckBox.setChecked(false); mActiveCheckBox.setChecked(true); Bundle extras = getIntent().getExtras(); updateUIFromExtras(extras); } } private void findViewsAndAddListeners() { Cursor contactCursor = getContentResolver().query( ContextProvider.Contexts.CONTENT_URI, new String[] {ContextProvider.Contexts._ID, ContextProvider.Contexts.NAME}, null, null, null); int size = contactCursor.getCount() + 1; mContextIds = new long[size]; mContextIds[0] = 0; mContextNames = new String[size]; mContextNames[0] = getText(R.string.none_empty).toString(); for (int i = 1; i < size; i++) { contactCursor.moveToNext(); mContextIds[i] = contactCursor.getLong(0); mContextNames[i] = contactCursor.getString(1); } contactCursor.close(); ArrayAdapter<String> adapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, mContextNames); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mDefaultContextSpinner.setAdapter(adapter); mParallelEntry.setOnClickListener(this); mActiveEntry.setOnClickListener(this); mActiveEntry.setOnFocusChangeListener(this); mDeletedEntry.setOnClickListener(this); mDeletedEntry.setOnFocusChangeListener(this); mDeletedCheckBox = (CheckBox) mDeletedEntry.findViewById(R.id.deleted_entry_checkbox); } @Override protected boolean isValid() { String name = mNameWidget.getText().toString(); return !TextUtils.isEmpty(name); } @Override protected void doDeleteAction() { super.doDeleteAction(); mNameWidget.setText(""); } @Override protected Project createItemFromUI(boolean commitValues) { Builder builder = Project.newBuilder(); if (mOriginalItem != null) { builder.mergeFrom(mOriginalItem); } builder.setName(mNameWidget.getText().toString()); builder.setModifiedDate(System.currentTimeMillis()); builder.setParallel(isParallel); Id defaultContextId = Id.NONE; int selectedItemPosition = mDefaultContextSpinner.getSelectedItemPosition(); if (selectedItemPosition > 0) { defaultContextId = Id.create(mContextIds[selectedItemPosition]); } builder.setDefaultContextId(defaultContextId); builder.setDeleted(mDeletedCheckBox.isChecked()); builder.setActive(mActiveCheckBox.isChecked()); return builder.build(); } @Override protected void updateUIFromExtras(Bundle extras) { // do nothing for now } @Override protected void updateUIFromItem(Project project) { mNameWidget.setTextKeepState(project.getName()); Id defaultContextId = project.getDefaultContextId(); if (defaultContextId.isInitialised()) { for (int i = 1; i < mContextIds.length; i++) { if (mContextIds[i] == defaultContextId.getId()) { mDefaultContextSpinner.setSelection(i); break; } } } else { mDefaultContextSpinner.setSelection(0); } isParallel = project.isParallel(); updateParallelSection(); mActiveCheckBox.setChecked(project.isActive()); mDeletedEntry.setVisibility(project.isDeleted() ? View.VISIBLE : View.GONE); mDeletedCheckBox.setChecked(project.isDeleted()); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.parallel_entry: { isParallel = !isParallel; updateParallelSection(); break; } case R.id.active_entry: { mActiveCheckBox.toggle(); break; } case R.id.deleted_entry: { mDeletedCheckBox.toggle(); break; } default: super.onClick(v); break; } } /** * @return id of layout for this view */ @Override protected int getContentViewResId() { return R.layout.project_editor; } @Override protected Intent getInsertIntent() { return new Intent(Intent.ACTION_INSERT, ProjectProvider.Projects.CONTENT_URI); } @Override protected CharSequence getItemName() { return getString(R.string.project_name); } @Override protected EntityEncoder<Project> getEncoder() { return mEncoder; } @Override protected EntityPersister<Project> getPersister() { return mPersister; } private void loadCursor() { if (mUri != null && mState == State.STATE_EDIT) { mCursor = managedQuery(mUri, ProjectProvider.Projects.FULL_PROJECTION, null, null, null); if (mCursor == null || mCursor.getCount() == 0) { // The cursor is empty. This can happen if the event was deleted. finish(); return; } } } private void updateParallelSection() { if (isParallel) { mParallelLabel.setText(R.string.parallel_title); mParallelButton.setImageResource(R.drawable.parallel); } else { mParallelLabel.setText(R.string.sequence_title); mParallelButton.setImageResource(R.drawable.sequence); } } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/editor/activity/ProjectEditorActivity.java
Java
asf20
8,950
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.editor.activity; import java.util.*; import android.provider.BaseColumns; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Task; import org.dodgybits.shuffle.android.core.model.Task.Builder; import org.dodgybits.shuffle.android.core.model.encoding.EntityEncoder; import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister; import org.dodgybits.shuffle.android.core.model.persistence.TaskPersister; import org.dodgybits.shuffle.android.core.util.CalendarUtils; import org.dodgybits.shuffle.android.core.util.Constants; import org.dodgybits.shuffle.android.core.util.OSUtils; import org.dodgybits.shuffle.android.list.activity.State; import org.dodgybits.shuffle.android.persistence.provider.ContextProvider; import org.dodgybits.shuffle.android.persistence.provider.ProjectProvider; import org.dodgybits.shuffle.android.persistence.provider.ReminderProvider; import org.dodgybits.shuffle.android.persistence.provider.TaskProvider; import org.dodgybits.shuffle.android.preference.model.Preferences; import roboguice.inject.InjectView; import android.app.Activity; import android.app.DatePickerDialog; import android.app.TimePickerDialog; import android.app.DatePickerDialog.OnDateSetListener; import android.app.TimePickerDialog.OnTimeSetListener; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.text.format.DateFormat; import android.text.format.DateUtils; import android.text.format.Time; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.TimePicker; import com.google.inject.Inject; import roboguice.util.Ln; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.DISPLAY_ORDER; /** * A generic activity for editing a task in the database. This can be used * either to simply view a task (Intent.VIEW_ACTION), view and edit a task * (Intent.EDIT_ACTION), or create a new task (Intent.INSERT_ACTION). */ public class TaskEditorActivity extends AbstractEditorActivity<Task> implements CompoundButton.OnCheckedChangeListener { private static final String cTag = "TaskEditorActivity"; private static final String[] cContextProjection = new String[] { ContextProvider.Contexts._ID, ContextProvider.Contexts.NAME }; private static final String[] cProjectProjection = new String[] { ProjectProvider.Projects._ID, ProjectProvider.Projects.NAME }; private static final String REMINDERS_WHERE = ReminderProvider.Reminders.TASK_ID + "=? AND (" + ReminderProvider.Reminders.METHOD + "=" + ReminderProvider.Reminders.METHOD_ALERT + " OR " + ReminderProvider.Reminders.METHOD + "=" + ReminderProvider.Reminders.METHOD_DEFAULT + ")"; private static final int MAX_REMINDERS = 3; private static final int cNewContextCode = 100; private static final int cNewProjectCode = 101; private @InjectView(R.id.description) EditText mDescriptionWidget; private @InjectView(R.id.context) Spinner mContextSpinner; private @InjectView(R.id.project) Spinner mProjectSpinner; private @InjectView(R.id.details) EditText mDetailsWidget; private String[] mContextNames; private long[] mContextIds; private String[] mProjectNames; private long[] mProjectIds; private boolean mSchedulingExpanded; private @InjectView(R.id.start_date) Button mStartDateButton; private @InjectView(R.id.due_date) Button mDueDateButton; private @InjectView(R.id.start_time) Button mStartTimeButton; private @InjectView(R.id.due_time) Button mDueTimeButton; private @InjectView(R.id.clear_dates) Button mClearButton; private @InjectView(R.id.is_all_day) CheckBox mAllDayCheckBox; private boolean mShowStart; private Time mStartTime; private boolean mShowDue; private Time mDueTime; private View mSchedulingExtra; private TextView mSchedulingDetail; private View mExpandButton; private View mCollapseButton; private @InjectView(R.id.completed_entry) View mCompleteEntry; private CheckBox mCompletedCheckBox; private @InjectView(R.id.deleted_entry) View mDeletedEntry; private @InjectView(R.id.deleted_entry_checkbox) CheckBox mDeletedCheckBox; private @InjectView(R.id.gcal_entry) View mUpdateCalendarEntry; private CheckBox mUpdateCalendarCheckBox; private TextView mCalendarLabel; private TextView mCalendarDetail; private ArrayList<Integer> mReminderValues; private ArrayList<String> mReminderLabels; private int mDefaultReminderMinutes; private @InjectView(R.id.reminder_items_container) LinearLayout mRemindersContainer; private ArrayList<Integer> mOriginalMinutes = new ArrayList<Integer>(); private ArrayList<LinearLayout> mReminderItems = new ArrayList<LinearLayout>(0); @Inject private TaskPersister mPersister; @Inject private EntityEncoder<Task> mEncoder; @Override protected void onCreate(Bundle icicle) { Log.d(cTag, "onCreate+"); super.onCreate(icicle); mStartTime = new Time(); mDueTime = new Time(); loadCursors(); findViewsAndAddListeners(); if (mState == State.STATE_EDIT) { // Make sure we are at the one and only row in the cursor. mCursor.moveToFirst(); // Modify our overall title depending on the mode we are running in. setTitle(R.string.title_edit_task); mCompleteEntry.setVisibility(View.VISIBLE); mOriginalItem = mPersister.read(mCursor); updateUIFromItem(mOriginalItem); } else if (mState == State.STATE_INSERT) { setTitle(R.string.title_new_task); mCompleteEntry.setVisibility(View.GONE); mDeletedEntry.setVisibility(View.GONE); mDeletedCheckBox.setChecked(false); // see if the context or project were suggested for this task Bundle extras = getIntent().getExtras(); updateUIFromExtras(extras); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(cTag, "Got resultCode " + resultCode + " with data " + data); switch (requestCode) { case cNewContextCode: if (resultCode == Activity.RESULT_OK) { if (data != null) { long newContextId = ContentUris.parseId(data.getData()); setupContextSpinner(); setSpinnerSelection(mContextSpinner, mContextIds, newContextId); } } break; case cNewProjectCode: if (resultCode == Activity.RESULT_OK) { if (data != null) { long newProjectId = ContentUris.parseId(data.getData()); setupProjectSpinner(); setSpinnerSelection(mProjectSpinner, mProjectIds, newProjectId); } } break; default: Log.e(cTag, "Unknown requestCode: " + requestCode); } } @Override protected boolean isValid() { String description = mDescriptionWidget.getText().toString(); return !TextUtils.isEmpty(description); } @Override protected void updateUIFromExtras(Bundle extras) { if (extras != null) { Long contextId = extras.getLong(TaskProvider.Tasks.CONTEXT_ID); setSpinnerSelection(mContextSpinner, mContextIds, contextId); Long projectId = extras.getLong(TaskProvider.Tasks.PROJECT_ID); setSpinnerSelection(mProjectSpinner, mProjectIds, projectId); } setWhenDefaults(); populateWhen(); setSchedulingVisibility(false); mStartTimeButton.setVisibility(View.VISIBLE); mDueTimeButton.setVisibility(View.VISIBLE); updateCalendarPanel(); updateRemindersVisibility(); } @Override protected void updateUIFromItem(Task task) { // If we hadn't previously retrieved the original task, do so // now. This allows the user to revert their changes. if (mOriginalItem == null) { mOriginalItem = task; } final String details = task.getDetails(); mDetailsWidget.setTextKeepState(details == null ? "" : details); mDescriptionWidget.setTextKeepState(task.getDescription()); final Id contextId = task.getContextId(); if (contextId.isInitialised()) { setSpinnerSelection(mContextSpinner, mContextIds, contextId.getId()); } final Id projectId = task.getProjectId(); if (projectId.isInitialised()) { setSpinnerSelection(mProjectSpinner, mProjectIds, projectId.getId()); } boolean allDay = task.isAllDay(); if (allDay) { String tz = mStartTime.timezone; mStartTime.timezone = Time.TIMEZONE_UTC; mStartTime.set(task.getStartDate()); mStartTime.timezone = tz; // Calling normalize to calculate isDst mStartTime.normalize(true); } else { mStartTime.set(task.getStartDate()); } if (allDay) { String tz = mStartTime.timezone; mDueTime.timezone = Time.TIMEZONE_UTC; mDueTime.set(task.getDueDate()); mDueTime.timezone = tz; // Calling normalize to calculate isDst mDueTime.normalize(true); } else { mDueTime.set(task.getDueDate()); } setWhenDefaults(); populateWhen(); // show scheduling section if either start or due date are set mSchedulingExpanded = mShowStart || mShowDue; setSchedulingVisibility(mSchedulingExpanded); mAllDayCheckBox.setChecked(allDay); updateTimeVisibility(!allDay); mCompletedCheckBox.setChecked(task.isComplete()); mDeletedEntry.setVisibility(task.isDeleted() ? View.VISIBLE : View.GONE); mDeletedCheckBox.setChecked(task.isDeleted()); updateCalendarPanel(); // Load reminders (if there are any) if (task.hasAlarms()) { Uri uri = ReminderProvider.Reminders.CONTENT_URI; ContentResolver cr = getContentResolver(); Cursor reminderCursor = cr.query(uri, ReminderProvider.Reminders.cFullProjection, REMINDERS_WHERE, new String[] {String.valueOf(task.getLocalId().getId())}, null); try { // First pass: collect all the custom reminder minutes (e.g., // a reminder of 8 minutes) into a global list. while (reminderCursor.moveToNext()) { int minutes = reminderCursor.getInt(ReminderProvider.Reminders.MINUTES_INDEX); addMinutesToList(this, mReminderValues, mReminderLabels, minutes); } // Second pass: create the reminder spinners reminderCursor.moveToPosition(-1); while (reminderCursor.moveToNext()) { int minutes = reminderCursor.getInt(ReminderProvider.Reminders.MINUTES_INDEX); mOriginalMinutes.add(minutes); addReminder(this, this, mReminderItems, mReminderValues, mReminderLabels, minutes); } } finally { reminderCursor.close(); } } updateRemindersVisibility(); } @Override protected Task createItemFromUI(boolean commitValues) { Builder builder = Task.newBuilder(); if (mOriginalItem != null) { builder.mergeFrom(mOriginalItem); } final String description = mDescriptionWidget.getText().toString(); final long modified = System.currentTimeMillis(); final String details = mDetailsWidget.getText().toString(); final Id contextId = getSpinnerSelectedId(mContextSpinner, mContextIds); final Id projectId = getSpinnerSelectedId(mProjectSpinner, mProjectIds); final boolean allDay = mAllDayCheckBox.isChecked(); final boolean complete = mCompletedCheckBox.isChecked(); final boolean hasAlarms = !mReminderItems.isEmpty(); final boolean deleted = mDeletedCheckBox.isChecked(); final boolean active = true; builder .setDescription(description) .setModifiedDate(modified) .setDetails(details) .setContextId(contextId) .setProjectId(projectId) .setAllDay(allDay) .setComplete(complete) .setDeleted(deleted) .setActive(active) .setHasAlarm(hasAlarms); // If we are creating a new task, set the creation date if (mState == State.STATE_INSERT) { builder.setCreatedDate(modified); } String timezone; long startMillis = 0L; long dueMillis = 0L; if (allDay) { // Reset start and end time, increment the monthDay by 1, and set // the timezone to UTC, as required for all-day events. timezone = Time.TIMEZONE_UTC; mStartTime.hour = 0; mStartTime.minute = 0; mStartTime.second = 0; mStartTime.timezone = timezone; startMillis = mStartTime.normalize(true); mDueTime.hour = 0; mDueTime.minute = 0; mDueTime.second = 0; mDueTime.monthDay++; mDueTime.timezone = timezone; dueMillis = mDueTime.normalize(true); } else { if (mShowStart && !Time.isEpoch(mStartTime)) { startMillis = mStartTime.toMillis(true); } if (mShowDue && !Time.isEpoch(mDueTime)) { dueMillis = mDueTime.toMillis(true); } if (mState == State.STATE_INSERT) { // The timezone for a new task is the currently displayed timezone timezone = TimeZone.getDefault().getID(); } else { timezone = mOriginalItem.getTimezone(); // The timezone might be null if we are changing an existing // all-day task to a non-all-day event. We need to assign // a timezone to the non-all-day task. if (TextUtils.isEmpty(timezone)) { timezone = TimeZone.getDefault().getID(); } } } final int order; if (commitValues) { order = mPersister.calculateTaskOrder(mOriginalItem, projectId, dueMillis); } else if (mOriginalItem == null) { order = 0; } else { order = mOriginalItem.getOrder(); } builder .setTimezone(timezone) .setStartDate(startMillis) .setDueDate(dueMillis) .setOrder(order); Id eventId = mOriginalItem == null ? Id.NONE : mOriginalItem.getCalendarEventId(); final boolean updateCalendar = mUpdateCalendarCheckBox.isChecked(); if (updateCalendar) { Uri calEntryUri = addOrUpdateCalendarEvent( eventId, description, details, projectId, contextId, timezone, startMillis, dueMillis, allDay); if (calEntryUri != null) { eventId = Id.create(ContentUris.parseId(calEntryUri)); mNextIntent = new Intent(Intent.ACTION_EDIT, calEntryUri); mNextIntent.putExtra("beginTime", startMillis); mNextIntent.putExtra("endTime", dueMillis); } Log.i(cTag, "Updated calendar event " + eventId); } builder.setCalendarEventId(eventId); return builder.build(); } @Override protected EntityEncoder<Task> getEncoder() { return mEncoder; } @Override protected EntityPersister<Task> getPersister() { return mPersister; } private Uri addOrUpdateCalendarEvent( Id calEventId, String title, String description, Id projectId, Id contextId, String timezone, long start, long end, boolean allDay) { if (projectId.isInitialised()) { String projectName = getProjectName(projectId); title = projectName + " - " + title; } if (description == null) { description = ""; } ContentValues values = new ContentValues(); if (!TextUtils.isEmpty(timezone)) { values.put("eventTimezone", timezone); } values.put("calendar_id", Preferences.getCalendarId(this)); values.put("title", title); values.put("allDay", allDay ? 1 : 0); if (start > 0L) { values.put("dtstart", start); // long (start date in ms) } if (end > 0L) { values.put("dtend", end); // long (end date in ms) } values.put("description", description); values.put("hasAlarm", 0); values.put("transparency", 0); values.put("visibility", 0); if (contextId.isInitialised()) { String contextName = getContextName(contextId); values.put("eventLocation", contextName); } Uri eventUri = null; try { eventUri = addCalendarEntry(values, calEventId, CalendarUtils.getEventContentUri()); } catch (Exception e) { Log.e(cTag, "Attempt failed to create calendar entry", e); mAnalytics.onError(Constants.cFlurryCalendarUpdateError, e.getMessage(), getClass().getName()); } return eventUri; } private Uri addCalendarEntry(ContentValues values, Id oldId, Uri baseUri) { ContentResolver cr = getContentResolver(); int updateCount = 0; Uri eventUri = null; if (oldId.isInitialised()) { eventUri = ContentUris.appendId(baseUri.buildUpon(), oldId.getId()).build(); // it's possible the old event was deleted, check number of records updated updateCount = cr.update(eventUri, values, null, null); } if (updateCount == 0) { eventUri = cr.insert(baseUri, values); } return eventUri; } @Override protected Intent getInsertIntent() { Intent intent = new Intent(Intent.ACTION_INSERT, TaskProvider.Tasks.CONTENT_URI); // give new task the same project and context as this one Bundle extras = intent.getExtras(); if (extras == null) extras = new Bundle(); Id contextId = getSpinnerSelectedId(mContextSpinner, mContextIds); if (contextId.isInitialised()) { extras.putLong(TaskProvider.Tasks.CONTEXT_ID, contextId.getId()); } Id projectId = getSpinnerSelectedId(mProjectSpinner, mProjectIds); if (projectId.isInitialised()) { extras.putLong(TaskProvider.Tasks.PROJECT_ID, projectId.getId()); } intent.putExtras(extras); return intent; } @Override protected Uri create() { Uri uri = super.create(); if (uri != null) { ContentResolver cr = getContentResolver(); ArrayList<Integer> reminderMinutes = reminderItemsToMinutes(mReminderItems, mReminderValues); long taskId = ContentUris.parseId(uri); saveReminders(cr, taskId, reminderMinutes, mOriginalMinutes); } return uri; } @Override protected Uri save() { Uri uri = super.save(); if (uri != null) { ContentResolver cr = getContentResolver(); ArrayList<Integer> reminderMinutes = reminderItemsToMinutes(mReminderItems, mReminderValues); long taskId = ContentUris.parseId(uri); saveReminders(cr, taskId, reminderMinutes, mOriginalMinutes); } return uri; } /** * @return id of layout for this view */ @Override protected int getContentViewResId() { return R.layout.task_editor; } @Override protected CharSequence getItemName() { return getString(R.string.task_name); } /** * Take care of deleting a task. Simply deletes the entry. */ @Override protected void doDeleteAction() { super.doDeleteAction(); mDescriptionWidget.setText(""); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.context_add: { Intent addContextIntent = new Intent(Intent.ACTION_INSERT, ContextProvider.Contexts.CONTENT_URI); startActivityForResult(addContextIntent, cNewContextCode); break; } case R.id.project_add: { Intent addProjectIntent = new Intent(Intent.ACTION_INSERT, ProjectProvider.Projects.CONTENT_URI); startActivityForResult(addProjectIntent, cNewProjectCode); break; } case R.id.scheduling_entry: { toggleSchedulingSection(); break; } case R.id.completed_entry: { mCompletedCheckBox.toggle(); break; } case R.id.deleted_entry: { mDeletedCheckBox.toggle(); break; } case R.id.gcal_entry: { CheckBox checkBox = (CheckBox) v.findViewById(R.id.update_calendar_checkbox); checkBox.toggle(); break; } case R.id.clear_dates: { mAllDayCheckBox.setChecked(false); mStartTime = new Time(); mDueTime = new Time(); setWhenDefaults(); populateWhen(); updateCalendarPanel(); break; } case R.id.reminder_remove: { LinearLayout reminderItem = (LinearLayout) v.getParent(); LinearLayout parent = (LinearLayout) reminderItem.getParent(); parent.removeView(reminderItem); mReminderItems.remove(reminderItem); updateRemindersVisibility(); break; } default: super.onClick(v); break; } } public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { if (mDueTime.hour == 0 && mDueTime.minute == 0) { mDueTime.monthDay--; // Do not allow an event to have an end time before the start time. if (mDueTime.before(mStartTime)) { mDueTime.set(mStartTime); } } } else { if (mDueTime.hour == 0 && mDueTime.minute == 0) { mDueTime.monthDay++; } } mShowStart = true; long startMillis = mStartTime.normalize(true); setDate(mStartDateButton, startMillis, mShowStart); setTime(mStartTimeButton, startMillis, mShowStart); mShowDue = true; long dueMillis = mDueTime.normalize(true); setDate(mDueDateButton, dueMillis, mShowDue); setTime(mDueTimeButton, dueMillis, mShowDue); updateTimeVisibility(!isChecked); } private void updateTimeVisibility(boolean showTime) { if (showTime) { mStartTimeButton.setVisibility(View.VISIBLE); mDueTimeButton.setVisibility(View.VISIBLE); } else { mStartTimeButton.setVisibility(View.GONE); mDueTimeButton.setVisibility(View.GONE); } } private void loadCursors() { // Get the task if we're editing if (mUri != null && mState == State.STATE_EDIT) { mCursor = managedQuery(mUri, TaskProvider.Tasks.FULL_PROJECTION, null, null, null); if (mCursor == null || mCursor.getCount() == 0) { // The cursor is empty. This can happen if the event was deleted. finish(); } } } private void findViewsAndAddListeners() { // The text view for our task description, identified by its ID in the XML file. setupContextSpinner(); ImageButton addContextButton = (ImageButton) findViewById(R.id.context_add); addContextButton.setOnClickListener(this); addContextButton.setOnFocusChangeListener(this); setupProjectSpinner(); ImageButton addProjectButton = (ImageButton) findViewById(R.id.project_add); addProjectButton.setOnClickListener(this); addProjectButton.setOnFocusChangeListener(this); mCompleteEntry.setOnClickListener(this); mCompleteEntry.setOnFocusChangeListener(this); mCompletedCheckBox = (CheckBox) mCompleteEntry.findViewById(R.id.completed_entry_checkbox); mDeletedEntry.setOnClickListener(this); mDeletedEntry.setOnFocusChangeListener(this); mUpdateCalendarEntry.setOnClickListener(this); mUpdateCalendarEntry.setOnFocusChangeListener(this); mUpdateCalendarCheckBox = (CheckBox) mUpdateCalendarEntry.findViewById(R.id.update_calendar_checkbox); mCalendarLabel = (TextView) mUpdateCalendarEntry.findViewById(R.id.gcal_label); mCalendarDetail = (TextView) mUpdateCalendarEntry.findViewById(R.id.gcal_detail); mStartDateButton.setOnClickListener(new DateClickListener(mStartTime)); mStartTimeButton.setOnClickListener(new TimeClickListener(mStartTime)); mDueDateButton.setOnClickListener(new DateClickListener(mDueTime)); mDueTimeButton.setOnClickListener(new TimeClickListener(mDueTime)); mAllDayCheckBox.setOnCheckedChangeListener(this); mClearButton.setOnClickListener(this); ViewGroup schedulingSection = (ViewGroup) findViewById(R.id.scheduling_section); View schedulingEntry = findViewById(R.id.scheduling_entry); schedulingEntry.setOnClickListener(this); schedulingEntry.setOnFocusChangeListener(this); mSchedulingExtra = schedulingSection.findViewById(R.id.scheduling_extra); mExpandButton = schedulingEntry.findViewById(R.id.expand); mCollapseButton = schedulingEntry.findViewById(R.id.collapse); mSchedulingDetail = (TextView) schedulingEntry.findViewById(R.id.scheduling_detail); mSchedulingExpanded = mSchedulingExtra.getVisibility() == View.VISIBLE; // Initialize the reminder values array. Resources r = getResources(); String[] strings = r.getStringArray(R.array.reminder_minutes_values); ArrayList<Integer> list = new ArrayList<Integer>(strings.length); for (String numberString: strings) { list.add(Integer.parseInt(numberString)); } mReminderValues = list; String[] labels = r.getStringArray(R.array.reminder_minutes_labels); mReminderLabels = new ArrayList<String>(Arrays.asList(labels)); mDefaultReminderMinutes = Preferences.getDefaultReminderMinutes(this); // Setup the + Add Reminder Button ImageButton reminderAddButton = (ImageButton) findViewById(R.id.reminder_add); reminderAddButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { addReminder(); } }); } private void setupContextSpinner() { Cursor contextCursor = getContentResolver().query( ContextProvider.Contexts.CONTENT_URI, cContextProjection, ContextProvider.Contexts.DELETED + "=0", null, ContextProvider.Contexts.NAME + " ASC"); int arraySize = contextCursor.getCount() + 1; mContextIds = new long[arraySize]; mContextIds[0] = 0; mContextNames = new String[arraySize]; mContextNames[0] = getText(R.string.none_empty).toString(); for (int i = 1; i < arraySize; i++) { contextCursor.moveToNext(); mContextIds[i] = contextCursor.getLong(0); mContextNames[i] = contextCursor.getString(1); } contextCursor.close(); ArrayAdapter<String> adapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, mContextNames); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mContextSpinner.setAdapter(adapter); } private void setupProjectSpinner() { Cursor projectCursor = getContentResolver().query( ProjectProvider.Projects.CONTENT_URI, cProjectProjection, ProjectProvider.Projects.DELETED + " = 0", null, ProjectProvider.Projects.NAME + " ASC"); int arraySize = projectCursor.getCount() + 1; mProjectIds = new long[arraySize]; mProjectIds[0] = 0; mProjectNames = new String[arraySize]; mProjectNames[0] = getText(R.string.none_empty).toString(); for (int i = 1; i < arraySize; i++) { projectCursor.moveToNext(); mProjectIds[i] = projectCursor.getLong(0); mProjectNames[i] = projectCursor.getString(1); } projectCursor.close(); ArrayAdapter<String> adapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, mProjectNames); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mProjectSpinner.setAdapter(adapter); } private Id getSpinnerSelectedId(Spinner spinner, long[] ids) { Id id = Id.NONE; int selectedItemPosition = spinner.getSelectedItemPosition(); if (selectedItemPosition > 0) { id = Id.create(ids[selectedItemPosition]); } return id; } private void setSpinnerSelection(Spinner spinner, long[] ids, Long id) { if (id == null || id == 0) { spinner.setSelection(0); } else { for (int i = 1; i < ids.length; i++) { if (ids[i] == id) { spinner.setSelection(i); break; } } } } private String getContextName(Id contextId) { String name = ""; final long id = contextId.getId(); for(int i = 0; i < mContextIds.length; i++) { long currentId = mContextIds[i]; if (currentId == id) { name = mContextNames[i]; break; } } return name; } private String getProjectName(Id projectId) { String name = ""; final long id = projectId.getId(); for(int i = 0; i < mProjectIds.length; i++) { long currentId = mProjectIds[i]; if (currentId == id) { name = mProjectNames[i]; break; } } return name; } private void addReminder() { if (mDefaultReminderMinutes == 0) { addReminder(this, this, mReminderItems, mReminderValues, mReminderLabels, 10 /* minutes */); } else { addReminder(this, this, mReminderItems, mReminderValues, mReminderLabels, mDefaultReminderMinutes); } updateRemindersVisibility(); } // Adds a reminder to the displayed list of reminders. // Returns true if successfully added reminder, false if no reminders can // be added. static boolean addReminder(Activity activity, View.OnClickListener listener, ArrayList<LinearLayout> items, ArrayList<Integer> values, ArrayList<String> labels, int minutes) { if (items.size() >= MAX_REMINDERS) { return false; } LayoutInflater inflater = activity.getLayoutInflater(); LinearLayout parent = (LinearLayout) activity.findViewById(R.id.reminder_items_container); LinearLayout reminderItem = (LinearLayout) inflater.inflate(R.layout.edit_reminder_item, null); parent.addView(reminderItem); Spinner spinner = (Spinner) reminderItem.findViewById(R.id.reminder_value); Resources res = activity.getResources(); spinner.setPrompt(res.getString(R.string.reminders_title)); int resource = android.R.layout.simple_spinner_item; ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity, resource, labels); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); ImageButton reminderRemoveButton; reminderRemoveButton = (ImageButton) reminderItem.findViewById(R.id.reminder_remove); reminderRemoveButton.setOnClickListener(listener); int index = findMinutesInReminderList(values, minutes); spinner.setSelection(index); items.add(reminderItem); return true; } private void toggleSchedulingSection() { mSchedulingExpanded = !mSchedulingExpanded; setSchedulingVisibility(mSchedulingExpanded); } private void setSchedulingVisibility(boolean visible) { if (visible) { mSchedulingExtra.setVisibility(View.VISIBLE); mExpandButton.setVisibility(View.GONE); mCollapseButton.setVisibility(View.VISIBLE); mSchedulingDetail.setText(R.string.scheduling_expanded); } else { mSchedulingExtra.setVisibility(View.GONE); mExpandButton.setVisibility(View.VISIBLE); mCollapseButton.setVisibility(View.GONE); mSchedulingDetail.setText(R.string.scheduling_collapsed); } } private void setWhenDefaults() { // it's possible to have: // 1) no times set // 2) due time set, but not start time // 3) start and due time set mShowStart = !Time.isEpoch(mStartTime); mShowDue = !Time.isEpoch(mDueTime); if (!mShowStart && !mShowDue) { mStartTime.setToNow(); // Round the time to the nearest half hour. mStartTime.second = 0; int minute = mStartTime.minute; if (minute > 0 && minute <= 30) { mStartTime.minute = 30; } else { mStartTime.minute = 0; mStartTime.hour += 1; } long startMillis = mStartTime.normalize(true /* ignore isDst */); mDueTime.set(startMillis + DateUtils.HOUR_IN_MILLIS); } else if (!mShowStart) { // default start to same as due mStartTime.set(mDueTime); } } private void populateWhen() { long startMillis = mStartTime.toMillis(false /* use isDst */); long endMillis = mDueTime.toMillis(false /* use isDst */); setDate(mStartDateButton, startMillis, mShowStart); setDate(mDueDateButton, endMillis, mShowDue); setTime(mStartTimeButton, startMillis, mShowStart); setTime(mDueTimeButton, endMillis, mShowDue); } private void setDate(TextView view, long millis, boolean showValue) { CharSequence value; if (showValue) { int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_ABBREV_WEEKDAY; value = DateUtils.formatDateTime(this, millis, flags); } else { value = ""; } view.setText(value); } private void setTime(TextView view, long millis, boolean showValue) { CharSequence value; if (showValue) { int flags = DateUtils.FORMAT_SHOW_TIME; if (DateFormat.is24HourFormat(this)) { flags |= DateUtils.FORMAT_24HOUR; } value = DateUtils.formatDateTime(this, millis, flags); } else { value = ""; } view.setText(value); } /** * Calculate where this task should appear on the list for the given project. * If no project is defined, order is meaningless, so return -1. * * New tasks go on the end of the list if no due date is defined. * If due date is defined, add either to the start, or after the task * closest to the end of the list with an earlier due date. * * For existing tasks, check if the project changed, and if so * treat like a new task, otherwise leave the order as is. * * @param projectId the project selected for this task * @param dueMillis due date of this task (or 0L if not defined) * @return 0-indexed order of task when displayed in the project view */ private int calculateTaskOrder(Id projectId, long dueMillis) { if (!projectId.isInitialised()) return -1; int order; if (mState == State.STATE_INSERT || !projectId.equals(mOriginalItem.getProjectId())) { // get current highest order value Cursor cursor = getContentResolver().query( TaskProvider.Tasks.CONTENT_URI, new String[] {BaseColumns._ID, TaskProvider.Tasks.DISPLAY_ORDER, TaskProvider.Tasks.DUE_DATE}, TaskProvider.Tasks.PROJECT_ID + " = ?", new String[] {String.valueOf(projectId.getId())}, TaskProvider.Tasks.DISPLAY_ORDER + " desc"); if (cursor.moveToFirst()) { if (dueMillis > 0L) { Ln.d("Due date defined - finding best place to insert in project task list"); Map<Long,Integer> updateValues = new HashMap<Long,Integer>(); do { long previousId = cursor.getLong(0); int previousOrder = cursor.getInt(1); long previousDueDate = cursor.getLong(2); if (previousDueDate > 0L && previousDueDate < dueMillis) { order = previousOrder + 1; Ln.d("Placing after task %d with earlier due date", previousId); break; } updateValues.put(previousId, previousOrder + 1); order = previousOrder; } while (cursor.moveToNext()); moveFollowingTasks(updateValues); } else { // no due date so put at end of list int highestOrder = cursor.getInt(1); order = highestOrder + 1; } } else { // no tasks in the project yet. order = 0; } cursor.close(); } else { order = mOriginalItem.getOrder(); } return order; } private void moveFollowingTasks(Map<Long,Integer> updateValues) { Set<Long> ids = updateValues.keySet(); ContentValues values = new ContentValues(); ContentResolver resolver = getContentResolver(); for (long id : ids) { values.clear(); values.put(DISPLAY_ORDER, updateValues.get(id)); Uri uri = ContentUris.withAppendedId(TaskProvider.Tasks.CONTENT_URI, id); resolver.update(uri, values, null, null); } } static void addMinutesToList(android.content.Context context, ArrayList<Integer> values, ArrayList<String> labels, int minutes) { int index = values.indexOf(minutes); if (index != -1) { return; } // The requested "minutes" does not exist in the list, so insert it // into the list. String label = constructReminderLabel(context, minutes, false); int len = values.size(); for (int i = 0; i < len; i++) { if (minutes < values.get(i)) { values.add(i, minutes); labels.add(i, label); return; } } values.add(minutes); labels.add(len, label); } /** * Finds the index of the given "minutes" in the "values" list. * * @param values the list of minutes corresponding to the spinner choices * @param minutes the minutes to search for in the values list * @return the index of "minutes" in the "values" list */ private static int findMinutesInReminderList(ArrayList<Integer> values, int minutes) { int index = values.indexOf(minutes); if (index == -1) { // This should never happen. Log.e(cTag, "Cannot find minutes (" + minutes + ") in list"); return 0; } return index; } // Constructs a label given an arbitrary number of minutes. For example, // if the given minutes is 63, then this returns the string "63 minutes". // As another example, if the given minutes is 120, then this returns // "2 hours". static String constructReminderLabel(android.content.Context context, int minutes, boolean abbrev) { Resources resources = context.getResources(); int value, resId; if (minutes % 60 != 0) { value = minutes; if (abbrev) { resId = R.plurals.Nmins; } else { resId = R.plurals.Nminutes; } } else if (minutes % (24 * 60) != 0) { value = minutes / 60; resId = R.plurals.Nhours; } else { value = minutes / ( 24 * 60); resId = R.plurals.Ndays; } String format = resources.getQuantityString(resId, value); return String.format(format, value); } private void updateRemindersVisibility() { if (mReminderItems.size() == 0) { mRemindersContainer.setVisibility(View.GONE); } else { mRemindersContainer.setVisibility(View.VISIBLE); } } private void updateCalendarPanel() { boolean enabled = true; if (mOriginalItem != null && mOriginalItem.getCalendarEventId().isInitialised()) { mCalendarLabel.setText(getString(R.string.update_gcal_title)); mCalendarDetail.setText(getString(R.string.update_gcal_detail)); } else if (mShowDue && mShowStart) { mCalendarLabel.setText(getString(R.string.add_to_gcal_title)); mCalendarDetail.setText(getString(R.string.add_to_gcal_detail)); } else { mCalendarLabel.setText(getString(R.string.add_to_gcal_title)); mCalendarDetail.setText(getString(R.string.add_to_gcal_detail_disabled)); enabled = false; } mUpdateCalendarEntry.setEnabled(enabled); mUpdateCalendarCheckBox.setEnabled(enabled); } static ArrayList<Integer> reminderItemsToMinutes(ArrayList<LinearLayout> reminderItems, ArrayList<Integer> reminderValues) { int len = reminderItems.size(); ArrayList<Integer> reminderMinutes = new ArrayList<Integer>(len); for (int index = 0; index < len; index++) { LinearLayout layout = reminderItems.get(index); Spinner spinner = (Spinner) layout.findViewById(R.id.reminder_value); int minutes = reminderValues.get(spinner.getSelectedItemPosition()); reminderMinutes.add(minutes); } return reminderMinutes; } /** * Saves the reminders, if they changed. Returns true if the database * was updated. * * @param cr the ContentResolver * @param taskId the id of the task whose reminders are being updated * @param reminderMinutes the array of reminders set by the user * @param originalMinutes the original array of reminders * @return true if the database was updated */ static boolean saveReminders(ContentResolver cr, long taskId, ArrayList<Integer> reminderMinutes, ArrayList<Integer> originalMinutes ) { // If the reminders have not changed, then don't update the database if (reminderMinutes.equals(originalMinutes)) { return false; } // Delete all the existing reminders for this event String where = ReminderProvider.Reminders.TASK_ID + "=?"; String[] args = new String[] { Long.toString(taskId) }; cr.delete(ReminderProvider.Reminders.CONTENT_URI, where, args); ContentValues values = new ContentValues(); int len = reminderMinutes.size(); // Insert the new reminders, if any for (int i = 0; i < len; i++) { int minutes = reminderMinutes.get(i); values.clear(); values.put(ReminderProvider.Reminders.MINUTES, minutes); values.put(ReminderProvider.Reminders.METHOD, ReminderProvider.Reminders.METHOD_ALERT); values.put(ReminderProvider.Reminders.TASK_ID, taskId); cr.insert(ReminderProvider.Reminders.CONTENT_URI, values); } return true; } /* This class is used to update the time buttons. */ private class TimeListener implements OnTimeSetListener { private View mView; public TimeListener(View view) { mView = view; } public void onTimeSet(TimePicker view, int hourOfDay, int minute) { // Cache the member variables locally to avoid inner class overhead. Time startTime = mStartTime; Time dueTime = mDueTime; // Cache the start and due millis so that we limit the number // of calls to normalize() and toMillis(), which are fairly // expensive. long startMillis; long dueMillis; if (mView == mStartTimeButton) { // The start time was changed. int hourDuration = dueTime.hour - startTime.hour; int minuteDuration = dueTime.minute - startTime.minute; startTime.hour = hourOfDay; startTime.minute = minute; startMillis = startTime.normalize(true); mShowStart = true; // Also update the due time to keep the duration constant. dueTime.hour = hourOfDay + hourDuration; dueTime.minute = minute + minuteDuration; dueMillis = dueTime.normalize(true); mShowDue = true; } else { // The due time was changed. startMillis = startTime.toMillis(true); dueTime.hour = hourOfDay; dueTime.minute = minute; dueMillis = dueTime.normalize(true); mShowDue = true; if (mShowStart) { // Do not allow an event to have a due time before the start time. if (dueTime.before(startTime)) { dueTime.set(startTime); dueMillis = startMillis; } } else { // if start time is not shown, default it to be the same as due time startTime.set(dueTime); mShowStart = true; } } // update all 4 buttons in case visibility has changed setDate(mStartDateButton, startMillis, mShowStart); setTime(mStartTimeButton, startMillis, mShowStart); setDate(mDueDateButton, dueMillis, mShowDue); setTime(mDueTimeButton, dueMillis, mShowDue); updateCalendarPanel(); } } private class TimeClickListener implements View.OnClickListener { private Time mTime; public TimeClickListener(Time time) { mTime = time; } public void onClick(View v) { new TimePickerDialog(TaskEditorActivity.this, new TimeListener(v), mTime.hour, mTime.minute, DateFormat.is24HourFormat(TaskEditorActivity.this)).show(); } } private class DateListener implements OnDateSetListener { View mView; public DateListener(View view) { mView = view; } public void onDateSet(DatePicker view, int year, int month, int monthDay) { // Cache the member variables locally to avoid inner class overhead. Time startTime = mStartTime; Time dueTime = mDueTime; // Cache the start and due millis so that we limit the number // of calls to normalize() and toMillis(), which are fairly // expensive. long startMillis; long dueMillis; if (mView == mStartDateButton) { // The start date was changed. int yearDuration = dueTime.year - startTime.year; int monthDuration = dueTime.month - startTime.month; int monthDayDuration = dueTime.monthDay - startTime.monthDay; startTime.year = year; startTime.month = month; startTime.monthDay = monthDay; startMillis = startTime.normalize(true); mShowStart = true; // Also update the end date to keep the duration constant. dueTime.year = year + yearDuration; dueTime.month = month + monthDuration; dueTime.monthDay = monthDay + monthDayDuration; dueMillis = dueTime.normalize(true); mShowDue = true; } else { // The end date was changed. startMillis = startTime.toMillis(true); dueTime.year = year; dueTime.month = month; dueTime.monthDay = monthDay; dueMillis = dueTime.normalize(true); mShowDue = true; if (mShowStart) { // Do not allow an event to have an end time before the start time. if (dueTime.before(startTime)) { dueTime.set(startTime); dueMillis = startMillis; } } else { // if start time is not shown, default it to be the same as due time startTime.set(dueTime); mShowStart = true; } } // update all 4 buttons in case visibility has changed setDate(mStartDateButton, startMillis, mShowStart); setTime(mStartTimeButton, startMillis, mShowStart); setDate(mDueDateButton, dueMillis, mShowDue); setTime(mDueTimeButton, dueMillis, mShowDue); updateCalendarPanel(); } } private class DateClickListener implements View.OnClickListener { private Time mTime; public DateClickListener(Time time) { mTime = time; } public void onClick(View v) { new DatePickerDialog(TaskEditorActivity.this, new DateListener(v), mTime.year, mTime.month, mTime.monthDay).show(); } } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/editor/activity/TaskEditorActivity.java
Java
asf20
52,420
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.editor.activity; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity; import roboguice.inject.InjectView; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.AdapterView.OnItemClickListener; public class IconPickerActivity extends FlurryEnabledActivity implements OnItemClickListener { @SuppressWarnings("unused") private static final String cTag = "IconPickerActivity"; public static final String TYPE = "vnd.android.cursor.dir/vnd.dodgybits.icons"; @InjectView(R.id.iconGrid) GridView mGrid; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.icon_picker); mGrid.setAdapter(new IconAdapter(this)); mGrid.setOnItemClickListener(this); } @SuppressWarnings("unchecked") public void onItemClick(AdapterView parent, View v, int position, long id) { Bundle bundle = new Bundle(); int iconId = (Integer)mGrid.getAdapter().getItem(position); String iconName = getResources().getResourceEntryName(iconId); bundle.putString("iconName", iconName); Intent mIntent = new Intent(); mIntent.putExtras(bundle); setResult(RESULT_OK, mIntent); finish(); } public class IconAdapter extends BaseAdapter { public IconAdapter(Context context) { loadIcons(); } private int[] mIconIds; private void loadIcons() { mIconIds = new int[] { R.drawable.accessories_calculator, R.drawable.accessories_text_editor, R.drawable.applications_accessories, R.drawable.applications_development, R.drawable.applications_games, R.drawable.applications_graphics, R.drawable.applications_internet, R.drawable.applications_office, R.drawable.applications_system, R.drawable.audio_x_generic, R.drawable.camera_photo, R.drawable.computer, R.drawable.emblem_favorite, R.drawable.emblem_important, R.drawable.format_justify_fill, R.drawable.go_home, R.drawable.network_wireless, R.drawable.office_calendar, R.drawable.start_here, R.drawable.system_file_manager, R.drawable.system_search, R.drawable.system_users, R.drawable.utilities_terminal, R.drawable.video_x_generic, R.drawable.weather_showers_scattered, R.drawable.x_office_address_book, }; } public View getView(int position, View convertView, ViewGroup parent) { ImageView i = new ImageView(IconPickerActivity.this); Integer iconId = mIconIds[position]; i.setImageResource(iconId); i.setScaleType(ImageView.ScaleType.FIT_CENTER); return i; } public final int getCount() { return mIconIds.length; } public final Object getItem(int position) { return mIconIds[position]; } public final long getItemId(int position) { return position; } } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/editor/activity/IconPickerActivity.java
Java
asf20
4,170
package org.dodgybits.shuffle.android.editor.activity; import android.os.Bundle; import android.text.format.Time; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.TextView; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity; import org.dodgybits.shuffle.android.list.activity.State; import roboguice.inject.InjectView; import roboguice.util.Ln; public class TaskEditorSchedulingActivity extends FlurryEnabledActivity { private boolean mShowStart; private Time mStartTime; private boolean mShowDue; private Time mDueTime; private @InjectView(R.id.start_date) Button mStartDateButton; private @InjectView(R.id.due_date) Button mDueDateButton; private @InjectView(R.id.start_time) Button mStartTimeButton; private @InjectView(R.id.due_time) Button mDueTimeButton; private @InjectView(R.id.clear_dates) Button mClearButton; private @InjectView(R.id.is_all_day) CheckBox mAllDayCheckBox; private @InjectView(R.id.gcal_entry) View mUpdateCalendarEntry; private CheckBox mUpdateCalendarCheckBox; private TextView mCalendarLabel; private TextView mCalendarDetail; @Override protected void onCreate(Bundle icicle) { Ln.d("onCreate+"); super.onCreate(icicle); mStartTime = new Time(); mDueTime = new Time(); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/editor/activity/TaskEditorSchedulingActivity.java
Java
asf20
1,441
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.editor.activity; import android.widget.*; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.Context.Builder; import org.dodgybits.shuffle.android.core.model.encoding.EntityEncoder; import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister; import org.dodgybits.shuffle.android.core.util.TextColours; import org.dodgybits.shuffle.android.core.view.ContextIcon; import org.dodgybits.shuffle.android.core.view.DrawableUtils; import org.dodgybits.shuffle.android.list.activity.State; import org.dodgybits.shuffle.android.list.view.ContextView; import org.dodgybits.shuffle.android.persistence.provider.ContextProvider; import roboguice.inject.InjectView; import android.app.Activity; import android.content.Intent; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.GradientDrawable.Orientation; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.View; import com.google.inject.Inject; public class ContextEditorActivity extends AbstractEditorActivity<Context> implements TextWatcher { private static final String cTag = "ContextEditorActivity"; private static final int COLOUR_PICKER = 0; private static final int ICON_PICKER = 1; private int mColourIndex; private ContextIcon mIcon; @InjectView(R.id.name) private EditText mNameWidget; @InjectView(R.id.colour_display) private TextView mColourWidget; @InjectView(R.id.icon_display) private ImageView mIconWidget; @InjectView(R.id.icon_none) private TextView mIconNoneWidget; @InjectView(R.id.icon_clear_button) private ImageButton mClearIconButton; @InjectView(R.id.context_preview) private ContextView mContext; private @InjectView(R.id.deleted_entry) View mDeletedEntry; private CheckBox mDeletedCheckBox; private @InjectView(R.id.active_entry) View mActiveEntry; private @InjectView(R.id.active_entry_checkbox) CheckBox mActiveCheckBox; @Inject private EntityPersister<Context> mPersister; @Inject private EntityEncoder<Context> mEncoder; @Override protected void onCreate(Bundle icicle) { Log.d(cTag, "onCreate+"); super.onCreate(icicle); loadCursor(); findViewsAndAddListeners(); if (mState == State.STATE_EDIT) { // Make sure we are at the one and only row in the cursor. mCursor.moveToFirst(); setTitle(R.string.title_edit_context); mOriginalItem = mPersister.read(mCursor); updateUIFromItem(mOriginalItem); } else if (mState == State.STATE_INSERT) { setTitle(R.string.title_new_context); mDeletedEntry.setVisibility(View.GONE); mDeletedCheckBox.setChecked(false); mActiveCheckBox.setChecked(true); Bundle extras = getIntent().getExtras(); updateUIFromExtras(extras); } } @Override protected boolean isValid() { String name = mNameWidget.getText().toString(); return !TextUtils.isEmpty(name); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(cTag, "Got resultCode " + resultCode + " with data " + data); switch (requestCode) { case COLOUR_PICKER: if (resultCode == Activity.RESULT_OK) { if (data != null) { mColourIndex = Integer.parseInt(data.getStringExtra("colour")); displayColour(); updatePreview(); } } break; case ICON_PICKER: if (resultCode == Activity.RESULT_OK) { if (data != null) { String iconName = data.getStringExtra("iconName"); mIcon = ContextIcon.createIcon(iconName, getResources()); displayIcon(); updatePreview(); } } break; default: Log.e(cTag, "Unknown requestCode: " + requestCode); } } /** * Take care of deleting a context. Simply deletes the entry. */ @Override protected void doDeleteAction() { super.doDeleteAction(); mNameWidget.setText(""); } /** * @return id of layout for this view */ @Override protected int getContentViewResId() { return R.layout.context_editor; } @Override protected Intent getInsertIntent() { return new Intent(Intent.ACTION_INSERT, ContextProvider.Contexts.CONTENT_URI); } @Override protected CharSequence getItemName() { return getString(R.string.context_name); } @Override protected Context createItemFromUI(boolean commitValues) { Builder builder = Context.newBuilder(); if (mOriginalItem != null) { builder.mergeFrom(mOriginalItem); } builder.setName(mNameWidget.getText().toString()); builder.setModifiedDate(System.currentTimeMillis()); builder.setColourIndex(mColourIndex); builder.setIconName(mIcon.iconName); builder.setDeleted(mDeletedCheckBox.isChecked()); builder.setActive(mActiveCheckBox.isChecked()); return builder.build(); } @Override protected void updateUIFromExtras(Bundle extras) { if (mColourIndex == -1) { mColourIndex = 0; } displayIcon(); displayColour(); updatePreview(); } @Override protected void updateUIFromItem(Context context) { mNameWidget.setTextKeepState(context.getName()); mColourIndex = context.getColourIndex(); displayColour(); final String iconName = context.getIconName(); mIcon = ContextIcon.createIcon(iconName, getResources()); displayIcon(); updatePreview(); mActiveCheckBox.setChecked(context.isActive()); mDeletedEntry.setVisibility(context.isDeleted() ? View.VISIBLE : View.GONE); mDeletedCheckBox.setChecked(context.isDeleted()); if (mOriginalItem == null) { mOriginalItem = context; } } @Override protected EntityEncoder<Context> getEncoder() { return mEncoder; } @Override protected EntityPersister<Context> getPersister() { return mPersister; } private void loadCursor() { if (mUri != null && mState == State.STATE_EDIT) { mCursor = managedQuery(mUri, ContextProvider.Contexts.FULL_PROJECTION, null, null, null); if (mCursor == null || mCursor.getCount() == 0) { // The cursor is empty. This can happen if the event was deleted. finish(); } } } private void findViewsAndAddListeners() { // The text view for our context description, identified by its ID in the XML file. mNameWidget.addTextChangedListener(this); mColourIndex = -1; mIcon = ContextIcon.NONE; View colourEntry = findViewById(R.id.colour_entry); colourEntry.setOnClickListener(this); colourEntry.setOnFocusChangeListener(this); View iconEntry = findViewById(R.id.icon_entry); iconEntry.setOnClickListener(this); iconEntry.setOnFocusChangeListener(this); mClearIconButton.setOnClickListener(this); mClearIconButton.setOnFocusChangeListener(this); mActiveEntry.setOnClickListener(this); mActiveEntry.setOnFocusChangeListener(this); mDeletedEntry.setOnClickListener(this); mDeletedEntry.setOnFocusChangeListener(this); mDeletedCheckBox = (CheckBox) mDeletedEntry.findViewById(R.id.deleted_entry_checkbox); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.colour_entry: { // Launch activity to pick colour Intent intent = new Intent(Intent.ACTION_PICK); intent.setType(ColourPickerActivity.TYPE); startActivityForResult(intent, COLOUR_PICKER); break; } case R.id.icon_entry: { // Launch activity to pick icon Intent intent = new Intent(Intent.ACTION_PICK); intent.setType(IconPickerActivity.TYPE); startActivityForResult(intent, ICON_PICKER); break; } case R.id.icon_clear_button: { mIcon = ContextIcon.NONE; displayIcon(); updatePreview(); break; } case R.id.active_entry: { mActiveCheckBox.toggle(); break; } case R.id.deleted_entry: { mDeletedCheckBox.toggle(); break; } default: super.onClick(v); break; } } private void displayColour() { int bgColour = TextColours.getInstance(this).getBackgroundColour(mColourIndex); GradientDrawable drawable = DrawableUtils.createGradient(bgColour, Orientation.TL_BR); drawable.setCornerRadius(8.0f); mColourWidget.setBackgroundDrawable(drawable); } private void displayIcon() { if (mIcon == ContextIcon.NONE) { mIconNoneWidget.setVisibility(View.VISIBLE); mIconWidget.setVisibility(View.GONE); mClearIconButton.setEnabled(false); } else { mIconNoneWidget.setVisibility(View.GONE); mIconWidget.setImageResource(mIcon.largeIconId); mIconWidget.setVisibility(View.VISIBLE); mClearIconButton.setEnabled(true); } } private void updatePreview() { String name = mNameWidget.getText().toString(); if (TextUtils.isEmpty(name) || mColourIndex == -1) { mContext.setVisibility(View.INVISIBLE); } else { mContext.updateView(createItemFromUI(false)); mContext.setVisibility(View.VISIBLE); } } @Override public void afterTextChanged(Editable s) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { updatePreview(); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/editor/activity/ContextEditorActivity.java
Java
asf20
10,872
package org.dodgybits.shuffle.android.synchronisation.tracks.activity; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity; import org.dodgybits.shuffle.android.preference.model.Preferences; import org.dodgybits.shuffle.android.preference.view.Progress; import org.dodgybits.shuffle.android.synchronisation.tracks.ApiException; import org.dodgybits.shuffle.android.synchronisation.tracks.SyncProgressListener; import org.dodgybits.shuffle.android.synchronisation.tracks.TracksSynchronizer; import roboguice.inject.InjectView; import android.os.AsyncTask; import android.os.Bundle; import android.widget.ProgressBar; import android.widget.TextView; import com.google.inject.Inject; import com.google.inject.internal.Nullable; /** * Activity to handle synchronization * * @author Morten Nielsen */ public class SynchronizeActivity extends FlurryEnabledActivity implements SyncProgressListener { private TracksSynchronizer synchronizer = null; @InjectView(R.id.info_text) @Nullable TextView mInfo; @InjectView(R.id.progress_horizontal) @Nullable ProgressBar mProgress; @Inject Analytics mAnalytics; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.synchronize); setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); super.onCreate(savedInstanceState); TextView url = (TextView) findViewById(R.id.syncUrl); TextView user = (TextView) findViewById(R.id.syncUser); url.setText(Preferences.getTracksUrl(this)); user.setText(Preferences.getTracksUser(this)); } @Override public void onResume() { super.onResume(); try { synchronizer = TracksSynchronizer.getActiveSynchronizer(this, mAnalytics); } catch (ApiException ignored) { } if (synchronizer != null) { synchronizer.registerListener(this); if (synchronizer.getStatus() != AsyncTask.Status.RUNNING) { synchronizer.execute(); } } } @Override public void onPause() { super.onPause(); if (synchronizer != null) { synchronizer.unRegisterListener(this); } } @Override public void progressUpdate(Progress progress) { if (mInfo != null) { mInfo.setText(progress.getDetails()); } if (mProgress != null) { mProgress.setProgress(progress.getProgressPercent()); } } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/synchronisation/tracks/activity/SynchronizeActivity.java
Java
asf20
2,662
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.dodgybits.shuffle.android.synchronisation.tracks.ssl; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; /** * A strategy to establish trustworthiness of certificates without consulting the trust manager * configured in the actual SSL context. This interface can be used to override the standard * JSSE certificate verification process. * * Copy of org.apache.http.conn.ssl.TrustStrategy version 4.1 not yet in Android. */ public interface TrustStrategy { /** * Determines whether the certificate chain can be trusted without consulting the trust manager * configured in the actual SSL context. This method can be used to override the standard JSSE * certificate verification process. * <p> * Please note that, if this method returns <code>false</code>, the trust manager configured * in the actual SSL context can still clear the certificate as trusted. * * @param chain the peer certificate chain * @param authType the authentication type based on the client certificate * @return <code>true</code> if the certificate can be trusted without verification by * the trust manager, <code>false</code> otherwise. * @throws CertificateException thrown if the certificate is not trusted or invalid. */ boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException; }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/synchronisation/tracks/ssl/TrustStrategy.java
Java
asf20
2,609
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.dodgybits.shuffle.android.synchronisation.tracks.ssl; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; /** * A trust strategy that accepts self-signed certificates as trusted. Verification of all other * certificates is done by the trust manager configured in the SSL context. * * Copy of org.apache.http.conn.ssl.TrustSelfSignedStrategy version 4.1 not yet in Android. */ public class TrustSelfSignedStrategy implements TrustStrategy { public boolean isTrusted( final X509Certificate[] chain, final String authType) throws CertificateException { return chain.length == 1; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/synchronisation/tracks/ssl/TrustSelfSignedStrategy.java
Java
asf20
1,852
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.dodgybits.shuffle.android.synchronisation.tracks.ssl; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.X509TrustManager; /** * Copy of org.apache.http.conn.ssl.TrustManagerDecorator version 4.1 not yet in Android. */ class TrustManagerDecorator implements X509TrustManager { private final X509TrustManager trustManager; private final TrustStrategy trustStrategy; TrustManagerDecorator(final X509TrustManager trustManager, final TrustStrategy trustStrategy) { super(); this.trustManager = trustManager; this.trustStrategy = trustStrategy; } public void checkClientTrusted( final X509Certificate[] chain, final String authType) throws CertificateException { this.trustManager.checkClientTrusted(chain, authType); } public void checkServerTrusted( final X509Certificate[] chain, final String authType) throws CertificateException { if (!this.trustStrategy.isTrusted(chain, authType)) { this.trustManager.checkServerTrusted(chain, authType); } } public X509Certificate[] getAcceptedIssuers() { return this.trustManager.getAcceptedIssuers(); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/synchronisation/tracks/ssl/TrustManagerDecorator.java
Java
asf20
2,444
package org.dodgybits.shuffle.android.synchronisation.tracks.ssl; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; import org.apache.http.conn.ssl.SSLSocketFactory; public class TrustedSSLSocketFactory extends SSLSocketFactory { private static SSLContext sslContext = null; private static final TrustStrategy trustStrategy = new TrustSelfSignedStrategy(); public TrustedSSLSocketFactory() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(null); if (sslContext == null) { initSSLContext(); } } @Override public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); } @Override public Socket createSocket() throws IOException { return sslContext.getSocketFactory().createSocket(); } static void initSSLContext() throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException { sslContext = SSLContext.getInstance("TLS"); KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(null, null); // use default key store KeyManager[] keymanagers = kmfactory.getKeyManagers(); TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmfactory.init((KeyStore)null); TrustManager[] trustmanagers = tmfactory.getTrustManagers(); for (int i = 0; i < trustmanagers.length; i++) { TrustManager tm = trustmanagers[i]; if (tm instanceof X509TrustManager) { trustmanagers[i] = new TrustManagerDecorator((X509TrustManager)tm, trustStrategy); } } sslContext.init(keymanagers, trustmanagers, null); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/synchronisation/tracks/ssl/TrustedSSLSocketFactory.java
Java
asf20
2,456
package org.dodgybits.shuffle.android.synchronisation.tracks; @SuppressWarnings("serial") public class ApiException extends Exception { public ApiException(String reason) { super(reason); } public ApiException(String reason, Exception e) { super(reason, e); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/synchronisation/tracks/ApiException.java
Java
asf20
316
package org.dodgybits.shuffle.android.synchronisation.tracks; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.dodgybits.shuffle.android.core.model.EntityBuilder; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister; import org.dodgybits.shuffle.android.persistence.provider.ContextProvider; import org.dodgybits.shuffle.android.persistence.provider.ProjectProvider; import org.dodgybits.shuffle.android.preference.view.Progress; import org.dodgybits.shuffle.android.synchronisation.tracks.ApiException; import org.dodgybits.shuffle.android.synchronisation.tracks.model.TracksEntity; import org.dodgybits.shuffle.android.synchronisation.tracks.parsing.IContextLookup; import org.dodgybits.shuffle.android.synchronisation.tracks.parsing.IProjectLookup; import org.dodgybits.shuffle.android.synchronisation.tracks.parsing.Parser; import android.database.Cursor; import android.net.Uri; import android.provider.BaseColumns; import android.text.TextUtils; import android.util.Log; /** * Base class for handling synchronization, template method object. * * @author Morten Nielsen */ public abstract class Synchronizer<Entity extends TracksEntity> implements IProjectLookup,IContextLookup { private static final String cTag = "Synchronizer"; protected EntityPersister<Entity> mPersister; protected WebClient mWebClient; protected android.content.Context mContext; protected final TracksSynchronizer mTracksSynchronizer; private int mBasePercent; public Synchronizer( EntityPersister<Entity> persister, TracksSynchronizer tracksSynchronizer, WebClient client, android.content.Context context, int basePercent) { mPersister = persister; mTracksSynchronizer = tracksSynchronizer; mWebClient = client; mContext = context; mBasePercent = basePercent; } public void synchronize() throws ApiException { mTracksSynchronizer.reportProgress(Progress.createProgress(mBasePercent, readingLocalText())); Map<Id, Entity> localEntities = getShuffleEntities(); verifyEntitiesForSynchronization(localEntities); mTracksSynchronizer.reportProgress(Progress.createProgress(mBasePercent, readingRemoteText())); TracksEntities<Entity> tracksEntities = getTrackEntities(); mergeAlreadySynchronizedEntities(localEntities, tracksEntities); addNewEntitiesToShuffle(tracksEntities); mTracksSynchronizer.reportProgress(Progress.createProgress( mBasePercent + 33, stageFinishedText())); } private void mergeAlreadySynchronizedEntities( Map<Id, Entity> localEntities, TracksEntities<Entity> tracksEntities) { int startCounter = localEntities.size() + 1; int count = 0; for (Entity localEntity : localEntities.values()) { count++; mTracksSynchronizer.reportProgress(Progress.createProgress(calculatePercent(startCounter, count), processingText())); mergeSingle(tracksEntities, localEntity); } } private int calculatePercent(int startCounter, int count) { int percent = mBasePercent + Math.round(((count * 100) / startCounter) * 0.33f); return percent; } private void addNewEntitiesToShuffle(TracksEntities<Entity> tracksEntities) { for (Entity remoteEntity : tracksEntities.getEntities().values()) { insertEntity(remoteEntity); } } public Id findProjectIdByTracksId(Id tracksId) { return findEntityLocalIdByTracksId(tracksId, ProjectProvider.Projects.CONTENT_URI); } public Id findContextIdByTracksId(Id tracksId) { return findEntityLocalIdByTracksId(tracksId, ContextProvider.Contexts.CONTENT_URI); } protected Id findTracksIdByProjectId(Id projectId) { return findEntityTracksIdByLocalId(projectId, ProjectProvider.Projects.CONTENT_URI); } protected Id findTracksIdByContextId(Id contextId) { return findEntityTracksIdByLocalId(contextId, ContextProvider.Contexts.CONTENT_URI); } protected abstract void verifyEntitiesForSynchronization(Map<Id, Entity> localEntities); protected abstract String readingRemoteText(); protected abstract String processingText(); protected abstract String readingLocalText(); protected abstract String stageFinishedText(); protected abstract String entityIndexUrl(); protected abstract Entity createMergedLocalEntity(Entity localEntity, Entity newEntity); protected abstract String createEntityUrl(Entity localEntity); protected abstract String createDocumentForEntity(Entity localEntity); protected abstract EntityBuilder<Entity> createBuilder(); private TracksEntities<Entity> getTrackEntities() throws ApiException { String tracksEntityXml; try { WebResult result = mWebClient.getUrlContent(entityIndexUrl()); StatusLine status = result.getStatus(); if(status.getStatusCode() == HttpStatus.SC_OK) tracksEntityXml = result.getContent(); else throw new ApiException("Invalid response from server: " + status.toString()); } catch (ApiException e) { Log.w(cTag, e); throw e; } return getEntityParser().parseDocument(tracksEntityXml); } protected abstract Parser<Entity> getEntityParser(); private Id findEntityLocalIdByTracksId(Id tracksId, Uri contentUri) { Id id = Id.NONE; Cursor cursor = mContext.getContentResolver().query( contentUri, new String[] { BaseColumns._ID}, "tracks_id = ?", new String[] {tracksId.toString()}, null); if (cursor.moveToFirst()) { id = Id.create(cursor.getLong(0)); } cursor.close(); return id; } private Id findEntityTracksIdByLocalId(Id localId, Uri contentUri) { Id id = Id.NONE; Cursor cursor = mContext.getContentResolver().query( contentUri, new String[] { "tracks_id" }, BaseColumns._ID + " = ?", new String[] {localId.toString()}, null); if (cursor.moveToFirst()) { id = Id.create(cursor.getLong(0)); } cursor.close(); return id; } private void insertEntity(Entity entity) { mPersister.insert(entity); } private void updateEntity(Entity entity) { mPersister.update(entity); } protected boolean deleteEntity(Entity entity) { return mPersister.updateDeletedFlag(entity.getLocalId(), true); } private Entity findEntityByLocalName(Collection<Entity> remoteEntities, Entity localEntity) { Entity foundEntity = null; for (Entity entity : remoteEntities) if (entity.getLocalName().equals(localEntity.getLocalName())) { foundEntity = entity; } return foundEntity; } private void mergeSingle(TracksEntities<Entity> tracksEntities, Entity localEntity) { final Map<Id, Entity> remoteEntities = tracksEntities.getEntities(); if (!localEntity.getTracksId().isInitialised()) { handleLocalEntityNotYetInTracks(localEntity, remoteEntities); return; } Entity remoteEntity = remoteEntities.get(localEntity.getTracksId()); if (remoteEntity != null) { mergeLocalAndRemoteEntityBasedOnModifiedDate(localEntity, remoteEntity); remoteEntities.remove(remoteEntity.getTracksId()); } else if (tracksEntities.isErrorFree()){ // only delete entities if we didn't encounter errors parsing deleteEntity(localEntity); } } private void handleLocalEntityNotYetInTracks(Entity localEntity, final Map<Id, Entity> remoteEntities) { Entity newEntity = findEntityByLocalName(remoteEntities.values(), localEntity); if (newEntity != null) { remoteEntities.remove(newEntity.getTracksId()); } else { newEntity = createEntityInTracks(localEntity); } if (newEntity != null) { updateEntity(createMergedLocalEntity(localEntity, newEntity)); } } private void mergeLocalAndRemoteEntityBasedOnModifiedDate(Entity localEntity, Entity remoteEntity) { final long remoteModified = remoteEntity.getModifiedDate(); final long localModified = localEntity.getModifiedDate(); if (remoteModified == localModified && remoteEntity.isDeleted() == localEntity.isDeleted()) return; if (remoteModified >= localModified) { updateEntity(createMergedLocalEntity(localEntity, remoteEntity)); } else { updateTracks(localEntity); } } private void updateTracks(Entity localEntity) { String document = createDocumentForEntity(localEntity); try { mWebClient.putContentToUrl(createEntityUrl(localEntity), document); } catch (ApiException e) { Log.w(cTag, "Failed to update entity in tracks " + localEntity + ":" + e.getMessage(), e); } } private Entity createEntityInTracks(Entity entity) { String document = createDocumentForEntity(entity); try { String location = mWebClient.postContentToUrl(entityIndexUrl(), document); if (!TextUtils.isEmpty(location.trim())) { Id id = parseIdFromLocation(location); EntityBuilder<Entity> builder = createBuilder(); builder.mergeFrom(entity); builder.setTracksId(id); entity = builder.build(); } } catch (ApiException e) { Log.w(cTag, "Failed to create entity in tracks " + entity + ":" + e.getMessage(), e); } return entity; } private Id parseIdFromLocation(String location) { String[] parts = location.split("/"); String document = parts[parts.length - 1]; long id = Long.parseLong( document ); return Id.create(id); } private Map<Id, Entity> getShuffleEntities() { Map<Id, Entity> list = new HashMap<Id, Entity>(); Cursor cursor = mContext.getContentResolver().query( mPersister.getContentUri(), mPersister.getFullProjection(), null, null, null); while (cursor.moveToNext()) { Entity entity = mPersister.read(cursor); list.put(entity.getLocalId(), entity); } cursor.close(); return list; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/synchronisation/tracks/Synchronizer.java
Java
asf20
11,087
package org.dodgybits.shuffle.android.synchronisation.tracks.parsing; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryTracksSyncError; import java.io.IOException; import java.io.StringReader; import java.util.HashMap; import java.util.Map; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; import org.dodgybits.shuffle.android.core.model.EntityBuilder; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.synchronisation.tracks.TracksEntities; import org.dodgybits.shuffle.android.synchronisation.tracks.model.TracksEntity; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.util.Log; import android.util.Xml; public abstract class Parser<E extends TracksEntity> { private static final String cTag = "Parser"; protected HashMap<String, Applier> appliers; private String mEntityName; private Analytics mAnalytics; public Parser(String entityName, Analytics analytics) { appliers = new HashMap<String, Applier>(); mEntityName = entityName; mAnalytics = analytics; } public TracksEntities<E> parseDocument(String tracksEntityXml) { Map<Id, E> entities = new HashMap<Id, E>(); boolean errorFree = true; XmlPullParser parser = Xml.newPullParser(); try { parser.setInput(new StringReader(tracksEntityXml)); int eventType = parser.getEventType(); boolean done = false; while (eventType != XmlPullParser.END_DOCUMENT && !done) { ParseResult<E> result = null; try { result = parseSingle(parser); } catch (Exception e) { logTracksError(e); errorFree = false; } if(!result.isSuccess()) { errorFree = false; } E entity = result.getResult(); if (entity != null && entity.isValid()) { entities.put(entity.getTracksId(), entity); } eventType = parser.getEventType(); String name = parser.getName(); if (eventType == XmlPullParser.END_TAG && name.equalsIgnoreCase(endIndexTag())) { done = true; } } } catch (XmlPullParserException e) { logTracksError(e); errorFree = false; } return new TracksEntities<E>(entities, errorFree); } private void logTracksError(Exception e) { Log.e(cTag, "Failed to parse " + endIndexTag() + " " + e.getMessage()); mAnalytics.onError(cFlurryTracksSyncError, e.getMessage(), getClass().getName()); } private String endIndexTag() { return this.mEntityName + "s"; } public ParseResult<E> parseSingle(XmlPullParser parser) { EntityBuilder<E> builder = createBuilder(); E entity = null; boolean success = true; try { int eventType = parser.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT && entity == null) { String name = parser.getName(); switch (eventType) { case XmlPullParser.START_DOCUMENT: break; case XmlPullParser.START_TAG: Applier applier = appliers.get(name); if(applier != null) { success &= applier.apply(parser.nextText()); } break; case XmlPullParser.END_TAG: if (name.equalsIgnoreCase(mEntityName)) { entity = builder.build(); } break; } eventType = parser.next(); } } catch (IOException e) { Log.d("Exception", "IO EXception", e); return new ParseResult<E>(); } catch (XmlPullParserException e) { Log.d("Exception", "pullparser exception", e); return new ParseResult<E>(); } return new ParseResult<E>(entity, success); } protected abstract EntityBuilder<E> createBuilder(); }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/synchronisation/tracks/parsing/Parser.java
Java
asf20
4,567
package org.dodgybits.shuffle.android.synchronisation.tracks.parsing; import java.text.ParseException; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.EntityBuilder; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Context.Builder; import org.dodgybits.shuffle.android.core.util.DateUtils; public class ContextParser extends Parser<Context> { private Builder specificBuilder; public ContextParser(Analytics analytics) { super("context", analytics); appliers.put("name", new Applier(){ @Override public boolean apply(String value) { specificBuilder.setName(value); return true; } }); appliers.put("hide", new Applier(){ @Override public boolean apply(String value) { boolean v = Boolean.parseBoolean(value); specificBuilder.setActive(!v); return true; } }); appliers.put("id", new Applier(){ @Override public boolean apply(String value) { Id tracksId = Id.create(Long.parseLong(value)); specificBuilder.setTracksId(tracksId); return true; } }); appliers.put("updated-at", new Applier(){ @Override public boolean apply(String value) { long date; try { date = DateUtils.parseIso8601Date(value); specificBuilder.setModifiedDate(date); return true; } catch (ParseException e) { return false; } } }); } @Override protected EntityBuilder<Context> createBuilder() { return specificBuilder = Context.newBuilder(); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/synchronisation/tracks/parsing/ContextParser.java
Java
asf20
1,889
package org.dodgybits.shuffle.android.synchronisation.tracks.parsing; public class ParseResult<T> { private boolean mSuccess; private T mResult; public ParseResult(T result, boolean success) { mSuccess = success; mResult = result; } public ParseResult() { mSuccess = false; mResult = null; } public T getResult() { return mResult; } public boolean isSuccess(){ return mSuccess; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/synchronisation/tracks/parsing/ParseResult.java
Java
asf20
436
package org.dodgybits.shuffle.android.synchronisation.tracks.parsing; import java.text.ParseException; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; import org.dodgybits.shuffle.android.core.model.EntityBuilder; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Task; import org.dodgybits.shuffle.android.core.model.Task.Builder; import org.dodgybits.shuffle.android.core.util.DateUtils; import android.text.TextUtils; import roboguice.util.Ln; public class TaskParser extends Parser<Task> { private Builder specificBuilder; protected IContextLookup mContextLookup; protected IProjectLookup mProjectLookup; public TaskParser(IContextLookup contextLookup, IProjectLookup projectLookup, Analytics analytics) { super("todo", analytics); mContextLookup = contextLookup; mProjectLookup = projectLookup; appliers.put("state", new Applier() { @Override public boolean apply(String value) { Ln.d("Got status %s", value); if( value.equals("completed")) { specificBuilder.setComplete(true); } return true; } }); appliers.put("description", new Applier(){ @Override public boolean apply(String value) { specificBuilder.setDescription(value); return true; } }); appliers.put("notes", new Applier(){ @Override public boolean apply(String value) { specificBuilder.setDetails(value); return true; } }); appliers.put("id", new Applier(){ @Override public boolean apply(String value) { Id tracksId = Id.create(Long.parseLong(value)); specificBuilder.setTracksId(tracksId); return true; } }); appliers.put("updated-at", new Applier(){ @Override public boolean apply(String value) { long date; try { date = DateUtils.parseIso8601Date(value); specificBuilder.setModifiedDate(date); return true; } catch (ParseException e) { return false; } } }); appliers.put("context-id", new Applier(){ @Override public boolean apply(String value) { if (!TextUtils.isEmpty(value)) { Id tracksId = Id.create(Long.parseLong(value)); Id context = mContextLookup.findContextIdByTracksId(tracksId); if (context.isInitialised()) { specificBuilder.setContextId(context); } } return true; } }); appliers.put("project-id", new Applier(){ @Override public boolean apply(String value) { if (!TextUtils.isEmpty(value)) { Id tracksId = Id.create(Long.parseLong(value)); Id project = mProjectLookup.findProjectIdByTracksId(tracksId); if (project.isInitialised()) { specificBuilder.setProjectId(project); } } return true; } }); appliers.put("created-at", new Applier(){ @Override public boolean apply(String value) { if (!TextUtils.isEmpty(value)) { try { long created = DateUtils.parseIso8601Date(value); specificBuilder.setCreatedDate(created); } catch (ParseException e) { // TODO Auto-generated catch block return false; } } return true; } }); appliers.put("due", new Applier(){ @Override public boolean apply(String value) { if (!TextUtils.isEmpty(value)) { try { long due = DateUtils.parseIso8601Date(value); specificBuilder.setDueDate(due); } catch (ParseException e) { // TODO Auto-generated catch block return false; } } return true; } }); appliers.put("show-from", new Applier(){ @Override public boolean apply(String value) { if (!TextUtils.isEmpty(value)) { try { long showFrom = DateUtils.parseIso8601Date(value); specificBuilder.setStartDate(showFrom); } catch (ParseException e) { // TODO Auto-generated catch block return false; } } return true; } }); } @Override protected EntityBuilder<Task> createBuilder() { return specificBuilder = Task.newBuilder(); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/synchronisation/tracks/parsing/TaskParser.java
Java
asf20
5,050
package org.dodgybits.shuffle.android.synchronisation.tracks.parsing; import org.dodgybits.shuffle.android.core.model.Id; public interface IProjectLookup { Id findProjectIdByTracksId(Id tracksId); }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/synchronisation/tracks/parsing/IProjectLookup.java
Java
asf20
213
package org.dodgybits.shuffle.android.synchronisation.tracks.parsing; import org.dodgybits.shuffle.android.core.model.Id; public interface IContextLookup { Id findContextIdByTracksId(Id tracksId); }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/synchronisation/tracks/parsing/IContextLookup.java
Java
asf20
213
package org.dodgybits.shuffle.android.synchronisation.tracks.parsing; public interface Applier { boolean apply(String value); }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/synchronisation/tracks/parsing/Applier.java
Java
asf20
135
package org.dodgybits.shuffle.android.synchronisation.tracks.parsing; import java.text.ParseException; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; import org.dodgybits.shuffle.android.core.model.EntityBuilder; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.android.core.model.Project.Builder; import org.dodgybits.shuffle.android.core.util.DateUtils; import android.text.TextUtils; import android.util.Log; public class ProjectParser extends Parser<Project> { private Builder specificBuilder; private IContextLookup mContextLookup; public ProjectParser(IContextLookup contextLookup, Analytics analytics) { super("project", analytics); mContextLookup = contextLookup; appliers.put("name", new Applier(){ @Override public boolean apply(String value) { specificBuilder.setName(value); return true; } }); appliers.put("state", new Applier(){ @Override public boolean apply(String value) { String v = value.toLowerCase(); Log.d("projectparser",v); if(v.equals("completed")) { // ignore completed for now? // specificBuilder.setDeleted(true); return true; } if(v.equals("hidden")) { specificBuilder.setActive(false); return true; } if(v.equals("active")) { specificBuilder.setActive(true); return true; } return false; } }); appliers.put("id", new Applier(){ @Override public boolean apply(String value) { Id tracksId = Id.create(Long.parseLong(value)); specificBuilder.setTracksId(tracksId); return true; } }); appliers.put("updated-at", new Applier(){ @Override public boolean apply(String value) { long date; try { date = DateUtils.parseIso8601Date(value); specificBuilder.setModifiedDate(date); return true; } catch (ParseException e) { return false; } } }); appliers.put("default-context-id", new Applier(){ @Override public boolean apply(String value) { if (!TextUtils.isEmpty(value)) { Id tracksId = Id.create(Long.parseLong(value)); Id defaultContextId = mContextLookup.findContextIdByTracksId(tracksId); if (defaultContextId.isInitialised()) { specificBuilder.setDefaultContextId(defaultContextId); } } return true; } }); } @Override protected EntityBuilder<Project> createBuilder() { return specificBuilder = Project.newBuilder(); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/synchronisation/tracks/parsing/ProjectParser.java
Java
asf20
3,070
package org.dodgybits.shuffle.android.synchronisation.tracks; import java.io.IOException; import java.io.StringWriter; import java.util.Map; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.EntityBuilder; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Context.Builder; import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister; import org.dodgybits.shuffle.android.core.util.DateUtils; import org.dodgybits.shuffle.android.synchronisation.tracks.parsing.ContextParser; import org.dodgybits.shuffle.android.synchronisation.tracks.parsing.Parser; import org.xmlpull.v1.XmlSerializer; import android.util.Xml; /** * @author Morten Nielsen */ public class ContextSynchronizer extends Synchronizer<Context> { private final String mTracksUrl; private Parser<Context> mParser; public ContextSynchronizer( EntityPersister<Context> persister, TracksSynchronizer tracksSynchronizer, WebClient client, android.content.Context context, Analytics analytics, int basePercent, String tracksUrl) { super(persister, tracksSynchronizer, client, context, basePercent); mParser = new ContextParser(analytics); mTracksUrl = tracksUrl; } @Override protected void verifyEntitiesForSynchronization(Map<Id, Context> localEntities) { } @Override protected String readingRemoteText() { return mContext.getString(R.string.readingRemoteContexts); } @Override protected String processingText() { return mContext.getString(R.string.processingContexts); } @Override protected String readingLocalText() { return mContext.getString(R.string.readingLocalContexts); } @Override protected String stageFinishedText() { return mContext.getString(R.string.doneWithContexts); } @Override protected EntityBuilder<Context> createBuilder() { return Context.newBuilder(); } @Override protected Context createMergedLocalEntity(Context localContext, Context newContext) { Builder builder = Context.newBuilder(); builder.mergeFrom(localContext); builder .setName(newContext.getName()) .setModifiedDate(newContext.getModifiedDate()) .setDeleted(newContext.isDeleted()) .setTracksId(newContext.getTracksId()); return builder.build(); } @Override protected String createDocumentForEntity(Context localContext) { XmlSerializer serializer = Xml.newSerializer(); StringWriter writer = new StringWriter(); try { serializer.setOutput(writer); //serializer.startDocument("UTF-8", true); String now = DateUtils.formatIso8601Date(System.currentTimeMillis()); serializer.startTag("", "context"); serializer.startTag("", "created-at").attribute("", "type", "datetime").text(now).endTag("", "created-at"); serializer.startTag("", "hide").attribute("", "type", "boolean").text(String.valueOf(!localContext.isActive())).endTag("", "hide"); serializer.startTag("", "name").text(localContext.getName()).endTag("", "name"); serializer.startTag("", "position").attribute("", "type", "integer").text("12").endTag("", "position"); serializer.startTag("", "state").text(localContext.isDeleted() ? "hidden" : "active").endTag("", "state"); serializer.startTag("", "updated-at").attribute("", "type", "datetime").text(now).endTag("", "updated-at"); serializer.endTag("", "context"); // serializer.endDocument(); serializer.flush(); } catch (IOException ignored) { } return writer.toString(); } @Override protected String createEntityUrl(Context localContext) { return mTracksUrl + "/contexts/" + localContext.getTracksId().getId() + ".xml"; } @Override protected String entityIndexUrl() { return mTracksUrl+"/contexts.xml"; } @Override protected Parser<Context> getEntityParser() { return mParser; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/synchronisation/tracks/ContextSynchronizer.java
Java
asf20
4,398
package org.dodgybits.shuffle.android.synchronisation.tracks; import org.apache.http.StatusLine; public class WebResult { private String mContent; private StatusLine mStatus; public WebResult(StatusLine status, String content) { mStatus = status; mContent = content; } public String getContent() { return mContent; } public StatusLine getStatus() { return mStatus; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/synchronisation/tracks/WebResult.java
Java
asf20
418
package org.dodgybits.shuffle.android.synchronisation.tracks.service; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; import org.dodgybits.shuffle.android.preference.model.Preferences; import org.dodgybits.shuffle.android.preference.view.Progress; import org.dodgybits.shuffle.android.synchronisation.tracks.ApiException; import org.dodgybits.shuffle.android.synchronisation.tracks.SyncProgressListener; import org.dodgybits.shuffle.android.synchronisation.tracks.TracksSynchronizer; import org.dodgybits.shuffle.android.synchronisation.tracks.activity.SynchronizeActivity; import roboguice.service.RoboService; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Handler; import android.os.IBinder; import android.text.format.DateUtils; import android.util.Log; import android.widget.RemoteViews; import com.google.inject.Inject; /** * This service handles synchronization in the background. * * @author Morten Nielsen */ public class SynchronizationService extends RoboService implements SyncProgressListener { private static final String cTag = "SynchronizationService"; private NotificationManager mNotificationManager; private Handler mHandler; private CheckTimer mCheckTimer; private PerformSynch mPerformSynch; private long interval = 0; private TracksSynchronizer synchronizer = null; private RemoteViews contentView; @Inject Analytics mAnalytics; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); String ns = Context.NOTIFICATION_SERVICE; mNotificationManager = (NotificationManager) getSystemService(ns); contentView = new RemoteViews(getPackageName(), R.layout.synchronize_notification_layout); contentView.setProgressBar(R.id.progress_horizontal, 100, 50, true); contentView.setImageViewResource(R.id.image, R.drawable.shuffle_icon); mHandler = new Handler(); mCheckTimer = new CheckTimer(); mPerformSynch = new PerformSynch(); mHandler.post(mCheckTimer); } private class CheckTimer implements Runnable { @Override public void run() { Log.d(cTag, "Checking preferences"); long newInterval = calculateIntervalInMilliseconds( Preferences.getTracksInterval(SynchronizationService.this)); if (interval != newInterval) { interval = newInterval; scheduleSynchronization(); } mHandler.postDelayed(this, 5L * DateUtils.MINUTE_IN_MILLIS); } private long calculateIntervalInMilliseconds(int selected) { long result = 0L; switch (selected) { case 1: // 30min result = 30L * DateUtils.MINUTE_IN_MILLIS; break; case 2: // 1hr result = DateUtils.HOUR_IN_MILLIS; break; case 3: result = 2L * DateUtils.HOUR_IN_MILLIS; break; case 4: result = 3L * DateUtils.HOUR_IN_MILLIS; break; } return result; } } private class PerformSynch implements Runnable { @Override public void run() { synchronize(); } } private void scheduleSynchronization() { mHandler.removeCallbacks(mPerformSynch); if (interval != 0L) { mHandler.post(mPerformSynch); } } private void synchronize() { Log.d(cTag, "Starting synch"); try { synchronizer = TracksSynchronizer.getActiveSynchronizer(this, mAnalytics); } catch (ApiException ignored) { } if (synchronizer != null) { synchronizer.registerListener(this); } if (synchronizer != null && Preferences.validateTracksSettings(this)) { if (synchronizer.getStatus() != AsyncTask.Status.RUNNING) synchronizer.execute(); } mHandler.postDelayed(mPerformSynch, interval); } private static final int NOTIFICATION_ID = 1; private void createNotification() { int icon = R.drawable.shuffle_icon; CharSequence tickerText = this.getText(R.string.app_name); long when = System.currentTimeMillis(); Notification notification = new Notification(icon, tickerText, when); Intent notificationIntent = new Intent(this, SynchronizeActivity.class); notification.contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.contentView = contentView; mNotificationManager.notify(NOTIFICATION_ID, notification); } private void clearNotification() { mNotificationManager.cancel(NOTIFICATION_ID); } @Override public void onDestroy() { super.onDestroy(); mHandler.removeCallbacks(mCheckTimer); mHandler.removeCallbacks(mPerformSynch); if (synchronizer != null) { synchronizer.unRegisterListener(this); } } @Override public void progressUpdate(Progress progress) { if (progress.getProgressPercent() == 100) clearNotification(); if (progress.getProgressPercent() == 0) createNotification(); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/synchronisation/tracks/service/SynchronizationService.java
Java
asf20
5,709
package org.dodgybits.shuffle.android.synchronisation.tracks; import java.util.Map; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.synchronisation.tracks.model.TracksEntity; public class TracksEntities<E extends TracksEntity> { private Map<Id, E> mEntities; private boolean mErrorFree; public TracksEntities(Map<Id, E> entities, boolean errorFree) { mEntities = entities; mErrorFree = errorFree; } public Map<Id, E> getEntities() { return mEntities; } public boolean isErrorFree() { return mErrorFree; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/synchronisation/tracks/TracksEntities.java
Java
asf20
658
package org.dodgybits.shuffle.android.synchronisation.tracks; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryTracksSyncCompletedEvent; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryTracksSyncError; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryTracksSyncStartedEvent; import java.util.LinkedList; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.android.core.model.Task; import org.dodgybits.shuffle.android.core.model.persistence.ContextPersister; import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister; import org.dodgybits.shuffle.android.core.model.persistence.ProjectPersister; import org.dodgybits.shuffle.android.core.model.persistence.TaskPersister; import org.dodgybits.shuffle.android.preference.model.Preferences; import org.dodgybits.shuffle.android.preference.view.Progress; import roboguice.inject.ContentResolverProvider; import android.content.ContentResolver; import android.content.Context; import android.content.ContextWrapper; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; /** * This task synchronizes shuffle with a tracks service. * * @author Morten Nielsen */ public class TracksSynchronizer extends AsyncTask<String, Progress, Void> { private static final String cTag = "TracksSynchronizer"; private static TracksSynchronizer synchronizer; private static LinkedList<SyncProgressListener> progressListeners = new LinkedList<SyncProgressListener>(); private final Context mContext; private final LinkedList<Integer> mMessages; private final ContextSynchronizer mContextSynchronizer; private final ProjectSynchronizer mProjectSynchronizer; private final TaskSynchronizer mTaskSynchronizer; private Analytics mAnalytics; // TODO inject sync classes (BIG job) public static TracksSynchronizer getActiveSynchronizer( ContextWrapper context, Analytics analytics) throws ApiException { TracksSynchronizer synchronizer = getSingletonSynchronizer(context, analytics); while (synchronizer.getStatus() == Status.FINISHED) { synchronizer = getSingletonSynchronizer(context, analytics); } return synchronizer; } private static TracksSynchronizer getSingletonSynchronizer(Context context, Analytics analytics) throws ApiException { if (synchronizer == null || synchronizer.getStatus() == Status.FINISHED) { synchronizer = new TracksSynchronizer( context, analytics, new WebClient(context, Preferences.getTracksUser(context), Preferences.getTracksPassword(context), Preferences.isTracksSelfSignedCert(context)), Preferences.getTracksUrl(context) ); } return synchronizer; } private TracksSynchronizer( Context context, Analytics analytics, WebClient client, String tracksUrl) { mContext = context; //TODO inject this ContentResolverProvider provider = new ContentResolverProvider() { @Override public ContentResolver get() { return mContext.getContentResolver(); } }; mAnalytics = analytics; EntityPersister<Task> taskPersister = new TaskPersister(provider, analytics); EntityPersister<org.dodgybits.shuffle.android.core.model.Context> contextPersister = new ContextPersister(provider, analytics); EntityPersister<Project> projectPersister = new ProjectPersister(provider, analytics); mContextSynchronizer = new ContextSynchronizer(contextPersister, this, client, context, mAnalytics, 0, tracksUrl); mProjectSynchronizer = new ProjectSynchronizer(projectPersister, this, client, context, mAnalytics, 33, tracksUrl); mTaskSynchronizer = new TaskSynchronizer(taskPersister, this, client, context, mAnalytics, 66, tracksUrl); mMessages = new LinkedList<Integer>(); } @Override protected void onProgressUpdate(Progress... progresses) { for (SyncProgressListener listener : progressListeners) { listener.progressUpdate(progresses[0]); } } public void registerListener(SyncProgressListener listener) { if (!progressListeners.contains(listener)) progressListeners.add(listener); } public void unRegisterListener(SyncProgressListener listener) { progressListeners.remove(listener); } @Override protected Void doInBackground(String... strings) { try { mAnalytics.onEvent(cFlurryTracksSyncStartedEvent); mContextSynchronizer.synchronize(); mProjectSynchronizer.synchronize(); mTaskSynchronizer.synchronize(); publishProgress(Progress.createProgress(100, "Synchronization Complete")); mAnalytics.onEvent(cFlurryTracksSyncCompletedEvent); } catch (ApiException e) { Log.w(cTag, "Tracks call failed", e); publishProgress(Progress.createErrorProgress(mContext.getString(R.string.web_error_message))); mAnalytics.onError(cFlurryTracksSyncError, e.getMessage(), getClass().getName()); } catch (Exception e) { Log.w(cTag, "Synch failed", e); publishProgress(Progress.createErrorProgress(mContext.getString(R.string.error_message))); mAnalytics.onError(cFlurryTracksSyncError, e.getMessage(), getClass().getName()); } return null; } @Override protected void onPostExecute(Void result) { if (mMessages.size() > 0) { for (Integer textId : mMessages) { Toast toast = Toast.makeText(mContext.getApplicationContext(), textId , Toast.LENGTH_SHORT); toast.show(); } } try { synchronizer = getSingletonSynchronizer(mContext, mAnalytics); } catch (ApiException ignored) { } } public void reportProgress(Progress progress) { publishProgress(progress); } public void postSyncMessage(int toastMessage) { mMessages.add(toastMessage); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/synchronisation/tracks/TracksSynchronizer.java
Java
asf20
6,500
package org.dodgybits.shuffle.android.synchronisation.tracks.model; import org.dodgybits.shuffle.android.core.model.Entity; import org.dodgybits.shuffle.android.core.model.Id; public interface TracksEntity extends Entity { Id getTracksId(); }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/synchronisation/tracks/model/TracksEntity.java
Java
asf20
251
package org.dodgybits.shuffle.android.synchronisation.tracks; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.util.LinkedList; import java.util.Map; import org.apache.http.HttpStatus; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; import org.dodgybits.shuffle.android.core.model.EntityBuilder; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Task; import org.dodgybits.shuffle.android.core.model.Task.Builder; import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister; import org.dodgybits.shuffle.android.core.util.DateUtils; import org.dodgybits.shuffle.android.synchronisation.tracks.parsing.ParseResult; import org.dodgybits.shuffle.android.synchronisation.tracks.parsing.Parser; import org.dodgybits.shuffle.android.synchronisation.tracks.parsing.TaskParser; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlSerializer; import android.content.Context; import android.util.Log; import android.util.Xml; /** * @author Morten Nielsen */ public final class TaskSynchronizer extends Synchronizer<Task> { private static final String cTag = "TaskSynchronizer"; private final String mTracksUrl; private Parser<Task> mParser; public TaskSynchronizer( EntityPersister<Task> persister, TracksSynchronizer tracksSynchronizer, WebClient client, Context context, Analytics analytics, int basePercent, String tracksUrl) { super(persister, tracksSynchronizer, client, context, basePercent); mParser = new TaskParser(this, this, analytics); this.mTracksUrl = tracksUrl; } @Override protected EntityBuilder<Task> createBuilder() { return Task.newBuilder(); } @Override protected void verifyEntitiesForSynchronization(Map<Id, Task> localEntities) { LinkedList<Id> tasksWithoutContext = new LinkedList<Id>(); for(Task t : localEntities.values()) { if(!t.getContextId().isInitialised()) { tasksWithoutContext.add(t.getLocalId()); } } if (tasksWithoutContext.size() > 0) { mTracksSynchronizer.postSyncMessage(R.string.cannotSyncTasksWithoutContext); for(Id id : tasksWithoutContext) { localEntities.remove(id); } } } @Override protected String readingRemoteText() { return mContext.getString(R.string.readingRemoteTasks); } @Override protected String processingText() { return mContext.getString(R.string.processingTasks); } @Override protected String readingLocalText() { return mContext.getString(R.string.readingLocalTasks); } @Override protected String stageFinishedText() { return mContext.getString(R.string.doneWithTasks); } protected Task createMergedLocalEntity(Task localTask, Task newTask) { Builder builder = Task.newBuilder(); builder.mergeFrom(localTask); builder .setDescription(newTask.getDescription()) .setDetails(newTask.getDetails()) .setContextId(newTask.getContextId()) .setProjectId(newTask.getProjectId()) .setModifiedDate(newTask.getModifiedDate()) .setStartDate(newTask.getStartDate()) .setDeleted(newTask.isDeleted()) .setDueDate(newTask.getDueDate()) .setAllDay(newTask.isAllDay()) .setTracksId(newTask.getTracksId()); return builder.build(); } protected String createDocumentForEntity(Task task) { XmlSerializer serializer = Xml.newSerializer(); StringWriter writer = new StringWriter(); try { serializer.setOutput(writer); //serializer.startDocument("UTF-8", true); serializer.startTag("", "todo"); if (task.isComplete()) { String completedDateStr = DateUtils.formatIso8601Date(task.getModifiedDate()); serializer.startTag("", "completed-at").attribute("", "type", "datetime").text(completedDateStr).endTag("", "completed-at"); } Id contextId = findTracksIdByContextId(task.getContextId()); if (contextId.isInitialised()) { serializer.startTag("", "context-id").attribute("", "type", "integer").text(contextId.toString()).endTag("", "context-id"); } String createdDateStr = DateUtils.formatIso8601Date(task.getCreatedDate()); serializer.startTag("", "created-at").attribute("", "type", "datetime").text(createdDateStr).endTag("", "created-at"); serializer.startTag("", "description").text(task.getDescription()).endTag("", "description"); if (task.getDueDate() != 0) { String dueDateStr = DateUtils.formatIso8601Date(task.getDueDate()); serializer.startTag("", "due").attribute("", "type", "datetime").text(dueDateStr).endTag("", "due"); } serializer.startTag("", "notes").text(task.getDetails() != null ? task.getDetails() : "").endTag("", "notes"); Id projectId = findTracksIdByProjectId(task.getProjectId()); if (projectId.isInitialised()) { serializer.startTag("", "project-id").attribute("", "type", "integer").text(projectId.toString()).endTag("", "project-id"); } if (task.getStartDate() != 0L) { serializer.startTag("", "show-from").attribute("", "type", "datetime").text(DateUtils.formatIso8601Date(task.getStartDate())).endTag("", "show-from"); } serializer.startTag("", "state").text(task.isComplete() ? "completed" : "active").endTag("", "state"); String updatedDateStr = DateUtils.formatIso8601Date(task.getModifiedDate()); serializer.startTag("", "updated-at").attribute("", "type", "datetime").text(updatedDateStr).endTag("", "updated-at"); serializer.endTag("", "todo"); serializer.flush(); } catch (IOException ignored) { Log.d(cTag, "Failed to serialize task", ignored); } Log.d(cTag, writer.toString()); return writer.toString(); } @Override protected String createEntityUrl(Task task) { return mTracksUrl + "/todos/" + task.getTracksId() + ".xml"; } @Override protected String entityIndexUrl() { return mTracksUrl + "/todos.xml"; } @Override protected Parser<Task> getEntityParser() { return mParser; } @Override protected boolean deleteEntity(Task t) { //Avoid extra calls if the entity is already deleted or completed. if(t.isComplete() || t.isDeleted()) return true; WebResult result; try { result = mWebClient.getUrlContent(this.createEntityUrl(t)); } catch (ApiException e1) { return false; } XmlPullParser parser = Xml.newPullParser(); if(result.getStatus().getStatusCode() == HttpStatus.SC_NOT_FOUND) { super.deleteEntity(t); } if(result.getStatus().getStatusCode() != HttpStatus.SC_OK) { return false; } try { parser.setInput(new StringReader(result.getContent())); } catch (Exception e) { return false; } ParseResult<Task> parseResult = getEntityParser().parseSingle(parser); if(parseResult.isSuccess() && parseResult.getResult().isComplete()){ Task task = Task.newBuilder().mergeFrom(t).mergeFrom(parseResult.getResult()).build(); mPersister.update(task); return true; } return false; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/synchronisation/tracks/TaskSynchronizer.java
Java
asf20
7,871
package org.dodgybits.shuffle.android.synchronisation.tracks; import org.dodgybits.shuffle.android.preference.view.Progress; /** * Items that can receive updates about synchronization progress * * @author Morten Nielsen */ public interface SyncProgressListener { void progressUpdate(Progress progress); }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/synchronisation/tracks/SyncProgressListener.java
Java
asf20
316
package org.dodgybits.shuffle.android.synchronisation.tracks; import java.io.IOException; import java.io.StringWriter; import java.util.Map; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; import org.dodgybits.shuffle.android.core.model.EntityBuilder; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.android.core.model.Project.Builder; import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister; import org.dodgybits.shuffle.android.core.util.DateUtils; import org.dodgybits.shuffle.android.synchronisation.tracks.parsing.Parser; import org.dodgybits.shuffle.android.synchronisation.tracks.parsing.ProjectParser; import org.xmlpull.v1.XmlSerializer; import android.util.Log; import android.util.Xml; /** * @author Morten Nielsen */ public final class ProjectSynchronizer extends Synchronizer<Project> { private static final String cTag = "ProjectSynchronizer"; private final String mTracksUrl; private Parser<Project> mParser; public ProjectSynchronizer( EntityPersister<Project> persister, TracksSynchronizer tracksSynchronizer, WebClient client, android.content.Context context, Analytics analytics, int basePercent, String tracksUrl) { super(persister, tracksSynchronizer, client, context, basePercent); mParser = new ProjectParser(this, analytics); mTracksUrl = tracksUrl; } @Override protected void verifyEntitiesForSynchronization(Map<Id, Project> localEntities) { } @Override protected EntityBuilder<Project> createBuilder() { return Project.newBuilder(); } @Override protected String readingRemoteText() { return mContext.getString(R.string.readingRemoteProjects); } @Override protected String processingText() { return mContext.getString(R.string.processingProjects); } @Override protected String readingLocalText() { return mContext.getString(R.string.readingLocalProjects); } @Override protected String stageFinishedText() { return mContext.getString(R.string.doneWithProjects); } protected Project createMergedLocalEntity(Project localProject, Project remoteProject) { Builder builder = Project.newBuilder(); builder.mergeFrom(localProject); builder .setName(remoteProject.getName()) .setModifiedDate(remoteProject.getModifiedDate()) .setArchived(remoteProject.isArchived()) .setDefaultContextId(remoteProject.getDefaultContextId()) .setDeleted(remoteProject.isDeleted()) .setTracksId(remoteProject.getTracksId()); return builder.build(); } protected String createDocumentForEntity(Project project) { XmlSerializer serializer = Xml.newSerializer(); StringWriter writer = new StringWriter(); try { serializer.setOutput(writer); String now = DateUtils.formatIso8601Date(System.currentTimeMillis()); serializer.startTag("", "project"); serializer.startTag("", "created-at").attribute("", "type", "datetime").text(now).endTag("", "created-at"); Id contextId = findTracksIdByContextId(project.getDefaultContextId()); if(contextId.isInitialised()) { serializer.startTag("", "default-context-id").attribute("", "type", "integer").text(contextId.toString()).endTag("", "default-context-id"); } serializer.startTag("", "name").text(project.getName()).endTag("", "name"); serializer.startTag("", "state").text(project.isActive() ? "active" : "hidden").endTag("", "state"); serializer.startTag("", "updated-at").attribute("", "type", "datetime").text(now).endTag("", "updated-at"); serializer.endTag("", "project"); serializer.flush(); } catch (IOException ignored) { Log.d(cTag, "Failed to serialize project", ignored); } return writer.toString(); } @Override protected String createEntityUrl(Project project) { return mTracksUrl+ "/projects/" + project.getTracksId().getId() + ".xml"; } @Override protected String entityIndexUrl() { return mTracksUrl+ "/projects.xml"; } @Override protected Parser<Project> getEntityParser() { return mParser; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/synchronisation/tracks/ProjectSynchronizer.java
Java
asf20
4,580
package org.dodgybits.shuffle.android.synchronisation.tracks; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.SingleClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import org.dodgybits.shuffle.android.synchronisation.tracks.ssl.TrustedSSLSocketFactory; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.util.Log; /** * Handles communication to the REST service * * @author Morten Nielsen */ public class WebClient { private String sUserAgent; private byte[] sBuffer = new byte[512]; private final String tracksUser; private final String tracksPassword; private final String cTag = "WebClient"; private final boolean selfSignedCert; public WebClient(Context context, String tracksUser, String tracksPassword, boolean selfSignedCert) throws ApiException { this.tracksUser = tracksUser; this.tracksPassword = tracksPassword; this.selfSignedCert = selfSignedCert; PackageManager manager = context.getPackageManager(); PackageInfo info = null; try { info = manager.getPackageInfo(context.getPackageName(), 0); } catch (PackageManager.NameNotFoundException ignored) { } if (info != null) { sUserAgent = String.format("%1$s %2$s", info.packageName, info.versionName); } } protected synchronized boolean deleteUrl(String url) throws ApiException { if (sUserAgent == null) { throw new ApiException("User-Agent string must be prepared"); } // Create client and set our specific user-agent string HttpClient client = CreateClient(); java.net.URI uri = URI.create(url); HttpHost host = GetHost(uri); HttpDelete request = new HttpDelete(uri.getPath()); request.setHeader("User-Agent", sUserAgent); try { HttpResponse response = client.execute(host, request); // Check if server response is valid StatusLine status = response.getStatusLine(); Log.i(cTag, "delete with response " + status.toString()); return status.getStatusCode() == HttpStatus.SC_OK; } catch (IOException e) { throw new ApiException("Problem communicating with API", e); } } private HttpClient CreateClient() { DefaultHttpClient client; if (selfSignedCert) { HttpParams params = new BasicHttpParams(); SchemeRegistry sr = new SchemeRegistry(); sr.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); try { sr.register(new Scheme("https", new TrustedSSLSocketFactory(), 443)); } catch (Exception e) { Log.v("Shuffle", e.toString() + ""); sr.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); } ClientConnectionManager cm = new SingleClientConnManager(params, sr); client = new DefaultHttpClient(cm, params); } else { client = new DefaultHttpClient(); } client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(tracksUser, tracksPassword)); return client; } public synchronized WebResult getUrlContent(String url) throws ApiException { if (sUserAgent == null) { throw new ApiException("User-Agent string must be prepared"); } // Create client and set our specific user-agent string HttpClient client = CreateClient(); java.net.URI uri = URI.create(url); HttpHost host = GetHost(uri); HttpGet request = new HttpGet(uri.getPath()); request.setHeader("User-Agent", sUserAgent); try { HttpResponse response = client.execute(host, request); // Check if server response is valid StatusLine status = response.getStatusLine(); Log.i(cTag, "get with response " + status.toString()); if (status.getStatusCode() != HttpStatus.SC_OK) { return new WebResult(status, null); } // Pull content stream from response HttpEntity entity = response.getEntity(); InputStream inputStream = entity.getContent(); ByteArrayOutputStream content = new ByteArrayOutputStream(); // Read response into a buffered stream int readBytes; while ((readBytes = inputStream.read(sBuffer)) != -1) { content.write(sBuffer, 0, readBytes); } return new WebResult(status,new String(content.toByteArray())); } catch (IOException e) { throw new ApiException("Problem communicating with API", e); } } private HttpHost GetHost(URI uri) { HttpHost host; int port = uri.getPort(); if (port == -1) { port = uri.getScheme().equalsIgnoreCase("https") ? 443 : 80; } host = new HttpHost(uri.getHost(), port, uri.getScheme()); return host; } protected synchronized String postContentToUrl(String url, String content) throws ApiException { if (sUserAgent == null) { throw new ApiException("User-Agent string must be prepared"); } // Create client and set our specific user-agent string HttpClient client = CreateClient(); java.net.URI uri = URI.create(url); HttpHost host = GetHost(uri); HttpPost request = new HttpPost(uri.getPath()); request.setHeader("User-Agent", sUserAgent); request.setHeader("Content-Type", "text/xml"); HttpEntity ent; try { ent = new StringEntity(content, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new ApiException("unsupported encoding set", e); } request.setEntity(ent); try { HttpResponse response = client.execute(host, request); // Check if server response is valid StatusLine status = response.getStatusLine(); Log.i(cTag, "post with response " + status.toString()); if (status.getStatusCode() != HttpStatus.SC_CREATED) { throw new ApiException("Invalid response from server: " + status.toString() + " for content: " + content); } Header[] header = response.getHeaders("Location"); if (header.length != 0) return header[0].getValue(); else return null; } catch (IOException e) { throw new ApiException("Problem communicating with API", e); } } protected synchronized String putContentToUrl(String url, String content) throws ApiException { if (sUserAgent == null) { throw new ApiException("User-Agent string must be prepared"); } // Create client and set our specific user-agent string HttpClient client = CreateClient(); java.net.URI uri = URI.create(url); HttpHost host = GetHost(uri); HttpPut request = new HttpPut(uri.getPath()); request.setHeader("User-Agent", sUserAgent); request.setHeader("Content-Type", "text/xml"); HttpEntity ent; try { ent = new StringEntity(content, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new ApiException("unsupported encoding", e); } request.setEntity(ent); try { HttpResponse response = client.execute(host, request); // Check if server response is valid StatusLine status = response.getStatusLine(); Log.i(cTag, "put with response " + status.toString()); if (status.getStatusCode() != HttpStatus.SC_OK) { throw new ApiException("Invalid response from server: " + status.toString()); } // Pull returnContent stream from response HttpEntity entity = response.getEntity(); InputStream inputStream = entity.getContent(); ByteArrayOutputStream returnContent = new ByteArrayOutputStream(); // Read response into a buffered stream int readBytes; while ((readBytes = inputStream.read(sBuffer)) != -1) { returnContent.write(sBuffer, 0, readBytes); } return new String(returnContent.toByteArray()); } catch (IOException e) { throw new ApiException("Problem communicating with API", e); } } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/synchronisation/tracks/WebClient.java
Java
asf20
9,817
package org.dodgybits.shuffle.android.widget; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.content.*; import android.database.Cursor; import android.net.Uri; import android.view.View; import android.widget.RemoteViews; import com.google.inject.Inject; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; 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.*; 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.inject.ContentResolverProvider; import roboguice.util.Ln; import java.util.*; 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; 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; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/widget/AbstractWidgetProvider.java
Java
asf20
10,229
/* * 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 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; /** * 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; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/widget/DarkWidgetProvider.java
Java
asf20
4,049
/* * 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 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.HashMap; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; 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.DefaultEntityCache; 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.core.view.ContextIcon; 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.Preferences; import roboguice.inject.ContentResolverProvider; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.ContentResolver; import android.content.ContentUris; import android.content.Intent; import android.content.SharedPreferences.Editor; import android.database.Cursor; import android.net.Uri; import android.util.Log; import android.view.View; import android.widget.RemoteViews; /** * 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; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/widget/LightWidgetProvider.java
Java
asf20
3,832
package org.dodgybits.shuffle.android.widget; import android.appwidget.AppWidgetManager; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.RemoteViews; 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 java.util.ArrayList; import java.util.List; /** * 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; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/widget/WidgetConfigure.java
Java
asf20
5,034
package org.dodgybits.shuffle.android.widget; import android.appwidget.AppWidgetManager; import android.content.Context; import android.content.Intent; import android.os.Bundle; import com.google.inject.Injector; import roboguice.application.RoboApplication; import roboguice.inject.ContextScope; import roboguice.receiver.RoboBroadcastReceiver; 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) { } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/widget/RoboAppWidgetProvider.java
Java
asf20
4,814
/* * 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 android.widget.ListView; 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.core.util.OSUtils; import org.dodgybits.shuffle.android.preference.model.Preferences; import android.content.AsyncQueryHandler; import android.content.ContentResolver; import android.database.Cursor; import android.net.Uri; 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."); } } } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/preference/activity/PreferencesActivity.java
Java
asf20
4,332
/* * 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(); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/preference/activity/PreferencesDeleteCompletedActivity.java
Java
asf20
1,680
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.preference.activity; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.model.persistence.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(); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/preference/activity/PreferencesDeleteAllActivity.java
Java
asf20
1,663
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.preference.activity; import 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 com.google.inject.Inject; import roboguice.inject.InjectView; import android.content.SharedPreferences; import android.os.Bundle; import android.text.format.DateUtils; import android.util.Log; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.LinearLayout; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.TableRow.LayoutParams; import roboguice.util.Ln; 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(); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/preference/activity/PreferencesAppearanceActivity.java
Java
asf20
7,079
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 = "PreferencesRestoreBackupActivity"; 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(); 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; } } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/preference/activity/PreferencesRestoreBackupActivity.java
Java
asf20
18,664
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_URL; import static org.dodgybits.shuffle.android.preference.model.Preferences.TRACKS_USER; import static org.dodgybits.shuffle.android.preference.model.Preferences.TRACKS_SELF_SIGNED_CERT; 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.util.Log; 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 SynchronizationSettingsActivity 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; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/preference/activity/SynchronizationSettingsActivity.java
Java
asf20
7,011
/* * 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(); }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/preference/activity/PreferencesDeleteActivity.java
Java
asf20
1,942
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.preference.activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import com.google.inject.Inject; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.model.persistence.ContextPersister; import org.dodgybits.shuffle.android.core.model.persistence.InitialDataGenerator; import org.dodgybits.shuffle.android.core.model.persistence.ProjectPersister; import org.dodgybits.shuffle.android.core.model.persistence.TaskPersister; import org.dodgybits.shuffle.android.core.view.AlertUtils; import roboguice.util.Ln; 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(); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/preference/activity/PreferencesPermanentlyDeleteActivity.java
Java
asf20
2,397
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; } } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/preference/activity/PreferencesCreateBackupActivity.java
Java
asf20
14,193
package org.dodgybits.shuffle.android.preference.model; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import org.dodgybits.shuffle.android.core.model.persistence.selector.Flag; import roboguice.util.Ln; 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; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/preference/model/ListPreferenceSettings.java
Java
asf20
6,447
/* * 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 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 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)); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/preference/model/Preferences.java
Java
asf20
7,647
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; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/preference/view/Progress.java
Java
asf20
1,181
/* * 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.view.activity; import android.content.ContentUris; import android.content.Intent; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.text.format.DateFormat; import android.text.format.DateUtils; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.inject.Inject; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.android.core.model.Task; import org.dodgybits.shuffle.android.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.util.CalendarUtils; import org.dodgybits.shuffle.android.core.view.ContextIcon; import org.dodgybits.shuffle.android.list.activity.State; import org.dodgybits.shuffle.android.list.view.LabelView; import org.dodgybits.shuffle.android.list.view.StatusView; import org.dodgybits.shuffle.android.persistence.provider.TaskProvider; import roboguice.inject.InjectView; import roboguice.util.Ln; /** * A generic activity for viewing a task. */ public class TaskViewActivity extends AbstractViewActivity<Task> { private @InjectView(R.id.complete_toggle_button) Button mCompleteButton; private @InjectView(R.id.project) TextView mProjectView; private @InjectView(R.id.description) TextView mDescriptionView; private @InjectView(R.id.context) LabelView mContextView; private @InjectView(R.id.details_entry) View mDetailsEntry; private @InjectView(R.id.details) TextView mDetailsView; private @InjectView(R.id.scheduling_entry) View mSchedulingEntry; private @InjectView(R.id.start) TextView mStartView; private @InjectView(R.id.due) TextView mDueView; private @InjectView(R.id.calendar_entry) View mCalendarEntry; private @InjectView(R.id.view_calendar_button) Button mViewCalendarButton; // private @InjectView(R.id.reminder_entry) View mReminderEntry; // private @InjectView(R.id.reminder) TextView mReminderView; private @InjectView(R.id.status) StatusView mStatusView; private @InjectView(R.id.completed) TextView mCompletedView; private @InjectView(R.id.created) TextView mCreatedView; private @InjectView(R.id.modified) TextView mModifiedView; @Inject private EntityCache<Project> mProjectCache; @Inject private EntityCache<Context> mContextCache; @Inject private TaskPersister mPersister; @Override protected void onCreate(Bundle icicle) { Ln.d("onCreate+"); super.onCreate(icicle); loadCursors(); mCursor.moveToFirst(); mOriginalItem = mPersister.read(mCursor); updateUIFromItem(mOriginalItem); Drawable icon = getResources().getDrawable(R.drawable.ic_menu_view); icon.setBounds(0, 0, 36, 36); mViewCalendarButton.setCompoundDrawables(icon, null, null, null); mViewCalendarButton.setOnClickListener(this); mCompleteButton.setOnClickListener(this); } @Override protected void updateUIFromItem(Task task) { Context context = mContextCache.findById(task.getContextId()); Project project = mProjectCache.findById(task.getProjectId()); updateCompleteButton(task.isComplete()); updateProject(project); updateDescription(task.getDescription()); updateContext(context); updateDetails(task.getDetails()); updateScheduling(task.getStartDate(), task.getDueDate()); updateCalendar(task.getCalendarEventId()); updateExtras(task, context, project); } @Override protected EntityPersister<Task> getPersister() { return mPersister; } /** * @return id of layout for this view */ @Override protected int getContentViewResId() { return R.layout.task_view; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.complete_toggle_button: { toggleComplete(); String text = getString(R.string.itemSavedToast, getString(R.string.task_name)); Toast.makeText(this, text, Toast.LENGTH_SHORT).show(); finish(); break; } case R.id.view_calendar_button: { Uri eventUri = ContentUris.appendId( CalendarUtils.getEventContentUri().buildUpon(), mOriginalItem.getCalendarEventId().getId()).build(); Intent viewCalendarEntry = new Intent(Intent.ACTION_VIEW, eventUri); viewCalendarEntry.putExtra(CalendarUtils.EVENT_BEGIN_TIME, mOriginalItem.getStartDate()); viewCalendarEntry.putExtra(CalendarUtils.EVENT_END_TIME, mOriginalItem.getDueDate()); startActivity(viewCalendarEntry); break; } default: super.onClick(v); break; } } protected final void toggleComplete() { Task updatedTask = Task.newBuilder().mergeFrom(mOriginalItem) .setComplete(!mOriginalItem.isComplete()).build(); mPersister.update(updatedTask); } private void loadCursors() { // Get the task if we're editing mCursor = managedQuery(mUri, TaskProvider.Tasks.FULL_PROJECTION, null, null, null); if (mCursor == null || mCursor.getCount() == 0) { // The cursor is empty. This can happen if the event was deleted. finish(); } } private void updateCompleteButton(boolean isComplete) { String label = getString(R.string.complete_toggle_button, isComplete ? getString(R.string.incomplete) : getString(R.string.complete)); mCompleteButton.setText(label); } private void updateProject(Project project) { if (project == null) { mProjectView.setVisibility(View.GONE); } else { mProjectView.setVisibility(View.VISIBLE); mProjectView.setText(project.getName()); } } private void updateDescription(String description) { mDescriptionView.setTextKeepState(description); } private void updateContext(Context context) { if (context != null) { mContextView.setVisibility(View.VISIBLE); mContextView.setText(context.getName()); mContextView.setColourIndex(context.getColourIndex()); ContextIcon icon = ContextIcon.createIcon(context.getIconName(), getResources()); int id = icon.smallIconId; if (id > 0) { mContextView.setIcon(getResources().getDrawable(id)); } else { mContextView.setIcon(null); } } else { mContextView.setVisibility(View.INVISIBLE); } } private void updateDetails(String details) { if (TextUtils.isEmpty(details)) { mDetailsEntry.setVisibility(View.GONE); } else { mDetailsEntry.setVisibility(View.VISIBLE); mDetailsView.setText(details); } } private void updateScheduling(long startMillis, long dueMillis) { mStartView.setText(formatDateTime(startMillis)); mDueView.setText(formatDateTime(dueMillis)); } private void updateCalendar(Id calendarEntry) { if (calendarEntry.isInitialised()) { mCalendarEntry.setVisibility(View.VISIBLE); } else { mCalendarEntry.setVisibility(View.GONE); } } private final int cDateFormatFlags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_ABBREV_WEEKDAY | DateUtils.FORMAT_SHOW_TIME; private String formatDateTime(long millis) { String value; if (millis > 0L) { int flags = cDateFormatFlags; if (DateFormat.is24HourFormat(this)) { flags |= DateUtils.FORMAT_24HOUR; } value = DateUtils.formatDateTime(this, millis, flags); } else { value = ""; } return value; } private void updateExtras(Task task, Context context, Project project) { mStatusView.updateStatus(task, context, project, !task.isComplete()); mCompletedView.setText(task.isComplete() ? getString(R.string.completed) : ""); mCreatedView.setText(formatDateTime(task.getCreatedDate())); mModifiedView.setText(formatDateTime(task.getModifiedDate())); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/view/activity/TaskViewActivity.java
Java
asf20
9,507
/* * 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.view.activity; import android.content.Intent; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity; import org.dodgybits.shuffle.android.core.model.Entity; import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister; import org.dodgybits.shuffle.android.core.view.MenuUtils; import roboguice.inject.InjectView; import roboguice.util.Ln; /** * A generic activity for editing an item in a database. This can be used either * to simply view an item (Intent.VIEW_ACTION), view and edit an item * (Intent.EDIT_ACTION), or create a new item (Intent.INSERT_ACTION). */ public abstract class AbstractViewActivity<E extends Entity> extends FlurryEnabledActivity implements View.OnClickListener { private @InjectView(R.id.edit_button) Button mEditButton; protected Uri mUri; protected Cursor mCursor; protected E mOriginalItem; @Override protected void onCreate(Bundle icicle) { Ln.d("onCreate+"); super.onCreate(icicle); mUri = getIntent().getData(); setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); setContentView(getContentViewResId()); Drawable icon = getResources().getDrawable(R.drawable.ic_menu_edit); icon.setBounds(0, 0, 36, 36); mEditButton.setCompoundDrawables(icon, null, null, null); mEditButton.setOnClickListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuUtils.addPrefsHelpMenuItems(this, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (MenuUtils.checkCommonItemsSelected(item, this, MenuUtils.INBOX_ID)) { return true; } return super.onOptionsItemSelected(item); } public void onClick(View v) { switch (v.getId()) { case R.id.edit_button: doEditAction(); break; } } protected void doEditAction() { Intent editIntent = new Intent(Intent.ACTION_EDIT, mUri); startActivity(editIntent); finish(); } /** * @return id of layout for this view */ abstract protected int getContentViewResId(); abstract protected void updateUIFromItem(E item); abstract protected EntityPersister<E> getPersister(); }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/view/activity/AbstractViewActivity.java
Java
asf20
3,150
package org.dodgybits.shuffle.android.persistence.migrations; import android.content.Context; 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 + ");"); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/persistence/migrations/V10Migration.java
Java
asf20
1,016
package org.dodgybits.shuffle.android.persistence.migrations; import android.content.Context; 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" + ");"); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/persistence/migrations/V1Migration.java
Java
asf20
1,528
package org.dodgybits.shuffle.android.persistence.migrations; import android.content.Context; 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"); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/persistence/migrations/V11Migration.java
Java
asf20
2,424
package org.dodgybits.shuffle.android.persistence.migrations; import android.content.Context; import android.database.sqlite.SQLiteDatabase; public interface Migration { public void migrate(SQLiteDatabase db); }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/persistence/migrations/Migration.java
Java
asf20
223
package org.dodgybits.shuffle.android.persistence.migrations; import android.content.Context; 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;"); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/persistence/migrations/V15Migration.java
Java
asf20
915
package org.dodgybits.shuffle.android.persistence.migrations; import android.content.Context; 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;"); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/persistence/migrations/V14Migration.java
Java
asf20
918
package org.dodgybits.shuffle.android.persistence.migrations; import android.content.Context; 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;"); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/persistence/migrations/V13Migration.java
Java
asf20
510
package org.dodgybits.shuffle.android.persistence.migrations; import static org.dodgybits.shuffle.android.persistence.provider.ContextProvider.CONTEXT_TABLE_NAME; import android.content.Context; 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" + ");"); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/persistence/migrations/V9Migration.java
Java
asf20
716
package org.dodgybits.shuffle.android.persistence.migrations; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.provider.BaseColumns; import org.dodgybits.shuffle.android.persistence.provider.TaskProvider; import roboguice.util.Ln; import java.util.HashMap; import java.util.Map; import java.util.Set; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.DISPLAY_ORDER; 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}); } } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/persistence/migrations/V16Migration.java
Java
asf20
2,542
package org.dodgybits.shuffle.android.persistence.migrations; import android.content.Context; 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;"); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/persistence/migrations/V12Migration.java
Java
asf20
1,087
/* * 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); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/persistence/AutoCompleteCursorAdapter.java
Java
asf20
2,366
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); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/persistence/provider/ReminderProvider.java
Java
asf20
2,087
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); } } } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/persistence/provider/TaskProvider.java
Java
asf20
4,062
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); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/persistence/provider/AbstractCollectionProvider.java
Java
asf20
16,337
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); } } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/persistence/provider/ContextProvider.java
Java
asf20
3,084
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); } } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/persistence/provider/ProjectProvider.java
Java
asf20
3,739
/* * 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"; }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/persistence/provider/Shuffle.java
Java
asf20
804
/** * */ 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()); } private Context mContext; DatabaseHelper(Context context) { super(context, AbstractCollectionProvider.cDatabaseName, null, AbstractCollectionProvider.cDatabaseVersion); mContext = context; } @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()); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/persistence/provider/DatabaseHelper.java
Java
asf20
2,007
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.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.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> extends AbstractListActivity<G> { private static final String cTag = "AbstractDrilldownListActivity"; protected SparseIntArray mTaskCountArray; protected int getChildCount(Id groupId) { return mTaskCountArray.get((int)groupId.getId()); } protected final DrilldownListConfig<G> getDrilldownListConfig() { return (DrilldownListConfig<G>)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(); }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/activity/AbstractDrilldownListActivity.java
Java
asf20
2,935
/* * 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 } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/activity/State.java
Java
asf20
923
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.activity; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.persistence.selector.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 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; /** * Display list of contexts with task children. */ public class ContextsActivity extends AbstractDrilldownListActivity<Context> { @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> 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; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/activity/ContextsActivity.java
Java
asf20
3,690
/* * 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.Flag; 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.annotation.TopTasks; import org.dodgybits.shuffle.android.list.config.AbstractTaskListConfig; import org.dodgybits.shuffle.android.list.config.ListConfig; import org.dodgybits.shuffle.android.list.config.StandardTaskQueries; import com.google.inject.Inject; import android.content.ContextWrapper; import android.os.Bundle; import org.dodgybits.shuffle.android.list.config.TaskListConfig; import org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings; public class TopTasksActivity extends AbstractTaskListActivity { @Inject private TaskPersister mTaskPersister; @Inject @TopTasks private TaskListConfig mTaskListConfig; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); } protected ListConfig<Task> createListConfig() { return mTaskListConfig; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/activity/task/TopTasksActivity.java
Java
asf20
2,007
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.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.annotation.Inbox; import org.dodgybits.shuffle.android.list.annotation.Tickler; import org.dodgybits.shuffle.android.list.config.AbstractTaskListConfig; import org.dodgybits.shuffle.android.list.config.ListConfig; import org.dodgybits.shuffle.android.list.config.StandardTaskQueries; import org.dodgybits.shuffle.android.list.config.TaskListConfig; import org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings; import android.content.ContextWrapper; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.view.Menu; import android.view.View; import com.google.inject.Inject; public class TicklerActivity extends AbstractTaskListActivity { @Inject private TaskPersister mTaskPersister; @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> createListConfig() { return mTaskListConfig; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/activity/task/TicklerActivity.java
Java
asf20
2,180
/* * 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.activity.ListPreferenceActivity; 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.InjectView; import android.content.Intent; import android.database.Cursor; import android.graphics.drawable.Drawable; 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.view.ContextMenu.ContextMenuInfo; import android.widget.AdapterView; import android.widget.Button; import android.widget.ImageButton; import android.widget.ListAdapter; import android.widget.SimpleCursorAdapter; import android.widget.Toast; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.internal.Nullable; public abstract class AbstractTaskListActivity extends AbstractListActivity<Task> implements SwipeListItemListener { private static final String cTag = "AbstractTaskListActivity"; @Inject Provider<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(); } 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(); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/activity/task/AbstractTaskListActivity.java
Java
asf20
5,532
/* * 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 android.content.ContextWrapper; 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; 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.annotation.Inbox; import org.dodgybits.shuffle.android.list.config.AbstractTaskListConfig; import org.dodgybits.shuffle.android.list.config.ListConfig; import org.dodgybits.shuffle.android.list.config.StandardTaskQueries; import org.dodgybits.shuffle.android.list.config.TaskListConfig; import org.dodgybits.shuffle.android.list.view.ButtonBar; import org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings; import org.dodgybits.shuffle.android.preference.model.Preferences; import roboguice.event.Observes; public class InboxActivity extends AbstractTaskListActivity { @Inject private TaskPersister mTaskPersister; @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> 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(); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/activity/task/InboxActivity.java
Java
asf20
3,409
/* * 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.TaskPersister; 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 private TaskPersister mTaskPersister; @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> 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; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/activity/task/ContextTasksActivity.java
Java
asf20
3,575
/* * 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 android.content.ContentUris; import android.content.ContextWrapper; 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.MenuItem; import android.view.View; import android.widget.AdapterView; import com.google.inject.Inject; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.android.core.model.Task; import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister; import org.dodgybits.shuffle.android.core.model.persistence.TaskPersister; import org.dodgybits.shuffle.android.core.model.persistence.selector.Flag; 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.ContextTasks; import org.dodgybits.shuffle.android.list.annotation.ProjectTasks; import org.dodgybits.shuffle.android.list.config.AbstractTaskListConfig; import org.dodgybits.shuffle.android.list.config.ContextTasksListConfig; 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 org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings; import java.util.ArrayList; import java.util.Arrays; import java.util.List; 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; @Inject private TaskPersister mTaskPersister; @Override public void onCreate(Bundle icicle) { Uri contextURI = getIntent().getData(); mProjectId = Id.create(ContentUris.parseId(contextURI)); super.onCreate(icicle); } @Override protected ListConfig<Task> 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); } } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/activity/task/ProjectTasksActivity.java
Java
asf20
5,952
/* * 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.Flag; 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.core.view.MenuUtils; import org.dodgybits.shuffle.android.list.annotation.DueTasks; import org.dodgybits.shuffle.android.list.config.AbstractTaskListConfig; import org.dodgybits.shuffle.android.list.config.DueActionsListConfig; import org.dodgybits.shuffle.android.list.config.ListConfig; import org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings; import roboguice.inject.InjectView; import android.content.ContextWrapper; 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"; @Inject private TaskPersister mTaskPersister; @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> 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; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/activity/task/TabbedDueActionsActivity.java
Java
asf20
4,216
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; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/activity/ListPreferenceActivity.java
Java
asf20
4,506
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.activity; import org.dodgybits.shuffle.android.core.model.Project; 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 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; /** * Display list of projects with task children. */ public class ProjectsActivity extends AbstractDrilldownListActivity<Project> { @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> 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; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/activity/ProjectsActivity.java
Java
asf20
3,538
/* * 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.widget.*; 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.Id; 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 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.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import roboguice.event.Observes; import roboguice.inject.InjectView; public abstract class AbstractListActivity<T extends Entity> 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> 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> createListConfig(); abstract protected ListAdapter createListAdapter(Cursor cursor); // custom helper methods protected final ListConfig<T> 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); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/activity/AbstractListActivity.java
Java
asf20
11,704
/* * 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 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.util.Log; import android.view.*; import android.view.ContextMenu.ContextMenuInfo; import android.widget.ExpandableListAdapter; import android.widget.ExpandableListView; import android.widget.SimpleCursorTreeAdapter; import android.widget.Toast; import com.google.inject.Inject; 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.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.EntityPersister; import org.dodgybits.shuffle.android.core.model.persistence.TaskPersister; 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; public abstract class AbstractExpandableActivity<G extends Entity> 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> getListConfig(); }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/activity/expandable/AbstractExpandableActivity.java
Java
asf20
20,457
/* * 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 android.database.Cursor; import android.graphics.drawable.Drawable; 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; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Task; import org.dodgybits.shuffle.android.core.model.persistence.selector.EntitySelector; import org.dodgybits.shuffle.android.core.model.persistence.selector.TaskSelector; import org.dodgybits.shuffle.android.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 java.util.Arrays; public class ExpandableContextsActivity extends AbstractExpandableActivity<Context> { private int mChildIdColumnIndex; private int mGroupIdColumnIndex; private SparseIntArray mTaskCountArray; @Inject ContextExpandableListConfig mListConfig; @Inject Provider<ExpandableTaskView> mTaskViewProvider; @Override protected ExpandableListConfig<Context> 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() { EntitySelector 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; } }; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/activity/expandable/ExpandableContextsActivity.java
Java
asf20
6,396
/* * 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 android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.util.SparseIntArray; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; 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; 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.EntitySelector; 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 java.util.Arrays; public class ExpandableProjectsActivity extends AbstractExpandableActivity<Project> { 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> 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() { EntitySelector 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); } } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/activity/expandable/ExpandableProjectsActivity.java
Java
asf20
9,110
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 { }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/annotation/Projects.java
Java
asf20
513
package org.dodgybits.shuffle.android.list.annotation; import com.google.inject.BindingAnnotation; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; @BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) public @interface Tickler { }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/annotation/Tickler.java
Java
asf20
512
package org.dodgybits.shuffle.android.list.annotation; import com.google.inject.BindingAnnotation; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.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 { }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/annotation/ExpandableProjects.java
Java
asf20
523
package org.dodgybits.shuffle.android.list.annotation; import com.google.inject.BindingAnnotation; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; @BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) public @interface ContextTasks { }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/annotation/ContextTasks.java
Java
asf20
517
package org.dodgybits.shuffle.android.list.annotation; import com.google.inject.BindingAnnotation; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; @BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) public @interface ExpandableContexts { }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/annotation/ExpandableContexts.java
Java
asf20
523
package org.dodgybits.shuffle.android.list.annotation; import com.google.inject.BindingAnnotation; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; @BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) public @interface TopTasks { }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/annotation/TopTasks.java
Java
asf20
513
package org.dodgybits.shuffle.android.list.annotation; import com.google.inject.BindingAnnotation; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; @BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) public @interface ProjectTasks { }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/annotation/ProjectTasks.java
Java
asf20
517
package org.dodgybits.shuffle.android.list.annotation; import com.google.inject.BindingAnnotation; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; @BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) public @interface DueTasks { }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/annotation/DueTasks.java
Java
asf20
513
package org.dodgybits.shuffle.android.list.annotation; import com.google.inject.BindingAnnotation; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; @BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) public @interface Contexts { }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/annotation/Contexts.java
Java
asf20
512
package org.dodgybits.shuffle.android.list.annotation; import com.google.inject.BindingAnnotation; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; @BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) public @interface Inbox { }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/annotation/Inbox.java
Java
asf20
510
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.view; import org.dodgybits.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); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/view/LabelView.java
Java
asf20
2,263
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.view; import android.R; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.widget.AdapterView; import android.widget.FrameLayout; import android.widget.ListView; public class SwipeListItemWrapper extends FrameLayout { private static final String cTag = "SwipeListItemWrapper"; private int mStartX; private int mStartY; private SwipeListItemListener mListener; private int mPosition; public SwipeListItemWrapper(Context context) { super(context); } public SwipeListItemWrapper(Context context, AttributeSet attrs) { super(context, attrs); } public SwipeListItemWrapper(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { final int action = ev.getAction(); final int x = (int)ev.getX(); final int y = (int)ev.getY(); boolean stealEvent = false; switch (action) { case MotionEvent.ACTION_MOVE: Log.d(cTag, "move event"); if (isValidSwipe(x, y)) { stealEvent = true; } break; case MotionEvent.ACTION_DOWN: Log.d(cTag, "down event"); mStartX = x; mStartY = y; break; case MotionEvent.ACTION_CANCEL: Log.d(cTag, "cancel event"); mPosition = AdapterView.INVALID_POSITION; // some parent component has stolen the event // nothing to do break; case MotionEvent.ACTION_UP: Log.d(cTag, "up event"); break; } return stealEvent; } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { // we've got a valid swipe event. Notify the listener (if any) if (mPosition != AdapterView.INVALID_POSITION && mListener != null) { mListener.onListItemSwiped(mPosition); } } return true; } public void setSwipeListItemListener(SwipeListItemListener listener) { mListener = listener; } /** * Check if this appears to be a swipe event. * * Consider it a swipe if it traverses at least a third of the screen, * and is mostly horizontal. */ private boolean isValidSwipe(final int x, final int y) { final int screenWidth = getWidth(); final int xDiff = Math.abs(x - mStartX); final int yDiff = Math.abs(y - mStartY); boolean horizontalValid = xDiff >= (screenWidth / 3); boolean verticalValid = yDiff > 0 && (xDiff / yDiff) > 4; mPosition = AdapterView.INVALID_POSITION; if (horizontalValid && verticalValid) { ListView list = (ListView) findViewById(R.id.list); if (list != null) { // adjust for list not being at top of screen mPosition = list.pointToPosition(mStartX, mStartY - list.getTop()); } } Log.d(cTag, "isValidSwipe hValid=" + horizontalValid + " vValid=" + verticalValid + " position=" + mPosition); return horizontalValid && verticalValid; } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/view/SwipeListItemWrapper.java
Java
asf20
3,874
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); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/view/StatusView.java
Java
asf20
5,847
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.view; import org.dodgybits.android.shuffle.R; import 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); } } } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/view/ProjectView.java
Java
asf20
3,236
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.view; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.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); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/view/ExpandableTaskView.java
Java
asf20
1,509
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.list.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); } }
115371172-shuffle
client/src/org/dodgybits/shuffle/android/list/view/ContextView.java
Java
asf20
4,007