I am doing a simple program for addition of two numbers which are input from EditText.
But when user clicks the button ‘Click to Add’ leaving the fields empty, program exits saying ‘Unfortunately, program has stopped.’
Here is the code:
public class MainActivity extends Activity {
long a, b, sum;
Button add, clr;
EditText e1, e2, res;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add = (Button) findViewById(R.id.bAdd);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) throws NumberFormatException {
// TODO Auto-generated method stub
e1 = (EditText) findViewById(R.id.tv1);
String str1 = e1.getText().toString();
e2 = (EditText) findViewById(R.id.tv2);
String str2 = e2.getText().toString();
try{
a = Integer.parseInt(str1);
b = Integer.parseInt(str2);
}catch(NumberFormatException e){
res.setText("Please enter valid entries");
}
sum = a + b;
res = (EditText) findViewById(R.id.result);
res.setText("Your sum is " + sum);
}
});
clr = (Button) findViewById(R.id.bClr);
clr.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) throws NumberFormatException {
// TODO Auto-generated method stub
e1.setText("");
e2.setText("");
res.setText("");
}
});
}
}
I want the app to respond ‘Please enter valid entries’ for blank EditText entries.
Your line:
must be moved so that your res variable is initialized before you use
res.setText. It’s not initialized in your catch statement.Move it to the position indicated below. You can initialise it when you do your other
findViewById