0

I am creating an app for counting points in games. This app has a edittext component. I want to check if the string retrieved from the edit text contains characters other than 0-9. This is because my app contains a integer.parse function wich crashes if characters other than 0-9 is inputed. All help will be greatly appreciated. Thanks in advance.

  • http://stackoverflow.com/questions/8248277/how-to-determine-if-a-string-has-non-alphanumeric-characters – zafrani Nov 14 '13 at 21:15

3 Answers3

3

If you just want to notify the user of an invalid character then you can wrap it in a try/catch and act accordingly

try
{
    int someInt = Integer.parseInt(et.getText().toString());
    // other code
}
catch (NumberFormatException e)
{
    // notify user with Toast, alert, etc...
}

You also can use a regular expression to look for the characters you want/don't want depending on your needs.

Just to be clear in case my code comment wasn't, I am suggesting that you do something with the exception and notify the user. Don't catch it and let it sit

codeMagic
  • 44,549
  • 13
  • 77
  • 93
2
public static boolean isNumeric(String str)
{
    for (char c : str.toCharArray())
    {
        if (!Character.isDigit(c)) return false;
    }
    return true;
}

OR

public boolean isNumeric(String s) {  
    return s.matches("[-+]?\\d*\\.?\\d+");  
} 
hasan
  • 23,815
  • 10
  • 63
  • 101
0

Firstly you can setup edittext as integer numbers only, so in your layout put

android:inputType="number"

It will set to integer numbers only in edit text.

All possible types here: http://developer.android.com/reference/android/widget/TextView.html#attr_android:inputType

Then you can test with regular expression or/and catch exception when parsing. Regular expression would be:

"string".matches("\\d+") // true when numbers only, false otherwise

Reference here:

http://developer.android.com/reference/java/lang/String.html#matches(java.lang.String) http://developer.android.com/reference/java/util/regex/Pattern.html

bart
  • 186
  • 2
  • 4