Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android TextUtils.isDigitsOnly returns true for empty string

Tags:

android

android.text.TextUtils.isDigitsOnly("")  

I'm using above code to check input string is a valid number or not but isDigitOnly() function return true for empty string.

How to make it to return false for empty string or there is other Android build in function?

like image 975
Rahul Avatar asked Jun 26 '17 13:06

Rahul


2 Answers

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.

like image 127
Willi Mentzel Avatar answered Nov 13 '22 20:11

Willi Mentzel


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
like image 20
silwar Avatar answered Nov 13 '22 20:11

silwar