@Override
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
   if (resultCode == RESULT_OK) {
     if (Intent.ACTION_EDIT.equals(getIntent().getAction())) {
       boolean isPushCapable = false;
       try {
         Store store = mAccount.getRemoteStore();
         isPushCapable = store.isPushCapable();
       } catch (Exception e) {
         Log.e(VisualVoicemail.LOG_TAG, "Could not get remote store", e);
       }
       if (isPushCapable && mAccount.getFolderPushMode() != FolderMode.NONE) {
         MailService.actionRestartPushers(this, null);
       }
       mAccount.save(Preferences.getPreferences(this));
       finish();
     } else {
       // first time setup, return to AccountSetup activity to save account
       setResult(RESULT_OK);
       finish();
     }
   } else {
     if (!Intent.ACTION_EDIT.equals(
         getIntent().getAction())) { // remove account if failed initial setup
       if (mAccount != null) Preferences.getPreferences(this).deleteAccount(mAccount);
     }
   }
 }
Esempio n. 2
0
 /**
  * Returns a note id from an intent if it contains one, either as part of its URI or as an extra
  *
  * <p>Returns -1 if no id was contained, this includes insert actions
  */
 long getNoteId(final Intent intent) {
   long retval = -1;
   if (intent != null
       && intent.getData() != null
       && (Intent.ACTION_EDIT.equals(intent.getAction())
           || Intent.ACTION_VIEW.equals(intent.getAction()))) {
     if (intent.getData().getPath().startsWith(TaskList.URI.getPath())) {
       // Find it in the extras. See DashClock extension for an example
       retval = intent.getLongExtra(Task.TABLE_NAME, -1);
     } else if ((intent
             .getData()
             .getPath()
             .startsWith(LegacyDBHelper.NotePad.Notes.PATH_VISIBLE_NOTES)
         || intent.getData().getPath().startsWith(LegacyDBHelper.NotePad.Notes.PATH_NOTES)
         || intent.getData().getPath().startsWith(Task.URI.getPath()))) {
       retval = Long.parseLong(intent.getData().getLastPathSegment());
     }
     // else if (null != intent
     // .getStringExtra(TaskDetailFragment.ARG_ITEM_ID)) {
     // retval = Long.parseLong(intent
     // .getStringExtra(TaskDetailFragment.ARG_ITEM_ID));
     // }
   }
   return retval;
 }
Esempio n. 3
0
 /**
  * Returns a list id from an intent if it contains one, either as part of its URI or as an extra
  *
  * <p>Returns -1 if no id was contained, this includes insert actions
  */
 long getListId(final Intent intent) {
   long retval = -1;
   if (intent != null
       && intent.getData() != null
       && (Intent.ACTION_EDIT.equals(intent.getAction())
           || Intent.ACTION_VIEW.equals(intent.getAction())
           || Intent.ACTION_INSERT.equals(intent.getAction()))) {
     if ((intent.getData().getPath().startsWith(NotePad.Lists.PATH_VISIBLE_LISTS)
         || intent.getData().getPath().startsWith(NotePad.Lists.PATH_LISTS)
         || intent.getData().getPath().startsWith(TaskList.URI.getPath()))) {
       try {
         retval = Long.parseLong(intent.getData().getLastPathSegment());
       } catch (NumberFormatException e) {
         retval = -1;
       }
     } else if (-1 != intent.getLongExtra(LegacyDBHelper.NotePad.Notes.COLUMN_NAME_LIST, -1)) {
       retval = intent.getLongExtra(LegacyDBHelper.NotePad.Notes.COLUMN_NAME_LIST, -1);
     } else if (-1 != intent.getLongExtra(TaskDetailFragment.ARG_ITEM_LIST_ID, -1)) {
       retval = intent.getLongExtra(TaskDetailFragment.ARG_ITEM_LIST_ID, -1);
     } else if (-1 != intent.getLongExtra(Task.Columns.DBLIST, -1)) {
       retval = intent.getLongExtra(Task.Columns.DBLIST, -1);
     }
   }
   return retval;
 }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    final Intent intent = getIntent();

    // Do some setup based on the action being performed.
    final String action = intent.getAction();
    if (Intent.ACTION_EDIT.equals(action)) {
      mState = STATE_EDIT;
      // mUri = intent.getData();
    } else if (Intent.ACTION_INSERT.equals(action)) {
      mState = STATE_INSERT;

    } else {
      // Whoops, unknown action! Bail.
      Log.e(TAG, "Unknown action, exiting");
      finish();
      return;
    }

    // Set the layout for this activity. You can find it in
    // res/layout/note_editor.xml
    setContentView(R.layout.note_editor);

    // The text view for our note, identified by its ID in the XML file.
    mText = (EditText) findViewById(R.id.note);

    // If an instance of this activity had previously stopped, we can
    // get the original text it started with.
    if (savedInstanceState != null) {
      mOriginalContent = savedInstanceState.getString(ORIGINAL_CONTENT);
    }
  }
Esempio n. 5
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_bookmark);

    Intent intent = getIntent();

    if (Intent.ACTION_SEND.equals(intent.getAction()) && intent.hasExtra(Intent.EXTRA_TEXT)) {
      bookmark = new Bookmark();

      ShareCompat.IntentReader reader = ShareCompat.IntentReader.from(this);

      String url = StringUtils.getUrl(reader.getText().toString());
      bookmark.setUrl(url);

      if (reader.getSubject() != null) bookmark.setDescription(reader.getSubject());

      if (url.equals("")) {
        Toast.makeText(this, R.string.add_bookmark_invalid_url, Toast.LENGTH_LONG).show();
      }

      if (intent.hasExtra(Constants.EXTRA_DESCRIPTION)) {
        bookmark.setDescription(intent.getStringExtra(Constants.EXTRA_DESCRIPTION));
      }
      bookmark.setNotes(intent.getStringExtra(Constants.EXTRA_NOTES));
      bookmark.setTagString(intent.getStringExtra(Constants.EXTRA_TAGS));
      bookmark.setShared(!intent.getBooleanExtra(Constants.EXTRA_PRIVATE, privateDefault));

      try {
        Bookmark old = BookmarkManager.GetByUrl(bookmark.getUrl(), this);
        bookmark = old.copy();
      } catch (Exception e) {

      }

    } else if (Intent.ACTION_EDIT.equals(intent.getAction())) {
      int id = Integer.parseInt(intent.getData().getLastPathSegment());
      try {
        bookmark = BookmarkManager.GetById(id, this);
        oldBookmark = bookmark.copy();

        update = true;
      } catch (ContentNotFoundException e) {
        e.printStackTrace();
      }
    }

    if (update) setTitle(getString(R.string.add_bookmark_edit_title));
    else setTitle(getString(R.string.add_bookmark_add_title));

    frag =
        (AddBookmarkFragment)
            getSupportFragmentManager().findFragmentById(R.id.add_bookmark_fragment);
    frag.loadBookmark(bookmark, oldBookmark);
  }
Esempio n. 6
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState != null) {
      final Object note = savedInstanceState.get(ORIGINAL_NOTE);
      if (note != null) mOriginalNote = (Note) note;
    }

    final Intent intent = getIntent();
    final String action = intent.getAction();
    if (Intent.ACTION_VIEW.equals(action) || Intent.ACTION_EDIT.equals(action)) {
      mState = STATE_EDIT;
      mUri = intent.getData();
    } else if (Intent.ACTION_INSERT.equals(action)) {
      mState = STATE_INSERT;
      if (mOriginalNote == null) {
        mUri = getContentResolver().insert(intent.getData(), null);
      } else {
        mUri = mOriginalNote.getUri();
      }

      setResult(RESULT_OK, (new Intent()).setAction(mUri.toString()));
    }

    if (mUri == null) {
      finish();
      return;
    }

    setContentView(R.layout.edit);

    mBodyText = (EditText) findViewById(R.id.body);

    Button confirmButton = (Button) findViewById(R.id.confirm);
    confirmButton.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View view) {
            finish();
          }
        });
    Button cancelButton = (Button) findViewById(R.id.cancel);
    cancelButton.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View view) {
            cancelNote();
          }
        });
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.contact_edit);
    initUI();

    Intent intent = getIntent();
    bundle = intent.getExtras();
    //		uri = intent.getData();
    String action = intent.getAction();
    if (Intent.ACTION_EDIT.equals(action)) {
      mState = STATE_EDIT;
    } else if (Intent.ACTION_INSERT.equals(action)) {
      mState = STATE_INSERT;
    }
  }
  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    if (savedInstanceState != null) {
      // Just restore from the saved state.  No loading.
      onRestoreInstanceState(savedInstanceState);
      if (mStatus == Status.SELECTING_ACCOUNT) {
        // Account select dialog is showing.  Don't setup the editor yet.
      } else if (mStatus == Status.LOADING) {
        startGroupMetaDataLoader();
      } else {
        setupEditorForAccount();
      }
    } else if (Intent.ACTION_EDIT.equals(mAction)) {
      startGroupMetaDataLoader();
    } else if (Intent.ACTION_INSERT.equals(mAction)) {
      final Account account =
          mIntentExtras == null
              ? null
              : (Account) mIntentExtras.getParcelable(Intents.Insert.EXTRA_ACCOUNT);
      final String dataSet =
          mIntentExtras == null ? null : mIntentExtras.getString(Intents.Insert.EXTRA_DATA_SET);

      if (account != null) {
        // Account specified in Intent - no data set can be specified in this manner.
        mAccountName = account.name;
        mAccountType = account.type;
        mDataSet = dataSet;
        setupEditorForAccount();
      } else {
        // No Account specified. Let the user choose from a disambiguation dialog.
        selectAccountAndCreateGroup();
      }
    } else {
      throw new IllegalArgumentException(
          "Unknown Action String "
              + mAction
              + ". Only support "
              + Intent.ACTION_EDIT
              + " or "
              + Intent.ACTION_INSERT);
    }
  }
Esempio n. 9
0
  /** Returns true the intent URI targets a note. Either an edit/view or insert. */
  boolean isNoteIntent(final Intent intent) {
    if (intent == null) {
      return false;
    }
    if (Intent.ACTION_SEND.equals(intent.getAction())
        || "com.google.android.gm.action.AUTO_SEND".equals(intent.getAction())) {
      return true;
    }

    if (intent.getData() != null
        && (Intent.ACTION_EDIT.equals(intent.getAction())
            || Intent.ACTION_VIEW.equals(intent.getAction())
            || Intent.ACTION_INSERT.equals(intent.getAction()))
        && (intent.getData().getPath().startsWith(LegacyDBHelper.NotePad.Notes.PATH_VISIBLE_NOTES)
            || intent.getData().getPath().startsWith(LegacyDBHelper.NotePad.Notes.PATH_NOTES)
            || intent.getData().getPath().startsWith(Task.URI.getPath()))
        && !intent.getData().getPath().startsWith(TaskList.URI.getPath())) {
      return true;
    }

    return false;
  }
  public void onBackPressed() {
    if (!Intent.ACTION_EDIT.equals(getIntent().getAction()) && mAccount != null)
      Preferences.getPreferences(this).deleteAccount(mAccount);

    super.onBackPressed();
  }
Esempio n. 11
0
  @Override
  protected void onNewIntent(Intent intent) {
    if (UI_DEBUG_PRINTS) Log.d("FragmentLayout", "On New Intent");

    // Search
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
      String query = intent.getStringExtra(SearchManager.QUERY);
      // list.onQueryTextChange(query);
      if (list != null && list.mSearchView != null) {
        list.mSearchView.setQuery(query, false);
      } else if (list != null) {
        list.onQueryTextSubmit(query);
      }
      // Edit or View a list or a note.
    } else if (Intent.ACTION_EDIT.equals(intent.getAction())
        || Intent.ACTION_VIEW.equals(intent.getAction())) {
      if (UI_DEBUG_PRINTS) Log.d("FragmentLayout", "On New Intent EDIT");
      // First, if we should display a list
      if (intent.getData() != null
          && intent.getData().getPath().startsWith(NotePad.Lists.PATH_VISIBLE_LIST_ID)) {
        // Get id to display
        String newId = intent.getData().getPathSegments().get(NotePad.Lists.ID_PATH_POSITION);
        long listId = Long.parseLong(newId);
        // Handle it differently depending on if the app has already
        // loaded or not.
        openListFromIntent(listId);
      } else if (intent.getData() != null
          && intent.getData().getPath().startsWith(NotePad.Notes.PATH_VISIBLE_NOTE_ID)) {
        if (list != null) {
          long listId = ALL_NOTES_ID;
          if (intent.getExtras() != null) {
            listId = intent.getExtras().getLong(NotePad.Notes.COLUMN_NAME_LIST, ALL_NOTES_ID);
          }
          // Open the containing list if we have to. No need to change
          // lists
          // if we are already displaying all notes.
          if (listId != -1 && currentListId != ALL_NOTES_ID && currentListId != listId) {
            openListFromIntent(listId);
          }
          if (listId != -1) {
            list.handleNoteIntent(intent);
          }
        }
      }
    } else if (Intent.ACTION_INSERT.equals(intent.getAction())) {
      if (UI_DEBUG_PRINTS) Log.d("FragmentLayout", "On New Intent INSERT");
      if (intent.getType() != null && intent.getType().equals(NotePad.Lists.CONTENT_TYPE)
          || intent.getData() != null
              && intent.getData().equals(NotePad.Lists.CONTENT_VISIBLE_URI)) {
        // get Title
        if (intent.getExtras() != null) {
          String title = intent.getExtras().getString(NotePad.Lists.COLUMN_NAME_TITLE, "");
          createList(title);
        }
      } else if (intent.getType() != null && intent.getType().equals(NotePad.Notes.CONTENT_TYPE)
          || intent.getData() != null
              && intent.getData().equals(NotePad.Notes.CONTENT_VISIBLE_URI)) {
        Log.d("FragmentLayout", "INSERT NOTE");
        if (list != null) {
          long listId = ALL_NOTES_ID;
          if (intent.getExtras() != null) {
            listId = intent.getExtras().getLong(NotePad.Notes.COLUMN_NAME_LIST, ALL_NOTES_ID);
          }

          // Open the containing list if we have to. No need to change
          // lists
          // if we are already displaying all notes.
          if (listId != -1 && currentListId != ALL_NOTES_ID && currentListId != listId) {
            openListFromIntent(listId);
          }
          if (listId != -1) {
            list.handleNoteIntent(intent);
          }
        }
      }
    }
  }
Esempio n. 12
0
  public void onClickOk(View v) {
    // Gets the action that triggered the intent filter for this Activity

    // TODO async

    final String action = getIntent().getAction();

    // For an edit action:
    if (Intent.ACTION_EDIT.equals(action)) {

      // Sets the Activity state to EDIT, and gets the URI for the data to
      // be edited.
      mState = STATE_EDIT;

      // For an insert or paste action:
    } else if (Intent.ACTION_INSERT.equals(action)) {
      // Sets the Activity state to INSERT, gets the general note URI, and
      // inserts an
      // empty record in the provider
      mState = STATE_INSERT;
      // mUri = getContentResolver().insert(intent.getData(), null);

      UserDataDbAdapter mUserDataDbAdapter = UserDataDbAdapter.getInstance(this);
      mUserDataDbAdapter.open();

      KanjiList list = null;
      list = mUserDataDbAdapter.createKanjiList(mText.getText().toString());
      // TODO check name not in use

      /*
       * If the attempt to insert the new note fails, shuts down this
       * Activity. The originating Activity receives back RESULT_CANCELED
       * if it requested a result. Logs that the insert failed.
       */
      if (list == null) {

        // Writes the log identifier, a message, and the URI that
        // failed.
        Log.e(Constants.DEBUG, "Failed to insert new list into " + getIntent().getData());

        // Closes the activity.
        finish();
        return;
      }

      // Since the new entry was created, this sets the result to be
      // returned
      // set the result to be returned.
      setResult(RESULT_OK, (new Intent()).putExtra(Constants.RESULT_ID, list.getId()));

      // If the action was other than EDIT or INSERT:
    } else {

      // Logs an error that the action was not understood, finishes the
      // Activity, and
      // returns RESULT_CANCELED to an originating Activity.
      Log.e(Constants.DEBUG, "Unknown action, exiting");
      finish();
      return;
    }
    finish();
  }
Esempio n. 13
0
  @SuppressWarnings("unchecked")
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.timer_edit, container, false);

    mName = (EditText) view.findViewById(R.id.EditTextTitle);
    mDescription = (EditText) view.findViewById(R.id.EditTextDescription);
    mEnabled = (CheckBox) view.findViewById(R.id.CheckBoxEnabled);
    mZap = (CheckBox) view.findViewById(R.id.CheckBoxZap);
    mAfterevent = (Spinner) view.findViewById(R.id.SpinnerAfterEvent);
    mLocation = (Spinner) view.findViewById(R.id.SpinnerLocation);
    mStartDate = (TextView) view.findViewById(R.id.TextViewBeginDate);
    mStartTime = (TextView) view.findViewById(R.id.TextViewBeginTime);
    mEndDate = (TextView) view.findViewById(R.id.TextViewEndDate);
    mEndTime = (TextView) view.findViewById(R.id.TextViewEndTime);
    mRepeatings = (TextView) view.findViewById(R.id.TextViewRepeated);
    mService = (TextView) view.findViewById(R.id.TextViewService);
    mTags = (TextView) view.findViewById(R.id.TextViewTags);

    // onClickListeners
    registerOnClickListener(mService, Statics.ITEM_PICK_SERVICE);
    registerOnClickListener(mStartDate, Statics.ITEM_PICK_BEGIN_DATE);
    registerOnClickListener(mStartTime, Statics.ITEM_PICK_BEGIN_TIME);
    registerOnClickListener(mEndDate, Statics.ITEM_PICK_END_DATE);
    registerOnClickListener(mEndTime, Statics.ITEM_PICK_END_TIME);
    registerOnClickListener(mRepeatings, Statics.ITEM_PICK_REPEATED);
    registerOnClickListener(mTags, Statics.ITEM_PICK_TAGS);

    mAfterevent.setOnItemSelectedListener(
        new OnItemSelectedListener() {
          @Override
          public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
            mTimer.put(Timer.KEY_AFTER_EVENT, Integer.valueOf(position).toString());
          }

          @Override
          public void onNothingSelected(AdapterView<?> parent) {
            // Auto is the default
            mAfterevent.setSelection(Timer.Afterevents.AUTO.intValue());
          }
        });

    mLocation.setOnItemSelectedListener(
        new OnItemSelectedListener() {
          @Override
          public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
            mTimer.put(Timer.KEY_LOCATION, DreamDroid.getLocations().get(position));
          }

          @Override
          public void onNothingSelected(AdapterView<?> parent) {
            // TODO implement some nothing-selected-handler for locations
          }
        });

    // Initialize if savedInstanceState won't and instance was not retained
    if (savedInstanceState == null && mTimer == null && mTimerOld == null) {
      HashMap<String, Object> map = (HashMap<String, Object>) getArguments().get(sData);
      ExtendedHashMap data = new ExtendedHashMap();
      data.putAll(map);

      mTimer = new ExtendedHashMap();
      mTimer.putAll((HashMap<String, Object>) data.get("timer"));

      if (Intent.ACTION_EDIT.equals(getArguments().get("action"))) {
        mTimerOld = mTimer.clone();
      } else {
        mTimerOld = null;
      }

      mSelectedTags = new ArrayList<>();

      if (DreamDroid.getLocations().size() == 0 || DreamDroid.getTags().size() == 0) {
        mGetLocationsAndTagsTask = new GetLocationsAndTagsTask();
        mGetLocationsAndTagsTask.execute();
      } else {
        reload();
      }
    } else if (savedInstanceState != null) {
      mTimer = savedInstanceState.getParcelable("timer");
      mTimerOld = savedInstanceState.getParcelable("timerOld");
      mSelectedTags =
          new ArrayList<>(Arrays.asList(savedInstanceState.getStringArray("selectedTags")));
      if (mTimer != null) {
        reload();
      }
    } else {
      reload();
    }

    registerFab(
        R.id.fab_save,
        view,
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            onItemSelected(Statics.ITEM_SAVE);
          }
        });
    return view;
  }
Esempio n. 14
0
  /**
   * Add controls to the mapView and to the Buttons
   *
   * @param savedInstanceState
   */
  private void addControls(Bundle savedInstanceState) {
    String action = getIntent().getAction();
    Log.v("MapsActivity", "action: " + action);

    // Coordinate Control
    mapView.addControl(new CoordinateControl(mapView, true));
    List<MapControl> group = new ArrayList<MapControl>();

    // Info Control
    MapInfoControl ic;
    if (getIntent().hasExtra(PARAMETERS.CUSTOM_MAPINFO_CONTROL)) {
      ic = (MapInfoControl) getIntent().getParcelableExtra(PARAMETERS.CUSTOM_MAPINFO_CONTROL);
      ic.activity = this;
      ic.mapView = mapView;
      ic.instantiateListener();
    } else {
      ic = new MapInfoControl(mapView, this);
    }
    ic.setActivationButton((ImageButton) findViewById(R.id.ButtonInfo));

    mapView.addControl(ic);

    if (!Intent.ACTION_VIEW.equals(action)) {
      Log.v("MapsActivity", "Adding MarkerControl");

      // Marker Control
      MarkerControl mc = new MarkerControl(mapView);
      // activation button
      ImageButton mcbmb = (ImageButton) findViewById(R.id.ButtonMarker);
      mcbmb.setVisibility(View.VISIBLE);
      mc.setActivationButton(mcbmb);
      // info button  // TODO: do we need this button?
      ImageButton mcib = (ImageButton) findViewById(R.id.marker_info_button);
      mcib.setVisibility(View.VISIBLE);
      mc.setInfoButton(mcib);

      mapView.addControl(mc);
      group.add(mc);
      mc.setGroup(group);
      mc.setMode(MarkerControl.MODE_EDIT);
    }

    // My location Control
    LocationControl lc = new LocationControl(mapView);
    lc.setActivationButton((ImageButton) findViewById(R.id.ButtonLocation));
    mapView.addControl(lc);

    // create and add group
    group.add(ic);

    ic.setGroup(group);

    // TODO move this in a control

    // Set modes for controls
    if (Intent.ACTION_VIEW.equals(action)) {
      ic.setMode(MapInfoControl.MODE_VIEW);
    } else if (Intent.ACTION_EDIT.equals(action)) {
      ic.setMode(MapInfoControl.MODE_EDIT);
      // Default edit mode
    } else {
      ic.setMode(MapInfoControl.MODE_EDIT);
    }
    if (savedInstanceState != null) {
      for (MapControl c : mapView.getControls()) {
        c.restoreState(savedInstanceState);
      }
    }
  }
Esempio n. 15
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // go fullscreen for devices with QVGA screen (only way I found
    // how to fit UI on the screen)
    Display display = getWindowManager().getDefaultDisplay();
    if ((display.getWidth() == 240 || display.getWidth() == 320)
        && (display.getHeight() == 240 || display.getHeight() == 320)) {
      requestWindowFeature(Window.FEATURE_NO_TITLE);
      getWindow()
          .setFlags(
              WindowManager.LayoutParams.FLAG_FULLSCREEN,
              WindowManager.LayoutParams.FLAG_FULLSCREEN);
      mFullScreen = true;
    }

    // theme must be set before setContentView
    AndroidUtils.setThemeFromPreferences(this);

    setContentView(R.layout.sudoku_edit);
    mRootLayout = (ViewGroup) findViewById(R.id.root_layout);
    mBoard = (SudokuBoardView) findViewById(R.id.sudoku_board);

    mDatabase = new SudokuDatabase(getApplicationContext());

    mGuiHandler = new Handler();

    Intent intent = getIntent();
    String action = intent.getAction();
    if (Intent.ACTION_EDIT.equals(action)) {
      // Requested to edit: set that state, and the data being edited.
      mState = STATE_EDIT;
      if (intent.hasExtra(EXTRA_SUDOKU_ID)) {
        mSudokuID = intent.getLongExtra(EXTRA_SUDOKU_ID, 0);
      } else {
        throw new IllegalArgumentException(
            String.format("Extra with key '%s' is required.", EXTRA_SUDOKU_ID));
      }
    } else if (Intent.ACTION_INSERT.equals(action)) {
      mState = STATE_INSERT;
      mSudokuID = 0;

      if (intent.hasExtra(EXTRA_FOLDER_ID)) {
        mFolderID = intent.getLongExtra(EXTRA_FOLDER_ID, 0);
      } else {
        throw new IllegalArgumentException(
            String.format("Extra with key '%s' is required.", EXTRA_FOLDER_ID));
      }

    } else {
      // Whoops, unknown action!  Bail.
      Log.e(TAG, "Unknown action, exiting.");
      finish();
      return;
    }

    if (savedInstanceState != null) {
      mGame = new SudokuGame();
      mGame.restoreState(savedInstanceState);
    } else {
      if (mSudokuID != 0) {
        // existing sudoku, read it from database
        mGame = mDatabase.getSudoku(mSudokuID);
        mGame.getCells().markAllCellsAsEditable();
      } else {
        mGame = SudokuGame.createEmptyGame();
      }
    }
    mBoard.setGame(mGame);

    mInputMethods = (IMControlPanel) findViewById(R.id.input_methods);
    mInputMethods.initialize(mBoard, mGame, null);

    // only numpad input method will be enabled
    for (InputMethod im : mInputMethods.getInputMethods()) {
      im.setEnabled(false);
    }
    mInputMethods.getInputMethod().setEnabled(true);
    mInputMethods.activateInputMethod();
  }
  /**
   * This is invoked only when the user makes changes to a widget, not when widgets are changed
   * programmatically. (The logic is simpler when you know that this is the last thing called after
   * an input change.)
   */
  private void validateFields() {
    AuthType authType = getSelectedAuthType();
    boolean isAuthTypeExternal = (AuthType.EXTERNAL == authType);

    ConnectionSecurity connectionSecurity = getSelectedSecurity();
    boolean hasConnectionSecurity = (connectionSecurity != ConnectionSecurity.NONE);

    if (isAuthTypeExternal && !hasConnectionSecurity) {

      // Notify user of an invalid combination of AuthType.EXTERNAL & ConnectionSecurity.NONE
      String toastText =
          getString(
              R.string.account_setup_incoming_invalid_setting_combo_notice,
              getString(R.string.account_setup_incoming_auth_type_label),
              AuthType.EXTERNAL.toString(),
              getString(R.string.account_setup_incoming_security_label),
              ConnectionSecurity.NONE.toString());
      Toast.makeText(this, toastText, Toast.LENGTH_LONG).show();

      // Reset the views back to their previous settings without recursing through here again
      OnItemSelectedListener onItemSelectedListener = mAuthTypeView.getOnItemSelectedListener();
      mAuthTypeView.setOnItemSelectedListener(null);
      mAuthTypeView.setSelection(mCurrentAuthTypeViewPosition, false);
      mAuthTypeView.setOnItemSelectedListener(onItemSelectedListener);
      updateViewFromAuthType();

      onItemSelectedListener = mSecurityTypeView.getOnItemSelectedListener();
      mSecurityTypeView.setOnItemSelectedListener(null);
      mSecurityTypeView.setSelection(mCurrentSecurityTypeViewPosition, false);
      mSecurityTypeView.setOnItemSelectedListener(onItemSelectedListener);
      updateAuthPlainTextFromSecurityType(getSelectedSecurity());

      mPortView.removeTextChangedListener(validationTextWatcher);
      mPortView.setText(mCurrentPortViewSetting);
      mPortView.addTextChangedListener(validationTextWatcher);

      authType = getSelectedAuthType();
      isAuthTypeExternal = (AuthType.EXTERNAL == authType);

      connectionSecurity = getSelectedSecurity();
      hasConnectionSecurity = (connectionSecurity != ConnectionSecurity.NONE);
    } else {
      mCurrentAuthTypeViewPosition = mAuthTypeView.getSelectedItemPosition();
      mCurrentSecurityTypeViewPosition = mSecurityTypeView.getSelectedItemPosition();
      mCurrentPortViewSetting = mPortView.getText().toString();
    }

    boolean hasValidCertificateAlias = mClientCertificateSpinner.getAlias() != null;
    boolean hasValidUserName = Utility.requiredFieldValid(mUsernameView);

    boolean hasValidPasswordSettings =
        hasValidUserName && !isAuthTypeExternal && Utility.requiredFieldValid(mPasswordView);

    boolean hasValidExternalAuthSettings =
        hasValidUserName && isAuthTypeExternal && hasConnectionSecurity && hasValidCertificateAlias;

    mNextButton.setEnabled(
        Utility.domainFieldValid(mServerView)
            && Utility.requiredFieldValid(mPortView)
            && (hasValidPasswordSettings || hasValidExternalAuthSettings)
            && (Intent.ACTION_EDIT.equals(getIntent().getAction())
                || !mAccountName.getText().toString().equals("")));
    Utility.setCompoundDrawablesAlpha(mNextButton, mNextButton.isEnabled() ? 255 : 128);
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.account_setup_incoming);

    mUsernameView = (EditText) findViewById(R.id.account_username);
    mPasswordView = (EditText) findViewById(R.id.account_password);
    mClientCertificateSpinner =
        (ClientCertificateSpinner) findViewById(R.id.account_client_certificate_spinner);
    mClientCertificateLabelView = (TextView) findViewById(R.id.account_client_certificate_label);
    mPasswordLabelView = (TextView) findViewById(R.id.account_password_label);
    TextView serverLabelView = (TextView) findViewById(R.id.account_server_label);
    mServerView = (EditText) findViewById(R.id.account_server);
    mPortView = (EditText) findViewById(R.id.account_port);
    mSecurityTypeView = (Spinner) findViewById(R.id.account_security_type);
    mAuthTypeView = (Spinner) findViewById(R.id.account_auth_type);
    mImapAutoDetectNamespaceView = (CheckBox) findViewById(R.id.imap_autodetect_namespace);
    mImapPathPrefixView = (EditText) findViewById(R.id.imap_path_prefix);
    mWebdavPathPrefixView = (EditText) findViewById(R.id.webdav_path_prefix);
    mWebdavAuthPathView = (EditText) findViewById(R.id.webdav_auth_path);
    mWebdavMailboxPathView = (EditText) findViewById(R.id.webdav_mailbox_path);
    mNextButton = (Button) findViewById(R.id.next);
    mCompressionMobile = (CheckBox) findViewById(R.id.compression_mobile);
    mCompressionWifi = (CheckBox) findViewById(R.id.compression_wifi);
    mCompressionOther = (CheckBox) findViewById(R.id.compression_other);
    // mSubscribedFoldersOnly = (CheckBox)findViewById(R.id.subscribed_folders_only);
    mRequiresCellular = (CheckBox) findViewById(R.id.account_requires_cellular);
    mAccountName = (EditText) findViewById(R.id.account_name);

    mNextButton.setOnClickListener(this);

    mImapAutoDetectNamespaceView.setOnCheckedChangeListener(
        new OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mImapPathPrefixView.setEnabled(!isChecked);
            if (isChecked && mImapPathPrefixView.hasFocus()) {
              mImapPathPrefixView.focusSearch(View.FOCUS_UP).requestFocus();
            } else if (!isChecked) {
              mImapPathPrefixView.requestFocus();
            }
          }
        });

    mAuthTypeAdapter = AuthTypeAdapter.get(this);
    mAuthTypeView.setAdapter(mAuthTypeAdapter);

    /*
     * Only allow digits in the port field.
     */
    mPortView.setKeyListener(DigitsKeyListener.getInstance("0123456789"));

    String accountUuid = getIntent().getStringExtra(EXTRA_ACCOUNT);
    mAccount = Preferences.getPreferences(this).getAccount(accountUuid);
    // mMakeDefault = getIntent().getBooleanExtra(EXTRA_MAKE_DEFAULT, false);

    /*
     * If we're being reloaded we override the original account with the one
     * we saved
     */
    if (savedInstanceState != null && savedInstanceState.containsKey(EXTRA_ACCOUNT)) {
      accountUuid = savedInstanceState.getString(EXTRA_ACCOUNT);
      mAccount = Preferences.getPreferences(this).getAccount(accountUuid);
    }

    boolean editSettings = Intent.ACTION_EDIT.equals(getIntent().getAction());

    try {
      ServerSettings settings = RemoteStore.decodeStoreUri(mAccount.getStoreUri());

      if (savedInstanceState == null) {
        // The first item is selected if settings.authenticationType is null or is not in
        // mAuthTypeAdapter
        mCurrentAuthTypeViewPosition =
            mAuthTypeAdapter.getAuthPosition(settings.authenticationType);
      } else {
        mCurrentAuthTypeViewPosition = savedInstanceState.getInt(STATE_AUTH_TYPE_POSITION);
      }
      mAuthTypeView.setSelection(mCurrentAuthTypeViewPosition, false);
      updateViewFromAuthType();

      if (settings.username != null) {
        mUsernameView.setText(settings.username);
      }

      if (settings.password != null) {
        mPasswordView.setText(settings.password);
      }

      if (settings.clientCertificateAlias != null) {
        mClientCertificateSpinner.setAlias(settings.clientCertificateAlias);
      }

      mStoreType = settings.type;
      if (Type.POP3 == settings.type) {
        serverLabelView.setText(R.string.account_setup_incoming_pop_server_label);
        findViewById(R.id.imap_path_prefix_section).setVisibility(View.GONE);
        findViewById(R.id.webdav_advanced_header).setVisibility(View.GONE);
        findViewById(R.id.webdav_mailbox_alias_section).setVisibility(View.GONE);
        findViewById(R.id.webdav_owa_path_section).setVisibility(View.GONE);
        findViewById(R.id.webdav_auth_path_section).setVisibility(View.GONE);
        findViewById(R.id.compression_section).setVisibility(View.GONE);
        findViewById(R.id.compression_label).setVisibility(View.GONE);
        // mSubscribedFoldersOnly.setVisibility(View.GONE);
      } else if (Type.IMAP == settings.type) {
        serverLabelView.setText(R.string.account_setup_incoming_imap_server_label);

        ImapStoreSettings imapSettings = (ImapStoreSettings) settings;

        mImapAutoDetectNamespaceView.setChecked(imapSettings.autoDetectNamespace);
        if (imapSettings.pathPrefix != null) {
          mImapPathPrefixView.setText(imapSettings.pathPrefix);
        }

        findViewById(R.id.webdav_advanced_header).setVisibility(View.GONE);
        findViewById(R.id.webdav_mailbox_alias_section).setVisibility(View.GONE);
        findViewById(R.id.webdav_owa_path_section).setVisibility(View.GONE);
        findViewById(R.id.webdav_auth_path_section).setVisibility(View.GONE);

        /*if (!editSettings) {
            findViewById(R.id.imap_folder_setup_section).setVisibility(View.GONE);
        }*/
      } else if (Type.WebDAV == settings.type) {
        serverLabelView.setText(R.string.account_setup_incoming_webdav_server_label);
        mConnectionSecurityChoices =
            new ConnectionSecurity[] {ConnectionSecurity.NONE, ConnectionSecurity.SSL_TLS_REQUIRED};

        // Hide the unnecessary fields
        findViewById(R.id.imap_path_prefix_section).setVisibility(View.GONE);
        findViewById(R.id.account_auth_type_label).setVisibility(View.GONE);
        findViewById(R.id.account_auth_type).setVisibility(View.GONE);
        findViewById(R.id.compression_section).setVisibility(View.GONE);
        findViewById(R.id.compression_label).setVisibility(View.GONE);
        // mSubscribedFoldersOnly.setVisibility(View.GONE);

        WebDavStoreSettings webDavSettings = (WebDavStoreSettings) settings;

        if (webDavSettings.path != null) {
          mWebdavPathPrefixView.setText(webDavSettings.path);
        }

        if (webDavSettings.authPath != null) {
          mWebdavAuthPathView.setText(webDavSettings.authPath);
        }

        if (webDavSettings.mailboxPath != null) {
          mWebdavMailboxPathView.setText(webDavSettings.mailboxPath);
        }
      } else {
        throw new Exception("Unknown account type: " + mAccount.getStoreUri());
      }

      if (!editSettings) {
        mAccount.setDeletePolicy(AccountCreator.getDefaultDeletePolicy(settings.type));
      }

      // Note that mConnectionSecurityChoices is configured above based on server type
      ConnectionSecurityAdapter securityTypesAdapter =
          ConnectionSecurityAdapter.get(this, mConnectionSecurityChoices);
      mSecurityTypeView.setAdapter(securityTypesAdapter);

      // Select currently configured security type
      if (savedInstanceState == null) {
        mCurrentSecurityTypeViewPosition =
            securityTypesAdapter.getConnectionSecurityPosition(settings.connectionSecurity);
      } else {

        /*
         * Restore the spinner state now, before calling
         * setOnItemSelectedListener(), thus avoiding a call to
         * onItemSelected(). Then, when the system restores the state
         * (again) in onRestoreInstanceState(), The system will see that
         * the new state is the same as the current state (set here), so
         * once again onItemSelected() will not be called.
         */
        mCurrentSecurityTypeViewPosition = savedInstanceState.getInt(STATE_SECURITY_TYPE_POSITION);
      }
      mSecurityTypeView.setSelection(mCurrentSecurityTypeViewPosition, false);

      updateAuthPlainTextFromSecurityType(settings.connectionSecurity);

      mCompressionMobile.setChecked(mAccount.useCompression(NetworkType.MOBILE));
      mCompressionWifi.setChecked(mAccount.useCompression(NetworkType.WIFI));
      mCompressionOther.setChecked(mAccount.useCompression(NetworkType.OTHER));

      if (settings.host != null) {
        mServerView.setText(settings.host);
      }

      if (settings.port != -1) {
        mPortView.setText(Integer.toString(settings.port));
      } else {
        updatePortFromSecurityType();
      }
      mCurrentPortViewSetting = mPortView.getText().toString();

      // mSubscribedFoldersOnly.setChecked(mAccount.subscribedFoldersOnly());
    } catch (Exception e) {
      failure(e);
    }
    // show & populate setup fields
    if (!Intent.ACTION_EDIT.equals(getIntent().getAction())) {
      findViewById(R.id.account_name_label).setVisibility(View.VISIBLE);
      mAccountName.setVisibility(View.VISIBLE);
      String desc = mAccount.getDescription();
      mAccountName.setText((desc != null ? desc : ""));
      findViewById(R.id.account_requires_cellular_label).setVisibility(View.VISIBLE);
      mRequiresCellular.setVisibility(View.VISIBLE);
      mRequiresCellular.setChecked(true);
    }
  }
  /**
   * Saves or creates the group based on the mode, and if successful finishes the activity. This
   * actually only handles saving the group name.
   *
   * @return true when successful
   */
  public boolean save() {
    if (!hasValidGroupName() || mStatus != Status.EDITING) {
      mStatus = Status.CLOSING;
      if (mListener != null) {
        mListener.onReverted();
      }
      return false;
    }

    // If we are about to close the editor - there is no need to refresh the data
    getLoaderManager().destroyLoader(LOADER_EXISTING_MEMBERS);

    // If there are no changes, then go straight to onSaveCompleted()
    if (!hasNameChange() && !hasMembershipChange()) {
      onSaveCompleted(false, mGroupUri);
      return true;
    }

    mStatus = Status.SAVING;

    Activity activity = getActivity();
    // If the activity is not there anymore, then we can't continue with the save process.
    if (activity == null) {
      return false;
    }
    Intent saveIntent = null;
    if (Intent.ACTION_INSERT.equals(mAction)) {
      // Create array of raw contact IDs for contacts to add to the group
      long[] membersToAddArray = convertToArray(mListMembersToAdd);

      // Create the save intent to create the group and add members at the same time
      saveIntent =
          ContactSaveService.createNewGroupIntent(
              activity,
              new AccountWithDataSet(mAccountName, mAccountType, mDataSet),
              mGroupNameView.getText().toString(),
              membersToAddArray,
              activity.getClass(),
              GroupEditorActivity.ACTION_SAVE_COMPLETED);
    } else if (Intent.ACTION_EDIT.equals(mAction)) {
      // Create array of raw contact IDs for contacts to add to the group
      long[] membersToAddArray = convertToArray(mListMembersToAdd);

      // Create array of raw contact IDs for contacts to add to the group
      long[] membersToRemoveArray = convertToArray(mListMembersToRemove);

      // Create the update intent (which includes the updated group name if necessary)
      saveIntent =
          ContactSaveService.createGroupUpdateIntent(
              activity,
              mGroupId,
              getUpdatedName(),
              membersToAddArray,
              membersToRemoveArray,
              activity.getClass(),
              GroupEditorActivity.ACTION_SAVE_COMPLETED);
    } else {
      throw new IllegalStateException("Invalid intent action type " + mAction);
    }
    activity.startService(saveIntent);
    return true;
  }
  protected void onNext() {
    try {

      ConnectionSecurity connectionSecurity = getSelectedSecurity();

      String username = mUsernameView.getText().toString();
      String password = null;
      String clientCertificateAlias = null;

      AuthType authType = getSelectedAuthType();
      if (authType == AuthType.EXTERNAL) {
        clientCertificateAlias = mClientCertificateSpinner.getAlias();
      } else {
        password = mPasswordView.getText().toString();
      }
      String host = mServerView.getText().toString();
      int port = Integer.parseInt(mPortView.getText().toString());

      Map<String, String> extra = null;
      if (Type.IMAP == mStoreType) {
        extra = new HashMap<String, String>();
        extra.put(
            ImapStoreSettings.AUTODETECT_NAMESPACE_KEY,
            Boolean.toString(mImapAutoDetectNamespaceView.isChecked()));
        extra.put(ImapStoreSettings.PATH_PREFIX_KEY, mImapPathPrefixView.getText().toString());
      } else if (Type.WebDAV == mStoreType) {
        extra = new HashMap<String, String>();
        extra.put(WebDavStoreSettings.PATH_KEY, mWebdavPathPrefixView.getText().toString());
        extra.put(WebDavStoreSettings.AUTH_PATH_KEY, mWebdavAuthPathView.getText().toString());
        extra.put(
            WebDavStoreSettings.MAILBOX_PATH_KEY, mWebdavMailboxPathView.getText().toString());
      }

      mAccount.deleteCertificate(host, port, CheckDirection.INCOMING);
      ServerSettings settings =
          new ServerSettings(
              mStoreType,
              host,
              port,
              connectionSecurity,
              authType,
              username,
              password,
              clientCertificateAlias,
              extra);

      mAccount.setStoreUri(RemoteStore.createStoreUri(settings));

      mAccount.setCompression(NetworkType.MOBILE, mCompressionMobile.isChecked());
      mAccount.setCompression(NetworkType.WIFI, mCompressionWifi.isChecked());
      mAccount.setCompression(NetworkType.OTHER, mCompressionOther.isChecked());
      // mAccount.setSubscribedFoldersOnly(mSubscribedFoldersOnly.isChecked());

      // visual voicemail specific setup
      if (!Intent.ACTION_EDIT.equals(getIntent().getAction())) {
        mAccount.setRequiresCellular(mRequiresCellular.isChecked());
        mAccount.setDescription(mAccountName.getText().toString());
        mAccount.setPhoneNumber("");
        mAccount = AccountCreator.initialVisualVoicemailSetup(AccountSetupIncoming.this, mAccount);
      }

      AccountSetupCheckSettings.actionCheckSettings(this, mAccount, CheckDirection.INCOMING);
    } catch (Exception e) {
      failure(e);
    }
  }