parseint of blank string crashes on android

Monkey Forums/Monkey Bug Reports/parseint of blank string crashes on android

slenkar(Posted 2013) [#1]
if LoadState is ""
on flash and html5 If I do
Local lev:Int=Int(LoadState())
it translates to zero

but in android it crashes:
E/AndroidRuntime( 8272): java.lang.NumberFormatException: Invalid int: ""
E/AndroidRuntime( 8272): at java.lang.Integer.invalidInt(Integer.java:138)
E/AndroidRuntime( 8272): at java.lang.Integer.parseInt(Integer.java:359)
E/AndroidRuntime( 8272): at java.lang.Integer.parseInt(Integer.java:332)


DGuy(Posted 2013) [#2]
The issue is Monkey is just calling the targets str-to-int routine (Integer.parseInt on Android) and Java throws exceptions on invalid str-to-int conversions (Unlike most (all?) other targets which return 0 or garbage.)

My work around was to write a simple wrapper for Integer.parseInt which catches any exceptions, logs an error and returns 0:

Monkey Code:[monkeycode]
#if TARGET="android"
import "native/numberparser.java"
EXTERN PRIVATE
class NumberParser
method ToInt( str$ )
method ToFloat%( str$ )
end
PRIVATE
Global NumParser:= new NumberParser
#end

function StrToInt( str$ )
#if TARGET="android"
return NumParser.ToInt( str )
#else
return Int(str)
#end
end

function StrToFloat%( str$ )
#if TARGET="android"
return NumParser.ToFloat( str )
#else
return Float(str)
#end
end
[/monkeycode]

Java code (updated w/ suggestions from Samah):
// numberparser.java
class NumberParser {
	private static final String _TAG = "[Monkey]";
	
	public static int ToInt( String str ) {
	    if( str == null ) {
	 		Log.i( _TAG, "NumberParser.ToInt: Invalid Number Format: 'null'" );
			return 0;
		}
		try {
			return Integer.parseInt( str );
		} catch( NumberFormatException e ) {
			Log.i( _TAG, String.format( "NumberParser.ToInt: Invalid Number Format: '%s'", str ) );
			return 0;
		}
	}

	public static float ToFloat( String str ) {
	    if( str == null ) {
	 		Log.i( _TAG, "NumberParser.ToFloat: Invalid Number Format: 'null'" );
			return 0.0f;
		}
		try {
			return Float.parseFloat( str );
		} catch( NumberFormatException e ) {
			Log.i( _TAG, String.format( "NumberParser.ToFloat: Invalid Number Format: '%s'", str ) );
			return 0.0f;
		}
	}
}

Not a perfect solution (would be nice if Monkey did something like this internally) but I hope it helps.


Samah(Posted 2013) [#3]
Don't catch Exception, catch NumberFormatException. Catching Exception is almost never a good idea.

Is there any reason you didn't make those methods static?


DGuy(Posted 2013) [#4]
@Samah: As you can tell Java is not my specialty! :)

After reading up on when/why its a good thing to make methods static, I've updated the code as per your suggestions ... Thanks!