字符串为空时如何停止应用崩溃 [英] How to stop the app crashing when String is empty
本文介绍了字符串为空时如何停止应用崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
没有文本时,应用程序崩溃!
我没有什么可以解决的!
谢谢
The app crash when there is no text ! I don't have what 'if' to put to fix that ! Thanks you
enter TextView TotalTextView;
EditText EnterPercentage;
EditText EnterPrice;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TotalTextView = (TextView) findViewById(R.id.TotalTextView);
EnterPercentage = (EditText) findViewById(R.id.EnterPercentage);
EnterPrice = (EditText) findViewById(R.id.EnterPrice);
Button CalcBtn = (Button) findViewById(R.id.CalcBtn);
CalcBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
float percentage = Float.parseFloat(EnterPercentage.getText().toString());
float prix = Float.parseFloat(EnterPrice.getText().toString());
float dec = percentage / 100;
float total = prix - dec * Float.parseFloat(EnterPrice.getText().toString());
TotalTextView.setText(String.format("%.2f", total));
}
});
感谢您的回答,我是一个初学者,所以...谢谢!
Thank for your answer, I am a begineer so... Thanks !
if (EnterPercentage.getText().equals("")) {
float percentage = Float.parseFloat(EnterPercentage.getText().toString());
float prix = Float.parseFloat(EnterPrice.getText().toString());
float dec = percentage / 100;
float total = prix - dec * Float.parseFloat(EnterPrice.getText().toString());
TotalTextView.setText(String.format("%.2f", total));
} else {
}
按钮不执行任何操作,但应用程序不会崩溃
the button don't do anything but the app doesn't crash
推荐答案
我们检查String的长度...为0时,我们什么也不做。当String> 0时,您的代码正在运行。
We check the length of the String... when it's 0 then we do nothing. When the String > 0 your code is running.
赞:
if (EnterPercentage.getText().trim().toString().length() == 0 || EnterPrice.getText().toString().length() == 0 ) {
//Textfields are empty.
Log.d("Error","Fields are empty");
} else {
//Textfield is full
float percentage = Float.parseFloat(EnterPercentage.getText().toString());
float prix = Float.parseFloat(EnterPrice.getText().toString());
float dec = percentage / 100;
float total = prix - dec * Float.parseFloat(EnterPrice.getText().toString());
TotalTextView.setText(String.format("%.2f", total));
}
这篇关于字符串为空时如何停止应用崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文