开发者

Why is my Android app force closing when I try to check if an EditText has a double

开发者 https://www.devze.com 2022-12-30 11:30 出处:网络
Scanner scanner = new Scanner(lapsPerMile_st); if (!scanner.hasNextDouble()) { Context context = getApplicationContext();
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();

                  开发者_如何学C  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?


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!
}


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: https://developer.android.com/reference/android/widget/TextView.html#attr_android:numeric

0

精彩评论

暂无评论...
验证码 换一张
取 消