TextUtils.isDigitsOnly Returns True if Given an Empty String
I happened across this problem while using the Android SDK’s TextUtils.isDigitsOnly() method recently.
This is the body of that method from the API 27 source:
public static boolean isDigitsOnly(CharSequence str) { final int len = str.length(); for (int cp, i = 0; i < len; i += Character.charCount(cp)) { cp = Character.codePointAt(str, i); if (!Character.isDigit(cp)) { return false; } } return true; }
Someone filed a bug report against it in January 2012. It seems no progress toward a fix has been made.
The app I’m coding is in Kotlin, and my first thought was to try to create my own local fix by creating my own local TextUtils.isDigitsOnly implementation in an extension function.
But this is not (yet) possible for a static method whose original definition is in a Java class (as opposed to a Kotlin class). Someone has filed a feature request to make it possible though. (It seems like a sensible request to me because there’s an asymmetry between Kotlin and Java with respect to extension functions: with Kotlin-defined classes you can reimplement both instance and companion object methods, but with Java-defined classes you can only reimplement instance methods.)
Anyway, in the mean time I replaced this expression:
TextUtils.isDigitsOnly(myString)
with this expression:
!TextUtils.isEmpty(myString) && TextUtils.isDigitsOnly(myString)