我创建了一个简单的应用来计算折扣。它在提供值时工作正常,但在使用空文本字段进行计算时会继续崩溃。在此先感谢.. !!
public class Firstctivity extends AppCompatActivity {
Button find;
EditText ed1,ed2;
TextView tv1;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_firstctivity);
find=(Button)findViewById(R.id.button);
tv1=(TextView)findViewById(R.id.text39);
ed1=(EditText)findViewById(R.id.sai);
ed2=(EditText)findViewById(R.id.editText);
find.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
final double a =Double.parseDouble(String.valueOf(ed1.getText()));
final double b =Double.parseDouble(String.valueOf(ed2.getText()));
double results;
double c;
try {
c = a * b;
results = c / 100;
String total2 = String.valueOf(results);
// String total2="fuck u";
tv1.setText("You have recieved Rs" + total2 + "/- concession.");
tv1.setBackgroundColor(Color.parseColor("#4169E1"));
}
catch (NumberFormatException ex)
{
}
}
});
}
}
答案 0 :(得分:1)
find.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if(ed1.getText().toString.length() >0){
try {
final double a =Double.parseDouble(String.valueOf(ed1.getText()));
final double b =Double.parseDouble(String.valueOf(ed2.getText()));
double results;
double c;
c = a * b;
results = c / 100;
String total2 = String.valueOf(results);
// String total2="fuck u";
tv1.setText("You have recieved Rs" + total2 + "/- concession.");
tv1.setBackgroundColor(Color.parseColor("#4169E1"));
}
catch (NumberFormatException ex)
{
}
}
}
});
答案 1 :(得分:1)
当您尝试计算折扣时,请调用ed1.getText()
,然后尝试将空值转换为double值,导致NullPointerException
。
要解决该问题,您必须检查getText()方法是否返回有效文本以进行转换。
答案 2 :(得分:0)
您需要检查空字符串和空值:
find.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ed1.getText() != null && !TextUtils.isEmpty(ed1.getText().toString()) &&
ed2.getText() != null && !TextUtils.isEmpty(ed2.getText().toString())) {
try {
final double a = Double.parseDouble(String.valueOf(ed1.getText().toString()));
final double b = Double.parseDouble(String.valueOf(ed2.getText().toString()));
double c = a * b;
double results = c / 100;
String total2 = String.valueOf(results);
// String total2="fuck u";
tv1.setText("You have recieved Rs" + total2 + "/- concession.");
tv1.setBackgroundColor(Color.parseColor("#4169E1"));
} catch (NumberFormatException ex) {
Log.e("SOME TAG", ex.getMessage(), ex);
}
}
}
});
答案 3 :(得分:0)
所以,只是为了澄清;删除try-catch。做if-stament并检查你的txt字段是否为空,然后再进行任何计算。完成点击事件没有任何问题和有效的计算。