ContextView2Activity.java :  » UnTagged » nextaction » net » kazed » nextaction » context » activity » Android Open Source

Android Open Source » UnTagged » nextaction 
nextaction » net » kazed » nextaction » context » activity » ContextView2Activity.java
package net.kazed.nextaction.context.activity;

import java.util.Iterator;

import net.kazed.android.inject.Autowired;
import net.kazed.android.inject.InjectedListActivity;
import net.kazed.nextaction.ApplicationResource;
import net.kazed.nextaction.NextActionApplication;
import net.kazed.nextaction.R;
import net.kazed.nextaction.database.ContextCache;
import net.kazed.nextaction.database.GtdContext;
import net.kazed.nextaction.database.Task;
import net.kazed.nextaction.database.TaskDao;
import net.kazed.nextaction.database.TreeNode;
import net.kazed.nextaction.help.Help;
import net.kazed.nextaction.menu.TimerOptionMenuItem;
import net.kazed.nextaction.timer.Notifier;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnTouchListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class ContextView2Activity extends InjectedListActivity {

    private static final String cTag = "ContextView2Activity";

    public static final String PICK_TASK = "net.kazed.nextaction.intent.PICK_TASK";
    
    private static final int NEW_TASK = 1;
    private static final int VIEW_TASK = 3;
    private static final int VIEW_CONTEXT = 4;
    private static final int NEW_CONTEXT = 5;
    private static final int EDIT_CONTEXT = 6;
    private static final int MENU_TIMER = EDIT_CONTEXT + 1;

    private static final int DIALOG_TIMER = 0;

    private TaskDao taskDao;
    
    private TextView numberOfTasksText;
    private int contextId;
    private Uri contextUri;
    private String action;
    private GtdContext context;
    private Cursor taskCursor;
    private ContextCache contextCache;
    private ContextTaskListAdapter listAdapter;
    private MotionEvent downStart;
    private ApplicationResource applicationResource;
    private TaskListDisplayMenu taskListDisplayMenu;
    private TimerOptionMenuItem timerOptionMenuItem;

    @Autowired
    public void setTaskDao(TaskDao taskDao) {
       this.taskDao = taskDao;
    }
    
    @Override
    public void onCreate(Bundle savedData) {
        super.onCreate(savedData);
        contextUri = getIntent().getData();
        action = getIntent().getAction();
        setContentView(R.layout.context_task_list);
        setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);

        NextActionApplication application = (NextActionApplication) getApplication();
        applicationResource = application.getApplicationResource();
        
        numberOfTasksText = (TextView) findViewById(R.id.number_of_tasks);
        contextId = (int) ContentUris.parseId(contextUri);
        taskListDisplayMenu = new TaskListDisplayMenu(this);
        contextCache = application.getContextCache();
        setCursor();

        getListView().setOnTouchListener(new ListOnTouchListener());
    }

    @Override
    protected void onResume() {
        context = contextCache.getContextTree((int) contextId).getData();
        String title = getResources().getString(R.string.context_view_title) + ": "
           + context.getAbsoluteContextPath(getContentResolver(), " > ");
        setTitle(title);
//        titleWidget.setText(context.getAbsoluteContextPath(getContentResolver(), " > "));
        numberOfTasksText.setText(Integer.toString(context.getNumberOfTasks()));

        super.onResume();
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        Object item = listAdapter.getItem(position);
        if (item instanceof GtdContext) {
            GtdContext context = (GtdContext) item;
            Uri itemUri = ContentUris.withAppendedId(GtdContext.CONTENT_URI, context.getId());
            Intent intent = new Intent(action, itemUri);
            startActivityForResult(intent, VIEW_CONTEXT);
        } else if (item instanceof Task) {
            Task task = (Task) item;
            Uri itemUri = ContentUris.withAppendedId(Task.CONTENT_URI, task.getId());
            if (PICK_TASK.equals(action)) {
                Intent intent = new Intent(PICK_TASK, itemUri);
                setResult(RESULT_OK, intent);
                finish();
            } else {
//                Uri itemUri = ContentUris.withAppendedId(Uri.parse("content://nextaction/task"), task.getId());
                Intent intent = new Intent(Intent.ACTION_VIEW, itemUri);
                startActivityForResult(intent, VIEW_TASK);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        taskCursor.requery();
        listAdapter.requery();
        if (resultCode == RESULT_OK) {
            if (requestCode == NEW_CONTEXT) {
                Uri newContextUri = data.getData();
                String idSegment = newContextUri.getLastPathSegment();
                if (idSegment != null) {
                    int id = Integer.parseInt(idSegment);
                    int position = listAdapter.getContextPosition(id);
                    getListView().setSelection(position);
                }
            } else if (requestCode == NEW_TASK || requestCode == VIEW_TASK) {
               Uri itemUri = data.getData();
               String idSegment = itemUri.getLastPathSegment();
               if (idSegment != null) {
                   int id = Integer.parseInt(idSegment);
                   int position = listAdapter.getTaskPosition(id);
                   getListView().setSelection(position);
               }
            } else {
            }
        }
        if (ContextView2Activity.PICK_TASK.equals(action)) {
            setResult(resultCode, data);
            finish();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        if (PICK_TASK.equals(action)) {
            inflater.inflate(R.menu.context_view_pick_task, menu);
        } else{
            inflater.inflate(R.menu.context_view, menu);
        }
        
        taskListDisplayMenu.onCreateOptionsMenu(menu);
        timerOptionMenuItem = new TimerOptionMenuItem(menu, MENU_TIMER);
        
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
       boolean handled = false;
        switch (item.getItemId()) {
        case R.id.menu_insert_task:
            Intent intent = new Intent(Intent.ACTION_INSERT, Task.CONTENT_URI);
            intent.putExtra(GtdContext.SELECTED_CONTEXT_ID, contextId);
            startActivityForResult(intent, NEW_TASK);
            break;
        case R.id.menu_insert_context:
            GtdContext newContext = new GtdContext("New context");
            newContext.setParentContextId(context.getId());
            ContentValues values = new ContentValues();
            newContext.toValues(values);
            Uri newContextUri = getContentResolver().insert(GtdContext.CONTENT_URI, values);

            Intent contextIntent = new Intent(Intent.ACTION_INSERT, newContextUri);
            startActivityForResult(contextIntent, NEW_CONTEXT);
            break;
        case R.id.menu_edit_context:
            Intent editIntent = new Intent(Intent.ACTION_EDIT, contextUri);
            startActivityForResult(editIntent, EDIT_CONTEXT);
            break;
        case R.id.menu_delete_context:
            AlertDialog.Builder builder = new AlertDialog.Builder(ContextView2Activity.this);
            builder.setTitle(R.string.context_delete_alert_title).setMessage(R.string.context_delete_alert_message).setIcon(
                            android.R.drawable.ic_dialog_alert);
            builder.setPositiveButton(R.string.alert_yes, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    getContentResolver().delete(contextUri, null, null);
                    finish();
                }
            });
            builder.setNegativeButton(R.string.alert_no, null);
            builder.show();
            break;
        case R.id.menu_help:
           Uri helpUri = Uri.withAppendedPath(Help.CONTENT_URI, "context-task-view.html");
           startActivity(new Intent(Intent.ACTION_VIEW, helpUri));
           break;
        case MENU_TIMER:
           showDialog(DIALOG_TIMER);
           handled = true;
          break;
        default:
           Log.d("onOptionsItemSelected", "item: " + item.getItemId() + " group: " + item.getGroupId());
            boolean displayChanged = taskListDisplayMenu.onOptionsItemSelected(item);
            if (displayChanged) {
                setCursor();
            }
            break;
        }
        handled = true;
        return handled || super.onOptionsItemSelected(item);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
       Dialog dialog = null;
       switch (id) {
       case DIALOG_TIMER:
          dialog = timerOptionMenuItem.createDialog(this, Notifier.TOPLEVEL_CONTENT_TIMER_URI);
          break;
       default:
          dialog = super.onCreateDialog(id);
          break;
       }
       return dialog;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    /**
     * Set query cursor.
     */
    private void setCursor() {
        String where = Task.Column.CONTEXT_ID + " = ?";
        String displayWhere = taskListDisplayMenu.getWhereClause();
        if (displayWhere != null) {
            where = where + " and " + displayWhere;
        }
        
        taskCursor = taskDao.queryTasksByContext(contextId, displayWhere);
        startManagingCursor(taskCursor);

        listAdapter = new ContextTaskListAdapter(contextCache, (int) contextId, taskCursor, applicationResource);
        setListAdapter(listAdapter);
    }
    
    private static class ContextTaskListAdapter extends BaseAdapter {

        private ContextCache contextCache;
        private Integer contextId;
        private Cursor taskCursor;
        private int numberOfContexts;
        private int numberOfTasks;
        private int firstTaskPosition;
        private TreeNode<GtdContext> contextNode;
        private ApplicationResource applicationResource;

        /**
         * Constructor.
         * @param contextId Parent context ID.
         * @param taskCursor Cursor for retrieving tasks.
         */
        public ContextTaskListAdapter(ContextCache contextCache, Integer contextId, Cursor taskCursor,
                        ApplicationResource applicationResource) {
            this.contextCache = contextCache;
            this.contextId = contextId;
            this.taskCursor = taskCursor;
            this.applicationResource = applicationResource;
            initializeQuery();
        }

        public void requery() {
            Log.d(cTag, "requery");
            initializeQuery();
            notifyDataSetChanged();
        }

        private void initializeQuery() {
           Log.d(cTag, "initializeQuery");
           contextNode = contextCache.getContextTree(contextId);
           numberOfContexts = contextNode.getChildren().size();
           numberOfTasks = taskCursor.getCount();
           firstTaskPosition = numberOfContexts;
       }

        /**
         * Get position of context with contextId.
         * @param contextId ID of context.
         * @return Position of context item, -1 if not found.
         */
        public int getContextPosition(int contextId) {
            int position = -1;
            int i = 0;
            for (Iterator<TreeNode<GtdContext>> nodeIterator = contextNode.getChildren().iterator(); position == -1
                            && nodeIterator.hasNext();) {
                TreeNode<GtdContext> childNode = (TreeNode<GtdContext>) nodeIterator.next();
                if (contextId == childNode.getData().getId()) {
                    position = i;
                }
                i++;
            }
            return position;
        }

        /**
         * Get position of task with taskId.
         * @param taskId ID of task.
         * @return Position of item, -1 if not found.
         */
        public int getTaskPosition(int taskId) {
            int position = -1;
            int i = 0;
            if (taskCursor.moveToFirst()) {
               while (!taskCursor.isAfterLast()) {
                  int retrievedTaskId = Task.retrieveId(taskCursor);
                  if (taskId == retrievedTaskId) {
                     position = i;
                  }
                  i++;
                  taskCursor.moveToNext();
               }
            }
            Log.d("getTaskPosition", "position: " + position);
            return position + numberOfContexts;
        }

        @Override
        public boolean areAllItemsEnabled() {
            return true;
        }

        @Override
        public boolean isEnabled(int position) {
            return isContextItem(position) || isTaskItem(position);
        }

        @Override
        public int getCount() {
            return numberOfContexts + numberOfTasks;
        }

        @Override
        public Object getItem(int position) {
            Object item = null;
            if (isContextItem(position)) {
                GtdContext context = contextNode.getChildren().get(position).getData();
                item = context;
            } else if (isTaskItem(position)) {
                taskCursor.moveToPosition(position - numberOfContexts);
                Task task = new Task(taskCursor);
                item = task;
            }
            return item;
        }

        @Override
        public long getItemId(int position) {
            long itemId = 0;
            if (isContextItem(position)) {
                GtdContext context = contextNode.getChildren().get(position).getData();
                itemId = context.getId();
            } else if (isTaskItem(position)) {
                taskCursor.moveToPosition(position - numberOfContexts);
                Task task = new Task(taskCursor);
                itemId = 10000 + task.getId();
            } else {
                itemId = 1000000 + position;
            }

            return itemId;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = null;

            if (isContextItem(position)) {
                ContextListItemView contextView = null;
                if (convertView instanceof ContextListItemView) {
                    contextView = (ContextListItemView) convertView;
                } else {
                    contextView = new ContextListItemView(parent.getContext(), R.layout.context_list_item_view);
                }
                GtdContext context = contextNode.getChildren().get(position).getData();
                contextView.updateView(context);
                view = contextView;
            } else if (isTaskItem(position)) {
                TaskListItemView taskView = null;
                if (convertView instanceof TaskListItemView) {
                    taskView = (TaskListItemView) convertView;
                } else {
                    taskView = new TaskListItemView(parent.getContext(), applicationResource);
                }
                taskCursor.moveToPosition(position - numberOfContexts);
                Task task = new Task(taskCursor);
                taskView.updateView(task);
                view = taskView;
            } else {
                Log.d(cTag, "unknown view");
            }

            return view;
        }

        @Override
        public int getViewTypeCount() {
            int count = 0;
            if (numberOfContexts > 0) {
                count++;
            }
            if (numberOfTasks > 0) {
                count++;
            }
            return 2;
        }

        @Override
        public int getItemViewType(int position) {
            int viewType = 0;
            if (isContextItem(position)) {
                viewType = 0;
            } else if (isTaskItem(position)) {
                viewType = 1;
            }
            return viewType;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public boolean isEmpty() {
            return numberOfContexts == 0 && numberOfTasks == 0;
        }

//        @Override
//        public void registerDataSetObserver(DataSetObserver observer) {
//            Log.d(cTag, "registerDataSetObserver");
//        }
//
//        @Override
//        public void unregisterDataSetObserver(DataSetObserver observer) {
//            Log.d(cTag, "unregisterDataSetObserver");
//        }

        private boolean isContextItem(int position) {
            return (position >= 0 && position < numberOfContexts);
        }

        private boolean isTaskItem(int position) {
            return (position >= firstTaskPosition);
        }

    }

    private class ListOnTouchListener implements OnTouchListener {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // keep track of the starting down-event
                downStart = MotionEvent.obtain(event);
                Log.d(cTag, "ACTION_DOWN: " + event);
                break;
            case MotionEvent.ACTION_MOVE:
                Log.d(cTag, "ACTION_MOVE: " + event);
                if (isSwiped(view, event)) {
                    Log.d(cTag, "ACTION_MOVE: swiped");
                    // figure out which child view we crossed
                    ListView list = (ListView) findViewById(android.R.id.list);
                    int position = list.pointToPosition((int) downStart.getX(), (int) downStart.getY());
                    Object item = listAdapter.getItem(position);
                    Log.d(cTag, "crossed: " + item);
                    if (item instanceof Task) {
                        Task task = (Task) item;
                        task.setComplete(!task.getComplete());
                        Log.d(cTag, "task: " + task.getDescription() + " - " + task.getComplete());
                        ContentValues values = new ContentValues();
                        task.toValues(values);
                        Uri taskUri = ContentUris.withAppendedId(Task.CONTENT_URI, task.getId());
                        getContentResolver().update(taskUri, values, null, null);
                        onContentChanged();
                    }
                    // and return true to consume this event
                    return true;
                }
                break;
            case MotionEvent.ACTION_UP:
                Log.d(cTag, "ACTION_UP: " + event);
                if (isSwiped(view, event)) {
                    Log.d(cTag, "ACTION_UP: swiped");
                    return true;
                }
                break;
            }

            return false;
        }

        public boolean isSwiped(View view, MotionEvent event) {
            boolean swiped = false;
            float deltaX = event.getX() - downStart.getX();
            if (Math.abs(deltaX) > 10 * 2) {
                // check if we crossed an item
                float targetWidth = view.getWidth() / 4;
                float deltaY = event.getY() - downStart.getY();
                boolean movedAcross = (Math.abs(deltaX) > targetWidth);
                boolean steadyHand = (Math.abs(deltaX / deltaY) > 2);
                swiped = movedAcross && steadyHand;
            }
            return swiped;
        }

    }

}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.