【发布时间】:2018-10-23 07:01:15
【问题描述】:
我一直在努力解决这个问题,每次我的应用程序中有一个空白字段时都会崩溃。
当我运行代码时,它告诉我第 32 行和第 37 行有一个错误,就在我将字符串从 textView 转换为整数以对这些数字进行操作的地方
如果你们能看看这个就太好了。
package com.studium.second.secondtest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
Activity miActividad;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
miActividad = this;
Button calcular = findViewById(R.id.button1);
calcular.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView textoBase = findViewById(R.id.areaBase);
String base = textoBase.getText().toString();
int numeroBase = Integer.parseInt(base);
TextView textoAltura = findViewById(R.id.areaAltura);
String altura = textoAltura.getText().toString();
int numeroAltura = Integer.parseInt(altura);
//Operación
final TextView cajaResultado = findViewById(R.id.areaResultado);
final int operacion = numeroAltura * numeroBase;
cajaResultado.setText(getResources().getString(R.string.textoResultado ) + " " + operacion);
if (base == null && altura != null){
AlertDialog.Builder builder = new AlertDialog.Builder(miActividad.getApplicationContext());
builder.setMessage("El parámetro base está vacío")
.setCancelable(false)
.setNegativeButton("Volver", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
if (base != null && altura == null){
AlertDialog.Builder builder = new AlertDialog.Builder(miActividad.getApplicationContext());
builder.setMessage("El parámetro altura está vacío")
.setCancelable(false)
.setNegativeButton("Volver", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
if (base == null && altura == null){
AlertDialog.Builder builder = new AlertDialog.Builder(miActividad.getApplicationContext());
builder.setMessage("Todos los parámetros están vacíos")
.setCancelable(false)
.setNegativeButton("Volver", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
});
}
}
【问题讨论】:
-
你的
String是空的,这就是为什么 -
先初始化你的字符串然后检查 if(base.gettext()!=""){...}