当我按下一个按钮在android studio中启动它时,我的项目合作伙伴的代码不断崩溃。这是我在logcat中遇到的错误。
原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'android.text.Editable android.widget.EditText.getText()'。
这是指第21行,其中:字符串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);
}
});
}
}
答案 0 :(得分:0)
由于name.getText()
获取空值而崩溃。在if
String fullName = name.getText().toString();
语句包围
示例:
String fullName;
if(!name.getText().toString().isEmpty()){
fullName = name.getText().toString();
}