NumberFormatException - Android

2019-03-04 11:53发布

问题:

I've uploaded my Android app to the Market today, and I received 4 errors regarding NumberFormatException,Double.parseDouble and Double.valueOf.

Here's the Logcat I see in the Developer Console:

java.lang.RuntimeException: Unable to start activity ComponentInfo{can.you.drive/can.you.drive.do_drive}: java.lang.NumberFormatException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1816)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1837)
at android.app.ActivityThread.access$1500(ActivityThread.java:132)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1033)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:143)
at android.app.ActivityThread.main(ActivityThread.java:4196)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NumberFormatException
at org.apache.harmony.luni.util.FloatingPointParser.parseDblImpl(Native Method)
at org.apache.harmony.luni.util.FloatingPointParser.parseDouble(FloatingPointParser.java:283)
at java.lang.Double.parseDouble(Double.java:318)
at java.lang.Double.valueOf(Double.java:356)
at can.you.drive.dont_drive.roundTwoDecimals(dont_drive.java:132)
at can.you.drive.do_drive.onCreate(do_drive.java:125)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1780)

Here's the function in which the error occurs(according to the Log) -

public static double roundTwoDecimals(double d) {
    DecimalFormat twoDForm = new DecimalFormat("#.###");
return Double.valueOf(twoDForm.format(d));
}

I know that d is double.

Also, this works fine on my phone(Nexus S running 2.3.4). I'm getting the error from other users. That's why I can't really debug it.

I really don't know what my cause this on some phones.

回答1:

I'd say it's got to do with localization, with . not being the decimal separator in the platforms where the error occurs. Why don't you use a less expensive method of rounding?

public double round(double d, int nDecimals)
{
    for(int i=0; i<nDecimals; ++i) d *= 10d;
    d=Math.round(d);
    for(int i=0; i<nDecimals; ++i) d /= 10d;
    return d;
}


回答2:

use try catch block to handle it.



回答3:

Perhaps the error occurs when someone from the Deutsch language uses your application. I've had this problem. They use a comma in place of a decimal (',' instead of '.'). This has thrown me off multiple times



回答4:

To debug it, add a ton of System.out.println()'s all over your code that spit out a variable when it is changed. These are easier than tools like gdb.