我有一个名为alt的edittext。它的输入类型是十进制数。我无法捕获空指针异常。如果edittext为空或未输入任何值,则我的应用程序崩溃。我在stackoverflow中搜索了很多,但找不到解决方案。 我尝试过使用以下
alt.getText().toString().equals("");
alt.getText().toString().matches("");
alt.getText().toString().contains("");
alt.getText().toString().trim().length() == 0;
Textutill.isEmpty(alt.getText());
我在try / catch语句中做了什么
这是我的代码
<EditText
android:id="@+id/eps"
android:layout_width="123dp"
android:layout_height="19dp"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:background="@android:color/white"
android:ems="10"
android:inputType="number|numberSigned|numberDecimal"
android:text="500"
android:textColor="@android:color/black"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.056" />
的java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_abu);
calculate = (Button) findViewById(R.id.button);
alt = (EditText) findViewById(R.id.eps);
public void calculateABU() {
calculate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
altValue = Float.valueOf(alt.getText().toString());
try{
if (altValue > 10000 || altValue < -400) {
Toast.makeText(getApplicationContext(), "-400 <= Altitude <= 10000 m", Toast.LENGTH_LONG).show();
}
}
catch (NullPointerException e){
if(TextUtils.isEmpty(alt.getText())){
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG).show();
}
}
答案 0 :(得分:0)
在召集浮动之前尝试Nullcheck
calculate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!TextUtils.isEmpty(alt.getText().toString())){
altValue = Float.valueOf(alt.getText().toString());
if (altValue > 10000 || altValue < -400) {
Toast.makeText(getApplicationContext(), "-400 <= Altitude <= 10000 m", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG).show();
}
}