eclipse - 当EditText为空时,android应用程序崩溃

时间:2013-02-21 20:46:15

标签: java android android-edittext

美好的一天。我在eclipse中为android编写应用程序,当EditText是空应用程序崩溃时。我尝试了很多方法,但它不起作用。当我输入它并且EditText是emty时,每次崩溃都会崩溃。对不起我的英语不好。 这是我的代码的一部分:

public class MainActivity extends Activity implements OnClickListener {

TextView mnozstvo;
TextView percento;
TextView hmotnost;
TextView vysledok1;
TextView vysledok2;
TextView text;
RadioButton muz1;
RadioButton zena1;
Button vysledok;
EditText coo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

text = (TextView)this.findViewById(R.id.text);

mnozstvo = (TextView)this.findViewById(R.id.dl);


percento = (TextView)this.findViewById(R.id.per);

hmotnost = (TextView)this.findViewById(R.id.kg);

vysledok1 = (TextView)this.findViewById(R.id.krv);

vysledok2 = (TextView)this.findViewById(R.id.dych);

muz1 = (RadioButton)this.findViewById(R.id.muz);

zena1 = (RadioButton)this.findViewById(R.id.zena);

vysledok = (Button)this.findViewById(R.id.vysledok);

vysledok.setOnClickListener(this);


}
.................
public void convertDollarsToEuros() {
double val = Double.parseDouble(mnozstvo.getText().toString());
double val1 = Double.parseDouble(percento.getText().toString());
double val2 = Double.parseDouble(hmotnost.getText().toString());

vysledok1.setText(Double.toString((val*val1*0.8)/(val2*0.68)));
vysledok2.setText(Double.toString(((val*val1*0.8)/(val2*0.68))/(2.1)));

text.setText(Double.toString(((val*val1*0.8)/(val2*0.68))*6.6164));



}

public void convertEurosToDollars() {

double val = Double.parseDouble(mnozstvo.getText().toString());
double val1 = Double.parseDouble(percento.getText().toString());
double val2 = Double.parseDouble(hmotnost.getText().toString());

vysledok1.setText(Double.toString((val*val1*0.8)/(val2*0.55)));
vysledok2.setText(Double.toString(((val*val1*0.8)/(val2*0.55))/(2.1)));
text.setText(Double.toString(((val*val1*0.8)/(val2*0.55))*6.6164));

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

Double.parseDouble()将引发NumberFormatException。

但是,不是等待异常发生然后处理它,你可以在尝试解析它之前检查字符串的长度。

您的代码应如下所示:

public void convertEurosToDollars() {
    double val = 0;
    double val1= 0;
    double val2= 0;
    if (mnozstvo.getText().length() > 0 ) {
        val = Double.parseDouble(mnozstvo.getText().toString());
    }
    if (percento.getText().length() > 0 ) {
        val2 = Double.parseDouble(percento.getText().toString());
    }
    if (hmotnost.getText().length() > 0 ) {
        val3 = Double.parseDouble(hmotnost.getText().toString());
    }       


    vysledok1.setText(Double.toString((val*val1*0.8)/(val2*0.55)));
    vysledok2.setText(Double.toString(((val*val1*0.8)/(val2*0.55))/(2.1)));
    text.setText(Double.toString(((val*val1*0.8)/(val2*0.55))*6.6164));
   }