views:

191

answers:

2
Scanner scanner = new Scanner(lapsPerMile_st);  
                if (!scanner.hasNextDouble()) {  
                    Context context = getApplicationContext();
                    String msg = "Please Enter Digits and Decmials Only";
                    int duration = Toast.LENGTH_LONG;
                    Toast.makeText(context, msg, duration).show();

                    lapsPerMileEditText.setText("");
                    return;
                } else {
                     //Edit box has only digits, Set data and display stats
                    data.setLapsPerMile(Integer.parseInt(lapsPerMile_st));

                    lapsRunLabel.setVisibility(0);
                    lapsRunTextView.setText(Integer.toString(data.getLapsRun()));

                    milesRunLabel.setVisibility(0);
                    milesRunTextView.setText(Double.toString(data.getLapsRun()/data.getLapsPerMile()));
                }


<EditText
android:id="@+id/mileCount"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginTop="110dp"
android:inputType="numberDecimal"
android:maxLength="4"
/>

For some reason if I enter a non decimal number such as 3, or 5, it works fine but when I enter a floating point such as 3.4 or 5.8 it force closes. I cant seem to figure out whats going on. Any ideas?

Thanks

+2  A: 

The culprit is almost certainly parseInt. Go ahead and connect to your device using the adb (adb logcat -v time) to view the log, as well as the stack trace generated when your app crashes.

ParseInt doesn't like any non-integer characters (I.E. It's bombing when it hits the decimal point).

I recommend using try-catch to surround your parseInt or Parse"Anything" methods.

Next, you may want to restrict the allowable characters to integer-type only within your layout XML: http://developer.android.com/intl/zh-CN/reference/android/widget/TextView.html#attr_android:numeric

Brad Hein
Yea it was supposed to be Double.parseDouble and good idea on the try catch. I really need to step up my error handling. Thanks
Mike
+1  A: 

Use the right type: Integer.parseInt, Float.ParseFloat, ... and take in account that you are using Java so if one ouf the parse's fails you'll get an exception: NumberFormatException.

String int_string = "1";
int data = 0; // 0 as default value
try
{ 
    data = Integer.parseInt (int_string); 
} 
catch (NumberFormatException e)
{ 
    // You are trying to parse and int from a string that is not an int!
}
Moss
I must have been exhausted when I was writing this. Thanks for the help on that I feel dumb but I doubt I am the first to make that mistake.
Mike
You are not the first and will not be the last hehehe, some times we forget about exceptions :P
Moss