按钮onClick后程序崩溃

时间:2013-04-23 02:34:01

标签: java android

不确定这里有什么问题。如果edittext中没有任何内容,则会发生崩溃。如果它们都被填写,它就可以工作。所以我的问题是if语句检查。即使edittexts为空,它也会进入if语句。它应该跳到else并记录并非所有字段都已完成。

问题出在这里(我认为) - 即使它不应该进入循环:

//Calculate Risk Score Button

Button calcButton = (Button) findViewById(R.id.calcButton);

calcButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        // Create and set values
        int smoker = 0;
        int medicated = 0;
        char gender = 'm';
        String selectedAge = (String) ageSpin.getSelectedItem();
        Log.i("TEST", "Before if");

        if (selectedAge != null
                && cholEdit.getText().toString() != null
                && hdlEdit.getText().toString() != null
                && sbpEdit.getText().toString() != null
                && genderGroup.getCheckedRadioButtonId() != -1
                && smokerGroup.getCheckedRadioButtonId() != -1
                && medsGroup.getCheckedRadioButtonId() != -1) {
        Log.i("TEST", "After if");

            // store values
            int age = Integer.parseInt(selectedAge.toString());
            int chol = Integer.parseInt(cholEdit.getText().toString());
            int hdl = Integer.parseInt(hdlEdit.getText().toString());
            int sbp = Integer.parseInt(sbpEdit.getText().toString());
            int genderId = genderGroup.getCheckedRadioButtonId();
            int smokeId = smokerGroup.getCheckedRadioButtonId();
            int medsId = medsGroup.getCheckedRadioButtonId();

            // Set gender, smoker and if medicated values
            if (genderId == R.id.maleR)
                gender = 'm';
            else if (genderId == R.id.femaleR)
                gender = 'f';

            if (smokeId == R.id.yesR)
                smoker = 1;
            else if (smokeId == R.id.noR)
                smoker = 0;

            if (medsId == R.id.yesR2)
                medicated = 1;
            else if (medsId == R.id.yesR2)
                medicated = 0;

            // Calculate Answer and Print
            String answer = calc.calculateRiskScore(age, gender, chol,
                    smoker, hdl, sbp, medicated);


            SharedPreferences settings = getSharedPreferences(
                    PREF_FILE, 0);
            SharedPreferences.Editor editor = settings.edit();

            editor.putInt("age", age);
            editor.putInt("chol", chol);
            editor.putInt("hdl", hdl);
            editor.putInt("sbp", sbp);
            editor.putInt("gender", genderId);
            editor.putInt("smoker", smoker);
            editor.putInt("med", medicated);
            editor.putString("risk", answer);

            editor.commit();

            displayRisk(answer);
        } else {
            Toast toast = Toast.makeText(getApplicationContext(),
                    "Not all fields are completed", Toast.LENGTH_SHORT);
            toast.show();
        }
    }
});

这是logcat错误。我得到了错误所说的内容,但它不应该在if语句中来实现:

04-22 21:26:43.920: I/TEST(22544): Before if
04-22 21:26:43.920: I/TEST(22544): After if
04-22 21:26:43.920: W/dalvikvm(22544): threadid=1: thread exiting with uncaught exception (group=0x41634438)
04-22 21:26:43.930: E/AndroidRuntime(22544): FATAL EXCEPTION: main
04-22 21:26:43.930: E/AndroidRuntime(22544): java.lang.NumberFormatException: Invalid int: ""
04-22 21:26:43.930: E/AndroidRuntime(22544):    at java.lang.Integer.invalidInt(Integer.java:138)
04-22 21:26:43.930: E/AndroidRuntime(22544):    at java.lang.Integer.parseInt(Integer.java:359)
04-22 21:26:43.930: E/AndroidRuntime(22544):    at java.lang.Integer.parseInt(Integer.java:332)
04-22 21:26:43.930: E/AndroidRuntime(22544):    at edu.auburn.eng.csse.comp3710.group04.CardiovascularActivity$1.onClick(CardiovascularActivity.java:83)
04-22 21:26:43.930: E/AndroidRuntime(22544):    at android.view.View.performClick(View.java:4198)
04-22 21:26:43.930: E/AndroidRuntime(22544):    at android.view.View$PerformClick.run(View.java:17164)
04-22 21:26:43.930: E/AndroidRuntime(22544):    at android.os.Handler.handleCallback(Handler.java:615)
04-22 21:26:43.930: E/AndroidRuntime(22544):    at android.os.Handler.dispatchMessage(Handler.java:92)
04-22 21:26:43.930: E/AndroidRuntime(22544):    at android.os.Looper.loop(Looper.java:137)
04-22 21:26:43.930: E/AndroidRuntime(22544):    at android.app.ActivityThread.main(ActivityThread.java:4918)
04-22 21:26:43.930: E/AndroidRuntime(22544):    at java.lang.reflect.Method.invokeNative(Native Method)
04-22 21:26:43.930: E/AndroidRuntime(22544):    at java.lang.reflect.Method.invoke(Method.java:511)
04-22 21:26:43.930: E/AndroidRuntime(22544):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
04-22 21:26:43.930: E/AndroidRuntime(22544):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
04-22 21:26:43.930: E/AndroidRuntime(22544):    at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:1)

不应检查“!= null”,而应检查isNullOrEmpty(编写一个检查“string == null || string.isEmpty()”的方法,因为显然那些toString方法返回空字符串( “”)和空字符串上的Integer.parseInt barfs与字符串“hello”上的相同。

答案 1 :(得分:1)

随着异常的抛出:

04-22 21:26:43.930: E/AndroidRuntime(22544): java.lang.NumberFormatException: Invalid int: ""
04-22 21:26:43.930: E/AndroidRuntime(22544):    at java.lang.Integer.invalidInt(Integer.java:138)
04-22 21:26:43.930: E/AndroidRuntime(22544):    at java.lang.Integer.parseInt(Integer.java:359)
04-22 21:26:43.930: E/AndroidRuntime(22544):    at java.lang.Integer.parseInt(Integer.java:332)

问题是:TextField用于获取文本,并解析int。因为这个文本字段是空的(你应该记住,空与NULL非常不同)。 TextField本身不为空,但您获得的文本为空("")。因此,Integer.parseInt将在这种情况下抛出异常。 (不会按照我们的意愿自动返回0)因此,在代码中,您必须在try-catch块中包围程序中的所有Integer.parseInt方法,以防止用户输入一些愚蠢的内容。

int chol = 0;
int hdl = 0;
int age = 0;
try {

                    age = Integer.parseInt(selectedAge.toString());
                    chol = Integer.parseInt(cholEdit.getText().toString());
                    hdl = Integer.parseInt(hdlEdit.getText().toString());

}

catch (Exception e) {
     chol = 0;
     hdl = 0;
     age = 0;
}

当您使用Integer.parseIntDouble.parseDouble ...

时,这是最好的模式

希望这可以帮助你:)