Sco*_*ggs 33 string android nullpointerexception string-parsing long-integer
我花了两个小时调试看起来极不可能的事情.我已经删除了辅助Android Activity的方法到这个:
public void onClick(View v) {
String str = "25";
long my_long = Long.getLong(str);
} // onClick (v)
Run Code Online (Sandbox Code Playgroud)
是的,我遇到了好的'NullPointerException:
09-11 02:02:50.444:ERROR/AndroidRuntime(1588):未捕获的处理程序:由于未捕获的异常而导致主线程退出09-11 02:02:50.464:ERROR/AndroidRuntime(1588):java.lang.NullPointerException
看起来(从其他测试中)Long.getLong(str)返回NULL,这让我疯狂.我错过了什么?
提前致谢.我很好,愚蠢地错过了明显的,但我的理智是在线.
MeL*_*ght 101
您错过了Long.getLong(String str)不应该将String解析为long 的事实,而是返回由该字符串表示的系统属性的long值.正如其他人所说,你真正需要的是Long.parseLong(String str).
为了理解这一点,举几个例子:
Long val= Long.getLong("32340");
Run Code Online (Sandbox Code Playgroud)
返回: null
Long val = Long.getLong("32340", 3000);
Run Code Online (Sandbox Code Playgroud)
返回: 3000
Long val = Long.parseLong("32340");
Run Code Online (Sandbox Code Playgroud)
返回: 32340
该文档将getLong()方法描述为:
返回由字符串标识的系统属性的 Long 值。
这是getLong()方法的代码,仅获取由字符串定义的属性值:
public static Long getLong(String string) {
if (string == null || string.length() == 0) {
return null;
}
String prop = System.getProperty(string);
if (prop == null) {
return null;
}
try {
return decode(prop);
} catch (NumberFormatException ex) {
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19485 次 |
| 最近记录: |