My app uses the proximity sensor to switch the screen on/off while on the app's main Activity. This works fine, however I've received a crash report from a HTC One S user:
08-23 11:25:04.754 E/AndroidRuntime(30499): FATAL EXCEPTION: main 08-23 11:25:04.754 E/AndroidRuntime(30499): java.lang.NumberFormatException: Invalid int: "38,654,705,664" 08-23 11:25:04.754 E/AndroidRuntime(30499): at java.lang.Integer.invalidInt(Integer.java:138) 08-23 11:25:04.754 E/AndroidRuntime(30499): at java.lang.Integer.parse(Integer.java:375) 08-23 11:25:04.754 E/AndroidRuntime(30499): at java.lang.Integer.decode(Integer.java:188) 08-23 11:25:04.754 E/AndroidRuntime(30499): at com.myapp.MyActivity.onSensorChanged(NotificationActivity.java:793) 08-23 11:25:04.754 E/AndroidRuntime(30499): at android.hardware.SystemSensorManager$ListenerDelegate$1.handleMessage(SystemSensorManager.java:204)
The code I'm using is
private NumberFormat numForm = new DecimalFormat();
@Override
public void onSensorChanged(SensorEvent event) {
float sensor = event.values[0];
String cm = numForm.format(sensor);
int dis = Integer.decode(cm);
Log.i(TAG, "Proximity distance: " + dis);
}
Is this a sensor calibration problem on the user's end, or can I simply surround the Integer-parsing with a try/catch to avoid obviously wrong values like "38,654,705,664"?
Casting form
float
toint
does never cause an exception. We just lose precision in such cases like yours. If you need a "full" value, you should rather work withfloat
and do not try to cast it. Now about bad values from sensor API. They can always come. If you can recognize them, you can exclude them from your calculations. If it is a must-requirement, you could implement some statistical filters. Hope this helps.