防止android应用程序崩溃
我有一个我创建的非常简单的转换器应用程序,如果数据输入到一个或另一个文本框中,它可以正常工作,但是如果我将它们都留空,然后单击一个或另一个转换按钮,它就会崩溃,所以我尝试包含一个if语句来处理这个问题,但它似乎忽略了该语句,并且无论如何都会崩溃。基本上我想做的是,如果点击按钮,没有输入数字,只需在屏幕上弹出一条消息,要求用户输入数据防止android应用程序崩溃,android,Android,我有一个我创建的非常简单的转换器应用程序,如果数据输入到一个或另一个文本框中,它可以正常工作,但是如果我将它们都留空,然后单击一个或另一个转换按钮,它就会崩溃,所以我尝试包含一个if语句来处理这个问题,但它似乎忽略了该语句,并且无论如何都会崩溃。基本上我想做的是,如果点击按钮,没有输入数字,只需在屏幕上弹出一条消息,要求用户输入数据 public class MainActivity extends Activity { @Override protected void onCreate(Bu
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText txtCentimetersValue = (EditText) findViewById(R.id.txtCentimetersValue);
final EditText txtInchesValue = (EditText) findViewById(R.id.txtInchesValue);
Button btnConvert = (Button) findViewById(R.id.btnConvert);
Button btnConvert2 = (Button) findViewById(R.id.btnConvert2);
Button btnClear = (Button) findViewById(R.id.btnClear);
btnClear.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0)
{
txtCentimetersValue.setText("");
txtInchesValue.setText("");
}
});
btnConvert.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0)
{
txtInchesValue.setText("");
double centimeters = Double.valueOf(txtCentimetersValue.getText().toString());
double inches = centimeters / 0.393700787;
txtInchesValue.setText(String.valueOf(inches));
}
});
btnConvert2.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0)
{
txtCentimetersValue.setText("");
double inches = Double.valueOf(txtInchesValue.getText().toString());
double centimeters = inches / 0.393700787;
txtCentimetersValue.setText(String.valueOf(centimeters));
}
});
}
}
所以我尝试包含一个if语句来处理这个问题,但它似乎忽略了那个语句,并崩溃了
我没有看到if语句,可能是您试图使用==
来比较字符串(这在Java中是无法做到的),或者认为值是null
。无论如何,您只需使用isEmpty()
:
做一些类似于英寸到厘米的事情。我同意《阿凡达》很奇怪,不知道他们为什么用它,无论如何,它工作得很好,谢谢!很高兴我能帮忙!不要忘记通过单击复选标记接受此答案作为解决方案。
String value = txtCentimetersValue.getText().toString();
if(!value.isEmpty()) {
double centimeters = Double.valueOf(value);
double inches = centimeters / 0.393700787;
txtInchesValue.setText(String.valueOf(inches));
}