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.
3 Answers
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

- 44,549
- 13
- 77
- 93
-
-
2Yup, and this is a good thing to do regardless. Another safety net you could add is the `android:digits` attribute on your EditText. Set it to `android:digits="0123456789"`. This will restrict entry to only those characters. – Kevin Coppock Nov 14 '13 at 21:15
-
1
-
@kcoppock yes, thank you. I should have mentioned that it should typically be used in parsing. – codeMagic Nov 14 '13 at 21:17
-
1Yeah, there's nothing bad about catching an exception. Catching and disregarding, sure, but there's absolutely nothing wrong with this approach. – Kevin Coppock Nov 14 '13 at 21:17
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+");
}

- 23,815
- 10
- 63
- 101
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

- 186
- 2
- 4