我正在尝试使用外部Java库来处理Android,但是在处理日期时它会抛出错误。
我把它缩小到这条线:
Long year = Long.parseLong("+2013");
抛出一个
Caused by: java.lang.NumberFormatException: Invalid long: "+2013"
但是,代码有效并且在纯Java应用程序中工作。为什么Long.parseLong()
在Android应用中的工作方式不同?
Android's documentation声明'+'Ascii标志得到承认:
public static long parseLong (String string)
将指定的字符串解析为带符号的十进制长值。 ASCII字符 - (' - ')和+('+')被识别为减号和加号。
答案 0 :(得分:0)
谢谢大家!管理以找出问题。
似乎API 17:Android 4.2(Jelly Bean)正在引发问题。 API无法正确处理parseLong()中的“+”符号。
解决了它将编译SDK更改为API 21及更高版本的问题。
API 20 parseLong()
/**
* Parses the specified string as a signed long value using the specified
* radix. The ASCII character \u002d ('-') is recognized as the minus sign.
*
* @param string
* the string representation of a long value.
* @param radix
* the radix to use when parsing.
* @return the primitive long value represented by {@code string} using
* {@code radix}.
* @throws NumberFormatException
* if {@code string} cannot be parsed as a long value, or
* {@code radix < Character.MIN_RADIX ||
* radix > Character.MAX_RADIX}.
*/
public static long parseLong(String string, int radix) throws NumberFormatException {
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
throw new NumberFormatException("Invalid radix: " + radix);
}
if (string == null) {
throw invalidLong(string);
}
int length = string.length(), i = 0;
if (length == 0) {
throw invalidLong(string);
}
boolean negative = string.charAt(i) == '-';
if (negative && ++i == length) {
throw invalidLong(string);
}
return parse(string, i, radix, negative);
}
API 21 parseLong()
/**
* Parses the specified string as a signed long value using the specified
* radix. The ASCII characters \u002d ('-') and \u002b ('+') are recognized
* as the minus and plus signs.
*
* @param string
* the string representation of a long value.
* @param radix
* the radix to use when parsing.
* @return the primitive long value represented by {@code string} using
* {@code radix}.
* @throws NumberFormatException
* if {@code string} cannot be parsed as a long value, or
* {@code radix < Character.MIN_RADIX ||
* radix > Character.MAX_RADIX}.
*/
public static long parseLong(String string, int radix) throws NumberFormatException {
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
throw new NumberFormatException("Invalid radix: " + radix);
}
if (string == null || string.isEmpty()) {
throw invalidLong(string);
}
char firstChar = string.charAt(0);
int firstDigitIndex = (firstChar == '-' || firstChar == '+') ? 1 : 0;
if (firstDigitIndex == string.length()) {
throw invalidLong(string);
}
return parse(string, firstDigitIndex, radix, firstChar == '-');
}