Example usage for android.widget EditText getText

List of usage examples for android.widget EditText getText

Introduction

In this page you can find the example usage for android.widget EditText getText.

Prototype

@Override
    public Editable getText() 

Source Link

Usage

From source file:com.lgallardo.qbittorrentclient.RefreshListener.java

public void addUrlTracker(final String hash) {

    // get prompts.xml view
    LayoutInflater li = LayoutInflater.from(MainActivity.this);
    View addTrackerView = li.inflate(R.layout.add_tracker, null);

    // URL input//from  w  ww . j a v a2  s . c  om
    final EditText urlInput = (EditText) addTrackerView.findViewById(R.id.url);

    if (!isFinishing()) {
        // Dialog
        Builder builder = new Builder(MainActivity.this);

        // Set add_torrent.xml to AlertDialog builder
        builder.setView(addTrackerView);

        // Cancel
        builder.setNeutralButton(R.string.cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User cancelled the dialog
                //                    Log.d("Debug", "addUrlTracker - Cancelled");
            }
        });

        // Ok
        builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User accepted the dialog
                //                    Log.d("Debug", "addUrlTracker - Adding tracker");
                addTracker(hash, urlInput.getText().toString());
            }
        });

        // Create dialog
        AlertDialog dialog = builder.create();

        // Show dialog
        dialog.show();
    }
}

From source file:com.irccloud.android.activity.MainActivity.java

void editTopic() {
    ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(buffer.bid);
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setInverseBackgroundForced(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB);
    View view = getDialogTextPrompt();
    TextView prompt = (TextView) view.findViewById(R.id.prompt);
    final EditText input = (EditText) view.findViewById(R.id.textInput);
    input.setText(c.topic_text);//from www  .  j  a  va 2  s  . com
    prompt.setVisibility(View.GONE);
    builder.setTitle("Channel Topic");
    builder.setView(view);
    builder.setPositiveButton("Set Topic", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            conn.topic(buffer.cid, buffer.name, input.getText().toString());
            dialog.dismiss();
        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    AlertDialog dialog = builder.create();
    dialog.setOwnerActivity(this);
    dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    dialog.show();
}

From source file:com.nttec.everychan.ui.presentation.BoardFragment.java

@SuppressLint("InflateParams")
private void runDelete(final DeletePostModel deletePostModel, final boolean hasFiles) {
    Context dialogContext = Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB
            ? new ContextThemeWrapper(activity, R.style.Theme_Neutron)
            : activity;//from   w w  w  .ja  v  a 2  s.  com
    View dlgLayout = LayoutInflater.from(dialogContext).inflate(R.layout.dialog_delete, null);
    final EditText inputField = (EditText) dlgLayout.findViewById(R.id.dialog_delete_password_field);
    final CheckBox onlyFiles = (CheckBox) dlgLayout.findViewById(R.id.dialog_delete_only_files);
    inputField.setText(chan.getDefaultPassword());

    if (!presentationModel.source.boardModel.allowDeletePosts
            && !presentationModel.source.boardModel.allowDeleteFiles) {
        Logger.e(TAG, "board model doesn't support deleting");
        return;
    } else if (!presentationModel.source.boardModel.allowDeletePosts) {
        onlyFiles.setEnabled(false);
        onlyFiles.setChecked(true);
    } else if (presentationModel.source.boardModel.allowDeleteFiles && hasFiles) {
        onlyFiles.setEnabled(true);
    } else {
        onlyFiles.setEnabled(false);
    }

    DialogInterface.OnClickListener dlgOnClick = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(final DialogInterface dialog, final int which) {
            if (currentTask != null)
                currentTask.cancel();
            if (pullableLayout.isRefreshing())
                setPullableNoRefreshing();
            deletePostModel.onlyFiles = onlyFiles.isChecked();
            deletePostModel.password = inputField.getText().toString();
            final ProgressDialog progressDlg = new ProgressDialog(activity);
            final CancellableTask deleteTask = new CancellableTask.BaseCancellableTask();
            progressDlg.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    deleteTask.cancel();
                }
            });
            progressDlg.setCanceledOnTouchOutside(false);
            progressDlg.setMessage(resources.getString(R.string.dialog_delete_progress));
            progressDlg.show();
            Async.runAsync(new Runnable() {
                @Override
                public void run() {
                    String error = null;
                    String targetUrl = null;
                    if (deleteTask.isCancelled())
                        return;
                    try {
                        targetUrl = chan.deletePost(deletePostModel, null, deleteTask);
                    } catch (Exception e) {
                        if (e instanceof InteractiveException) {
                            if (deleteTask.isCancelled())
                                return;
                            ((InteractiveException) e).handle(activity, deleteTask,
                                    new InteractiveException.Callback() {
                                        @Override
                                        public void onSuccess() {
                                            if (!deleteTask.isCancelled()) {
                                                progressDlg.dismiss();
                                                onClick(dialog, which);
                                            }
                                        }

                                        @Override
                                        public void onError(String message) {
                                            if (!deleteTask.isCancelled()) {
                                                progressDlg.dismiss();
                                                Toast.makeText(activity, message, Toast.LENGTH_LONG).show();
                                                runDelete(deletePostModel, hasFiles);
                                            }
                                        }
                                    });
                            return;
                        }

                        Logger.e(TAG, "cannot delete post", e);
                        error = e.getMessage() == null ? "" : e.getMessage();
                    }
                    if (deleteTask.isCancelled())
                        return;
                    final boolean success = error == null;
                    final String result = success ? targetUrl : error;
                    Async.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (deleteTask.isCancelled())
                                return;
                            progressDlg.dismiss();
                            if (success) {
                                if (result == null) {
                                    update();
                                } else {
                                    UrlHandler.open(result, activity);
                                }
                            } else {
                                Toast.makeText(activity,
                                        TextUtils.isEmpty(result) ? resources.getString(R.string.error_unknown)
                                                : result,
                                        Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                }
            });
        }
    };
    new AlertDialog.Builder(activity).setTitle(R.string.dialog_delete_password).setView(dlgLayout)
            .setPositiveButton(R.string.dialog_delete_button, dlgOnClick)
            .setNegativeButton(android.R.string.cancel, null).create().show();
}

From source file:au.com.wallaceit.reddinator.SubredditSelectActivity.java

private void showMultiEditDialog(final String multiPath) {
    JSONObject multiObj = global.getSubredditManager().getMultiData(multiPath);

    @SuppressLint("InflateParams")
    LinearLayout dialogView = (LinearLayout) getLayoutInflater().inflate(R.layout.dialog_multi_edit, null); // passing null okay for dialog
    final Button saveButton = (Button) dialogView.findViewById(R.id.multi_save_button);
    final Button renameButton = (Button) dialogView.findViewById(R.id.multi_rename_button);
    multiName = (TextView) dialogView.findViewById(R.id.multi_pname);
    final EditText displayName = (EditText) dialogView.findViewById(R.id.multi_name);
    final EditText description = (EditText) dialogView.findViewById(R.id.multi_description);
    final EditText color = (EditText) dialogView.findViewById(R.id.multi_color);
    final Spinner icon = (Spinner) dialogView.findViewById(R.id.multi_icon);
    final Spinner visibility = (Spinner) dialogView.findViewById(R.id.multi_visibility);
    final Spinner weighting = (Spinner) dialogView.findViewById(R.id.multi_weighting);

    ArrayAdapter<CharSequence> iconAdapter = ArrayAdapter.createFromResource(SubredditSelectActivity.this,
            R.array.multi_icons, android.R.layout.simple_spinner_item);
    iconAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    icon.setAdapter(iconAdapter);// w w  w  .ja v  a 2  s .co m
    ArrayAdapter<CharSequence> visibilityAdapter = ArrayAdapter.createFromResource(SubredditSelectActivity.this,
            R.array.multi_visibility, android.R.layout.simple_spinner_item);
    visibilityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    visibility.setAdapter(visibilityAdapter);
    ArrayAdapter<CharSequence> weightsAdapter = ArrayAdapter.createFromResource(SubredditSelectActivity.this,
            R.array.multi_weights, android.R.layout.simple_spinner_item);
    weightsAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    weighting.setAdapter(weightsAdapter);

    try {
        multiName.setText(multiObj.getString("name"));
        displayName.setText(multiObj.getString("display_name"));
        description.setText(multiObj.getString("description_md"));
        color.setText(multiObj.getString("key_color"));
        String iconName = multiObj.getString("icon_name");
        icon.setSelection(iconAdapter.getPosition(iconName.equals("") ? "none" : iconName));
        visibility.setSelection(iconAdapter.getPosition(multiObj.getString("visibility")));
        weighting.setSelection(iconAdapter.getPosition(multiObj.getString("weighting_scheme")));
    } catch (JSONException e) {
        e.printStackTrace();
    }

    ViewPager pager = (ViewPager) dialogView.findViewById(R.id.multi_pager);
    LinearLayout tabsWidget = (LinearLayout) dialogView.findViewById(R.id.multi_tab_widget);
    pager.setAdapter(new SimpleTabsAdapter(new String[] { "Subreddits", "Settings" },
            new int[] { R.id.multi_subreddits, R.id.multi_settings }, SubredditSelectActivity.this,
            dialogView));
    SimpleTabsWidget simpleTabsWidget = new SimpleTabsWidget(SubredditSelectActivity.this, tabsWidget);
    simpleTabsWidget.setViewPager(pager);
    ThemeManager.Theme theme = global.mThemeManager.getActiveTheme("appthemepref");
    int headerColor = Color.parseColor(theme.getValue("header_color"));
    int headerText = Color.parseColor(theme.getValue("header_text"));
    simpleTabsWidget.setBackgroundColor(headerColor);
    simpleTabsWidget.setTextColor(headerText);
    simpleTabsWidget.setInidicatorColor(Color.parseColor(theme.getValue("tab_indicator")));

    ListView subList = (ListView) dialogView.findViewById(R.id.multi_subredditList);
    multiSubsAdapter = new SubsListAdapter(SubredditSelectActivity.this, multiPath);
    subList.setAdapter(multiSubsAdapter);
    renameButton.getBackground().setColorFilter(headerColor, PorterDuff.Mode.MULTIPLY);
    renameButton.setTextColor(headerText);
    renameButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            showMultiRenameDialog(multiPath);
        }
    });

    saveButton.getBackground().setColorFilter(headerColor, PorterDuff.Mode.MULTIPLY);
    saveButton.setTextColor(headerText);
    saveButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            System.out.println("Save multi");
            JSONObject multiObj = new JSONObject();
            try {
                multiObj.put("decription_md", description.getText().toString());
                multiObj.put("display_name", displayName.getText().toString());
                multiObj.put("icon_name", icon.getSelectedItem().toString().equals("none") ? ""
                        : icon.getSelectedItem().toString());
                multiObj.put("key_color", color.getText().toString());
                multiObj.put("subreddits",
                        global.getSubredditManager().getMultiData(multiPath).getJSONArray("subreddits"));
                multiObj.put("visibility", visibility.getSelectedItem().toString());
                multiObj.put("weighting_scheme", weighting.getSelectedItem().toString());

                new SubscriptionEditTask(SubscriptionEditTask.ACTION_MULTI_EDIT).execute(multiPath, multiObj);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });

    AlertDialog.Builder builder = new AlertDialog.Builder(SubredditSelectActivity.this);

    multiDialog = builder.setView(dialogView).show();
}

From source file:com.kll.collect.android.activities.FormEntryActivity.java

/**
 * Creates a view given the View type and an event
 *
 * @param event/*from w w w . j  ava  2s.  c o  m*/
 * @param advancingPage
 *            -- true if this results from advancing through the form
 * @return newly created View
 */
private View createView(int event, boolean advancingPage, int swipeCase) {
    FormController formController = Collect.getInstance().getFormController();
    /*   setTitle(getString(R.string.app_name) + " > "
    + formController.getFormTitle());*/
    int questioncount = formController.getFormDef().getDeepChildCount();

    switch (event) {
    case FormEntryController.EVENT_BEGINNING_OF_FORM:
        progressValue = 0.0;
        progressUpdate(progressValue, questioncount);
        View startView = View.inflate(this, R.layout.form_entry_start, null);
        /*setTitle(getString(R.string.app_name) + " > "
              + formController.getFormTitle());*/

        Drawable image = null;
        File mediaFolder = formController.getMediaFolder();
        String mediaDir = mediaFolder.getAbsolutePath();
        BitmapDrawable bitImage = null;
        // attempt to load the form-specific logo...
        // this is arbitrarily silly
        bitImage = new BitmapDrawable(getResources(), mediaDir + File.separator + "form_logo.png");

        if (bitImage != null && bitImage.getBitmap() != null && bitImage.getIntrinsicHeight() > 0
                && bitImage.getIntrinsicWidth() > 0) {
            image = bitImage;
        }

        if (image == null) {
            // show the opendatakit zig...
            // image =
            // getResources().getDrawable(R.drawable.opendatakit_zig);
            ((ImageView) startView.findViewById(R.id.form_start_bling)).setVisibility(View.GONE);
        } else {
            ImageView v = ((ImageView) startView.findViewById(R.id.form_start_bling));
            v.setImageDrawable(image);
            v.setContentDescription(formController.getFormTitle());
        }

        // change start screen based on navigation prefs
        String navigationChoice = PreferenceManager.getDefaultSharedPreferences(this)
                .getString(PreferencesActivity.KEY_NAVIGATION, PreferencesActivity.KEY_NAVIGATION);
        Boolean useSwipe = false;
        Boolean useButtons = false;
        ImageView ia = ((ImageView) startView.findViewById(R.id.image_advance));
        ImageView ib = ((ImageView) startView.findViewById(R.id.image_backup));
        TextView ta = ((TextView) startView.findViewById(R.id.text_advance));
        TextView tb = ((TextView) startView.findViewById(R.id.text_backup));
        TextView d = ((TextView) startView.findViewById(R.id.description));

        if (navigationChoice != null) {
            if (navigationChoice.contains(PreferencesActivity.NAVIGATION_SWIPE)) {
                useSwipe = true;
            }
            if (navigationChoice.contains(PreferencesActivity.NAVIGATION_BUTTONS)) {
                useButtons = true;
            }
        }
        if (useSwipe && !useButtons) {
            d.setText(getString(R.string.swipe_instructions, formController.getFormTitle()));
        } else if (useButtons && !useSwipe) {
            ia.setVisibility(View.GONE);
            ib.setVisibility(View.GONE);
            ta.setVisibility(View.GONE);
            tb.setVisibility(View.GONE);
            d.setText(getString(R.string.buttons_instructions, formController.getFormTitle()));
        } else {
            d.setText(getString(R.string.swipe_buttons_instructions, formController.getFormTitle()));
        }

        if (mBackButton.isShown()) {
            mBackButton.setEnabled(false);
        }
        if (mNextButton.isShown()) {
            mNextButton.setEnabled(true);
        }

        return startView;
    case FormEntryController.EVENT_END_OF_FORM:
        progressValue = questioncount;
        progressUpdate(progressValue, questioncount);
        View endView = View.inflate(this, R.layout.form_entry_end, null);

        ((ImageView) endView.findViewById(R.id.completed))
                .setImageDrawable(getResources().getDrawable(R.drawable.complete_tick));
        ((TextView) endView.findViewById(R.id.description))
                .setText(getString(R.string.save_enter_data_description, formController.getFormTitle()));

        // checkbox for if finished or ready to send
        final CheckBox instanceComplete = ((CheckBox) endView.findViewById(R.id.mark_finished));
        instanceComplete.setChecked(isInstanceComplete(true));

        if (!mAdminPreferences.getBoolean(AdminPreferencesActivity.KEY_MARK_AS_FINALIZED, true)) {
            instanceComplete.setVisibility(View.GONE);
        }

        // edittext to change the displayed name of the instance
        final EditText saveAs = (EditText) endView.findViewById(R.id.save_name);

        // disallow carriage returns in the name
        InputFilter returnFilter = new InputFilter() {
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
                    int dend) {
                for (int i = start; i < end; i++) {
                    if (Character.getType((source.charAt(i))) == Character.CONTROL) {
                        return "";
                    }
                }
                return null;
            }
        };
        saveAs.setFilters(new InputFilter[] { returnFilter });
        String saveName = getSaveName();

        if (saveName == null) {
            // no meta/instanceName field in the form -- see if we have a
            // name for this instance from a previous save attempt...
            if (getContentResolver().getType(getIntent().getData()) == InstanceColumns.CONTENT_ITEM_TYPE) {
                Uri instanceUri = getIntent().getData();
                Cursor instance = null;
                try {
                    instance = getContentResolver().query(instanceUri, null, null, null, null);
                    if (instance.getCount() == 1) {
                        instance.moveToFirst();
                        saveName = instance.getString(instance.getColumnIndex(InstanceColumns.DISPLAY_NAME));
                    }
                } finally {
                    if (instance != null) {
                        instance.close();
                    }
                }
            }
            if (saveName == null) {
                // last resort, default to the form title
                saveName = formController.getFormTitle();
            }
            // present the prompt to allow user to name the form
            TextView sa = (TextView) endView.findViewById(R.id.save_form_as);
            sa.setVisibility(View.VISIBLE);
            saveAs.setText(saveName);
            saveAs.setEnabled(true);
            saveAs.setVisibility(View.VISIBLE);
        } else {
            // if instanceName is defined in form, this is the name -- no
            // revisions
            // display only the name, not the prompt, and disable edits
            TextView sa = (TextView) endView.findViewById(R.id.save_form_as);
            sa.setVisibility(View.GONE);
            saveAs.setText(saveName);
            saveAs.setEnabled(false);
            saveAs.setBackgroundColor(Color.WHITE);
            saveAs.setVisibility(View.VISIBLE);
        }

        // override the visibility settings based upon admin preferences
        if (!mAdminPreferences.getBoolean(AdminPreferencesActivity.KEY_SAVE_AS, true)) {
            saveAs.setVisibility(View.GONE);
            TextView sa = (TextView) endView.findViewById(R.id.save_form_as);
            sa.setVisibility(View.GONE);
        }

        // Create 'save' button
        ((Button) endView.findViewById(R.id.save_exit_button)).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Collect.getInstance().getActivityLogger().logInstanceAction(this, "createView.saveAndExit",
                        instanceComplete.isChecked() ? "saveAsComplete" : "saveIncomplete");
                // Form is marked as 'saved' here.
                if (saveAs.getText().length() < 1) {
                    Toast.makeText(FormEntryActivity.this, R.string.save_as_error, Toast.LENGTH_SHORT).show();
                } else {
                    saveDataToDisk(EXIT, instanceComplete.isChecked(), saveAs.getText().toString());
                }
            }
        });

        if (mBackButton.isShown()) {
            mBackButton.setEnabled(true);
        }
        if (mNextButton.isShown()) {
            mNextButton.setEnabled(false);
        }

        return endView;
    case FormEntryController.EVENT_QUESTION:
    case FormEntryController.EVENT_GROUP:
    case FormEntryController.EVENT_REPEAT:
        ODKView odkv = null;
        // should only be a group here if the event_group is a field-list
        try {
            double depth = (double) formController.getFormIndex().getDepth();
            double local_index = (double) formController.getFormIndex().getLocalIndex();
            double instance_index = (double) formController.getFormIndex().getInstanceIndex();
            Log.i("Question coint", Integer.toString(questioncount));

            Log.i("Depth", Integer.toString(formController.getFormIndex().getDepth()));
            Log.i("Local Index", Integer.toString(formController.getFormIndex().getLocalIndex()));
            Log.i("Instance Index", Integer.toString(formController.getFormIndex().getInstanceIndex()));

            if (swipeCase == NEXT) {

                Log.i("progressValue", Double.toString(progressValue));

            }
            if (swipeCase == PREVIOUS) {
                progressValue = progressValue - (1 - (instance_index * local_index / questioncount * depth));

                Log.i("progressValue", Double.toString(progressValue));
            }
            Log.i("progressValue", Double.toString(progressValue));
            progressUpdate(progressValue, questioncount);
            FormEntryPrompt[] prompts = formController.getQuestionPrompts();
            FormEntryCaption[] groups = formController.getGroupsForCurrentIndex();
            odkv = new ODKView(this, formController.getQuestionPrompts(), groups, advancingPage);
            Log.i(t, "created view for group "
                    + (groups.length > 0 ? groups[groups.length - 1].getLongText() : "[top]") + " "
                    + (prompts.length > 0 ? prompts[0].getQuestionText() : "[no question]"));
        } catch (RuntimeException e) {
            Log.e(t, e.getMessage(), e);
            // this is badness to avoid a crash.
            try {
                event = formController.stepToNextScreenEvent();
                createErrorDialog(e.getMessage(), DO_NOT_EXIT);
            } catch (JavaRosaException e1) {
                Log.e(t, e1.getMessage(), e1);
                createErrorDialog(e.getMessage() + "\n\n" + e1.getCause().getMessage(), DO_NOT_EXIT);
            }
            return createView(event, advancingPage, swipeCase);
        }

        // Makes a "clear answer" menu pop up on long-click
        for (QuestionWidget qw : odkv.getWidgets()) {
            if (!qw.getPrompt().isReadOnly()) {
                registerForContextMenu(qw);
            }
        }

        if (mBackButton.isShown() && mNextButton.isShown()) {
            mBackButton.setEnabled(true);
            mNextButton.setEnabled(true);
        }
        return odkv;
    default:
        Log.e(t, "Attempted to create a view that does not exist.");
        // this is badness to avoid a crash.
        try {
            event = formController.stepToNextScreenEvent();
            createErrorDialog(getString(R.string.survey_internal_error), EXIT);
        } catch (JavaRosaException e) {
            Log.e(t, e.getMessage(), e);
            createErrorDialog(e.getCause().getMessage(), EXIT);
        }
        return createView(event, advancingPage, swipeCase);
    }

}

From source file:com.updetector.MainActivity.java

/**
* Handle Performance Tuning Click/*from   w  ww . j  av a  2s.com*/
*/
private void handleAdvancedSetting() {
    final Dialog dialog = new Dialog(this);
    dialog.setTitle(R.string.menu_item_advanced_settings);
    dialog.setContentView(R.layout.advanced_setting);

    final SharedPreferences mPrefs = getSharedPreferences(Constants.SHARED_PREFERENCES, Context.MODE_PRIVATE);
    final Editor editor = mPrefs.edit();

    final ToggleButton classifierForCIVOnButton = (ToggleButton) dialog.findViewById(R.id.civ_classifier_on);
    classifierForCIVOnButton.setChecked(mPrefs.getBoolean(Constants.PREFERENCE_KEY_CIV_CLASSIFIER_ON, false));

    final ToggleButton isOutdoorButton = (ToggleButton) dialog.findViewById(R.id.is_outdoor);
    isOutdoorButton.setChecked(mPrefs.getBoolean(Constants.PREFERENCE_KEY_IS_OUTDOOR, false));

    final EditText notificationTresholdText = (EditText) dialog.findViewById(R.id.notification_threshold);
    notificationTresholdText
            .setText(String.format("%.2f", mPrefs.getFloat(Constants.PREFERENCE_KEY_NOTIFICATION_THRESHOLD,
                    (float) Constants.DEFAULT_DETECTION_THRESHOLD)));

    //final EditText detectionIntervalText=(EditText)dialog.findViewById(R.id.detection_interval);
    //detectionIntervalText.setText(String.valueOf(mPrefs.getInt(Constants.PREFERENCE_KEY_DETECTION_INTERVAL, Constants.DETECTION_INTERVAL_DEFAULT_VALUE) ));

    final EditText googleActivityUpdateIntervalText = (EditText) dialog
            .findViewById(R.id.google_activity_update_interval);
    googleActivityUpdateIntervalText
            .setText(String.valueOf(mPrefs.getInt(Constants.PREFERENCE_KEY_GOOGLE_ACTIVITY_UPDATE_INTERVAL,
                    Constants.GOOGLE_ACTIVITY_UPDATE_INTERVAL_DEFAULT_VALUE)));

    //final ToggleButton useGoogleActivityInFusion=(ToggleButton)dialog.findViewById(R.id.use_google_for_motion_state_in_fusion);
    //useGoogleActivityInFusion.setChecked(mPrefs.getBoolean(Constants.PREFERENCE_KEY_USE_GOOGLE_ACTIVITY_IN_FUSION, false));

    final ToggleButton logAcclRawButton = (ToggleButton) dialog.findViewById(R.id.log_raw_switch);
    logAcclRawButton.setChecked(mPrefs.getBoolean(Constants.LOGGING_ACCL_RAW_SWITCH, false));

    final ToggleButton logGoogleActUpdatesButton = (ToggleButton) dialog
            .findViewById(R.id.log_google_updates_switch);
    logGoogleActUpdatesButton.setChecked(mPrefs.getBoolean(Constants.LOGGING_GOOGLE_ACTIVITY_UPDATE, false));

    final ToggleButton logDetectionButton = (ToggleButton) dialog.findViewById(R.id.log_report_switch);
    logDetectionButton.setChecked(mPrefs.getBoolean(Constants.LOGGING_DETECTION_SWITCH, false));

    final ToggleButton logErrorButton = (ToggleButton) dialog.findViewById(R.id.log_error_switch);
    logErrorButton.setChecked(mPrefs.getBoolean(Constants.LOGGING_ERROR_SWITCH, true));

    //final EditText deltaForConditionalProb=(EditText)dialog.findViewById(R.id.normal_dist_delta);
    //deltaForConditionalProb.setText(String.valueOf(mPrefs.getFloat(Constants.CIV_DELTA_CONDITIONAL_PROBABILITY, 2)) );      

    final Button applyButton = (Button) dialog.findViewById(R.id.performance_apply_button);
    final Button cancelButton = (Button) dialog.findViewById(R.id.peformance_cancel_button);
    applyButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            if (classifierForCIVOnButton.isChecked())
                editor.putBoolean(Constants.PREFERENCE_KEY_CIV_CLASSIFIER_ON, true);
            else
                editor.putBoolean(Constants.PREFERENCE_KEY_CIV_CLASSIFIER_ON, false);

            if (isOutdoorButton.isChecked())
                editor.putBoolean(Constants.PREFERENCE_KEY_IS_OUTDOOR, true);
            else
                editor.putBoolean(Constants.PREFERENCE_KEY_IS_OUTDOOR, false);

            if (logAcclRawButton.isChecked())
                editor.putBoolean(Constants.LOGGING_ACCL_RAW_SWITCH, true);
            else
                editor.putBoolean(Constants.LOGGING_ACCL_RAW_SWITCH, false);

            if (logGoogleActUpdatesButton.isChecked())
                editor.putBoolean(Constants.LOGGING_GOOGLE_ACTIVITY_UPDATE, true);
            else
                editor.putBoolean(Constants.LOGGING_GOOGLE_ACTIVITY_UPDATE, false);

            if (logDetectionButton.isChecked())
                editor.putBoolean(Constants.LOGGING_DETECTION_SWITCH, true);
            else
                editor.putBoolean(Constants.LOGGING_DETECTION_SWITCH, false);

            if (logErrorButton.isChecked())
                editor.putBoolean(Constants.LOGGING_ERROR_SWITCH, true);
            else
                editor.putBoolean(Constants.LOGGING_ERROR_SWITCH, false);

            float notificationTreshold;
            try {
                notificationTreshold = Float.parseFloat(notificationTresholdText.getText().toString());
            } catch (Exception ex) {
                notificationTreshold = (float) Constants.DEFAULT_DETECTION_THRESHOLD;
            }
            editor.putFloat(Constants.PREFERENCE_KEY_NOTIFICATION_THRESHOLD, notificationTreshold);

            /*int detectionInterval;
            try{
               detectionInterval=Integer.parseInt(
             detectionIntervalText.getText().toString());
            }catch(Exception ex){
               detectionInterval=Constants.DETECTION_INTERVAL_DEFAULT_VALUE;
            }
            editor.putInt(Constants.PREFERENCE_KEY_DETECTION_INTERVAL, detectionInterval);*/

            /*if (useGoogleActivityInFusion.isChecked())
               editor.putBoolean(Constants.PREFERENCE_KEY_USE_GOOGLE_ACTIVITY_IN_FUSION, true);
            else
               editor.putBoolean(Constants.PREFERENCE_KEY_USE_GOOGLE_ACTIVITY_IN_FUSION, false);*/

            int googleActivityUpdateInterval;
            try {
                googleActivityUpdateInterval = Integer
                        .parseInt(googleActivityUpdateIntervalText.getText().toString());
            } catch (Exception ex) {
                googleActivityUpdateInterval = Constants.GOOGLE_ACTIVITY_UPDATE_INTERVAL_DEFAULT_VALUE;
            }
            editor.putInt(Constants.PREFERENCE_KEY_GOOGLE_ACTIVITY_UPDATE_INTERVAL,
                    googleActivityUpdateInterval);

            /*try{
               Float delta=Float.parseFloat(deltaForConditionalProb.getText().toString());
               editor.putFloat(Constants.CIV_DELTA_CONDITIONAL_PROBABILITY, delta);
            }catch(Exception ex){
               Toast.makeText(getApplicationContext(), "Input must be a float number", Toast.LENGTH_SHORT).show();
            }*/

            editor.commit();
            dialog.cancel();
        }
    });

    cancelButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            dialog.cancel();
        }
    });
    dialog.show();
}

From source file:com.nttec.everychan.ui.presentation.BoardFragment.java

private void initSearchBar() {
    if (searchBarInitialized)
        return;/*from www  .j av  a2 s .  com*/
    final EditText field = (EditText) searchBarView.findViewById(R.id.board_search_field);
    final TextView results = (TextView) searchBarView.findViewById(R.id.board_search_result);
    if (pageType == TYPE_POSTSLIST) {
        field.setHint(R.string.search_bar_in_thread_hint);
    }
    final View.OnClickListener searchOnClickListener = new View.OnClickListener() {
        private int lastFound = -1;

        @Override
        public void onClick(View v) {
            if (v != null && v.getId() == R.id.board_search_close) {
                searchHighlightActive = false;
                adapter.notifyDataSetChanged();
                searchBarView.setVisibility(View.GONE);
            } else if (listView != null && listView.getChildCount() > 0 && adapter != null
                    && cachedSearchResults != null) {
                boolean atEnd = listView.getChildAt(listView.getChildCount() - 1).getTop()
                        + listView.getChildAt(listView.getChildCount() - 1).getHeight() == listView.getHeight();

                View topView = listView.getChildAt(0);
                if ((v == null || v.getId() == R.id.board_search_previous) && topView.getTop() < 0
                        && listView.getChildCount() > 1)
                    topView = listView.getChildAt(1);
                int currentListPosition = listView.getPositionForView(topView);

                int newResultIndex = Collections.binarySearch(cachedSearchResults, currentListPosition);
                if (newResultIndex >= 0) {
                    if (v != null) {
                        if (v.getId() == R.id.board_search_next)
                            ++newResultIndex;
                        else if (v.getId() == R.id.board_search_previous)
                            --newResultIndex;
                    }
                } else {
                    newResultIndex = -newResultIndex - 1;
                    if (v != null && v.getId() == R.id.board_search_previous)
                        --newResultIndex;
                }
                while (newResultIndex < 0)
                    newResultIndex += cachedSearchResults.size();
                newResultIndex %= cachedSearchResults.size();

                if (v != null && v.getId() == R.id.board_search_next && lastFound == newResultIndex && atEnd)
                    newResultIndex = 0;
                lastFound = newResultIndex;

                listView.setSelection(cachedSearchResults.get(newResultIndex));
                results.setText((newResultIndex + 1) + "/" + cachedSearchResults.size());
            }
        }
    };
    for (int id : new int[] { R.id.board_search_close, R.id.board_search_previous, R.id.board_search_next }) {
        searchBarView.findViewById(id).setOnClickListener(searchOnClickListener);
    }
    field.setOnKeyListener(new View.OnKeyListener() {
        private boolean searchUsingChan() {
            if (pageType != TYPE_THREADSLIST)
                return false;
            if (presentationModel != null)
                if (presentationModel.source != null)
                    if (presentationModel.source.boardModel != null)
                        if (!presentationModel.source.boardModel.searchAllowed)
                            return false;
            return true;
        }

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                if (searchUsingChan()) {
                    UrlPageModel model = new UrlPageModel();
                    model.chanName = chan.getChanName();
                    model.type = UrlPageModel.TYPE_SEARCHPAGE;
                    model.boardName = tabModel.pageModel.boardName;
                    model.searchRequest = field.getText().toString();
                    UrlHandler.open(model, activity);
                } else {
                    int highlightColor = ThemeUtils.getThemeColor(activity.getTheme(),
                            R.attr.searchHighlightBackground, Color.RED);
                    String request = field.getText().toString().toLowerCase(Locale.US);

                    if (cachedSearchRequest == null || !request.equals(cachedSearchRequest)) {
                        cachedSearchRequest = request;
                        cachedSearchResults = new ArrayList<Integer>();
                        cachedSearchHighlightedSpanables = new SparseArray<Spanned>();
                        List<PresentationItemModel> safePresentationList = presentationModel
                                .getSafePresentationList();
                        if (safePresentationList != null) {
                            for (int i = 0; i < safePresentationList.size(); ++i) {
                                PresentationItemModel model = safePresentationList.get(i);
                                if (model.hidden && !staticSettings.showHiddenItems)
                                    continue;
                                String comment = model.spannedComment.toString().toLowerCase(Locale.US)
                                        .replace('\n', ' ');
                                List<Integer> altFoundPositions = null;
                                if (model.floating) {
                                    int floatingpos = FlowTextHelper.getFloatingPosition(model.spannedComment);
                                    if (floatingpos != -1 && floatingpos < model.spannedComment.length()
                                            && model.spannedComment.charAt(floatingpos) == '\n') {
                                        String altcomment = comment.substring(0, floatingpos)
                                                + comment.substring(floatingpos + 1,
                                                        Math.min(model.spannedComment.length(),
                                                                floatingpos + request.length()));
                                        int start = 0;
                                        int curpos;
                                        while (start < altcomment.length()
                                                && (curpos = altcomment.indexOf(request, start)) != -1) {
                                            if (altFoundPositions == null)
                                                altFoundPositions = new ArrayList<Integer>();
                                            altFoundPositions.add(curpos);
                                            start = curpos + request.length();
                                        }
                                    }
                                }

                                if (comment.contains(request) || altFoundPositions != null) {
                                    cachedSearchResults.add(Integer.valueOf(i));
                                    SpannableStringBuilder spannedHighlited = new SpannableStringBuilder(
                                            safePresentationList.get(i).spannedComment);
                                    int start = 0;
                                    int curpos;
                                    while (start < comment.length()
                                            && (curpos = comment.indexOf(request, start)) != -1) {
                                        start = curpos + request.length();
                                        if (altFoundPositions != null
                                                && Collections.binarySearch(altFoundPositions, curpos) >= 0)
                                            continue;
                                        spannedHighlited.setSpan(new BackgroundColorSpan(highlightColor),
                                                curpos, curpos + request.length(),
                                                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    }
                                    if (altFoundPositions != null) {
                                        for (Integer pos : altFoundPositions) {
                                            spannedHighlited.setSpan(new BackgroundColorSpan(highlightColor),
                                                    pos, pos + request.length(),
                                                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                        }
                                    }
                                    cachedSearchHighlightedSpanables.put(i, spannedHighlited);
                                }
                            }
                        }
                    }

                    if (cachedSearchResults.size() == 0) {
                        Toast.makeText(activity, R.string.notification_not_found, Toast.LENGTH_LONG).show();
                    } else {
                        boolean firstTime = !searchHighlightActive;
                        searchHighlightActive = true;
                        adapter.notifyDataSetChanged();
                        searchBarView.findViewById(R.id.board_search_next).setVisibility(View.VISIBLE);
                        searchBarView.findViewById(R.id.board_search_previous).setVisibility(View.VISIBLE);
                        searchBarView.findViewById(R.id.board_search_result).setVisibility(View.VISIBLE);
                        searchOnClickListener
                                .onClick(firstTime ? null : searchBarView.findViewById(R.id.board_search_next));
                    }
                }
                try {
                    InputMethodManager imm = (InputMethodManager) activity
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(field.getWindowToken(), 0);
                } catch (Exception e) {
                    Logger.e(TAG, e);
                }
                return true;
            }
            return false;
        }
    });
    field.addTextChangedListener(new OnSearchTextChangedListener(this));
    field.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
    if (resources.getDimensionPixelSize(R.dimen.panel_height) < field.getMeasuredHeight())
        searchBarView.getLayoutParams().height = field.getMeasuredHeight();
    searchBarInitialized = true;
}

From source file:course1778.mobileapp.safeMedicare.Main.FamMemFrag.java

public void onClick(DialogInterface di, int whichButton) {
    // get strings from edittext boxes, then insert them into database
    ContentValues values = new ContentValues(DatabaseHelper.CONTENT_VALUE_COUNT);
    ContentValues drugInteractionValues = new ContentValues(4);
    Dialog dlg = (Dialog) di;
    EditText title = (EditText) dlg.findViewById(R.id.title);
    TimePicker tp = (TimePicker) dlg.findViewById(R.id.timePicker);
    Spinner mySpinner = (Spinner) dlg.findViewById(R.id.spinner);
    String fre = mySpinner.getSelectedItem().toString();
    EditText dosage = (EditText) dlg.findViewById(R.id.dosage);
    EditText instruction = (EditText) dlg.findViewById(R.id.instruction);
    RadioGroup radioButtonGroup = (RadioGroup) dlg.findViewById(R.id.radioGroup);
    int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
    View radioButton = radioButtonGroup.findViewById(radioButtonID);
    int shape = radioButtonGroup.indexOfChild(radioButton) / 2;
    int Fre;/*  www .j ava2  s  .c o  m*/
    //int day = 0;
    int monday = 0, tuesday = 0, wednesday = 0, thursday = 0, friday = 0, saturday = 0, sunday = 0;

    // clear array list
    drug_interaction_list.clear();
    curr_drug_interaction_list.clear();

    // loop through database
    crsInteractions.moveToPosition(-1);
    while (crsInteractions.moveToNext()) {
        // drug names
        drugName = crsInteractions.getString(crsInteractions.getColumnIndex(DatabaseHelper.SHEET_1_DRUG_NAMES));

        // corresponding interacted drugs/foods
        interactionName = crsInteractions
                .getString(crsInteractions.getColumnIndex(DatabaseHelper.SHEET_1_DRUG_INTERACTIONS));

        // interaction result
        interactionResult = crsInteractions
                .getString(crsInteractions.getColumnIndex(DatabaseHelper.SHEET_1_INTERACTION_RESULT));

        // medication name entered by user
        medNameFieldTxt = textView.getText().toString();

        // check if newly entered medication name matches current drug name
        if (drugName.equals(medNameFieldTxt)) {
            /**if found, check if the corresponding interaction
             * drug in the list of all added drugs by user
             */
            if (db.isNameExitOnDB(interactionName)) {
                // interaction found
                Log.d("myinteraction", "Found Interaction");

                String interaction_result = medNameFieldTxt + "/" + interactionName + "\n";

                // only insert new drug interactions if they have not yet exist
                if (!dbInteraction.isDrugInteractionExist(medNameFieldTxt, interactionName)) {
                    // insert the drug interaction into our new dynamic drug interaction db
                    drugInteractionValues.put(DatabaseInteractionHelper.USR_NAME,
                            ParseUser.getCurrentUser().getUsername());
                    drugInteractionValues.put(DatabaseInteractionHelper.DRUG_NAME, medNameFieldTxt);
                    drugInteractionValues.put(DatabaseInteractionHelper.DRUG_INTERACTION, interactionName);
                    drugInteractionValues.put(DatabaseInteractionHelper.DRUG_INTERACTION_SHOW,
                            DatabaseInteractionHelper.DRUG_INTERACTION_SHOW_TRUE);

                    dbInteraction.getWritableDatabase().insert(DatabaseInteractionHelper.TABLE,
                            DatabaseInteractionHelper.DRUG_NAME, drugInteractionValues);
                }

                drug_interaction_list.add(interaction_result);
                curr_drug_interaction_list.add(interactionName);
            }
        }
    }

    Log.d("mydatabase3", DatabaseUtils.dumpCursorToString(dbInteraction.getCursor()));

    // display all iteractions in pop window if there is any
    String interaction_results = "\n";
    for (int i = 0; i < curr_drug_interaction_list.size(); i++) {
        String interaction = medNameFieldTxt + " & " + curr_drug_interaction_list.get(i) + "\n\n";
        interaction_results = interaction_results.concat(interaction);
    }

    if (drug_interaction_list.size() != 0) {
        // inflate a dialog to display the drug interactions warning
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View resultView = inflater.inflate(R.layout.drug_interaction_result, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        builder.setTitle(R.string.drug_interaction_result_title).setView(resultView)
                // go to drug interaction list button
                .setNegativeButton(R.string.drug_interaction_list, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // drug interaction page
                        DrugInteractions drugInterac = new DrugInteractions();
                        FragmentTransaction transaction;
                        transaction = getFragmentManager().beginTransaction();
                        transaction.replace(R.id.fragmentContainer, drugInterac);
                        transaction.addToBackStack(null);
                        // Commit the transaction
                        transaction.commit();
                    }
                })

                // ok button
                .setPositiveButton(R.string.dismiss, null).show();

        TextView interactionResultView = (TextView) resultView.findViewById(R.id.resultView);

        // add warning message into the pop up window
        interaction_results = interaction_results.concat(getString(R.string.interaction_warning));

        // display on pop up window
        interactionResultView.setText(interaction_results);
    }

    // write the list of drug interactions into file
    Helpers.writeToFile(getContext(), drug_interaction_list, "drug_interaction_list");

    Log.d("mydatabase", DatabaseUtils.dumpCursorToString(db.getCursor()));

    if (fre == "Ten Times a Day") {
        Fre = 10;
    } else if (fre == "Twice a Day") {
        Fre = 2;
    } else if (fre == "Three Times a Day") {
        Fre = 3;
    } else if (fre == "Four Times a Day") {
        Fre = 4;
    } else if (fre == "Five Times a Day") {
        Fre = 5;
    } else if (fre == "Six Times a Day") {
        Fre = 6;
    } else if (fre == "Seven Times a Day") {
        Fre = 7;
    } else if (fre == "Eight Times a Day") {
        Fre = 8;
    } else if (fre == "Nine Times a Day") {
        Fre = 9;
    } else {
        Fre = 1;
    }

    if (((CheckBox) dlg.findViewById(R.id.MonCheck)).isChecked()) {
        monday = monday + 1;
    }
    if (((CheckBox) dlg.findViewById(R.id.TueCheck)).isChecked()) {
        tuesday = tuesday + 1;
    }
    if (((CheckBox) dlg.findViewById(R.id.WedCheck)).isChecked()) {
        wednesday = wednesday + 1;
    }
    if (((CheckBox) dlg.findViewById(R.id.ThuCheck)).isChecked()) {
        thursday = thursday + 1;
    }
    if (((CheckBox) dlg.findViewById(R.id.FriCheck)).isChecked()) {
        friday = friday + 1;
    }
    if (((CheckBox) dlg.findViewById(R.id.SatCheck)).isChecked()) {
        saturday = saturday + 1;
    }
    if (((CheckBox) dlg.findViewById(R.id.SunCheck)).isChecked()) {
        sunday = sunday + 1;
    }

    // clear focus before retrieving the min and hr
    tp.clearFocus();

    int tpMinute = tp.getCurrentMinute();
    int tpHour = tp.getCurrentHour();
    // an order number to order the list view items
    int orderNum = tpHour * 60 + tpMinute;
    tp.setIs24HourView(true);

    String titleStr = title.getText().toString();
    String timeHStr = Helpers.StringFormatter(tpHour, "00");
    String timeMStr = Helpers.StringFormatter(tpMinute, "00");
    String dosageStr = dosage.getText().toString();
    String instructionStr = instruction.getText().toString();

    Log.d("mytime", Integer.toString(tpHour));
    Log.d("mytime", Integer.toString(tpMinute));

    values.put(DatabaseHelper.USRNAME, ParseUser.getCurrentUser().getUsername());
    values.put(DatabaseHelper.TITLE, titleStr);
    values.put(DatabaseHelper.TIME_H, timeHStr);
    values.put(DatabaseHelper.TIME_M, timeMStr);
    values.put(DatabaseHelper.FREQUENCY, Fre);
    //values.put(DatabaseHelper.DAY, day);

    values.put(DatabaseHelper.MONDAY, monday);
    values.put(DatabaseHelper.TUESDAY, tuesday);
    values.put(DatabaseHelper.WEDNESDAY, wednesday);
    values.put(DatabaseHelper.THURSDAY, thursday);
    values.put(DatabaseHelper.FRIDAY, friday);
    values.put(DatabaseHelper.SATURDAY, saturday);
    values.put(DatabaseHelper.SUNDAY, sunday);

    values.put(DatabaseHelper.DOSAGE, dosageStr);
    values.put(DatabaseHelper.INSTRUCTION, instructionStr);
    values.put(DatabaseHelper.SHAPE, shape);
    values.put(DatabaseHelper.ORDER_NUM, orderNum);

    Bundle bundle = new Bundle();
    // add extras here..
    bundle.putString(DatabaseHelper.TITLE, title.getText().toString());
    bundle.putString(DatabaseHelper.TIME_H, timeHStr);
    bundle.putString(DatabaseHelper.TIME_M, timeMStr);
    bundle.putInt(DatabaseHelper.FREQUENCY, Fre);
    //bundle.putInt(DatabaseHelper.DAY, day);

    bundle.putInt(DatabaseHelper.MONDAY, monday);
    bundle.putInt(DatabaseHelper.TUESDAY, tuesday);
    bundle.putInt(DatabaseHelper.WEDNESDAY, wednesday);
    bundle.putInt(DatabaseHelper.THURSDAY, thursday);
    bundle.putInt(DatabaseHelper.FRIDAY, friday);
    bundle.putInt(DatabaseHelper.SATURDAY, saturday);
    bundle.putInt(DatabaseHelper.SUNDAY, sunday);

    bundle.putString(DatabaseHelper.DOSAGE, dosageStr);
    bundle.putString(DatabaseHelper.INSTRUCTION, instructionStr);
    bundle.putInt(DatabaseHelper.SHAPE, shape);
    bundle.putInt(DatabaseHelper.ORDER_NUM, orderNum);
    //Alarm alarm = new Alarm(getActivity().getApplicationContext(), bundle);

    // get unique notifyId for each alarm
    int length = title.length();
    for (int i = 0; i < length; i++) {
        notifyId = (int) titleStr.charAt(i) + notifyId;
    }
    notifyId = Integer.parseInt(timeHStr + timeMStr);

    // saving it into parse.com
    ParseObject parseObject = new ParseObject(Helpers.PARSE_OBJECT);
    parseObject.put(DatabaseHelper.USRNAME, ParseUser.getCurrentUser().getUsername());
    parseObject.put(DatabaseHelper.TITLE, titleStr);
    parseObject.put(DatabaseHelper.TIME_H, timeHStr);
    parseObject.put(DatabaseHelper.TIME_M, timeMStr);
    parseObject.put(DatabaseHelper.FREQUENCY, Fre);
    //parseObject.put(DatabaseHelper.DAY, day);

    parseObject.put(DatabaseHelper.MONDAY, monday);
    parseObject.put(DatabaseHelper.TUESDAY, tuesday);
    parseObject.put(DatabaseHelper.WEDNESDAY, wednesday);
    parseObject.put(DatabaseHelper.THURSDAY, thursday);
    parseObject.put(DatabaseHelper.FRIDAY, friday);
    parseObject.put(DatabaseHelper.SATURDAY, saturday);
    parseObject.put(DatabaseHelper.SUNDAY, sunday);

    parseObject.put(DatabaseHelper.DOSAGE, dosageStr);
    parseObject.put(DatabaseHelper.INSTRUCTION, instructionStr);
    parseObject.put(DatabaseHelper.SHAPE, shape);
    parseObject.put(DatabaseHelper.NOFITY_ID, notifyId);
    parseObject.put(DatabaseHelper.ORDER_NUM, orderNum);
    parseObject.saveInBackground();

    task = new InsertTask().execute(values);
}

From source file:com.irccloud.android.activity.MainActivity.java

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
private void showUserPopup(UsersDataSource.User user, Spanned message) {
    ArrayList<String> itemList = new ArrayList<String>();
    final String[] items;
    final Spanned text_to_copy = message;

    selected_user = user;//from   ww  w .j a  v a  2  s .co  m

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setInverseBackgroundForced(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB);

    if (message != null) {
        if (message.getSpans(0, message.length(), URLSpan.class).length > 0)
            itemList.add("Copy URL");
        itemList.add("Copy Message");
    }

    if (selected_user != null) {
        itemList.add("Whois");
        itemList.add("Send a message");
        itemList.add("Mention");
        itemList.add("Invite to a channel");
        itemList.add("Ignore");
        if (buffer.type.equalsIgnoreCase("channel")) {
            UsersDataSource.User self_user = UsersDataSource.getInstance().getUser(buffer.bid, server.nick);
            if (self_user != null && self_user.mode != null) {
                if (self_user.mode.contains(server != null ? server.MODE_OPER : "Y")
                        || self_user.mode.contains(server != null ? server.MODE_OWNER : "q")
                        || self_user.mode.contains(server != null ? server.MODE_ADMIN : "a")
                        || self_user.mode.contains(server != null ? server.MODE_OP : "o")) {
                    if (selected_user.mode.contains(server != null ? server.MODE_OP : "o"))
                        itemList.add("Deop");
                    else
                        itemList.add("Op");
                }
                if (self_user.mode.contains(server != null ? server.MODE_OPER : "Y")
                        || self_user.mode.contains(server != null ? server.MODE_OWNER : "q")
                        || self_user.mode.contains(server != null ? server.MODE_ADMIN : "a")
                        || self_user.mode.contains(server != null ? server.MODE_OP : "o")
                        || self_user.mode.contains(server != null ? server.MODE_HALFOP : "h")) {
                    itemList.add("Kick");
                    itemList.add("Ban");
                }
            }
        }
        itemList.add("Copy Hostmask");
    }

    items = itemList.toArray(new String[itemList.size()]);

    if (selected_user != null)
        if (selected_user.hostmask != null && selected_user.hostmask.length() > 0)
            builder.setTitle(selected_user.nick + "\n(" + selected_user.hostmask + ")");
        else
            builder.setTitle(selected_user.nick);
    else
        builder.setTitle("Message");

    builder.setItems(items, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialogInterface, int item) {
            if (conn == null || buffer == null)
                return;

            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setInverseBackgroundForced(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB);
            View view;
            final TextView prompt;
            final EditText input;
            AlertDialog dialog;

            if (items[item].equals("Copy Message")) {
                if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
                    android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(
                            CLIPBOARD_SERVICE);
                    clipboard.setText(text_to_copy);
                } else {
                    @SuppressLint("ServiceCast")
                    android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(
                            CLIPBOARD_SERVICE);
                    if (clipboard != null) {
                        android.content.ClipData clip = android.content.ClipData
                                .newPlainText("IRCCloud Message", text_to_copy);
                        clipboard.setPrimaryClip(clip);
                    } else {
                        Toast.makeText(MainActivity.this, "Unable to copy message. Please try again.",
                                Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                Toast.makeText(MainActivity.this, "Message copied to clipboard", Toast.LENGTH_SHORT).show();
            } else if (items[item].equals("Copy Hostmask")) {
                if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
                    android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(
                            CLIPBOARD_SERVICE);
                    clipboard.setText(selected_user.nick + "!" + selected_user.hostmask);
                } else {
                    @SuppressLint("ServiceCast")
                    android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(
                            CLIPBOARD_SERVICE);
                    android.content.ClipData clip = android.content.ClipData.newPlainText("Hostmask",
                            selected_user.nick + "!" + selected_user.hostmask);
                    clipboard.setPrimaryClip(clip);
                }
                Toast.makeText(MainActivity.this, "Hostmask copied to clipboard", Toast.LENGTH_SHORT).show();
            } else if (items[item].equals("Copy URL") && text_to_copy != null) {
                final ArrayList<String> urlListItems = new ArrayList<String>();

                for (URLSpan o : text_to_copy.getSpans(0, text_to_copy.length(), URLSpan.class)) {
                    String url = o.getURL();
                    url = url.replace(getResources().getString(R.string.IMAGE_SCHEME) + "://", "http://");
                    url = url.replace(getResources().getString(R.string.IMAGE_SCHEME_SECURE) + "://",
                            "https://");
                    if (server != null) {
                        url = url.replace(
                                getResources().getString(R.string.IRCCLOUD_SCHEME) + "://cid/" + server.cid
                                        + "/",
                                ((server.ssl > 0) ? "ircs://" : "irc://") + server.hostname + ":" + server.port
                                        + "/");
                    }
                    urlListItems.add(url);
                }
                if (urlListItems.size() == 1) {
                    if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
                        android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(
                                CLIPBOARD_SERVICE);
                        clipboard.setText(urlListItems.get(0));
                    } else {
                        @SuppressLint("ServiceCast")
                        android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(
                                CLIPBOARD_SERVICE);
                        android.content.ClipData clip = android.content.ClipData
                                .newPlainText(urlListItems.get(0), urlListItems.get(0));
                        clipboard.setPrimaryClip(clip);
                    }
                    Toast.makeText(MainActivity.this, "URL copied to clipboard", Toast.LENGTH_SHORT).show();
                } else {
                    builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setInverseBackgroundForced(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB);
                    builder.setTitle("Choose a URL");

                    builder.setItems(urlListItems.toArray(new String[urlListItems.size()]),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
                                        android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(
                                                CLIPBOARD_SERVICE);
                                        clipboard.setText(urlListItems.get(i));
                                    } else {
                                        @SuppressLint("ServiceCast")
                                        android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(
                                                CLIPBOARD_SERVICE);
                                        android.content.ClipData clip = android.content.ClipData
                                                .newPlainText(urlListItems.get(i), urlListItems.get(i));
                                        clipboard.setPrimaryClip(clip);
                                    }
                                    Toast.makeText(MainActivity.this, "URL copied to clipboard",
                                            Toast.LENGTH_SHORT).show();
                                }
                            });
                    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    dialog = builder.create();
                    dialog.setOwnerActivity(MainActivity.this);
                    dialog.getWindow()
                            .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                    dialog.show();
                }
            } else if (items[item].equals("Whois")) {
                conn.whois(buffer.cid, selected_user.nick, null);
            } else if (items[item].equals("Send a message")) {
                conn.say(buffer.cid, null, "/query " + selected_user.nick);
            } else if (items[item].equals("Mention")) {
                if (!getSharedPreferences("prefs", 0).getBoolean("mentionTip", false)) {
                    Toast.makeText(MainActivity.this, "Double-tap a message to quickly reply to the sender",
                            Toast.LENGTH_LONG).show();
                    SharedPreferences.Editor editor = getSharedPreferences("prefs", 0).edit();
                    editor.putBoolean("mentionTip", true);
                    editor.commit();
                }
                onUserDoubleClicked(selected_user.nick);
            } else if (items[item].equals("Invite to a channel")) {
                view = getDialogTextPrompt();
                prompt = (TextView) view.findViewById(R.id.prompt);
                input = (EditText) view.findViewById(R.id.textInput);
                input.setText("");
                prompt.setText("Invite " + selected_user.nick + " to a channel");
                builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")");
                builder.setView(view);
                builder.setPositiveButton("Invite", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        conn.invite(buffer.cid, input.getText().toString(), selected_user.nick);
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                dialog = builder.create();
                dialog.setOwnerActivity(MainActivity.this);
                dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                dialog.show();
            } else if (items[item].equals("Ignore")) {
                view = getDialogTextPrompt();
                prompt = (TextView) view.findViewById(R.id.prompt);
                input = (EditText) view.findViewById(R.id.textInput);
                input.setText("*!" + selected_user.hostmask);
                prompt.setText("Ignore messages for " + selected_user.nick + " at this hostmask");
                builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")");
                builder.setView(view);
                builder.setPositiveButton("Ignore", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        conn.ignore(buffer.cid, input.getText().toString());
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                dialog = builder.create();
                dialog.setOwnerActivity(MainActivity.this);
                dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                dialog.show();
            } else if (items[item].equals("Op")) {
                conn.mode(buffer.cid, buffer.name,
                        "+" + (server != null ? server.MODE_OP : "o") + " " + selected_user.nick);
            } else if (items[item].equals("Deop")) {
                conn.mode(buffer.cid, buffer.name,
                        "-" + (server != null ? server.MODE_OP : "o") + " " + selected_user.nick);
            } else if (items[item].equals("Kick")) {
                view = getDialogTextPrompt();
                prompt = (TextView) view.findViewById(R.id.prompt);
                input = (EditText) view.findViewById(R.id.textInput);
                input.setText("");
                prompt.setText("Give a reason for kicking");
                builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")");
                builder.setView(view);
                builder.setPositiveButton("Kick", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        conn.kick(buffer.cid, buffer.name, selected_user.nick, input.getText().toString());
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                dialog = builder.create();
                dialog.setOwnerActivity(MainActivity.this);
                dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                dialog.show();
            } else if (items[item].equals("Ban")) {
                view = getDialogTextPrompt();
                prompt = (TextView) view.findViewById(R.id.prompt);
                input = (EditText) view.findViewById(R.id.textInput);
                input.setText("*!" + selected_user.hostmask);
                prompt.setText("Add a banmask for " + selected_user.nick);
                builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")");
                builder.setView(view);
                builder.setPositiveButton("Ban", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        conn.mode(buffer.cid, buffer.name, "+b " + input.getText().toString());
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                dialog = builder.create();
                dialog.setOwnerActivity(MainActivity.this);
                dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                dialog.show();
            }
            dialogInterface.dismiss();
        }
    });

    AlertDialog dialog = builder.create();
    dialog.setOwnerActivity(this);
    dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
        @Override
        public void onDismiss(DialogInterface dialogInterface) {
            MessageViewFragment mvf = (MessageViewFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.messageViewFragment);
            if (mvf != null)
                mvf.longPressOverride = false;
        }
    });
    dialog.show();
}