解决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.

Long.getLong() failing, returning null to valid string

up vote 2 down vote favorite
1

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

active oldest votes
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
up vote 3 down vote

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
up vote 3 down vote

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
up vote 3 down vote

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

你可能感兴趣的:(Android开发)