java - Program crashes with empty text field -
i need trying fix code. thought simple (probably is) can't it. have simple adding calculator. works fine, if leave 1 or both number text fields empty, program crashes.
i have if statement, apparently not telling right thing.
public class mainactivity extends activity { double firstnum, secondnum, answernum; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); final edittext first = (edittext) findviewbyid(r.id.txtfirst); final edittext second = (edittext) findviewbyid(r.id.txtsecond); final textview answer = (textview) findviewbyid(r.id.txtanswer); button calc = (button) findviewbyid(r.id.btncalc); calc.setonclicklistener(new onclicklistener() { @override public void onclick(view v) { // todo auto-generated method stub // convert pulled info double using variable names firstnum = double.parsedouble(first.gettext().tostring()); secondnum = double.parsedouble(second.gettext().tostring()); if (first == null || second == null) { toast.maketext(mainactivity.this, "please enter value", toast.length_short).show(); } else { // add numbers answernum = (firstnum + secondnum); //set format decimalformat total = new decimalformat ("###,###,###.##"); answer.settext("answer " + total.format(answernum)); } } }); } }
if want validate edittext means try following code work fine.
public class mainactivity extends activity { double firstnum = 0; double secondnum = 0, answernum; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); final edittext first = (edittext) findviewbyid(r.id.edittext1); final edittext second = (edittext) findviewbyid(r.id.edittext2); final textview answer = (textview) findviewbyid(r.id.textview1); button calc = (button) findviewbyid(r.id.button1); calc.setonclicklistener(new onclicklistener() { @override public void onclick(view v) { // todo auto-generated method stub if (first.gettext().tostring().equals("") || second.gettext().tostring().equals("")) { toast.maketext(mainactivity.this, "please enter value", toast.length_short).show(); } else { firstnum = double.parsedouble(first.gettext().tostring()); secondnum = double.parsedouble(second.gettext().tostring()); answernum = (firstnum + secondnum); decimalformat total = new decimalformat("###,###,###.##"); answer.settext("answer " + total.format(answernum)); } } }); } }
Comments
Post a Comment