public ManagePreferences(Context _context, String _contactId) {
    contactId = _contactId;
    context = _context;
    useDatabase = false;

    if (Log.DEBUG) Log.v("contactId = " + contactId);
    long contactIdLong;
    try {
      contactIdLong = Long.parseLong(contactId);
    } catch (NumberFormatException e) {
      contactIdLong = 0;
    }

    if (contactIdLong > 0) {
      mDbAdapter = new SmsPopupDbAdapter(context);
      try {
        mDbAdapter.open(true); // Open database read-only
        contactCursor = mDbAdapter.fetchContactSettings(contactIdLong);
        if (contactCursor != null) {
          if (Log.DEBUG) Log.v("Contact found - using database");
          useDatabase = true;
        }
        mDbAdapter.close();
      } catch (SQLException e) {
        if (Log.DEBUG) Log.v("Error opening or creating database");
        useDatabase = false;
      }
    } else {
      if (Log.DEBUG) Log.v("Contact NOT found - using prefs");
    }

    mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
  }
 public void putString(int resPrefId, String newVal, String dbColumnNum) {
   if (useDatabase) {
     mDbAdapter.open(); // Open write
     mDbAdapter.updateContact(Long.valueOf(contactId), dbColumnNum, newVal);
     mDbAdapter.close();
   } else {
     SharedPreferences.Editor settings = mPrefs.edit();
     settings.putString(context.getString(resPrefId), newVal);
     settings.commit();
   }
 }
  @Override
  protected void onPause() {
    super.onPause();
    if (Log.DEBUG) Log.v("SMSPopupActivity: onPause()");

    // Hide the soft keyboard in case it was shown via quick reply
    hideSoftKeyboard();

    // Shutdown eyes-free TTS
    if (eyesFreeTts != null) {
      eyesFreeTts.shutdown();
    }

    // Shutdown Android TTS
    if (androidTextToSpeechAvailable) {
      if (androidTts != null) {
        androidTts.shutdown();
      }
    }

    // Dismiss loading dialog
    if (mProgressDialog != null) {
      mProgressDialog.dismiss();
    }

    if (wasVisible) {
      // Cancel the receiver that will clear our locks
      ClearAllReceiver.removeCancel(getApplicationContext());
      ClearAllReceiver.clearAll(!exitingKeyguardSecurely);
    }

    mDbAdapter.close();
  }
 public void close() {
   if (contactCursor != null) {
     contactCursor.close();
   }
   if (mDbAdapter != null) {
     mDbAdapter.close();
   }
 }
  /*
   * Create Dialog
   */
  @Override
  protected Dialog onCreateDialog(int id) {
    if (Log.DEBUG) Log.v("onCreateDialog()");

    switch (id) {
        /*
         * Delete message dialog
         */
      case DIALOG_DELETE:
        return new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setTitle(getString(R.string.pref_show_delete_button_dialog_title))
            .setMessage(getString(R.string.pref_show_delete_button_dialog_text))
            .setPositiveButton(
                android.R.string.ok,
                new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int whichButton) {
                    deleteMessage();
                  }
                })
            .setNegativeButton(android.R.string.cancel, null)
            .create();

        /*
         * Quick Reply Dialog
         */
      case DIALOG_QUICKREPLY:
        LayoutInflater factory = getLayoutInflater();
        final View qrLayout = factory.inflate(R.layout.message_quick_reply, null);
        qrEditText = (EditText) qrLayout.findViewById(R.id.QuickReplyEditText);
        final TextView qrCounterTextView =
            (TextView) qrLayout.findViewById(R.id.QuickReplyCounterTextView);
        final Button qrSendButton = (Button) qrLayout.findViewById(R.id.send_button);

        final ImageButton voiceRecognitionButton =
            (ImageButton) qrLayout.findViewById(R.id.SpeechRecogButton);

        voiceRecognitionButton.setOnClickListener(
            new OnClickListener() {
              public void onClick(View view) {
                final Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                intent.putExtra(
                    RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                    RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);

                // Check if the device has the ability to do speech recognition
                final PackageManager packageManager = SmsPopupActivity.this.getPackageManager();
                List<ResolveInfo> list = packageManager.queryIntentActivities(intent, 0);

                if (list.size() > 0) {
                  // TODO: really I should allow voice input here without unlocking first (I allow
                  // quick replies without unlock anyway)
                  exitingKeyguardSecurely = true;
                  ManageKeyguard.exitKeyguardSecurely(
                      new LaunchOnKeyguardExit() {
                        public void LaunchOnKeyguardExitSuccess() {
                          SmsPopupActivity.this.startActivityForResult(
                              intent, VOICE_RECOGNITION_REQUEST_CODE);
                        }
                      });
                } else {
                  Toast.makeText(
                          SmsPopupActivity.this,
                          R.string.error_no_voice_recognition,
                          Toast.LENGTH_LONG)
                      .show();
                  view.setEnabled(false);
                }
              }
            });

        qrEditText.addTextChangedListener(new QmTextWatcher(this, qrCounterTextView, qrSendButton));
        qrEditText.setOnEditorActionListener(
            new OnEditorActionListener() {
              public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                // event != null means enter key pressed
                if (event != null) {
                  // if shift is not pressed then move focus to send button
                  if (!event.isShiftPressed()) {
                    if (v != null) {
                      View focusableView = v.focusSearch(View.FOCUS_RIGHT);
                      if (focusableView != null) {
                        focusableView.requestFocus();
                        return true;
                      }
                    }
                  }

                  // otherwise allow keypress through
                  return false;
                }

                if (actionId == EditorInfo.IME_ACTION_SEND) {
                  if (v != null) {
                    sendQuickReply(v.getText().toString());
                  }
                  return true;
                }

                // else consume
                return true;
              }
            });

        quickreplyTextView = (TextView) qrLayout.findViewById(R.id.QuickReplyTextView);
        QmTextWatcher.getQuickReplyCounterText(
            qrEditText.getText().toString(), qrCounterTextView, qrSendButton);

        qrSendButton.setOnClickListener(
            new OnClickListener() {
              public void onClick(View v) {
                sendQuickReply(qrEditText.getText().toString());
              }
            });

        // Construct basic AlertDialog using AlertDialog.Builder
        final AlertDialog qrAlertDialog =
            new AlertDialog.Builder(this)
                .setIcon(android.R.drawable.ic_dialog_email)
                .setTitle(R.string.quickreply_title)
                .create();

        // Set the custom layout with no spacing at the bottom
        qrAlertDialog.setView(qrLayout, 0, 5, 0, 0);

        // Preset messages button
        Button presetButton = (Button) qrLayout.findViewById(R.id.PresetMessagesButton);
        presetButton.setOnClickListener(
            new OnClickListener() {
              public void onClick(View v) {
                showDialog(DIALOG_PRESET_MSG);
              }
            });

        // Cancel button
        Button cancelButton = (Button) qrLayout.findViewById(R.id.CancelButton);
        cancelButton.setOnClickListener(
            new OnClickListener() {
              public void onClick(View v) {
                if (qrAlertDialog != null) {
                  hideSoftKeyboard();
                  qrAlertDialog.dismiss();
                }
              }
            });

        // Ensure this dialog is counted as "editable" (so soft keyboard will always show on top)
        qrAlertDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

        qrAlertDialog.setOnDismissListener(
            new OnDismissListener() {
              public void onDismiss(DialogInterface dialog) {
                if (Log.DEBUG) Log.v("Quick Reply Dialog: onDissmiss()");
              }
            });

        // Update quick reply views now that they have been created
        updateQuickReplyView("");

        /*
         * TODO: due to what seems like a bug, setting selection to 0 here doesn't seem to work
         * but setting it to 1 first then back to 0 does.  I couldn't find a way around this :|
         * To reproduce, comment out the below line and set a quick reply signature, when
         * clicking Quick Reply the cursor will be positioned at the end of the EditText
         * rather than the start.
         */
        if (qrEditText.getText().toString().length() > 0) qrEditText.setSelection(1);

        qrEditText.setSelection(0);

        return qrAlertDialog;

        /*
         * Preset messages dialog
         */
      case DIALOG_PRESET_MSG:
        mDbAdapter.open(true);
        mCursor = mDbAdapter.fetchAllQuickMessages();
        startManagingCursor(mCursor);

        AlertDialog.Builder mDialogBuilder =
            new AlertDialog.Builder(this)
                .setIcon(android.R.drawable.ic_dialog_email)
                .setTitle(R.string.pref_message_presets_title)
                .setOnCancelListener(
                    new OnCancelListener() {
                      public void onCancel(DialogInterface dialog) {
                        showDialog(DIALOG_QUICKREPLY);
                      }
                    });

        // If user has some presets defined ...
        if (mCursor != null && mCursor.getCount() > 0) {

          mDialogBuilder.setCursor(
              mCursor,
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int item) {
                  if (Log.DEBUG) Log.v("Item clicked = " + item);
                  mCursor.moveToPosition(item);
                  if (Log.DEBUG)
                    Log.v(
                        "Item text = " + mCursor.getString(SmsPopupDbAdapter.KEY_QUICKMESSAGE_NUM));

                  quickReply(mCursor.getString(SmsPopupDbAdapter.KEY_QUICKMESSAGE_NUM));
                }
              },
              SmsPopupDbAdapter.KEY_QUICKMESSAGE);
        } else { // Otherwise display a placeholder as user has no presets
          MatrixCursor emptyCursor =
              new MatrixCursor(
                  new String[] {SmsPopupDbAdapter.KEY_ROWID, SmsPopupDbAdapter.KEY_QUICKMESSAGE});
          emptyCursor.addRow(new String[] {"0", getString(R.string.message_presets_empty_text)});
          mDialogBuilder.setCursor(
              emptyCursor,
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int item) {
                  // startActivity(new Intent(
                  // SmsPopupActivity.this.getApplicationContext(),
                  // net.everythingandroid.smspopup.ConfigPresetMessagesActivity.class));
                }
              },
              SmsPopupDbAdapter.KEY_QUICKMESSAGE);
        }

        return mDialogBuilder.create();

        /*
         * Loading Dialog
         */
      case DIALOG_LOADING:
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage(getString(R.string.loading_message));
        mProgressDialog.setIndeterminate(true);
        mProgressDialog.setCancelable(true);
        return mProgressDialog;
    }

    return null;
  }