Example usage for android.text Editable toString

List of usage examples for android.text Editable toString

Introduction

In this page you can find the example usage for android.text Editable toString.

Prototype

public String toString();

Source Link

Document

Returns a string containing the characters in this sequence in the same order as this sequence.

Usage

From source file:com.dirkgassen.wator.ui.fragment.NewWorld.java

/**
 * Checks the given text for validity: the text must not be empty and the value must be between {@code min} and
 * {@code max}. If the text is not valid one of the given string resources is loaded and set as the error text
 * on the given {@link EditText}.//from   w ww . j a v  a 2  s .c om
 *
 * This method can be called to validate the text from a {@link AfterTextWatcher}.
 *
 * @param inputNo index into the {@link #inputs} array that specifies which {@link EditText} is being validated
 * @param s       the text entered and to be verified
 * @param min     minimum value to check for
 * @param max     maximum value to check for
 * @param emptyErrorResourceId string resource ID for the error when the text is empty
 * @param minErrorResourceId string resource ID for the error when the text is a value that is smaller than {@code min}
 * @param maxErrorResourceId string resource ID for the error when the text is a value that is larger than {@code max}
 * @return        {@code true} if the entered text is valid; {@code false} otherwise
 */
private boolean doMinMaxCheck(int inputNo, Editable s, int min, int max, @StringRes int emptyErrorResourceId,
        @StringRes int minErrorResourceId, @StringRes int maxErrorResourceId) {
    if (s.length() == 0) {
        inputs[inputNo].setError(getString(emptyErrorResourceId));
        return false;
    }
    int value = Integer.valueOf(s.toString());
    if (value < min) {
        inputs[inputNo].setError(getString(minErrorResourceId, min));
        return false;
    } else if (value > max) {
        inputs[inputNo].setError(getString(maxErrorResourceId, max));
        return false;
    } else {
        inputs[inputNo].setError(null);
        return true;
    }
}

From source file:com.dirkgassen.wator.ui.fragment.NewWorld.java

/**
 * Validate the "initial fish count" {@link EditText}. The text is already provided as a parameter.
 *
 * If the text is valid the "initial shark count" {@link EditText} is validated as well to eventually remove an
 * error that previously existed (e.g., number of initial fish was reduced so that the number of shark are now valid).
 *
 * Note that the "initial shark count" {@link EditText} is not validated if the text is invalid to not add
 * an error message to the "initial shark count" {@link EditText} if this text value is invalid.
 *
 * @param s         text of the "initial fish count" {@link EditText}
 * @param worldSize size of the world/*from w  w  w.  java  2s.co  m*/
 */
private void validateInitialSharkCount(Editable s, int worldSize) {
    if (s.length() == 0) {
        inputs[INITIAL_SHARK_COUNT_INPUT].setError(getString(R.string.initial_shark_count_empty_error));
    } else {
        Editable fishCountEditable = inputs[INITIAL_FISH_COUNT_INPUT].getText();
        int initialSharkValue = Integer.valueOf(s.toString());
        int initialFishValue = fishCountEditable.length() == 0 ? 0
                : Integer.valueOf(fishCountEditable.toString());
        int max = worldSize - initialFishValue;
        if (max < 0) {
            max = 0;
        }
        if (initialSharkValue > max) {
            inputs[INITIAL_SHARK_COUNT_INPUT].setError(getString(R.string.too_many_shark_error, max));
        } else {
            inputs[INITIAL_SHARK_COUNT_INPUT].setError(null);
            if (fishCountEditable.length() > 0 && initialFishValue < worldSize - initialSharkValue) {
                inputs[INITIAL_FISH_COUNT_INPUT].setError(null);
            }
        }
    }
}

From source file:es.usc.citius.servando.calendula.fragments.MedicineCreateOrEditFragment.java

private void enableSearchButton() {
    searchButton.setVisibility(View.VISIBLE);
    searchButton.setOnClickListener(new View.OnClickListener() {
        @Override/*from  w  w w  . ja  v  a2  s  . c o  m*/
        public void onClick(View v) {
            Editable editable = mNameTextView.getText();
            ((MedicinesActivity) getActivity()).showSearchView(editable != null ? editable.toString() : null);
        }
    });
}

From source file:com.digi.android.wva.fragments.EndpointOptionsDialog.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    if (mConfig == null && savedInstanceState == null) {
        Log.e(TAG, "mConfig is null, not showing dialog!");
        return null;
    }//from   www .jav a2 s . co  m

    LayoutInflater inf = getActivity().getLayoutInflater();
    View v = inf.inflate(R.layout.dialog_endpoint_options, null);

    // Suppresses warnings, and ensures the layout exists.
    assert v != null;
    final TextView subIntervalTV = (TextView) v.findViewById(R.id.textView_interval);
    final TextView alarmInfoTV = (TextView) v.findViewById(R.id.alarm_info);
    final CheckBox subscribedCB = (CheckBox) v.findViewById(R.id.subscribedCheckbox);
    final CheckBox alarmCB = (CheckBox) v.findViewById(R.id.alarmCheckbox);
    final EditText subInterval = (EditText) v.findViewById(R.id.subscriptionInterval);
    final EditText alarmThreshold = (EditText) v.findViewById(R.id.alarmThreshold);
    final Spinner typeSpinner = (Spinner) v.findViewById(R.id.alarmTypeSpinner);
    final LinearLayout makeAlarmSection = (LinearLayout) v.findViewById(R.id.section_make_alarm);
    final LinearLayout showAlarmSection = (LinearLayout) v.findViewById(R.id.section_show_alarm);
    final CheckBox dcSendCB = (CheckBox) v.findViewById(R.id.dcPushCheckbox);

    String alarmInfo = "No alarm yet";
    boolean isSubscribed = false;
    String endpointName = "UNKNOWN";
    int sinterval = 10;
    boolean alarmCreated = false;
    double threshold = 0;
    int alarmtypeidx = 0;

    boolean isSendingToDC = false;

    if (savedInstanceState != null && savedInstanceState.containsKey("config")) {
        mConfig = savedInstanceState.getParcelable("config");
    }

    if (mConfig != null) {
        endpointName = mConfig.getEndpoint();
        alarmInfo = mConfig.getAlarmSummary();

        if (mConfig.getSubscriptionConfig() != null) {
            isSubscribed = mConfig.getSubscriptionConfig().isSubscribed();
            sinterval = mConfig.getSubscriptionConfig().getInterval();
            isSendingToDC = mConfig.shouldBePushedToDeviceCloud();
        } else {
            // Not subscribed; default interval value from preferences.
            String i = PreferenceManager.getDefaultSharedPreferences(getActivity())
                    .getString("pref_default_interval", "0");
            try {
                sinterval = Integer.parseInt(i);
            } catch (NumberFormatException e) {
                Log.d(TAG, "Failed to parse default interval from preferences: " + i);
                sinterval = 0;
            }
        }

        if (mConfig.getAlarmConfig() != null) {
            alarmCreated = mConfig.getAlarmConfig().isCreated();
            threshold = mConfig.getAlarmConfig().getThreshold();
            String typestr = AlarmType.makeString(mConfig.getAlarmConfig().getType());
            for (int i = 0; i < alarmTypes.length; i++) {
                if (alarmTypes[i].toLowerCase(Locale.US).equals(typestr))
                    alarmtypeidx = i;
            }
        }
    }

    // Set up event listeners on EditText and CheckBox items

    subscribedCB.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            subInterval.setEnabled(isChecked);
            subIntervalTV.setEnabled(isChecked);
        }
    });

    alarmCB.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            typeSpinner.setEnabled(isChecked);
            alarmThreshold.setEnabled(false);
            // If type spinner is set to Change, we want threshold disabled again
            if (isChecked) {
                alarmThreshold.setEnabled(!shouldDisableAlarmThreshold(typeSpinner.getSelectedItemPosition()));
            }
        }
    });

    typeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
            if (alarmCB.isChecked() && shouldDisableAlarmThreshold(position))
                alarmThreshold.setEnabled(false);
            else if (!alarmCB.isChecked())
                alarmThreshold.setEnabled(false);
            else
                alarmThreshold.setEnabled(true);
        }

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

    subIntervalTV.setEnabled(false);
    subInterval.setEnabled(false);
    alarmThreshold.setEnabled(false);
    typeSpinner.setEnabled(false);
    alarmInfoTV.setText(alarmInfo);

    // Click checkboxes, show data depending on if subscription or alarm
    // has been added already
    if (isSubscribed)
        subscribedCB.performClick();
    if (alarmCreated) {
        showAlarmSection.setVisibility(View.VISIBLE);
        makeAlarmSection.setVisibility(View.GONE);
        alarmCB.setText("Remove alarm");
    } else {
        makeAlarmSection.setVisibility(View.VISIBLE);
        showAlarmSection.setVisibility(View.GONE);
        alarmCB.setText("Create alarm");
    }

    dcSendCB.setChecked(isSendingToDC);

    subInterval.setText(Integer.toString(sinterval));

    alarmThreshold.setText(Double.toString(threshold));

    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.alarm_types,
            android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    typeSpinner.setAdapter(adapter);
    typeSpinner.setSelection(alarmtypeidx);

    DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int i) {
            // Fetch the EndpointsAdapter's configuration for this endpoint.
            // (We might have gotten mConfig from the saved instance bundle)
            EndpointConfiguration cfg = EndpointsAdapter.getInstance()
                    .findEndpointConfiguration(mConfig.getEndpoint());

            // Set whether this endpoint's data should be pushed to Device Cloud
            if (cfg != null) {
                cfg.setPushToDeviceCloud(dcSendCB.isChecked());
            }

            // Handle (un)subscribing

            if (isUnsubscribing(subscribedCB.isChecked())) {
                unsubscribe(mConfig.getEndpoint());
            } else if (subscribedCB.isChecked()) {
                if (handleMakingSubscription(subInterval)) {
                    // Subscription was successful... most likely.
                    Log.d(TAG, "Probably subscribed to endpoint.");
                } else {
                    // Invalid interval.
                    Toast.makeText(getActivity(),
                            getString(R.string.configure_endpoints_toast_invalid_sub_interval),
                            Toast.LENGTH_SHORT).show();
                }
            }

            // Handle adding/removing alarm as necessary

            if (isRemovingAlarm(alarmCB.isChecked())) {
                removeAlarm(mConfig.getEndpoint(), mConfig.getAlarmConfig().getType());
            } else if (alarmCB.isChecked()) {
                Editable thresholdText = alarmThreshold.getText();
                String thresholdString;
                if (thresholdText == null)
                    thresholdString = "";
                else
                    thresholdString = thresholdText.toString();

                double threshold;
                try {
                    threshold = Double.parseDouble(thresholdString);
                } catch (NumberFormatException e) {
                    Toast.makeText(getActivity(), getString(R.string.configure_endpoints_invalid_threshold),
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                int alarmidx = typeSpinner.getSelectedItemPosition();
                if (alarmidx == -1) {
                    // But... how?
                    Log.wtf(TAG, "alarm type index -1 ?");
                    return;
                }
                String type = alarmTypes[alarmidx];
                AlarmType atype = AlarmType.fromString(type);

                createAlarm(mConfig.getEndpoint(), atype, threshold);
            }

            dialog.dismiss();
        }
    };

    return new AlertDialog.Builder(getActivity()).setView(v).setTitle("Endpoint: " + endpointName)
            .setPositiveButton("Save", clickListener)
            .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // Cancel means just dismiss the dialog.
                    dialog.dismiss();
                }
            }).create();
}

From source file:com.wart.magister.SelectSchoolActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_select_school);
    // Display the Actionbar arrow
    getActionBar().setDisplayHomeAsUpEnabled(false);

    ((EditText) findViewById(R.id.select_school_edittext)).addTextChangedListener(new TextWatcher() {
        @Override//  w  ww . ja  v a 2 s .  c o  m
        public void afterTextChanged(Editable e) {
            if (e.length() > 0) {
                showProgress(true);
                if (mRetrieveSchoolsRequest != null && !mRetrieveSchoolsRequest.isFinished())
                    mRetrieveSchoolsRequest.cancel(true);
                mRetrieveSchoolsRequest = Global.AsyncHttpClient.get(
                        "http://app.schoolmaster.nl/schoolLicentieService.asmx/Search?term="
                                + e.toString().replace(" ", "%20").toLowerCase().trim(),
                        new TextHttpResponseHandler() {
                            @Override
                            public void onSuccess(int statusCode, Header[] headers, String responseBody) {
                                try {
                                    SAXParserFactory factory = SAXParserFactory.newInstance();
                                    SAXParser saxParser = factory.newSAXParser();

                                    mRetrievedSchools.clear();
                                    DefaultHandler handler = new DefaultHandler() {
                                        private String currentValue;
                                        private School currentSchool;

                                        @Override
                                        public void characters(char ch[], int start, int length)
                                                throws SAXException {
                                            currentValue = new String(ch, start, length);
                                        }

                                        @Override
                                        public void endElement(String uri, String localName, String qName)
                                                throws SAXException {
                                            if (qName.equalsIgnoreCase("medius"))
                                                currentSchool.URL = currentValue;
                                            else if (qName.equalsIgnoreCase("licentie"))
                                                currentSchool.License = currentValue;
                                        }

                                        @Override
                                        public void startElement(String uri, String localName, String qName,
                                                Attributes attributes) throws SAXException {
                                            if (qName.equalsIgnoreCase("school")) {
                                                currentSchool = new School();
                                                mRetrievedSchools.add(currentSchool);
                                            }
                                        }
                                    };
                                    saxParser.parse(new InputSource(new StringReader(responseBody)), handler);

                                    String[] names = new String[mRetrievedSchools.size()];
                                    for (int i = 0; i < mRetrievedSchools.size(); i++)
                                        names[i] = mRetrievedSchools.get(i).License;

                                    mSchoolsList.setAdapter(new ArrayAdapter<String>(SelectSchoolActivity.this,
                                            android.R.layout.simple_list_item_1, names));
                                } catch (Exception e) {
                                    Log.e(TAG, "Error in onSuccess", e);
                                }
                            }

                            @Override
                            public void onFailure(String responseBody, Throwable error) {
                                mSchoolsList.setAdapter(null);
                                Log.e(TAG, "Retrieving schools failed", error);
                            }

                            @Override
                            public void onFinish() {
                                showProgress(false);
                            }
                        });
            }
        }

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

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });

    mSchoolsList = (ListView) findViewById(R.id.select_school_listview);
    mSchoolsList.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (mTestMediusRequest != null && !mTestMediusRequest.isFinished())
                mTestMediusRequest.cancel(true);
            ((TextView) findViewById(R.id.select_school_status_message)).setText("Testing school...");
            showProgress(true);

            Data.set(Data.MEDIUSURL, Data.buildMediusUrl(mRetrievedSchools.get(position).URL));
            Log.v(TAG, "posting to " + Data.getString(Data.MEDIUSURL));
            byte[] request = new byte[54];
            request[0] = 0x52;
            request[1] = 0x4f;
            request[2] = 49;
            request[3] = 48;
            request[4] = 55;
            request[12] = 95;
            request[13] = -38;
            request[14] = -109;
            request[15] = 13;
            request[16] = -14;
            request[17] = 92;
            request[18] = 7;
            request[19] = 86;
            request[20] = -77;
            request[21] = -23;
            request[22] = 9;
            request[23] = 22;
            request[24] = 71;
            request[25] = -53;
            request[26] = -81;
            request[27] = 45;
            request[28] = 5;
            request[32] = 76;
            request[33] = 111;
            request[34] = 103;
            request[35] = 105;
            request[36] = 110;
            request[37] = 13;
            request[41] = 71;
            request[42] = 101;
            request[43] = 116;
            request[44] = 83;
            request[45] = 99;
            request[46] = 104;
            request[47] = 111;
            request[48] = 111;
            request[49] = 108;
            request[50] = 78;
            request[51] = 97;
            request[52] = 109;
            request[53] = 101;

            Log.i(TAG, "Testing the url...");
            mTestMediusRequest = Global.AsyncHttpClient.post(SelectSchoolActivity.this,
                    Data.getString(Data.MEDIUSURL), new ByteArrayEntity(request), "text/html",
                    new BinaryHttpResponseHandler(new String[] { "text/html" }) {
                        @Override
                        public void onSuccess(byte[] binaryData) {

                            if (binaryData != null) {
                                Log.i(TAG, "Received " + binaryData.length + " bytes of data");
                                Serializer s = new Serializer(binaryData);
                                try {
                                    if (s.readROHeader(null, "login", "getschoolname")) {
                                        Data.set(Data.LICENSE, s.readString());
                                        MediusCall.setLicense(Data.getString(Data.LICENSE));
                                    } else
                                        Log.e(TAG, "Geblokkeerd door webserver");
                                } catch (Exception e) {
                                    Log.e(TAG, "Error in TestMedius.onSuccess", e);
                                }
                                Log.i(TAG, "Succesfully tested the medius");
                                SelectSchoolActivity.this.startActivity(
                                        new Intent(SelectSchoolActivity.this, LoginActivity.class));
                            } else
                                Log.e(TAG, "TestMedius timed out");
                        }

                        @Override
                        public void onFailure(int statusCode, Header[] headers, byte[] binaryData,
                                Throwable error) {
                            Log.e(TAG, "Error in TestMedius.onFaillure", error);
                        }

                        @Override
                        public void onFinish() {
                            showProgress(false);
                        }
                    });
        }
    });
    mSearchLayout = (LinearLayout) findViewById(R.id.select_school_status_layout);
}

From source file:edu.cens.loci.ui.widget.GenericEditorView.java

/**
 * Prepare this editor using the given {@link DataKind} for defining
 * structure and {@link ValuesDelta} describing the content to edit.
 */// ww w.j  a  v  a  2s .c om
public void setValues(DataKind kind, ValuesDelta entry, EntityDelta state, boolean readOnly,
        ViewIdGenerator vig) {
    mKind = kind;
    mEntry = entry;
    mState = state;
    mReadOnly = readOnly;
    mViewIdGenerator = vig;

    setId(vig.getId(state, kind, entry, ViewIdGenerator.NO_VIEW_INDEX));

    final boolean enabled = !readOnly;

    //Log.d(TAG, "setValues: kind=" + mKind.mimeType);

    if (!entry.isVisible()) {
        // Hide ourselves entirely if deleted
        setVisibility(View.GONE);
        return;
    } else {
        setVisibility(View.VISIBLE);
    }

    // Display label selector if multiple types available
    final boolean hasTypes = EntityModifier.hasEditTypes(kind);
    mLabel.setVisibility(hasTypes ? View.VISIBLE : View.GONE);
    mLabel.setEnabled(enabled);
    if (hasTypes) {
        mType = EntityModifier.getCurrentType(entry, kind);
        rebuildLabel();
    }

    // Build out set of fields
    mFields.removeAllViews();
    boolean hidePossible = false;
    int n = 0;

    if (mKind.mimeType.equals(WifiFingerprint.CONTENT_ITEM_TYPE)) {

        //Log.d(TAG, "setValues: Wifi");

        for (EditField field : kind.fieldList) {
            Button fieldView = (Button) mInflater.inflate(RES_WIFI_FIELD, mFields, false);

            mWifiFieldButtonId = vig.getId(state, kind, entry, n++);

            fieldView.setId(mWifiFieldButtonId);

            final String column = field.column;
            final String value = entry.getAsString(column);
            fieldView.setText("Fingerprint on " + MyDateUtils.getAbrv_MMM_d_h_m(new Long(value)));

            final String extra1column = field.extra1;
            final String extra1value = entry.getAsString(extra1column);
            try {
                mWifiFingerprint = new LociWifiFingerprint(extra1value);
                mWifiFingerprintTimeStamp = MyDateUtils.getDateFormatLong(new Long(value));
            } catch (JSONException e) {
                MyLog.e(LociConfig.D.JSON, TAG, "LociWifiFingerprint parsing failed");
                e.printStackTrace();
            }

            // Hide field when empty and optional value
            final boolean couldHide = (field.optional);
            final boolean willHide = (mHideOptional && couldHide);
            fieldView.setVisibility(willHide ? View.GONE : View.VISIBLE);
            fieldView.setEnabled(enabled);
            hidePossible = hidePossible || couldHide;

            fieldView.setOnClickListener(this);

            mFields.addView(fieldView);
        }
    } else if (mKind.mimeType.equals(Keyword.CONTENT_ITEM_TYPE)) {

        //Log.d(TAG, "setValues: Keywords");

        for (EditField field : kind.fieldList) {

            AutoCompleteTextView fieldView = (AutoCompleteTextView) mInflater.inflate(RES_AUTOCOMPLETE_FIELD,
                    mFields, false);
            fieldView.setId(vig.getId(state, kind, entry, n++));
            if (field.titleRes > 0) {
                fieldView.setHint(field.titleRes);
            }
            int inputType = field.inputType;
            fieldView.setInputType(inputType);
            fieldView.setMinLines(field.minLines);

            // Read current value from state
            final String column = field.column;
            final String value = entry.getAsString(column);
            fieldView.setText(value);

            // Prepare listener for writing changes
            fieldView.addTextChangedListener(new TextWatcher() {
                public void afterTextChanged(Editable s) {
                    // Trigger event for newly changed value
                    onFieldChanged(column, s.toString());
                }

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

                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }
            });

            // Hide field when empty and optional value
            final boolean couldHide = (field.optional);
            final boolean willHide = (mHideOptional && couldHide);
            fieldView.setVisibility(willHide ? View.GONE : View.VISIBLE);
            fieldView.setEnabled(enabled);
            hidePossible = hidePossible || couldHide;

            String[] usedKeywords = getResources().getStringArray(R.array.keyword_default);

            LociDbUtils myDb = new LociDbUtils(getContext());
            ArrayList<String> suggestedKeywords = myDb.getSavedKeywords();
            HashSet<String> suggestedKeywordsSet = new HashSet<String>();

            for (String keyword : suggestedKeywords) {
                suggestedKeywordsSet.add(keyword);
            }

            //Log.d(TAG, "size of usedKeywords : " + usedKeywords.length);
            //Log.d(TAG, "size of suggestedKeywords : " + suggestedKeywords.size());

            for (String usedKeyword : usedKeywords) {
                if (!suggestedKeywordsSet.contains(usedKeyword))
                    suggestedKeywords.add(usedKeyword);
            }

            //Log.d(TAG, "size of suggestedKeywords : " + suggestedKeywords.size());

            Collections.sort(suggestedKeywords);

            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getContext(),
                    R.layout.item_suggestion_list, suggestedKeywords);
            fieldView.setAdapter(adapter);
            fieldView.setThreshold(0);

            mFields.addView(fieldView);
        }

    } else {

        //Log.d(TAG, "General Types...");

        for (EditField field : kind.fieldList) {
            // Inflate field from definition
            EditText fieldView = (EditText) mInflater.inflate(RES_FIELD, mFields, false);
            fieldView.setId(vig.getId(state, kind, entry, n++));
            if (field.titleRes > 0) {
                fieldView.setHint(field.titleRes);
            }
            int inputType = field.inputType;
            fieldView.setInputType(inputType);
            if (inputType == InputType.TYPE_CLASS_PHONE) {
                fieldView.addTextChangedListener(new PhoneNumberFormattingTextWatcher());
            }
            fieldView.setMinLines(field.minLines);

            // Read current value from state
            final String column = field.column;
            final String value = entry.getAsString(column);
            fieldView.setText(value);

            //Log.d(TAG, "setValues: column=" + column);
            //Log.d(TAG, "setValues: value=" + value);

            // Prepare listener for writing changes
            fieldView.addTextChangedListener(new TextWatcher() {
                public void afterTextChanged(Editable s) {
                    // Trigger event for newly changed value
                    onFieldChanged(column, s.toString());
                }

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

                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }
            });

            // Hide field when empty and optional value
            final boolean couldHide = (field.optional);
            final boolean willHide = (mHideOptional && couldHide);
            fieldView.setVisibility(willHide ? View.GONE : View.VISIBLE);
            fieldView.setEnabled(enabled);
            hidePossible = hidePossible || couldHide;

            mFields.addView(fieldView);
        }
    }

    // When hiding fields, place expandable
    if (hidePossible) {
        mMore.setVisibility(mHideOptional ? View.VISIBLE : View.GONE);
        mLess.setVisibility(mHideOptional ? View.GONE : View.VISIBLE);
    } else {
        mMore.setVisibility(View.GONE);
        mLess.setVisibility(View.GONE);
    }
    mMore.setEnabled(enabled);
    mLess.setEnabled(enabled);
}

From source file:com.bloodtolife.bloodapp.CommentsFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_comments, container, false);
    db = new SQLiteHandler(getActivity());

    RecyclerView mCommentsView = (RecyclerView) rootView.findViewById(R.id.comment_list);
    mEditText = (EditText) rootView.findViewById(R.id.editText);
    final Button sendButton = (Button) rootView.findViewById(R.id.send_comment);

    final DatabaseReference commentsRef = FirebaseUtil.getCommentsRef().child(mPostRef);
    mAdapter = new FirebaseRecyclerAdapter<Comment, CommentViewHolder>(Comment.class, R.layout.comment_item,
            CommentViewHolder.class, commentsRef) {
        @Override//from   w  w w  .  j  a v  a 2 s. c o  m
        protected void populateViewHolder(final CommentViewHolder viewHolder, Comment comment, int position) {
            user_ = db.getUserDetails();
            viewHolder.commentAuthor.setText(user_.get("name"));
            GlideUtil.loadProfileIcon(user_.get("profile_pic_url"), viewHolder.commentPhoto);

            viewHolder.authorRef = user_.get("uid");
            viewHolder.commentTime.setText(DateUtils.getRelativeTimeSpanString((long) comment.getTimestamp()));
            viewHolder.commentText.setText(comment.getText());
        }
    };
    sendButton.setEnabled(false);
    mEditText.setHint(R.string.new_comment_hint);
    mEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(DEFAULT_MSG_LENGTH_LIMIT) });
    mEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (editable.length() > 0) {
                sendButton.setEnabled(true);
            } else {
                sendButton.setEnabled(false);
            }
        }
    });
    sendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Clear input box and hide keyboard.
            final Editable commentText = mEditText.getText();
            mEditText.setText("");
            InputMethodManager inputManager = (InputMethodManager) getActivity()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(mEditText.getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);

            FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
            if (user == null) {
                Toast.makeText(getActivity(), R.string.user_logged_out_error, Toast.LENGTH_SHORT).show();
            }

            Comment comment = new Comment(user.getDisplayName(), commentText.toString(), ServerValue.TIMESTAMP);
            commentsRef.push().setValue(comment, new DatabaseReference.CompletionListener() {
                @Override
                public void onComplete(DatabaseError error, DatabaseReference firebase) {
                    if (error != null) {
                        Log.w(TAG, "Error posting comment: " + error.getMessage());
                        Toast.makeText(getActivity(), "Error posting comment.", Toast.LENGTH_SHORT).show();
                        mEditText.setText(commentText);
                    }
                }
            });
        }
    });
    mCommentsView.setLayoutManager(new LinearLayoutManager(getActivity()));
    mCommentsView.setAdapter(mAdapter);
    return rootView;
}

From source file:com.tinfoil.sms.sms.SendMessageActivity.java

private void setupPhoneBox() {
    //Do in thread.
    tc = dba.getAllRows(DBAccessor.ALL);

    phoneBox = (AutoCompleteTextView) findViewById(R.id.new_message_number);
    List<String> contact;
    if (tc != null) {
        contact = SMSUtility.contactDisplayMaker(tc);
    } else {//from   w ww. ja v a  2 s  .c  o m
        contact = null;
    }
    final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.auto_complete_list_item,
            contact);

    phoneBox.setAdapter(adapter);

    phoneBox.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(final Editable s) {

            final String[] info = s.toString().split(", ");

            if (!info[0].trim().equals("")) {
                if (info.length > 1 && !info[0].trim().equalsIgnoreCase(s.toString())) {
                    SendMessageActivity.this.newCont.setName(info[0].trim());
                    SendMessageActivity.this.newCont.setNumber(info[1].trim());
                } else {
                    if (SMSUtility.isANumber(info[0].trim())) {
                        if (newCont.isNumbersEmpty()) {
                            newCont.addNumber(info[0].trim());
                        } else {
                            newCont.setNumber(info[0].trim());
                        }
                    } else {
                        newCont = new TrustedContact();
                    }
                }
            } else {
                newCont = new TrustedContact();
            }
        }

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

        public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {
        }
    });
}

From source file:com.gimranov.zandy.app.AttachmentActivity.java

@Override
protected Dialog onCreateDialog(int id) {
    final String attachmentKey = b.getString("attachmentKey");
    final String itemKey = b.getString("itemKey");
    final String content = b.getString("content");
    final String mode = b.getString("mode");
    AlertDialog dialog;//from ww  w  . j a v  a 2s  .  c o m
    switch (id) {
    case DIALOG_CONFIRM_NAVIGATE:
        dialog = new AlertDialog.Builder(this).setTitle(getResources().getString(R.string.view_online_warning))
                .setPositiveButton(getResources().getString(R.string.view),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                // The behavior for invalid URIs might be nasty, but
                                // we'll cross that bridge if we come to it.
                                try {
                                    Uri uri = Uri.parse(content);
                                    startActivity(new Intent(Intent.ACTION_VIEW).setData(uri));
                                } catch (ActivityNotFoundException e) {
                                    // There can be exceptions here; not sure what would prompt us to have
                                    // URIs that the browser can't load, but it apparently happens.
                                    Toast.makeText(getApplicationContext(), getResources()
                                            .getString(R.string.attachment_intent_failed_for_uri, content),
                                            Toast.LENGTH_SHORT).show();
                                }
                            }
                        })
                .setNeutralButton(getResources().getString(R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                // do nothing
                            }
                        })
                .create();
        return dialog;
    case DIALOG_CONFIRM_DELETE:
        dialog = new AlertDialog.Builder(this)
                .setTitle(getResources().getString(R.string.attachment_delete_confirm))
                .setPositiveButton(getResources().getString(R.string.menu_delete),
                        new DialogInterface.OnClickListener() {
                            @SuppressWarnings("unchecked")
                            public void onClick(DialogInterface dialog, int whichButton) {
                                Attachment a = Attachment.load(attachmentKey, db);
                                a.delete(db);
                                ArrayAdapter<Attachment> la = (ArrayAdapter<Attachment>) getListAdapter();
                                la.clear();
                                for (Attachment at : Attachment.forItem(Item.load(itemKey, db), db)) {
                                    la.add(at);
                                }
                            }
                        })
                .setNegativeButton(getResources().getString(R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                // do nothing
                            }
                        })
                .create();
        return dialog;
    case DIALOG_NOTE:
        final EditText input = new EditText(this);
        input.setText(content, BufferType.EDITABLE);

        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle(getResources().getString(R.string.note)).setView(input).setPositiveButton(
                        getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
                            @SuppressWarnings("unchecked")
                            public void onClick(DialogInterface dialog, int whichButton) {
                                Editable value = input.getText();
                                String fixed = value.toString().replaceAll("\n\n", "\n<br>");
                                if (mode != null && mode.equals("new")) {
                                    Log.d(TAG, "Attachment created with parent key: " + itemKey);
                                    Attachment att = new Attachment(getBaseContext(), "note", itemKey);
                                    att.setNoteText(fixed);
                                    att.dirty = APIRequest.API_NEW;
                                    att.save(db);
                                } else {
                                    Attachment att = Attachment.load(attachmentKey, db);
                                    att.setNoteText(fixed);
                                    att.dirty = APIRequest.API_DIRTY;
                                    att.save(db);
                                }
                                ArrayAdapter<Attachment> la = (ArrayAdapter<Attachment>) getListAdapter();
                                la.clear();
                                for (Attachment a : Attachment.forItem(Item.load(itemKey, db), db)) {
                                    la.add(a);
                                }
                                la.notifyDataSetChanged();
                            }
                        })
                .setNeutralButton(getResources().getString(R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                // do nothing
                            }
                        });
        // We only want the delete option when this isn't a new note
        if (mode == null || !"new".equals(mode)) {
            builder = builder.setNegativeButton(getResources().getString(R.string.menu_delete),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            Bundle b = new Bundle();
                            b.putString("attachmentKey", attachmentKey);
                            b.putString("itemKey", itemKey);
                            removeDialog(DIALOG_CONFIRM_DELETE);
                            AttachmentActivity.this.b = b;
                            showDialog(DIALOG_CONFIRM_DELETE);
                        }
                    });
        }
        dialog = builder.create();
        return dialog;
    case DIALOG_FILE_PROGRESS:
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog
                .setMessage(getResources().getString(R.string.attachment_downloading, b.getString("title")));
        mProgressDialog.setIndeterminate(true);
        return mProgressDialog;
    default:
        Log.e(TAG, "Invalid dialog requested");
        return null;
    }
}

From source file:com.jaredrummler.android.colorpicker.ColorPickerDialog.java

@Override
public void afterTextChanged(Editable s) {
    if (hexEditText.isFocused()) {
        int color = parseColorString(s.toString());
        if (color != colorPicker.getColor()) {
            fromEditText = true;/*from   w  w  w  . j a  va2 s  . c o m*/
            colorPicker.setColor(color, true);
        }
    }
}