解决java的Long.getLong(str)的NullPointerException错误

问题:long temp = Long.getLong("1366937075");出现空指针NullPointerException错误
解决:用Long.parseLong(String str)替换。
疑问:Long tmp = Long.getLong("1366937075");这个返回也为null,为什么?
 
参考:http://stackoverflow.com/questions/7376857/long-getlong-failing-returning-null-to-valid-string
 
 
 
 
tack Overflow  is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I've spent the past two hours debugging what seems extremely unlikely. I've stripped the method of a secondary Android Activity to exactly this:

public void onClick(View v) {
        String str = "25";
        long my_long = Long.getLong(str);
} // onClick (v)

And yeah, I get a crash with the good ol' NullPointerException:

09-11 02:02:50.444: ERROR/AndroidRuntime(1588): Uncaught handler: thread main exiting due to uncaught exception 09-11 02:02:50.464: ERROR/AndroidRuntime(1588): java.lang.NullPointerException

It looks like (from other tests) that Long.getLong(str) returns NULL, which is driving me bonkers. WHAT AM I MISSING?

Thanks in advance. I'm okay with stupidly missing the obvious, but my sanity is on the line.

share | improve this question
 
1 
use Long.parseLong(str); instead of Long.getLong(str);  –  user370305   Sep 11 '11 at 7:31

4 Answers

up vote 12 down vote accepted

You are missing the fact that Long.getLong(String str) is not supposed to parse a String to a long, but rather to return a long value of a system property represented by that string. As others have suggested, what you actually need is Long.parseLong(String str).

share | improve this answer
 
Ahh, that makes perfect sense. Thanks!  –  Scott Biggs   Sep 11 '11 at 16:57
 
Very descriptive reply.+1 for that.  –  Android Killer   Sep 11 '11 at 17:30
 
Thanks and welcome :)  –  MeLight   Sep 11 '11 at 18:35

I think you are using wrong function use Long.parseLong(str) then you can get the right answer.

share | improve this answer
 
You are absolutely right. Thanks for the help!  –  Scott Biggs   Sep 11 '11 at 18:52
 
My pleasure to help u buddy.  –  Android Killer   Sep 12 '11 at 2:26

you can use Long.parsLong(String) instead of getLong(String) it will solve the problem

share | improve this answer
 
Thanks, the change worked!  –  Scott Biggs   Sep 11 '11 at 18:52

Long.parseLong(someString) approved. Don't forget to catch NumberFormatException if there's a probability of unparsable string.

share | improve this answer
 
Yes, thank you! Wasn't thinking along those lines.  –  Scott Biggs   Sep 11 '11 at 16:58
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值