java - 由于文本输入错误,应用程序不断崩溃
问题描述
当我在 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);
}
});
}
}
解决方案
name.getText()
它因为获取空值而崩溃。if
用声明包围String fullName = name.getText().toString();
例子 :
String fullName;
if(!name.getText().toString().isEmpty()){
fullName = name.getText().toString();
}
推荐阅读
- python - botocore.exceptions.clienterror 调用copyobject操作时发生错误(keyTooLongError)
- unity3d - Unity中如何将两个着色器合并为一个着色器
- python - 有没有办法让一个循环有两个范围?
- c# - 在一个国家/地区生成随机纬度/经度多边形?
- hibernate - 休眠缓存不适用于一对一关系的反面
- python - matplotlib:使用 matplotlib 或 seaborn 显示每个日期的所有产品价格的折线图
- reactjs - 如何在数组中添加对象
- angular - ngbTooltip 和 ngb 分页不起作用
- python - `__dict__` 何时重新初始化?
- c++ - 如何使用 libpqxx 获取 postgres sqlerrorcode?