Example usage for android.app Dialog findViewById

List of usage examples for android.app Dialog findViewById

Introduction

In this page you can find the example usage for android.app Dialog findViewById.

Prototype

@Nullable
public <T extends View> T findViewById(@IdRes int id) 

Source Link

Document

Finds the first descendant view with the given ID or null if the ID is invalid (< 0), there is no matching view in the hierarchy, or the dialog has not yet been fully created (for example, via #show() or #create() ).

Usage

From source file:com.sentaroh.android.TaskAutomation.Config.ProfileMaintenanceActionProfile.java

final static private void setActivityExtraDataEditItemViewVisibility(final GlobalParameters mGlblParms,
        Dialog dialog, final AdapterDataArrayEditList aed_array_adapter, final Spinner spinnerExtraDataType) {
    //      final EditText et_key=(EditText)dialog.findViewById(R.id.edit_activity_extra_data_item_key);
    final EditText et_string = (EditText) dialog.findViewById(R.id.edit_activity_extra_data_item_data_string);
    final EditText et_int = (EditText) dialog.findViewById(R.id.edit_activity_extra_data_item_data_int);
    final CheckBox cb_array = (CheckBox) dialog.findViewById(R.id.edit_activity_extra_data_item_array);

    final Button btn_add_array = (Button) dialog.findViewById(R.id.edit_activity_extra_data_item_add_array);
    final ListView lv_array = (ListView) dialog.findViewById(R.id.edit_activity_extra_data_item_array_listview);
    final TextView lv_spacer = (TextView) dialog.findViewById(R.id.edit_activity_extra_data_item_array_spacer);
    final Button update_apply = (Button) dialog
            .findViewById(R.id.edit_activity_extra_data_item_data_update_apply);
    final Button update_cancel = (Button) dialog
            .findViewById(R.id.edit_activity_extra_data_item_data_update_cancel);
    final Spinner spinnerExtraDataBoolean = (Spinner) dialog
            .findViewById(R.id.edit_activity_extra_data_item_data_boolean);

    cb_array.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override//  w  w  w  .j  a v a2 s.c  o m
        final public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
            if (isChecked) {
                btn_add_array.setVisibility(Button.VISIBLE);
                lv_array.setVisibility(Button.VISIBLE);
                lv_spacer.setVisibility(TextView.GONE);
                et_string.setVisibility(EditText.GONE);
                et_int.setVisibility(EditText.GONE);
                spinnerExtraDataBoolean.setVisibility(Spinner.GONE);
            } else {
                btn_add_array.setVisibility(Button.GONE);
                lv_array.setVisibility(Button.GONE);
                lv_spacer.setVisibility(TextView.VISIBLE);
                update_apply.setVisibility(Button.GONE);
                update_cancel.setVisibility(Button.GONE);
                if (spinnerExtraDataType.getSelectedItem().toString()
                        .equals(PROFILE_ACTION_TYPE_ACTIVITY_EXTRA_DATA_VALUE_STRING)) {
                    et_string.setVisibility(EditText.VISIBLE);
                    et_int.setVisibility(EditText.GONE);
                    spinnerExtraDataBoolean.setVisibility(LinearLayout.GONE);
                } else if (spinnerExtraDataType.getSelectedItem().toString()
                        .equals(PROFILE_ACTION_TYPE_ACTIVITY_EXTRA_DATA_VALUE_INT)) {
                    et_string.setVisibility(EditText.GONE);
                    et_int.setVisibility(EditText.VISIBLE);
                    spinnerExtraDataBoolean.setVisibility(LinearLayout.GONE);
                } else if (spinnerExtraDataType.getSelectedItem().toString()
                        .equals(PROFILE_ACTION_TYPE_ACTIVITY_EXTRA_DATA_VALUE_BOOLEAN)) {
                    et_string.setVisibility(EditText.GONE);
                    et_int.setVisibility(EditText.GONE);
                    spinnerExtraDataBoolean.setVisibility(LinearLayout.VISIBLE);
                }
            }
        }
    });
    spinnerExtraDataType.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        final public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, long arg3) {
            if (!cb_array.isChecked()) {
                if (spinnerExtraDataType.getSelectedItem().toString()
                        .equals(PROFILE_ACTION_TYPE_ACTIVITY_EXTRA_DATA_VALUE_STRING)) {
                    et_string.setVisibility(EditText.VISIBLE);
                    et_int.setVisibility(EditText.GONE);
                    spinnerExtraDataBoolean.setVisibility(LinearLayout.GONE);
                } else if (spinnerExtraDataType.getSelectedItem().toString()
                        .equals(PROFILE_ACTION_TYPE_ACTIVITY_EXTRA_DATA_VALUE_INT)) {
                    et_string.setVisibility(EditText.GONE);
                    et_int.setVisibility(EditText.VISIBLE);
                    spinnerExtraDataBoolean.setVisibility(LinearLayout.GONE);
                } else if (spinnerExtraDataType.getSelectedItem().toString()
                        .equals(PROFILE_ACTION_TYPE_ACTIVITY_EXTRA_DATA_VALUE_BOOLEAN)) {
                    et_string.setVisibility(EditText.GONE);
                    et_int.setVisibility(EditText.GONE);
                    spinnerExtraDataBoolean.setVisibility(LinearLayout.VISIBLE);
                }
            }
            //            Log.v("","c="+currentSelectedExtraDataType+", n="+spinnerExtraDataType.getSelectedItem().toString());
            if (!spinnerExtraDataType.getSelectedItem().toString()
                    .equals(mGlblParms.currentSelectedExtraDataType)) {
                aed_array_adapter.clear();
                aed_array_adapter.notifyDataSetChanged();
                //               Log.v("","size="+aed_array_adapter.getCount());
                mGlblParms.currentSelectedExtraDataType = spinnerExtraDataType.getSelectedItem().toString();
            }
        }

        @Override
        final public void onNothingSelected(AdapterView<?> arg0) {
        }

    });
}

From source file:fiskinfoo.no.sintef.fiskinfoo.Implementation.UtilityOnClickListeners.java

@Override
public OnClickListener getSubscriptionCheckBoxOnClickListener(final PropertyDescription subscription,
        final Subscription activeSubscription, final User user) {
    return new OnClickListener() {
        @Override/*from   w  w w  .ja v a  2s .co m*/
        public void onClick(final View v) {
            UtilityRowsInterface utilityRowsInterface = new UtilityRows();
            final FiskInfoUtility fiskInfoUtility = new FiskInfoUtility();

            final Dialog dialog;

            int iconId = fiskInfoUtility.subscriptionApiNameToIconId(subscription.ApiName);

            if (iconId != -1) {
                dialog = new UtilityDialogs().getDialogWithTitleIcon(v.getContext(),
                        R.layout.dialog_manage_subscription, subscription.Name, iconId);
            } else {
                dialog = new UtilityDialogs().getDialog(v.getContext(), R.layout.dialog_manage_subscription,
                        subscription.Name);
            }

            final Switch subscribedSwitch = (Switch) dialog.findViewById(R.id.manage_subscription_switch);
            final LinearLayout formatsContainer = (LinearLayout) dialog
                    .findViewById(R.id.manage_subscription_formats_container);
            final LinearLayout intervalsContainer = (LinearLayout) dialog
                    .findViewById(R.id.manage_subscription_intervals_container);
            final EditText subscriptionEmailEditText = (EditText) dialog
                    .findViewById(R.id.manage_subscription_email_edit_text);

            final Button subscribeButton = (Button) dialog.findViewById(R.id.manage_subscription_update_button);
            Button cancelButton = (Button) dialog.findViewById(R.id.manage_subscription_cancel_button);

            final boolean isSubscribed = activeSubscription != null;
            final Map<String, String> subscriptionFrequencies = new HashMap<>();

            dialog.setTitle(subscription.Name);

            if (isSubscribed) {
                subscriptionEmailEditText.setText(activeSubscription.SubscriptionEmail);

                subscribedSwitch.setVisibility(View.VISIBLE);
                subscribedSwitch.setChecked(true);
                subscribedSwitch
                        .setText(v.getResources().getString(R.string.manage_subscription_subscription_active));

                subscribedSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        System.out.println("This is checked:" + isChecked);
                        String switchText = isChecked
                                ? v.getResources().getString(R.string.manage_subscription_subscription_active)
                                : v.getResources()
                                        .getString(R.string.manage_subscription_subscription_cancellation);
                        subscribedSwitch.setText(switchText);
                    }
                });
            } else {
                subscriptionEmailEditText.setText(user.getUsername());
            }

            for (String format : subscription.Formats) {
                final RadioButtonRow row = utilityRowsInterface.getRadioButtonRow(v.getContext(), format);
                if (isSubscribed && activeSubscription.FileFormatType.equals(format)) {
                    row.setSelected(true);
                }

                formatsContainer.addView(row.getView());
            }

            for (String interval : subscription.SubscriptionInterval) {
                final RadioButtonRow row = utilityRowsInterface.getRadioButtonRow(v.getContext(),
                        SubscriptionInterval.getType(interval).toString());

                if (activeSubscription != null) {
                    row.setSelected(activeSubscription.SubscriptionIntervalName.equals(interval));
                }

                subscriptionFrequencies.put(SubscriptionInterval.getType(interval).toString(), interval);
                intervalsContainer.addView(row.getView());
            }

            if (intervalsContainer.getChildCount() == 1) {
                ((RadioButton) intervalsContainer.getChildAt(0)
                        .findViewById(R.id.radio_button_row_radio_button)).setChecked(true);
            }

            subscribeButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View subscribeButton) {
                    String subscriptionFormat = null;
                    String subscriptionInterval = null;
                    String subscriptionEmail;

                    BarentswatchApi barentswatchApi = new BarentswatchApi();
                    barentswatchApi.setAccesToken(user.getToken());
                    final IBarentswatchApi api = barentswatchApi.getApi();

                    for (int i = 0; i < formatsContainer.getChildCount(); i++) {
                        if (((RadioButton) formatsContainer.getChildAt(i)
                                .findViewById(R.id.radio_button_row_radio_button)).isChecked()) {
                            subscriptionFormat = ((TextView) formatsContainer.getChildAt(i)
                                    .findViewById(R.id.radio_button_row_text_view)).getText().toString();
                            break;
                        }
                    }

                    if (subscriptionFormat == null) {
                        Toast.makeText(v.getContext(),
                                v.getContext().getString(R.string.choose_subscription_format),
                                Toast.LENGTH_LONG).show();
                        return;
                    }

                    for (int i = 0; i < intervalsContainer.getChildCount(); i++) {
                        if (((RadioButton) intervalsContainer.getChildAt(i)
                                .findViewById(R.id.radio_button_row_radio_button)).isChecked()) {
                            subscriptionInterval = ((TextView) intervalsContainer.getChildAt(i)
                                    .findViewById(R.id.radio_button_row_text_view)).getText().toString();
                            break;
                        }
                    }

                    if (subscriptionInterval == null) {
                        Toast.makeText(v.getContext(),
                                v.getContext().getString(R.string.choose_subscription_interval),
                                Toast.LENGTH_LONG).show();
                        return;
                    }

                    subscriptionEmail = subscriptionEmailEditText.getText().toString();

                    if (!(new FiskInfoUtility().isEmailValid(subscriptionEmail))) {
                        Toast.makeText(v.getContext(), v.getContext().getString(R.string.error_invalid_email),
                                Toast.LENGTH_LONG).show();
                        return;
                    }

                    if (isSubscribed) {
                        if (subscribedSwitch.isChecked()) {
                            if (!(subscriptionFormat.equals(activeSubscription.FileFormatType)
                                    && activeSubscription.SubscriptionIntervalName
                                            .equals(subscriptionFrequencies.get(subscriptionInterval))
                                    && user.getUsername().equals(subscriptionEmail))) {
                                SubscriptionSubmitObject updatedSubscription = new SubscriptionSubmitObject(
                                        subscription.ApiName, subscriptionFormat, user.getUsername(),
                                        user.getUsername(), subscriptionFrequencies.get(subscriptionInterval));
                                Subscription newSubscriptionObject = api.updateSubscription(
                                        String.valueOf(activeSubscription.Id), updatedSubscription);

                                if (newSubscriptionObject != null) {
                                    ((CheckBox) v).setChecked(true);
                                }
                            }
                        } else {
                            Response response = api.deleteSubscription(String.valueOf(activeSubscription.Id));

                            if (response.getStatus() == 204) {
                                ((CheckBox) v).setChecked(false);
                                Toast.makeText(v.getContext(), R.string.subscription_update_successful,
                                        Toast.LENGTH_LONG).show();
                            } else {
                                Toast.makeText(v.getContext(), R.string.subscription_update_failed,
                                        Toast.LENGTH_LONG).show();
                            }
                        }
                    } else {
                        SubscriptionSubmitObject newSubscription = new SubscriptionSubmitObject(
                                subscription.ApiName, subscriptionFormat, user.getUsername(),
                                user.getUsername(), subscriptionFrequencies.get(subscriptionInterval));

                        Subscription response = api.setSubscription(newSubscription);

                        if (response != null) {
                            ((CheckBox) v).setChecked(true);
                            // TODO: add to "Mine abonnementer"
                            Toast.makeText(v.getContext(), R.string.subscription_update_successful,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(v.getContext(), R.string.subscription_update_failed,
                                    Toast.LENGTH_LONG).show();
                        }
                    }

                    dialog.dismiss();
                }
            });

            cancelButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View cancelButton) {
                    ((CheckBox) v).setChecked(isSubscribed);

                    dialog.dismiss();
                }
            });

            dialog.show();

        }
    };
}

From source file:org.onebusaway.android.ui.SituationDialogFragment.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Bundle args = getArguments();//w w w  .j ava2  s .c  om
    final String situationId = args.getString(ID);

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()).setView(R.layout.situation)
            .setPositiveButton(R.string.hide, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int which) {
                    Dialog dialog = (Dialog) dialogInterface;

                    // Update the database to indicate that this alert has been hidden
                    ObaContract.ServiceAlerts.insertOrUpdate(situationId, new ContentValues(), false, true);

                    // Show the UNDO snackbar
                    Snackbar.make(getActivity().findViewById(R.id.fragment_arrivals_list),
                            R.string.alert_hidden_snackbar_text, Snackbar.LENGTH_SHORT)
                            .setAction(R.string.alert_hidden_snackbar_action, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    ObaContract.ServiceAlerts.insertOrUpdate(situationId, new ContentValues(),
                                            false, false);
                                    if (mListener != null) {
                                        mListener.onUndo();
                                    }
                                }
                            }).show();
                    dialog.dismiss();
                    if (mListener != null) {
                        mListener.onDismiss(true);
                    }
                }
            }).setNegativeButton(R.string.close, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    if (mListener != null) {
                        mListener.onDismiss(false);
                    }
                }
            });

    final android.support.v7.app.AlertDialog dialog = builder.create();
    dialog.show();

    // Set the title, description, and URL (if provided)
    TextView title = (TextView) dialog.findViewById(R.id.alert_title);
    title.setText(args.getString(TITLE));

    TextView desc = (TextView) dialog.findViewById(R.id.alert_description);
    desc.setText(args.getString(DESCRIPTION));

    TextView urlView = (TextView) dialog.findViewById(R.id.alert_url);

    // Remove any previous clickable spans just to be safe
    UIUtils.removeAllClickableSpans(urlView);

    final String url = args.getString(URL);
    if (!TextUtils.isEmpty(url)) {
        urlView.setVisibility(View.VISIBLE);

        ClickableSpan urlClick = new ClickableSpan() {
            public void onClick(View v) {
                getActivity().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            }
        };
        UIUtils.setClickableSpan(urlView, urlClick);
    } else {
        urlView.setVisibility(View.GONE);
    }

    // Update the database to indicate that this alert has been read
    ObaContract.ServiceAlerts.insertOrUpdate(args.getString(ID), new ContentValues(), true, null);

    return dialog;
}

From source file:fiskinfoo.no.sintef.fiskinfoo.Implementation.UtilityOnClickListeners.java

public OnClickListener getToolEntryEditDialogOnClickListener(final Activity activity,
        final FragmentManager fragmentManager, final GpsLocationTracker locationTracker,
        final ToolEntry toolEntry, final User user) {
    return new OnClickListener() {
        @Override/*from   w  ww.j  a  va  2 s  .  com*/
        public void onClick(final View editButton) {
            final DialogInterface dialogInterface = new UtilityDialogs();
            final Dialog dialog = dialogInterface.getDialog(editButton.getContext(),
                    R.layout.dialog_register_new_tool, R.string.edit_tool);
            ((Button) dialog.findViewById(R.id.dialog_register_tool_create_tool_button))
                    .setText(editButton.getContext().getString(R.string.save));

            final Button updateButton = (Button) dialog
                    .findViewById(R.id.dialog_register_tool_create_tool_button);
            final Button cancelButton = (Button) dialog.findViewById(R.id.dialog_register_tool_cancel_button);
            final LinearLayout fieldContainer = (LinearLayout) dialog
                    .findViewById(R.id.dialog_register_tool_main_container);
            final DatePickerRow setupDateRow = new DatePickerRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.tool_set_date_colon), fragmentManager);
            final TimePickerRow setupTimeRow = new TimePickerRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.tool_set_time_colon), fragmentManager, false);
            final CoordinatesRow coordinatesRow = new CoordinatesRow(activity, locationTracker);
            final SpinnerRow toolRow = new SpinnerRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.tool_type), ToolType.getValues());
            final CheckBoxRow toolRemovedRow = new CheckBoxRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.tool_removed_row_text), true);
            final EditTextRow commentRow = new EditTextRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.comment_field_header),
                    editButton.getContext().getString(R.string.comment_field_hint));

            final EditTextRow contactPersonNameRow = new EditTextRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.contact_person_name),
                    editButton.getContext().getString(R.string.contact_person_name));
            final EditTextRow contactPersonPhoneRow = new EditTextRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.contact_person_phone),
                    editButton.getContext().getString(R.string.contact_person_phone));
            final EditTextRow contactPersonEmailRow = new EditTextRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.contact_person_email),
                    editButton.getContext().getString(R.string.contact_person_email));
            final EditTextRow vesselNameRow = new EditTextRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.vessel_name),
                    editButton.getContext().getString(R.string.vessel_name));
            final EditTextRow vesselPhoneNumberRow = new EditTextRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.vessel_phone_number),
                    editButton.getContext().getString(R.string.vessel_phone_number));
            final EditTextRow vesselIrcsNumberRow = new EditTextRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.ircs_number),
                    editButton.getContext().getString(R.string.ircs_number));
            final EditTextRow vesselMmsiNumberRow = new EditTextRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.mmsi_number),
                    editButton.getContext().getString(R.string.mmsi_number));
            final EditTextRow vesselImoNumberRow = new EditTextRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.imo_number),
                    editButton.getContext().getString(R.string.imo_number));
            final EditTextRow vesselRegistrationNumberRow = new EditTextRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.registration_number),
                    editButton.getContext().getString(R.string.registration_number));
            final ErrorRow errorRow = new ErrorRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.error_minimum_identification_factors_not_met),
                    false);

            final SimpleDateFormat sdfMilliSeconds = new SimpleDateFormat(
                    editButton.getContext().getString(R.string.datetime_format_yyyy_mm_dd_t_hh_mm_ss_sss),
                    Locale.getDefault());
            final SimpleDateFormat sdf = new SimpleDateFormat(
                    editButton.getContext().getString(R.string.datetime_format_yyyy_mm_dd_t_hh_mm_ss),
                    Locale.getDefault());

            View.OnClickListener deleteButtonRowOnClickListener = new OnClickListener() {
                @Override
                public void onClick(View v) {
                    String confirmationText;

                    switch (toolEntry.getToolStatus()) {
                    case STATUS_RECEIVED:
                    case STATUS_SENT_UNCONFIRMED:
                        confirmationText = v.getContext()
                                .getString(R.string.confirm_registered_tool_deletion_text);
                        break;
                    case STATUS_UNSENT:
                    case STATUS_UNREPORTED:
                        confirmationText = v.getContext().getString(R.string.confirm_tool_deletion_text);
                        break;
                    case STATUS_REMOVED_UNCONFIRMED:
                        confirmationText = v.getContext()
                                .getString(R.string.confirm_registered_tool_with_local_changes_deletion_text);
                        break;
                    default:
                        confirmationText = v.getContext()
                                .getString(R.string.confirm_tool_deletion_text_general);
                        break;
                    }

                    final Dialog deleteToolDialog = dialogInterface.getConfirmationDialog(v.getContext(),
                            v.getContext().getString(R.string.delete_tool), confirmationText,
                            v.getContext().getString(R.string.delete));
                    Button confirmToolDeletionButton = (Button) deleteToolDialog
                            .findViewById(R.id.dialog_bottom_confirm_bottom);

                    confirmToolDeletionButton.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            View parentView = (View) ((editButton.getParent()).getParent());
                            ((LinearLayout) parentView).removeView(((View) (editButton.getParent())));
                            Toast.makeText(v.getContext(), v.getContext().getString(R.string.tool_deleted),
                                    Toast.LENGTH_LONG).show();

                            user.getToolLog().removeTool(toolEntry.getSetupDate(), toolEntry.getToolLogId());
                            user.writeToSharedPref(v.getContext());

                            deleteToolDialog.dismiss();
                            dialog.dismiss();
                        }
                    });

                    deleteToolDialog.show();
                }
            };

            View.OnClickListener archiveToolOnClickListener = new OnClickListener() {
                @Override
                public void onClick(View v) {
                    String confirmationText;

                    switch (toolEntry.getToolStatus()) {
                    case STATUS_RECEIVED:
                        confirmationText = v.getContext().getString(R.string.confirm_registered_tool_archiving);
                        break;
                    case STATUS_UNSENT:
                        if (!toolEntry.getId().isEmpty()) {
                            confirmationText = v.getContext().getString(R.string.confirm_tool_archiving_text);
                        } else {
                            confirmationText = v.getContext().getString(
                                    R.string.confirm_registered_tool_with_local_changes_archiving_text);
                        }
                        break;
                    default:
                        confirmationText = v.getContext()
                                .getString(R.string.confirm_tool_archiving_text_general);
                        break;
                    }

                    final Dialog archiveDialog = dialogInterface.getConfirmationDialog(v.getContext(),
                            v.getContext().getString(R.string.archive_tool), confirmationText,
                            v.getContext().getString(R.string.archive));
                    Button confirmToolArchiveButton = (Button) archiveDialog
                            .findViewById(R.id.dialog_bottom_confirm_bottom);

                    confirmToolArchiveButton.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            View parentView = (View) ((editButton.getParent()).getParent()).getParent();
                            ((LinearLayout) parentView)
                                    .removeView(((View) (editButton.getParent()).getParent()));
                            Toast.makeText(v.getContext(), v.getContext().getString(R.string.tool_archived),
                                    Toast.LENGTH_LONG).show();

                            toolEntry.setToolStatus(ToolEntryStatus.STATUS_REMOVED);
                            user.writeToSharedPref(v.getContext());

                            archiveDialog.dismiss();
                            dialog.dismiss();
                        }
                    });

                    archiveDialog.show();
                }
            };

            ActionRow archiveRow = new ActionRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.archive_tool), R.drawable.ic_archive_black_24dp,
                    archiveToolOnClickListener);
            ActionRow deleteRow = new ActionRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.delete_tool), R.drawable.ic_delete_black_24dp,
                    deleteButtonRowOnClickListener);

            commentRow.setInputType(InputType.TYPE_CLASS_TEXT);
            commentRow.setHelpText(editButton.getContext().getString(R.string.comment_help_description));
            vesselNameRow.setInputType(InputType.TYPE_CLASS_TEXT);
            contactPersonPhoneRow
                    .setHelpText(editButton.getContext().getString(R.string.vessel_name_help_description));
            vesselPhoneNumberRow.setInputType(InputType.TYPE_CLASS_PHONE);
            vesselIrcsNumberRow.setInputType(InputType.TYPE_CLASS_TEXT);
            vesselIrcsNumberRow.setInputFilters(new InputFilter[] {
                    new InputFilter.LengthFilter(
                            editButton.getContext().getResources().getInteger(R.integer.input_length_ircs)),
                    new InputFilter.AllCaps() });
            vesselIrcsNumberRow.setHelpText(editButton.getContext().getString(R.string.ircs_help_description));
            vesselMmsiNumberRow.setInputType(InputType.TYPE_CLASS_NUMBER);
            vesselMmsiNumberRow.setInputFilters(new InputFilter[] { new InputFilter.LengthFilter(
                    editButton.getContext().getResources().getInteger(R.integer.input_length_mmsi)) });
            vesselMmsiNumberRow.setHelpText(editButton.getContext().getString(R.string.mmsi_help_description));
            vesselImoNumberRow.setInputType(InputType.TYPE_CLASS_NUMBER);
            vesselImoNumberRow.setInputFilters(new InputFilter[] { new InputFilter.LengthFilter(
                    editButton.getContext().getResources().getInteger(R.integer.input_length_imo)) });
            vesselImoNumberRow.setHelpText(editButton.getContext().getString(R.string.imo_help_description));
            vesselRegistrationNumberRow.setInputType(InputType.TYPE_CLASS_TEXT);
            vesselRegistrationNumberRow.setInputFilters(new InputFilter[] {
                    new InputFilter.LengthFilter(editButton.getContext().getResources()
                            .getInteger(R.integer.input_length_registration_number)),
                    new InputFilter.AllCaps() });
            vesselRegistrationNumberRow.setHelpText(
                    editButton.getContext().getString(R.string.registration_number_help_description));
            contactPersonNameRow.setInputType(InputType.TYPE_TEXT_VARIATION_PERSON_NAME);
            contactPersonPhoneRow.setInputType(InputType.TYPE_CLASS_PHONE);
            contactPersonEmailRow.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
            contactPersonNameRow.setHelpText(
                    editButton.getContext().getString(R.string.contact_person_name_help_description));
            contactPersonPhoneRow.setHelpText(
                    editButton.getContext().getString(R.string.contact_person_phone_help_description));
            contactPersonEmailRow.setHelpText(
                    editButton.getContext().getString(R.string.contact_person_email_help_description));
            coordinatesRow.setCoordinates(activity, toolEntry.getCoordinates());

            setupDateRow.setEnabled(false);

            /* Should these fields be editable after tools are reported? */
            //                vesselRegistrationNumberRow.setEnabled(toolEntry.getToolStatus() == ToolEntryStatus.STATUS_UNREPORTED);
            //                vesselImoNumberRow.setEnabled(toolEntry.getToolStatus() == ToolEntryStatus.STATUS_UNREPORTED);
            //                vesselMmsiNumberRow.setEnabled(toolEntry.getToolStatus() == ToolEntryStatus.STATUS_UNREPORTED);
            //                vesselNameRow.setEnabled(toolEntry.getToolStatus() == ToolEntryStatus.STATUS_UNREPORTED);
            //                vesselIrcsNumberRow.setEnabled(toolEntry.getToolStatus() == ToolEntryStatus.STATUS_UNREPORTED);

            ArrayAdapter<String> currentAdapter = toolRow.getAdapter();
            toolRow.setSelectedSpinnerItem(currentAdapter.getPosition(toolEntry.getToolType().toString()));
            toolRemovedRow.setChecked(!toolEntry.getRemovedTime().isEmpty());
            commentRow.setText(toolEntry.getComment());
            contactPersonNameRow.setText(toolEntry.getContactPersonName());
            contactPersonPhoneRow
                    .setText(!toolEntry.getContactPersonPhone().equals("") ? toolEntry.getContactPersonPhone()
                            : toolEntry.getVesselPhone());
            contactPersonEmailRow
                    .setText(!toolEntry.getContactPersonEmail().equals("") ? toolEntry.getContactPersonEmail()
                            : toolEntry.getVesselEmail());
            vesselNameRow.setText(toolEntry.getVesselName());
            vesselPhoneNumberRow.setText(toolEntry.getVesselPhone());
            vesselIrcsNumberRow.setText(toolEntry.getIRCS());
            vesselMmsiNumberRow.setText(toolEntry.getMMSI());
            vesselImoNumberRow.setText(toolEntry.getIMO());
            vesselRegistrationNumberRow.setText(toolEntry.getRegNum());

            sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
            Date setupDate = null;
            String toolSetupDateTime;

            try {
                setupDate = sdf.parse(toolEntry.getSetupDateTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }

            sdfMilliSeconds.setTimeZone(TimeZone.getDefault());
            toolSetupDateTime = sdfMilliSeconds.format(setupDate);
            setupDateRow.setDate(toolSetupDateTime.substring(0, 10));
            setupTimeRow.setTime(toolSetupDateTime.substring(toolEntry.getSetupDateTime().indexOf('T') + 1,
                    toolEntry.getSetupDateTime().indexOf('T') + 6));

            fieldContainer.addView(coordinatesRow.getView());
            fieldContainer.addView(setupDateRow.getView());
            fieldContainer.addView(setupTimeRow.getView());
            fieldContainer.addView(toolRow.getView());
            fieldContainer.addView(toolRemovedRow.getView());
            fieldContainer.addView(commentRow.getView());
            fieldContainer.addView(contactPersonNameRow.getView());
            fieldContainer.addView(contactPersonPhoneRow.getView());
            fieldContainer.addView(contactPersonEmailRow.getView());
            fieldContainer.addView(vesselNameRow.getView());
            fieldContainer.addView(vesselPhoneNumberRow.getView());
            fieldContainer.addView(vesselIrcsNumberRow.getView());
            fieldContainer.addView(vesselMmsiNumberRow.getView());
            fieldContainer.addView(vesselImoNumberRow.getView());
            fieldContainer.addView(vesselRegistrationNumberRow.getView());
            fieldContainer.addView(errorRow.getView());

            if (toolEntry.getToolStatus() != ToolEntryStatus.STATUS_UNREPORTED) {
                fieldContainer.addView(archiveRow.getView());
            }

            fieldContainer.addView(deleteRow.getView());

            updateButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View updateButton) {
                    List<Point> coordinates = coordinatesRow.getCoordinates();
                    ToolType toolType = ToolType.createFromValue(toolRow.getCurrentSpinnerItem());
                    boolean toolRemoved = toolRemovedRow.isChecked();
                    String vesselName = vesselNameRow.getFieldText();
                    String vesselPhoneNumber = vesselPhoneNumberRow.getFieldText();
                    String toolSetupDate = setupDateRow.getDate();
                    String toolSetupTime = setupTimeRow.getTime();
                    String toolSetupDateTime;
                    String commentString = commentRow.getFieldText();
                    String vesselIrcsNumber = vesselIrcsNumberRow.getFieldText();
                    String vesselMmsiNumber = vesselMmsiNumberRow.getFieldText();
                    String vesselImoNumber = vesselImoNumberRow.getFieldText();
                    String registrationNumber = vesselRegistrationNumberRow.getFieldText();
                    String contactPersonName = contactPersonNameRow.getFieldText();
                    String contactPersonPhone = contactPersonPhoneRow.getFieldText();
                    String contactPersonEmail = contactPersonEmailRow.getFieldText();
                    FiskInfoUtility utility = new FiskInfoUtility();
                    boolean validated;
                    boolean edited = false;
                    boolean ircsValidated;
                    boolean mmsiValidated;
                    boolean imoValidated;
                    boolean regNumValidated;
                    boolean minimumIdentificationFactorsMet;

                    validated = coordinates != null;
                    if (!validated) {
                        return;
                    }

                    validated = utility.validateName(contactPersonNameRow.getFieldText().trim());
                    contactPersonNameRow.setError(validated ? null
                            : updateButton.getContext().getString(R.string.error_invalid_name));
                    if (!validated) {
                        ((ScrollView) fieldContainer.getParent()).post(new Runnable() {
                            @Override
                            public void run() {
                                ((ScrollView) fieldContainer.getParent()).scrollTo(0,
                                        contactPersonNameRow.getView().getBottom());
                                contactPersonNameRow.requestFocus();
                            }
                        });

                        return;
                    }

                    validated = utility.validatePhoneNumber(contactPersonPhoneRow.getFieldText().trim());
                    contactPersonPhoneRow.setError(validated ? null
                            : updateButton.getContext().getString(R.string.error_invalid_phone_number));
                    if (!validated) {
                        ((ScrollView) fieldContainer.getParent()).post(new Runnable() {
                            @Override
                            public void run() {
                                ((ScrollView) fieldContainer.getParent()).scrollTo(0,
                                        contactPersonPhoneRow.getView().getBottom());
                                contactPersonPhoneRow.requestFocus();
                            }
                        });

                        return;
                    }

                    validated = utility.isEmailValid(contactPersonEmailRow.getFieldText().trim());
                    contactPersonEmailRow.setError(validated ? null
                            : updateButton.getContext().getString(R.string.error_invalid_email));
                    if (!validated) {
                        ((ScrollView) fieldContainer.getParent()).post(new Runnable() {
                            @Override
                            public void run() {
                                ((ScrollView) fieldContainer.getParent()).scrollTo(0,
                                        contactPersonEmailRow.getView().getBottom());
                                contactPersonEmailRow.requestFocus();
                            }
                        });

                        return;
                    }

                    validated = vesselNameRow.getFieldText().trim() != null
                            && !vesselNameRow.getFieldText().isEmpty();
                    vesselNameRow.setError(validated ? null
                            : updateButton.getContext().getString(R.string.error_invalid_vessel_name));
                    if (!validated) {
                        ((ScrollView) fieldContainer.getParent()).post(new Runnable() {
                            @Override
                            public void run() {
                                ((ScrollView) fieldContainer.getParent()).scrollTo(0,
                                        vesselNameRow.getView().getBottom());
                                vesselNameRow.requestFocus();
                            }
                        });

                        return;
                    }

                    validated = vesselPhoneNumberRow.getFieldText().trim() != null
                            && !vesselPhoneNumberRow.getFieldText().isEmpty();
                    vesselPhoneNumberRow.setError(validated ? null
                            : updateButton.getContext().getString(R.string.error_invalid_phone_number));
                    if (!validated) {
                        ((ScrollView) fieldContainer.getParent()).post(new Runnable() {
                            @Override
                            public void run() {
                                ((ScrollView) fieldContainer.getParent()).scrollTo(0,
                                        vesselPhoneNumberRow.getView().getBottom());
                                vesselPhoneNumberRow.requestFocus();
                            }
                        });

                        return;
                    }

                    validated = (ircsValidated = utility.validateIRCS(vesselIrcsNumber))
                            || vesselIrcsNumber.isEmpty();
                    vesselIrcsNumberRow.setError(validated ? null
                            : updateButton.getContext().getString(R.string.error_invalid_ircs));
                    if (!validated) {
                        ((ScrollView) fieldContainer.getParent()).post(new Runnable() {
                            @Override
                            public void run() {
                                ((ScrollView) fieldContainer.getParent()).scrollTo(0,
                                        vesselIrcsNumberRow.getView().getBottom());
                                vesselIrcsNumberRow.requestFocus();
                            }
                        });

                        return;
                    }

                    validated = (mmsiValidated = utility.validateMMSI(vesselMmsiNumber))
                            || vesselMmsiNumber.isEmpty();
                    vesselMmsiNumberRow.setError(validated ? null
                            : updateButton.getContext().getString(R.string.error_invalid_mmsi));
                    if (!validated) {
                        ((ScrollView) fieldContainer.getParent()).post(new Runnable() {
                            @Override
                            public void run() {
                                ((ScrollView) fieldContainer.getParent()).scrollTo(0,
                                        vesselMmsiNumberRow.getView().getBottom());
                                vesselMmsiNumberRow.requestFocus();
                            }
                        });

                        return;
                    }

                    validated = (imoValidated = utility.validateIMO(vesselImoNumber))
                            || vesselImoNumber.isEmpty();
                    vesselImoNumberRow.setError(
                            validated ? null : updateButton.getContext().getString(R.string.error_invalid_imo));
                    if (!validated) {
                        ((ScrollView) fieldContainer.getParent()).post(new Runnable() {
                            @Override
                            public void run() {
                                ((ScrollView) fieldContainer.getParent()).scrollTo(0,
                                        vesselImoNumberRow.getView().getBottom());
                                vesselImoNumberRow.requestFocus();
                            }
                        });

                        return;
                    }

                    validated = (regNumValidated = utility.validateRegistrationNumber(registrationNumber))
                            || registrationNumber.isEmpty();
                    vesselRegistrationNumberRow.setError(validated ? null
                            : editButton.getContext().getString(R.string.error_invalid_registration_number));
                    if (!validated) {
                        ((ScrollView) fieldContainer.getParent().getParent()).post(new Runnable() {
                            @Override
                            public void run() {
                                ((ScrollView) fieldContainer.getParent().getParent()).scrollTo(0,
                                        vesselRegistrationNumberRow.getView().getBottom());
                                vesselRegistrationNumberRow.requestFocus();
                            }
                        });

                        return;
                    }

                    sdf.setTimeZone(TimeZone.getDefault());
                    Date setupDate = null;
                    String setupDateString = toolSetupDate + "T" + toolSetupTime + ":00Z";

                    try {
                        setupDate = sdf.parse(setupDateString);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                    sdfMilliSeconds.setTimeZone(TimeZone.getTimeZone("UTC"));
                    setupDateString = sdfMilliSeconds.format(setupDate);
                    toolSetupDateTime = setupDateString.substring(0, setupDateString.indexOf('.')).concat("Z");

                    minimumIdentificationFactorsMet = !vesselName.isEmpty()
                            && (ircsValidated || mmsiValidated || imoValidated || regNumValidated);

                    if ((coordinates != null && coordinates.size() != toolEntry.getCoordinates().size())
                            || toolType != toolEntry.getToolType()
                            || (toolRemoved) == (toolEntry.getRemovedTime().isEmpty())
                            || (vesselName != null && !vesselName.equals(toolEntry.getVesselName()))
                            || (vesselPhoneNumber != null
                                    && !vesselPhoneNumber.equals(toolEntry.getVesselPhone()))
                            || (toolSetupDateTime != null
                                    && !toolSetupDateTime.equals(toolEntry.getSetupDateTime()))
                            || (vesselIrcsNumber != null && !vesselIrcsNumber.equals(toolEntry.getIRCS()))
                            || (vesselMmsiNumber != null && !vesselMmsiNumber.equals(toolEntry.getMMSI()))
                            || (vesselImoNumber != null && !vesselImoNumber.equals(toolEntry.getIMO()))
                            || (registrationNumber != null && !registrationNumber.equals(toolEntry.getRegNum()))
                            || (contactPersonName != null
                                    && !contactPersonName.equals(toolEntry.getContactPersonName()))
                            || (contactPersonPhone != null
                                    && !contactPersonPhone.equals(toolEntry.getContactPersonPhone()))
                            || (contactPersonEmail != null
                                    && !contactPersonEmail.equals(toolEntry.getContactPersonEmail()))
                            || (commentString != null && !commentString.equals(toolEntry.getComment()))) {
                        edited = true;
                    } else {
                        List<Point> points = toolEntry.getCoordinates();
                        for (int i = 0; i < coordinates.size(); i++) {
                            if (coordinates.get(i).getLatitude() != points.get(i).getLatitude()
                                    || coordinates.get(i).getLongitude() != points.get(i).getLongitude()) {
                                edited = true;
                                break;
                            }
                        }
                    }

                    if (edited) {
                        if (!minimumIdentificationFactorsMet) {
                            errorRow.setVisibility(!minimumIdentificationFactorsMet);
                            return;
                        }

                        Date lastChangedDate = new Date();
                        Date previousSetupDate = null;
                        SimpleDateFormat sdfSetupCompare = new SimpleDateFormat("yyyyMMdd",
                                Locale.getDefault());

                        String lastChangedDateString = sdfMilliSeconds.format(lastChangedDate).concat("Z");
                        sdfSetupCompare.setTimeZone(TimeZone.getTimeZone("UTC"));

                        try {
                            previousSetupDate = sdf.parse(toolEntry.getSetupDateTime()
                                    .substring(0, toolEntry.getSetupDateTime().length() - 1).concat(".000"));
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }

                        if (!sdfSetupCompare.format(previousSetupDate)
                                .equals(sdfSetupCompare.format(setupDate))) {
                            // TODO: setup date is changed, tool needs to be moved in log so the app does not crash when trying to delete tool.
                            //                                user.getToolLog().removeTool(toolEntry.getSetupDate(), toolEntry.getToolLogId());
                            //                                user.getToolLog().addTool(toolEntry, toolEntry.getSetupDateTime().substring(0, 10));
                            //                                user.writeToSharedPref(editButton.getContext());
                        }

                        ToolEntryStatus toolStatus = (toolRemoved ? ToolEntryStatus.STATUS_REMOVED_UNCONFIRMED
                                : (toolEntry.getToolStatus() == ToolEntryStatus.STATUS_UNREPORTED
                                        ? ToolEntryStatus.STATUS_UNREPORTED
                                        : ToolEntryStatus.STATUS_UNSENT));

                        toolEntry.setToolStatus(toolStatus);
                        toolEntry.setCoordinates(coordinates);
                        toolEntry.setToolType(toolType);
                        toolEntry.setVesselName(vesselName);
                        toolEntry.setVesselPhone(vesselPhoneNumber);
                        toolEntry.setSetupDateTime(toolSetupDateTime);
                        toolEntry.setRemovedTime(toolRemoved ? lastChangedDateString : null);
                        toolEntry.setComment(commentString);
                        toolEntry.setIRCS(vesselIrcsNumber);
                        toolEntry.setMMSI(vesselMmsiNumber);
                        toolEntry.setIMO(vesselImoNumber);
                        toolEntry.setRegNum(registrationNumber);
                        toolEntry.setLastChangedDateTime(lastChangedDateString);
                        toolEntry.setLastChangedBySource(lastChangedDateString);
                        toolEntry.setContactPersonName(contactPersonName);
                        toolEntry.setContactPersonPhone(contactPersonPhone);
                        toolEntry.setContactPersonEmail(contactPersonEmail);

                        try {
                            ImageView notificationView = (ImageView) ((View) editButton.getParent())
                                    .findViewById(R.id.tool_log_row_reported_image_view);

                            if (notificationView != null) {
                                notificationView.setVisibility(View.VISIBLE);
                                notificationView.setOnClickListener(new OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Toast.makeText(v.getContext(),
                                                R.string.notification_tool_unreported_changes,
                                                Toast.LENGTH_LONG).show();
                                    }
                                });
                            }

                            TextView dateTimeTextView = (TextView) ((View) editButton.getParent())
                                    .findViewById(R.id.tool_log_row_latest_date_text_view);
                            TextView toolTypeTextView = (TextView) ((View) editButton.getParent())
                                    .findViewById(R.id.tool_log_row_tool_type_text_view);
                            TextView positionTextView = (TextView) ((View) editButton.getParent())
                                    .findViewById(R.id.tool_log_row_tool_position_text_view);
                            StringBuilder sb = new StringBuilder();

                            sb.append(FiskInfoUtility
                                    .decimalToDMS((toolEntry.getCoordinates().get(0).getLatitude())));
                            sb.append(", ");
                            sb.append(FiskInfoUtility
                                    .decimalToDMS((toolEntry.getCoordinates().get(0).getLongitude())));

                            String coordinateString = sb.toString();
                            coordinateString = toolEntry.getCoordinates().size() < 2 ? coordinateString
                                    : coordinateString + "\n..";

                            sdfMilliSeconds.setTimeZone(TimeZone.getTimeZone("GMT+1"));
                            setupDateString = sdfMilliSeconds.format(setupDate);

                            dateTimeTextView.setText(setupDateString.substring(0, 16).replace("T", " "));
                            toolTypeTextView.setText(toolEntry.getToolType().toString());
                            positionTextView.setText(coordinateString);

                            Date toolDate;
                            Date currentDate = new Date();
                            try {
                                toolDate = sdf.parse(toolEntry.getSetupDateTime()
                                        .substring(0, toolEntry.getSetupDateTime().length() - 1)
                                        .concat(".000"));

                                long diff = currentDate.getTime() - toolDate.getTime();
                                double days = diff / updateButton.getContext().getResources()
                                        .getInteger(R.integer.milliseconds_in_a_day);

                                if (days > 14) {
                                    dateTimeTextView.setTextColor(ContextCompat
                                            .getColor(updateButton.getContext(), (R.color.error_red)));
                                } else {
                                    dateTimeTextView.setTextColor(toolTypeTextView.getCurrentTextColor());
                                }
                            } catch (ParseException e) {
                                e.printStackTrace();
                                return;
                            }
                        } catch (ClassCastException e) {
                            e.printStackTrace();
                        }

                        user.writeToSharedPref(updateButton.getContext());
                    } else {
                        Toast.makeText(editButton.getContext(), R.string.no_changes_made, Toast.LENGTH_LONG)
                                .show();
                    }

                    dialog.dismiss();
                }
            });

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

            dialog.show();
        }
    };
}

From source file:org.csp.everyaware.offline.Map.java

private void insertAnnDialog(final ExtendedLatLng annLatLng) {
    final Dialog insertDialog = new Dialog(Map.this);
    insertDialog.setContentView(R.layout.insert_dialog);
    insertDialog.getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    insertDialog.setTitle(R.string.annotation_insertion);
    insertDialog.setCancelable(false);/*from w  w  w  . jav a2 s  . c  o  m*/

    //get reference to send button
    final Button sendButton = (Button) insertDialog.findViewById(R.id.send_button);
    sendButton.setEnabled(false); //active only if there's text

    //get reference to cancel/close window button
    final Button cancelButton = (Button) insertDialog.findViewById(R.id.cancel_button);
    cancelButton.setEnabled(true); //active all time
    cancelButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            insertDialog.dismiss();
        }
    });

    //get reference to edittext in which user writes annotation
    final EditText editText = (EditText) insertDialog.findViewById(R.id.annotation_editText);
    editText.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //if modified text length is more than 0, activate send button
            if (s.length() > 0)
                sendButton.setEnabled(true);
            else
                sendButton.setEnabled(false);
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });

    //get checkbox references
    CheckBox facebookChBox = (CheckBox) insertDialog.findViewById(R.id.facebook_checkBox);
    CheckBox twitterChBox = (CheckBox) insertDialog.findViewById(R.id.twitter_checkBox);

    //activate check boxes depends from log in facebook/twitter
    boolean[] logs = new boolean[2];
    logs[0] = Utils.getValidFbSession(getApplicationContext());
    logs[1] = Utils.getValidTwSession(getApplicationContext());

    facebookChBox.setEnabled(logs[0]);
    twitterChBox.setEnabled(logs[1]);

    //checked on check boxes
    final boolean[] checkeds = Utils.getShareCheckedOn(getApplicationContext());
    if (checkeds[0] == true)
        facebookChBox.setChecked(true);
    else
        facebookChBox.setChecked(false);
    if (checkeds[1] == true)
        twitterChBox.setChecked(true);
    else
        twitterChBox.setChecked(false);

    facebookChBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton arg0, boolean checked) {
            Utils.setShareCheckedOn(checked, checkeds[1], getApplicationContext());
            checkeds[0] = checked;
        }
    });

    twitterChBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton arg0, boolean checked) {
            Utils.setShareCheckedOn(checkeds[0], checked, getApplicationContext());
            checkeds[1] = checked;
        }
    });

    //send annotation to server and on facebook/twitter if user is logged on 
    sendButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            //1 - read inserted annotation
            String annotation = editText.getText().toString();

            //2 - update record on db with annotation and save recordId            
            double recordId = annLatLng.mRecordId;

            int result = mDbManager.updateRecordAnnotation(recordId, annotation);

            if (result == 1)
                Toast.makeText(getApplicationContext(), "Updated record", Toast.LENGTH_LONG).show();
            else
                Toast.makeText(getApplicationContext(), "Error!", Toast.LENGTH_LONG).show();

            boolean[] checks = Utils.getShareCheckedOn(getApplicationContext());

            //3 - share on facebook is user wants and internet is active now
            if (checks[0] == true) {
                Record annotatedRecord = mDbManager.loadRecordById(recordId);
                try {
                    FacebookManager fb = FacebookManager.getInstance(null, null);
                    if (fb != null)
                        fb.postMessageOnWall(annotatedRecord);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            //4 - share on twitter is user wants and internet is active now
            if (checks[1] == true) {
                Record annotatedRecord = mDbManager.loadRecordById(recordId);

                try {
                    TwitterManager twManager = TwitterManager.getInstance(null);
                    twManager.postMessage(annotatedRecord);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            //5 - show marker for annotated record
            Record annotatedRecord = mDbManager.loadRecordById(recordId);

            String userAnn = annotatedRecord.mUserData1;

            if (!userAnn.equals("") && (annotatedRecord.mValues[0] != 0)) {
                BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.annotation_marker);
                Marker marker = mGoogleMap.addMarker(new MarkerOptions()
                        .position(new LatLng(annotatedRecord.mValues[0], annotatedRecord.mValues[1]))
                        .title("BC: " + String.valueOf(annotatedRecord.mBcMobile) + " "
                                + getResources().getString(R.string.micrograms))
                        .snippet("Annotation: " + userAnn).icon(icon).anchor(0f, 1f));
            }

            insertDialog.dismiss();
        }
    });

    insertDialog.show();
}

From source file:org.thoughtland.xlocation.ActivityApp.java

private void optionLegend() {
    // Show help//from  ww  w  .  ja  v  a  2 s  .co  m
    Dialog dialog = new Dialog(ActivityApp.this);
    dialog.requestWindowFeature(Window.FEATURE_LEFT_ICON);
    dialog.setTitle(R.string.menu_legend);
    dialog.setContentView(R.layout.legend);
    dialog.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, getThemed(R.attr.icon_launcher));

    ((ImageView) dialog.findViewById(R.id.imgHelpHalf)).setImageBitmap(getHalfCheckBox());
    ((ImageView) dialog.findViewById(R.id.imgHelpOnDemand)).setImageBitmap(getOnDemandCheckBox());

    for (View child : Util.getViewsByTag((ViewGroup) dialog.findViewById(android.R.id.content), "main"))
        child.setVisibility(View.GONE);

    ((LinearLayout) dialog.findViewById(R.id.llUnsafe))
            .setVisibility(PrivacyManager.cVersion3 ? View.VISIBLE : View.GONE);

    dialog.setCancelable(true);
    dialog.show();
}

From source file:de.cachebox_test.splash.java

@SuppressWarnings("deprecation")
@Override/*from  ww  w  .  j  av a  2  s  .  c o  m*/
protected void onStart() {
    super.onStart();
    Log.debug(log, "onStart");

    if (android.os.Build.VERSION.SDK_INT >= 23) {
        PermissionCheck.checkNeededPermissions(this);
    }

    // initial GDX
    Gdx.files = new AndroidFiles(this.getAssets(), this.getFilesDir().getAbsolutePath());
    // first, try to find stored preferences of workPath
    androidSetting = this.getSharedPreferences(Global.PREFS_NAME, 0);

    workPath = androidSetting.getString("WorkPath", Environment.getDataDirectory() + "/cachebox");
    boolean askAgain = androidSetting.getBoolean("AskAgain", true);
    showSandbox = androidSetting.getBoolean("showSandbox", false);

    Global.initTheme(this);
    Global.InitIcons(this);

    CB_Android_FileExplorer fileExplorer = new CB_Android_FileExplorer(this);
    PlatformConnector.setGetFileListener(fileExplorer);
    PlatformConnector.setGetFolderListener(fileExplorer);

    String LangPath = androidSetting.getString("Sel_LanguagePath", "");
    if (LangPath.length() == 0) {
        // set default lang

        String locale = Locale.getDefault().getLanguage();
        if (locale.contains("de")) {
            LangPath = "data/lang/de/strings.ini";
        } else if (locale.contains("cs")) {
            LangPath = "data/lang/cs/strings.ini";
        } else if (locale.contains("cs")) {
            LangPath = "data/lang/cs/strings.ini";
        } else if (locale.contains("fr")) {
            LangPath = "data/lang/fr/strings.ini";
        } else if (locale.contains("nl")) {
            LangPath = "data/lang/nl/strings.ini";
        } else if (locale.contains("pl")) {
            LangPath = "data/lang/pl/strings.ini";
        } else if (locale.contains("pt")) {
            LangPath = "data/lang/pt/strings.ini";
        } else if (locale.contains("hu")) {
            LangPath = "data/lang/hu/strings.ini";
        } else {
            LangPath = "data/lang/en-GB/strings.ini";
        }
    }

    new Translation(workPath, FileType.Internal);
    try {
        Translation.LoadTranslation(LangPath);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // check Write permission
    if (!askAgain) {
        if (!FileIO.checkWritePermission(workPath)) {
            askAgain = true;
            if (!ToastEx) {
                ToastEx = true;
                String WriteProtectionMsg = Translation.Get("NoWriteAcces");
                Toast.makeText(splash.this, WriteProtectionMsg, Toast.LENGTH_LONG).show();
            }
        }
    }

    if ((askAgain)) {
        // no saved workPath found -> search sd-cards and if more than 1 is found give the user the possibility to select one

        String externalSd = getExternalSdPath("/CacheBox");

        boolean hasExtSd;
        final String externalSd2 = externalSd;

        if (externalSd != null) {
            hasExtSd = (externalSd.length() > 0) && (!externalSd.equalsIgnoreCase(workPath));
        } else {
            hasExtSd = false;
        }

        // externe SD wurde gefunden != internal
        // oder Tablet Layout mglich
        // -> Auswahldialog anzeigen
        try {
            final Dialog dialog = new Dialog(context) {
                @Override
                public boolean onKeyDown(int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        splash.this.finish();
                    }
                    return super.onKeyDown(keyCode, event);
                }
            };

            dialog.setContentView(R.layout.sdselectdialog);
            TextView title = (TextView) dialog.findViewById(R.id.select_sd_title);
            title.setText(Translation.Get("selectWorkSpace") + "\n\n");
            /*
             * TextView tbLayout = (TextView) dialog.findViewById(R.id.select_sd_layout); tbLayout.setText("\nLayout"); final RadioGroup
             * rgLayout = (RadioGroup) dialog.findViewById(R.id.select_sd_radiogroup); final RadioButton rbHandyLayout = (RadioButton)
             * dialog.findViewById(R.id.select_sd_handylayout); final RadioButton rbTabletLayout = (RadioButton)
             * dialog.findViewById(R.id.select_sd_tabletlayout); rbHandyLayout.setText("Handy-Layout");
             * rbTabletLayout.setText("Tablet-Layout"); if (!GlobalCore.posibleTabletLayout) {
             * rgLayout.setVisibility(RadioGroup.INVISIBLE); rbHandyLayout.setChecked(true); } else { if (GlobalCore.isTab) {
             * rbTabletLayout.setChecked(true); } else { rbHandyLayout.setChecked(true); } }
             */
            final CheckBox cbAskAgain = (CheckBox) dialog.findViewById(R.id.select_sd_askagain);
            cbAskAgain.setText(Translation.Get("AskAgain"));
            cbAskAgain.setChecked(askAgain);
            Button buttonI = (Button) dialog.findViewById(R.id.button1);
            buttonI.setText("Internal SD\n\n" + workPath);
            buttonI.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // close select dialog
                    dialog.dismiss();

                    // show please wait dialog
                    showPleaseWaitDialog();

                    // use internal SD -> nothing to change
                    Thread thread = new Thread() {
                        @Override
                        public void run() {
                            boolean askAgain = cbAskAgain.isChecked();
                            // boolean useTabletLayout = rbTabletLayout.isChecked();
                            saveWorkPath(askAgain/* , useTabletLayout */);
                            dialog.dismiss();
                            startInitial();
                        }
                    };
                    thread.start();
                }
            });
            Button buttonE = (Button) dialog.findViewById(R.id.button2);
            final boolean isSandbox = externalSd == null ? false
                    : externalSd.contains("Android/data/de.cachebox_test");
            if (!hasExtSd) {
                buttonE.setVisibility(Button.INVISIBLE);
            } else {
                String extSdText = isSandbox ? "External SD SandBox\n\n" : "External SD\n\n";
                buttonE.setText(extSdText + externalSd);
            }

            buttonE.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // show KitKat Massage?

                    if (isSandbox && !showSandbox) {
                        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

                        // set title
                        alertDialogBuilder.setTitle("KitKat Sandbox");

                        // set dialog message
                        alertDialogBuilder.setMessage(Translation.Get("Desc_Sandbox")).setCancelable(false)
                                .setPositiveButton(Translation.Get("yes"),
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int id) {
                                                // if this button is clicked, run Sandbox Path

                                                showSandbox = true;
                                                Config.AcceptChanges();

                                                // close select dialog
                                                dialog.dismiss();

                                                // show please wait dialog
                                                showPleaseWaitDialog();

                                                // use external SD -> change workPath
                                                Thread thread = new Thread() {
                                                    @Override
                                                    public void run() {
                                                        workPath = externalSd2;
                                                        boolean askAgain = cbAskAgain.isChecked();
                                                        // boolean useTabletLayout = rbTabletLayout.isChecked();
                                                        saveWorkPath(askAgain/* , useTabletLayout */);
                                                        startInitial();
                                                    }
                                                };
                                                thread.start();
                                            }
                                        })
                                .setNegativeButton(Translation.Get("no"),
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int id) {
                                                // if this button is clicked, just close
                                                // the dialog box and do nothing
                                                dialog.cancel();
                                            }
                                        });

                        // create alert dialog
                        AlertDialog alertDialog = alertDialogBuilder.create();

                        // show it
                        alertDialog.show();
                    } else {
                        // close select dialog
                        dialog.dismiss();

                        // show please wait dialog
                        showPleaseWaitDialog();

                        // use external SD -> change workPath
                        Thread thread = new Thread() {
                            @Override
                            public void run() {
                                workPath = externalSd2;
                                boolean askAgain = cbAskAgain.isChecked();
                                // boolean useTabletLayout = rbTabletLayout.isChecked();
                                saveWorkPath(askAgain/* , useTabletLayout */);
                                startInitial();
                            }
                        };
                        thread.start();
                    }
                }
            });

            LinearLayout ll = (LinearLayout) dialog.findViewById(R.id.scrollViewLinearLayout);

            // add all Buttons for created Workspaces

            AdditionalWorkPathArray = getAdditionalWorkPathArray();

            for (final String AddWorkPath : AdditionalWorkPathArray) {

                final String Name = FileIO.GetFileNameWithoutExtension(AddWorkPath);

                if (!FileIO.checkWritePermission(AddWorkPath)) {
                    // delete this Work Path
                    deleteWorkPath(AddWorkPath);
                    continue;
                }

                Button buttonW = new Button(context);
                buttonW.setText(Name + "\n\n" + AddWorkPath);

                buttonW.setOnLongClickListener(new OnLongClickListener() {

                    @Override
                    public boolean onLongClick(View v) {

                        // setting the MassageBox then the UI_sizes are not initial in this moment
                        Resources res = splash.this.getResources();
                        float scale = res.getDisplayMetrics().density;
                        float calcBase = 533.333f * scale;

                        FrameLayout frame = (FrameLayout) findViewById(R.id.frameLayout1);
                        int width = frame.getMeasuredWidth();
                        int height = frame.getMeasuredHeight();

                        MessageBox.Builder.WindowWidth = width;
                        MessageBox.Builder.WindowHeight = height;
                        MessageBox.Builder.textSize = (calcBase
                                / res.getDimensionPixelSize(R.dimen.BtnTextSize)) * scale;
                        MessageBox.Builder.ButtonHeight = (int) (50 * scale);

                        // Ask before delete
                        msg = (MessageBox) MessageBox.Show(Translation.Get("shuredeleteWorkspace", Name),
                                Translation.Get("deleteWorkspace"), MessageBoxButtons.YesNo,
                                MessageBoxIcon.Question, new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        if (which == MessageBox.BUTTON_POSITIVE) {
                                            // Delete this Workpath only from Settings don't delete any File
                                            deleteWorkPath(AddWorkPath);
                                        }
                                        // Start again to exclude the old Folder
                                        msg.dismiss();
                                        onStart();
                                    }

                                });

                        dialog.dismiss();
                        return true;
                    }
                });

                buttonW.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // close select dialog
                        dialog.dismiss();

                        // show please wait dialog
                        showPleaseWaitDialog();

                        // use external SD -> change workPath
                        Thread thread = new Thread() {
                            @Override
                            public void run() {
                                workPath = AddWorkPath;
                                boolean askAgain = cbAskAgain.isChecked();
                                // boolean useTabletLayout = rbTabletLayout.isChecked();
                                saveWorkPath(askAgain/* , useTabletLayout */);
                                startInitial();
                            }
                        };
                        thread.start();

                    }
                });

                ll.addView(buttonW);
            }

            Button buttonC = (Button) dialog.findViewById(R.id.buttonCreateWorkspace);
            buttonC.setText(Translation.Get("createWorkSpace"));
            buttonC.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // close select dialog
                    dialog.dismiss();
                    getFolderReturnListener = new IgetFolderReturnListener() {

                        @Override
                        public void getFolderReturn(String Path) {
                            if (FileIO.checkWritePermission(Path)) {

                                AdditionalWorkPathArray.add(Path);
                                writeAdditionalWorkPathArray(AdditionalWorkPathArray);
                                // Start again to include the new Folder
                                onStart();
                            } else {
                                String WriteProtectionMsg = Translation.Get("NoWriteAcces");
                                Toast.makeText(splash.this, WriteProtectionMsg, Toast.LENGTH_LONG).show();
                            }
                        }
                    };

                    PlatformConnector.getFolder("", Translation.Get("select_folder"), Translation.Get("select"),
                            getFolderReturnListener);

                }
            });

            dialog.show();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    } else {
        if (GlobalCore.displayType == DisplayType.Large || GlobalCore.displayType == DisplayType.xLarge)
            GlobalCore.isTab = isLandscape;

        // restore the saved workPath
        // test whether workPath is available by checking the free size on the SD
        String workPathToTest = workPath.substring(0, workPath.lastIndexOf("/"));
        long bytesAvailable = 0;
        try {
            StatFs stat = new StatFs(workPathToTest);
            bytesAvailable = (long) stat.getBlockSize() * (long) stat.getBlockCount();
        } catch (Exception ex) {
            bytesAvailable = 0;
        }
        if (bytesAvailable == 0) {
            // there is a workPath stored but this workPath is not available at the moment (maybe SD is removed)
            Toast.makeText(splashActivity,
                    "WorkPath " + workPath + " is not available!\nMaybe SD-Card is removed?", Toast.LENGTH_LONG)
                    .show();
            finish();
            return;
        }

        startInitial();
    }

}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

public static void view_showAboutDialog(Context context, int titleResourceId, int aboutLayout, int okButtonId) {
    final Dialog dialog = new Dialog(context);
    dialog.setContentView(aboutLayout);/*from   www.  ja va  2s  .  co m*/
    dialog.setTitle(titleResourceId);

    Button dialogButton = (Button) dialog.findViewById(okButtonId);
    dialogButton.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            dialog.dismiss();
        }
    });

    dialog.show();
}

From source file:co.taqat.call.LinphoneActivity.java

public Dialog displayDialog(String text) {
    Dialog dialog = new Dialog(this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    Drawable d = new ColorDrawable(ContextCompat.getColor(this, R.color.colorC));
    d.setAlpha(200);/*from  ww  w  .  ja v a 2  s. c o m*/
    dialog.setContentView(R.layout.dialog);
    dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.MATCH_PARENT);
    dialog.getWindow().setBackgroundDrawable(d);

    TextView customText = (TextView) dialog.findViewById(R.id.customText);
    customText.setText(text);
    return dialog;
}

From source file:com.sentaroh.android.TaskAutomation.Config.ProfileMaintenanceActionProfile.java

final static private void editDataArrayListItem(final GlobalParameters mGlblParms, final String edit_data,
        final int pos) {
    final Dialog dialog = new Dialog(mGlblParms.context);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    //      dialog.getWindow().setSoftInputMode(
    //                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    dialog.setContentView(R.layout.data_array_item_edit_dlg);
    //      final TextView dlg_msg = (TextView) dialog.findViewById(R.id.data_array_item_edit_dlg_msg);
    final TextView dlg_title = (TextView) dialog.findViewById(R.id.data_array_item_edit_dlg_title);
    dlg_title.setText("Edit data");
    final EditText dlg_value = (EditText) dialog.findViewById(R.id.data_array_item_edit_dlg_value);
    final Button dlg_apply = (Button) dialog.findViewById(R.id.data_array_item_edit_dlg_apply);
    final Button dlg_cancel = (Button) dialog.findViewById(R.id.data_array_item_edit_dlg_cancel);

    //      CommonDialog.setDlgBoxSizeCompact(dialog);

    dlg_value.setText(edit_data);/* w w  w.jav a 2  s .co m*/

    // CANCEL?
    dlg_cancel.setOnClickListener(new View.OnClickListener() {
        final public void onClick(View v) {
            mGlblParms.actionCompareDataAdapter.getItem(pos).while_edit = false;
            mGlblParms.actionCompareDataAdapter.notifyDataSetChanged();
            dialog.dismiss();
        }
    });
    // Apply?
    dlg_apply.setOnClickListener(new View.OnClickListener() {
        final public void onClick(View v) {
            mGlblParms.actionCompareDataAdapter.getItem(pos).while_edit = false;
            mGlblParms.actionCompareDataAdapter.getItem(pos).data_value = dlg_value.getText().toString();
            mGlblParms.actionCompareDataAdapter.notifyDataSetChanged();
            dialog.dismiss();
        }
    });
    // Cancel?
    dialog.setOnCancelListener(new Dialog.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface arg0) {
            dlg_cancel.performClick();
        }
    });
    //      dialog.setCancelable(false);
    dialog.show();
}