0

I am getting the DOB String in this format "\/Date(588657600000-0400)\/" which i am parsing as below.

String target = custom.getDOB();
if (target == null || target == "") {
    holder.item3.setText("-");
} else {
    long millis = Long.parseLong(target.substring(
                 target.indexOf("(") + 1, target.indexOf("-")));
    java.text.DateFormat df = new SimpleDateFormat("MM-dd-yyyy", Locale.ENGLISH);
    holder.item3.setText(df.format(new Date(millis)));
}

I am getting this error "04-08 22:44:09.864: E/AndroidRuntime(3837): java.lang.NumberFormatException: Invalid long: "" . I am checking before, whether my String object contains null or "" and setting it to "-", but still i am getting this exception.

Update:

04-08 22:59:17.423: E/AndroidRuntime(4175): java.lang.NumberFormatException: Invalid long: "" 04-08 22:59:17.423: E/AndroidRuntime(4175): at java.lang.Long.invalidLong(Long.java:125) 04-08 22:59:17.423: E/AndroidRuntime(4175): at java.lang.Long.parseLong(Long.java:346) 04-08 22:59:17.423: E/AndroidRuntime(4175): at java.lang.Long.parseLong(Long.java:319)

I changed my null and empty string literal check to this, but i still get this error.

if(target == null || target.equals(""))
theJava
  • 14,620
  • 45
  • 131
  • 172

3 Answers3

6

Use String#equals to compare string values; the == operator compares object references for equality.

if (target == null || target.equals("")) {

You are using == correctly when testing for null, because you are ensuring that your target reference isn't null .

rgettman
  • 176,041
  • 30
  • 275
  • 357
  • i am getting error at this point... long millis = Long.parseLong(target.substring(target.indexOf("(") + 1, target.indexOf("-"))); // – theJava Apr 08 '13 at 23:02
  • Please think about this. What does target.indexOf("-") return? – Simon Apr 08 '13 at 23:08
  • @Simon: it should return me the position/index of "-" inside of my string. – theJava Apr 08 '13 at 23:14
  • @theJava Like I say, please think about (and learn to use the debugger). indexOf("-") returns, for example, 25. indexOf("(") returns say 10 (which you add one to). You are then trying to parse the string of 25 characters starting from the 12th character of your string. – Simon Apr 09 '13 at 00:36
  • @Simon: sure sir... i am slow leaner, yes i will keep this in ma mind. – theJava Apr 09 '13 at 00:41
0

As a shortcut for checking if a String is null or "" you also can use

StringUtils.isEmpty(target)

ssantos
  • 16,001
  • 7
  • 50
  • 70
0
  Use Try and catch 

      String  values=Util.getStringFromSP(getActivity(),"time");
        try {
        PERIOD_MS = Long.parseLong(values);
    } catch (Exception e) {

        Log.d("time", "" + values);
        if (PERIOD_MS == 0) {
            PERIOD_MS = 1000;
        }