I'm a beginner in Android development. I am making a basic square equations solver. I use the code below to get strings from EditText elements:
a = mA.getText().toString(); b = mB.getText().toString(); c = mC.getText().toString(); Then I use Double.valueOf() method to convert them into doubles and solve the equatation(s is a Solver instance):
mSolution.setText(s.solve(Double.valueOf(a), Double.valueOf(b), Double.valueOf(c))); If EditText is empty, an attempt to solve it gives me an exception
java.lang.NumberFormatException: Invalid double: ""
I guess, the .toString() method returns null or "", but the if statement doesn't work here :c.
5 Answers
you should check Strings with equals like
if(!"".equals(mB.getText().toString())) //then your if statement 1Why dont you catch that Exception?
try{ mSolution.setText(s.solve(Double.valueOf(a),Double.valueOf(b), Double.valueOf(c))); } catch(NumberFormatException e){ //whatever you feel necessary to do when en empty string is presented } Advantage: You don't have to check every String for its correctness. Disadvantage: You dont know which String is not correct. BUT: You could for example insert Arashs code in the catch, so that at that point you can check which string is faulty.
You got java.lang.NumberFormatException: Invalid double: "" because you trying to convert NULL value into Double
so before convert this value you must check the String is null or not like below:
if(!a.equals("") && !b.equals("") && !c.equals("")){ //Do your job } Try this
try { if (a != null && a.length != 0 && b != null && b.length != 0 && b != null && b.length != 0) { mSolution.setText(s.solve(Double.valueOf(a), Double.valueOf(b), Double.valueOf(c))); } } catch (NumberFormatException e) { e.printStackTrace(); } You are getting java.lang.NumberFormatException: Invalid double: "" because the values of a',b, orc` is sometime empty i.e "".
Double.valueOf() will return NumberFormatException if it is empty. To avoid this you can give check points like below,
if(mA.getText().toString().equals("") ||mB.getText().toString().equals("")||mC.getText().toString().equals("") ) { Toast.makeText(getApplicationContext(), "Edittext is empty", Toast.LENGTH_SHORT).show(); } else { a = mA.getText().toString(); b = mB.getText().toString(); c = mC.getText().toString(); }