Integer.parseInt and NumberFormatException on Android
4950 Репутация автора
I ran the following code in my Android app
NumberFormatException : Invalid Int : "+91"
How is the version of Android causing this difference?Автор: Ashwin Источник Размещён: 06.05.2015 08:38
5648 Репутация автора
It works after Java 7.
Android 5 introduces the new parseInt feature like the Java 7 version - Martin Nordholts's answer points exactly the revision
So this means that your Lollipop uses a newer sdk based on Java 7 which has the parseInt method with the sign handling part too.
KitKat did introduce some java 7 features into Android sdk 19, but not the new parseInt. Lower versions use an earlier implementation of parseInt (Java 6's version) so they will obviously fail as well.
Автор: Laurentiu L. Размещён: 06.05.2015 08:43
4335 Репутация автора
This behaviour is actually part of Java 7, as the docs state:
Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value.
However, in Java 6 only the
- symbol was accepted.
The Android SDK 21+ has JDK7 dependencies, which is presumably why you are experiencing this behaviour.Автор: Ed George Размещён: 06.05.2015 08:45
9548 Репутация автора
Support for explicit
+ was added in this commit:
Support explicit + in Byte, Short, Integer, Long. Bug: 5239391 Change-Id: I2b25228815d70d570d537db0ed9b5b759f25b5a3
which has been included starting with
android-5.0.0_r1. If you have fetched the Git repository, you can verify with:
git tag --contains 6b40837ee3a023bba698c38fd6d6e46ae0065a55
which gives you
android-5.0.0_r1 android-5.0.0_r2 android-5.0.0_r3 ...
Even though documentation can give insights into why the change was made (to achieve Java 7 behavior as other answers point out), analyzing the history of the source code gives the most accurate answer to when the behavior changed, since documentation does not necessarily match implementation.Автор: Martin Nordholts Размещён: 06.05.2015 08:48
442 Репутация автора
With Android Version 19 (KitKat) Java 7 is supported, so you don't get this error. I recommend not to use
+, because you only need a sign if you have a negative integer.