将EditText / String转换为Integer时,我的应用程序崩溃

时间:2019-01-06 17:38:02

标签: java android numberformatexception

我正在为我的A2级计算机科学课程工作编写应用程序,并且在尝试将EditText转换为整数时遇到错误。我正在创建一个旨在帮助管理Scout组的应用程序,并且目前正在允许用户创建包含Scout详细信息的记录,并将其插入数据库中。这行显然是错误的:

emergencyhome=Integer.parseInt(findViewById(R.id.txtEmergencyHomePhone).toString());

这出现在Logcat中:

01-06 17:23:18.789 20899-20899/com.example.atomi.scoutmanagerprototype
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.atomi.scoutmanagerprototype, PID: 20899
    java.lang.IllegalStateException: Could not execute method for android:onClick
        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
        at android.view.View.performClick(View.java:4761)
        at android.view.View$PerformClick.run(View.java:19767)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5310)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
        at android.view.View.performClick(View.java:4761) 
        at android.view.View$PerformClick.run(View.java:19767) 
        at android.os.Handler.handleCallback(Handler.java:739) 
        at android.os.Handler.dispatchMessage(Handler.java:95) 
        at android.os.Looper.loop(Looper.java:135) 
        at android.app.ActivityThread.main(ActivityThread.java:5310) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at java.lang.reflect.Method.invoke(Method.java:372) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696) 
     Caused by: java.lang.NumberFormatException: Invalid int: "android.support.v7.widget.AppCompatEditText{261e7d93 VFED..CL........ 198,1096-498,1155 #7f0700dd app:id/txtEmergencyHomePhone}"
        at java.lang.Integer.invalidInt(Integer.java:138)
        at java.lang.Integer.parse(Integer.java:410)
        at java.lang.Integer.parseInt(Integer.java:367)
        at java.lang.Integer.parseInt(Integer.java:334)
        at com.example.atomi.scoutmanagerprototype.frmAddAScout.saveScout(frmAddAScout.java:202)
        at java.lang.reflect.Method.invoke(Native Method) 
        at java.lang.reflect.Method.invoke(Method.java:372) 
        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385) 
        at android.view.View.performClick(View.java:4761) 
        at android.view.View$PerformClick.run(View.java:19767) 
        at android.os.Handler.handleCallback(Handler.java:739) 
        at android.os.Handler.dispatchMessage(Handler.java:95) 
        at android.os.Looper.loop(Looper.java:135) 
        at android.app.ActivityThread.main(ActivityThread.java:5310) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at java.lang.reflect.Method.invoke(Method.java:372) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)

任何帮助将不胜感激。提前致谢。我已经在下面的上下文中附加了代码。

package com.example.atomi.scoutmanagerprototype;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class frmAddAScout extends AppCompatActivity {

    RadioGroup genderGroup;
    RadioGroup photoGroup;
    TextView lblError;
    TextView genderID; //This is to help with another issue that I'm in the process of solving, don't worry about it.
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_frm_add_ascout);
        genderGroup=findViewById(R.id.grpGender);
        photoGroup=findViewById(R.id.grpPhotos);
        lblError=findViewById(R.id.lblError);
        genderID=findViewById(R.id.genderID);
        //Creating options for the section spinner & populating it
        List<String> sectionArray=new ArrayList<>();
        sectionArray.add("Beavers");
        sectionArray.add("Cubs");
        sectionArray.add("Scouts");
        sectionArray.add("Explorers");
        sectionArray.add("Network");
        sectionArray.add("Leaders");

        ArrayAdapter<String> sectionAdapter=new ArrayAdapter<>(
                this, android.R.layout.simple_spinner_dropdown_item, sectionArray
        );

        sectionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        Spinner sectionItems=findViewById(R.id.spinSection);
        sectionItems.setAdapter(sectionAdapter);

        //creating options for the swimming spinner & populating it
        List<String> swimmingArray=new ArrayList<>();
        swimmingArray.add("Unable to swim");
        swimmingArray.add("Fairly confident");
        swimmingArray.add("Very confident");

        ArrayAdapter<String> swimmingAdapter=new ArrayAdapter<>(
                this, android.R.layout.simple_spinner_dropdown_item, swimmingArray
        );

        swimmingAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        Spinner swimmingItems=findViewById(R.id.spinSwimming);
        swimmingItems.setAdapter(swimmingAdapter);
    }


    public void backToScoutMenu(View view)
    {
        Intent goBack = new Intent(frmAddAScout.this, frmScoutsMenu.class);
        startActivity(goBack);
    }


    public void saveScout(View v)
    {
        databaseHandler db;
        db=new databaseHandler(this);
        //To do: Import all IDs created thus far & check against them to ensure it's unique here

        int id = (int)(Math.random()*(9999)+1);
        String firstname;
        if (findViewById(R.id.txtForename).toString().length() > 0)
        {
            firstname=(findViewById(R.id.txtForename).toString());
        }
        else
        {
            lblError.setText("Error - please fill all necessary fields");
            return;
        }

        String lastname;
        if ((findViewById(R.id.txtSurname).toString().length() > 0))
        {
            lastname=(findViewById(R.id.txtSurname).toString());
        }
        else
        {
            lblError.setText("Error - please fill all necessary fields");
            return;
        }

        String dob;
        if ((findViewById(R.id.txtDateOfBirth).toString().length() > 0))
        {
            dob=(findViewById(R.id.txtDateOfBirth).toString());
        }
        else
        {
            lblError.setText("Error - please fill all necessary fields");
            return;
        }

        Spinner grabSection=findViewById(R.id.spinSection);
        String section=(grabSection.getSelectedItem().toString());

        boolean sex;
        int genderselected=genderGroup.getCheckedRadioButtonId();
        if (genderselected==2131165338)
        {
            sex=true; //True means male
        }
        else if (genderselected==2131165337)
        {
            sex=false;
        }
        else
        {
            lblError.setText("Error - please fill all necessary fields");
            genderID.setText("ID: "+ genderselected);
            return;
        }

        String address1;
        if ((findViewById(R.id.txtAddress1).toString()).length() > 0)
        {
            address1=(findViewById(R.id.txtAddress1).toString());
        }
        else
        {
            lblError.setText("Error - please fill all necessary fields");
            return;
        }

        String address2;
        if ((findViewById(R.id.txtAddress2).toString()).length() > 0)
        {
            address2=(findViewById(R.id.txtAddress2).toString());
        }
        else
        {
            lblError.setText("Error - please fill all necessary fields");
            return;
        }

        String city;
        if ((findViewById(R.id.txtCity).toString()).length() > 0)
        {
            city=(findViewById(R.id.txtCity).toString());
        }
        else
        {
            lblError.setText("Error - please fill all necessary fields");
            return;
        }

        String postcode;
        if ((findViewById(R.id.txtPostCode).toString()).length() > 0)
        {
            postcode=(findViewById(R.id.txtPostCode).toString());
        }
        else
        {
            lblError.setText("Error - please fill all necessary fields");
            return;
        }

        String religion;
        if ((findViewById(R.id.txtReligion).toString()).length() > 0)
        {
            religion=(findViewById(R.id.txtReligion).toString());
        }
        else
        {
            lblError.setText("Error - please fill all necessary fields");
            return;
        }

        String emergencyname;
        if ((findViewById(R.id.txtEmergencyContactName).toString()).length() > 0)
        {
            emergencyname=(findViewById(R.id.txtEmergencyContactName).toString());
        }
        else
        {
            lblError.setText("Error - please fill all necessary fields");
            return;
        }

        int emergencyhome;
        if ((HomePhone.toString()).length() > 0)
        {
            emergencyhome=Integer.parseInt(findViewById(R.id.txtEmergencyHomePhone).toString());
        }
        else
        {
            lblError.setText("Error - please fill all necessary fields");
            return;
        }

        int emergencymobile;
        if ((findViewById(R.id.txtEmergencyMobilePhone).toString()).length() > 0)
        {
            emergencymobile=Integer.parseInt(findViewById(R.id.txtEmergencyMobilePhone).toString());
        }
        else
        {
            lblError.setText("Error - please fill all necessary fields");
            return;
        }

        String emergencyemail;
        if ((findViewById(R.id.txtEmergencyEmail).toString()).length() > 0)
        {
            emergencyemail=(findViewById(R.id.txtEmergencyEmail).toString());
        }
        else
        {
            lblError.setText("Error - please fill all necessary fields");
            return;
        }

        String medicaldetails;
        if ((findViewById(R.id.txtMedicalDetails).toString()).length() > 0)
        {
            medicaldetails=(findViewById(R.id.txtMedicalDetails).toString());
        }
        else
        {
            lblError.setText("Error - please fill all necessary fields");
            return;
        }

        String allergies;
        if ((findViewById(R.id.txtAllergies).toString()).length() > 0)
        {
            allergies=(findViewById(R.id.txtAllergies).toString());
        }
        else
        {
            lblError.setText("Error - please fill all necessary fields");
            return;
        }

        String lasttetanus;
        if ((findViewById(R.id.txtLastTetanus).toString()).length() > 0)
        {
            lasttetanus=(findViewById(R.id.txtLastTetanus).toString());
        }
        else
        {
            lblError.setText("Error - please fill all necessary fields");
            return;
        }

        int swimmingability;
        String swimmingString=(findViewById(R.id.listSwimmingAbility).toString());
        if (swimmingString.equals("Unable to swim"))
        {
            swimmingability=0;
        }
        else if (swimmingString.equals("Fairly confident"))
        {
            swimmingability=1;
        }
        else if (swimmingString.equals("Very confident"))
        {
            swimmingability=2;
        }
        else
        {
            lblError.setText("Error - an unknown error has occurred.  Please try again.");
            return;
        }

        String school;
        if ((findViewById(R.id.txtSchool).toString()).length() > 0)
        {
            school=(findViewById(R.id.txtSchool).toString());
        }
        else
        {
            lblError.setText("Error - please fill all necessary fields");
            return;
        }

        boolean photos;
        int photosAllowed=photoGroup.getCheckedRadioButtonId();
        if (photosAllowed==0)
        {
            photos=true; //True means male
        }
        else if (photosAllowed==1)
        {
            photos=false;
        }
        else
        {
            lblError.setText("Error - please fill all necessary fields");
            genderID.setText("Photo ID: "+ photosAllowed);
            return;
        }

        String moveup;
        if ((findViewById(R.id.txtMoveUp).toString()).length() > 0)
        {
            moveup=(findViewById(R.id.txtMoveUp).toString());
        }
        else
        {
            lblError.setText("Error - please fill all necessary fields");
            return;
        }

        scoutDetails Scout=new scoutDetails(id, firstname, lastname, dob, section, sex, address1, address2, city, postcode, religion, emergencyname, emergencyhome, emergencymobile, emergencyemail, medicaldetails, allergies, lasttetanus, swimmingability, school, photos, moveup);
        db.createScout(Scout);

        backToScoutMenu(v);

    }
}

2 个答案:

答案 0 :(得分:0)

如果txtEmergencyHomePhone是一个EditText,则需要从中获取实际文本。

findViewById(R.id.txtEmergencyHomePhone).toString()是错误的。

您需要使用

EditText editText = findViewById(R.id.txtEmergencyHomePhone);
String text = editText.getText().toString();

然后将其解析为int。

答案 1 :(得分:0)

请勿使用toString()从EditText获取整数。 这是从EditText获取整数的方法:

//Create and initialize your EditText
EditText editText = findViewById(R.id.txtEmergencyHomePhone);

//Get the String that's contained in the EditText
String userInput = editText.getText().toString();

//Convert the String to an Integer
int emergencyHome = Integer.parseInt(userInput);

如果您想将所有这些都合并在一行中(就像忍者一样),那么这就是要走的路:

int emergencyHome = Integer.parseInt(((EditText) findViewById(R.id.txtEmergencyHomePhone)).getText().toString());

我希望这会有所帮助。.编码愉快!