Android TextUtils.isDigitsOnly returns true for empty string

As Selvin mentioned correctly this is actually a bug that persists until today. See here.

You can get around that by doing this:

Java

boolean myIsDigitsOnly(String str) {
    return str.isEmpty() && TextUtils.isDigitsOnly(str); 
}

Now you call your own custom method:

myIsDigitsOnly(""); // returns false

Kotlin

In Kotlin, you don't need TextUtils at all. Just create your own extension function like this:

fun String.isDigitsOnly() = all(Char::isDigit) && isNotEmpty()

Try it out here!


Thanks to silwar who inspired me to make the Java one more concise.


For Kotlin Users

Although its an old question with accepted answer, this is suggestion to improve this answer in Kotlin language by following code

fun String.myIsDigitsOnly(): Boolean {
   return TextUtils.isDigitsOnly(this) && this.isNotEmpty()
}

Now you can call your method like

"".myIsDigitsOnly() // returns false

or

"123523423".myIsDigitsOnly() // returns false

Tags:

Android