由于文本输入错误,应用程序不断崩溃[重复]
Posted
技术标签:
【中文标题】由于文本输入错误,应用程序不断崩溃[重复]【英文标题】:App keeps crashing due to error in text input [duplicate] 【发布时间】:2019-05-02 03:12:56 【问题描述】:当我在 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
为空(来自 findViewById),或者.getText()
为空;我敢打赌前者。在链式调用之前添加检查。
【参考方案1】:
它崩溃是因为name.getText()
正在获取空值。在String fullName = name.getText().toString();
中用if
语句包围
例子:
String fullName;
if(!name.getText().toString().isEmpty())
fullName = name.getText().toString();
【讨论】:
这种方法不能解决问题。如果name
为null,这种方法仍然会抛出NPE。以上是关于由于文本输入错误,应用程序不断崩溃[重复]的主要内容,如果未能解决你的问题,请参考以下文章
应用程序不断因 NullPointerException 而崩溃 [重复]
UIViewControllerHierarchyInconsistency 错误 - 应用程序不断崩溃