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

前端 未结 5 1251
遥遥无期
遥遥无期 2020-12-16 09:44

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 voi         


        
相关标签:
5条回答
  • 2020-12-16 10:01

    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).

    0 讨论(0)
  • 2020-12-16 10:02

    To understand this, some examples:

    Long val= Long.getLong("32340");
    

    returns: null

    Long val = Long.getLong("32340", 3000);
    

    returns: 3000

    Using Long.parseLong() :

    Long val  = Long.parseLong("32340");
    

    returns: 32340

    The documentation describe getLong() method as :

    Returns the Long value of the system property identified by string.

    this is the code of the getLong() method and only get a property value defined by a string:

      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;
            }
        }
    

    If you want to parse a String to Long, the best way is using Long.parseLong() method.

    0 讨论(0)
  • 2020-12-16 10:06

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

    0 讨论(0)
  • 2020-12-16 10:09

    You can use Long.parseLong(String), instead of getLong(String): it will solve the problem.

    0 讨论(0)
  • 2020-12-16 10:16

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

    0 讨论(0)
提交回复
热议问题