Tony
Tony

Reputation: 163

Android check EditText

i have a EditText which always contains an integer...but sometimes also contains the text..how do I check if my string contains text fields in the EditText? Thanks in advance.

Upvotes: 2

Views: 4295

Answers (4)

Bostwickenator
Bostwickenator

Reputation: 380

You can also register a http://developer.android.com/reference/android/text/TextWatcher.html on the EditText to do these operations as the field is changed. This allows you to do nice things like reject invalid characters as they are entered or turn the text red while it is invalid.

Upvotes: 0

Simone Casagranda
Simone Casagranda

Reputation: 1215

I think that you can check if your text contains only numbers and/or letters. If you build an utility method like this:

public static boolean isNumeric(String s){
  if(TextUtils.isEmpty(s)){
    return false;
  }
  Pattern p = Pattern.compile("[-+]?[0-9]*");
  Matcher m = p.matcher(s);
  return m.matches();
}

...then you can use it easily to check if your text retrieved from your TextView contains an integer or not :)

  String text = textview.getText().toString();
  if(TextUtils.isEmpty()){
    // We have got an empty string
  } else if(isNumeric(text){
    // Do something
  }else{
    // It's not numeric do something else
  }

Upvotes: 2

Raunak
Raunak

Reputation: 6507

I would approach the problem in the following manner:

String mEditText = mDisplay.getText().toString();
if(mEditText.matches("[0-9]+")) {
    // mEditText only contains numbers
} else {
    // mEditText contains number + text, or text only. 
}

Upvotes: 8

Tyler Treat
Tyler Treat

Reputation: 14998

Check out java.lang.Character.isDigit(). You can check if a String is numeric by iterating over its characters and checking if they are digits.

Reference

Upvotes: 0

Related Questions