You can set android:hint="0" in your XML file, and then in your code you can check if it is empty (possibly using TextUtils.isEmpty() ) and set some variable to 0.
android:hint="0" will make "0" in your EditText s, but "0" will disappear when something is entered.
Then you can change onClick() to the following:
class clicker implements Button.OnClickListener { public void onClick(View v) { String a,b,c,d; Integer vis; a = txtbox1.getText().toString(); b = txtbox2.getText().toString(); c = txtbox3.getText().toString(); d = txtbox4.getText().toString(); try { vis = Integer.parseInt(a)*2+Integer.parseInt(b)*3+Integer.parseInt(c)*4+Integer.parseInt(d)*5; tv.setText(vis.toString()); } catch (NumberFormatException e) { vis = "0"; }
Or you can create a method to check the value, try to parse to int or return the default value.
public int getInt(String edtValue, int defaultValue) { int value = defaultValue; if (edtValue != null) { try { value = Integer.parseInt(edtValue); } catch (NumberFormatException e) { value = defaultValue; } } return value; }
Then you change your call to
vis = this.getInt(a, 0) * 2 + this.getInt(b, 0) * 3 + this.getInt(c, 0) * 4 + this.getInt(d, 0) * 5;
source share