首页 > 解决方案 > 由于文本输入错误,应用程序不断崩溃

问题描述

当我在 android studio 中按下按钮启动它时,我的项目合作伙伴的代码不断崩溃。这是我在 logcat 中遇到的错误。
原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法 'android.text.Editable android.widget.EditText.getText()'。

这指的是第 21 行,其中: String fullName = name.getText().toString();

帮助?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



    Intent intent = new Intent(MainActivity1.this, SecondActivity.class);

    EditText name = (EditText)findViewById(R.id.entName);
    String fullName = name.getText().toString();
    intent.putExtra("name_key", fullName);

    EditText ages = findViewById(R.id.age);
    String age = ages.getText().toString();
    intent.putExtra("age_key", age);

    RadioGroup gender = findViewById(R.id.genRGroup);
    int genderPos = gender.getCheckedRadioButtonId();
    int male = findViewById(R.id.male).getId();
    int female = findViewById(R.id.female).getId();
    String gen;

    if (genderPos == male) {
        gen = "Male";
    } else if (genderPos == female) {
        gen = "Female";
    } else {
        gen = "Other";
    }
    intent.putExtra("gen_key", gen);

    Button theBtn = findViewById(R.id.addAPersonButt);
    theBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intents = new Intent (MainActivity1.this, MainActivity2.class);
            startActivity(intents);
        }
    });

    Button conButt = findViewById(R.id.confirm);
    conButt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity1.this, SecondActivity.class);

            EditText name = findViewById(R.id.entName);
            String fullName = name.getText().toString();
            intent.putExtra("name_key", fullName);

            EditText ages = findViewById(R.id.age);
            String age = ages.getText().toString();
            intent.putExtra("age_key", age);

            RadioGroup gender = findViewById(R.id.genRGroup);
            int genderPos = gender.getCheckedRadioButtonId();
            int male = findViewById(R.id.male).getId();
            int female = findViewById(R.id.female).getId();
            String gen;

            if (genderPos == male) {
                gen = "Male";
            } else if (genderPos == female) {
                gen = "Female";
            } else {
                gen = "Other";
            }
            intent.putExtra("gen_key", gen);

            startActivity(intent);
        }
    });

}

}

标签: javanullpointerexceptiontextinput

解决方案


name.getText()它因为获取空值而崩溃。if用声明包围String fullName = name.getText().toString();

例子 :

String fullName;
if(!name.getText().toString().isEmpty()){
    fullName = name.getText().toString();
}

推荐阅读