Reputation: 13
I am having this issue with Edittext in android studio.The app works fine but app crashes with no input
Here is the java code
public void onButtonClick (View v)
{
int num1,num2,sum;
EditText e1 = (EditText)findViewById(R.id.num1);
EditText e2 = (EditText)findViewById(R.id.num2);
TextView t1 = (TextView)findViewById(R.id.sum);
num1 = Integer.parseInt(e1.getText().toString());
num2 = Integer.parseInt(e2.getText().toString());
sum = num1 + num2;
t1.setText(Integer.toString(sum));
}
Upvotes: 0
Views: 2007
Reputation: 5629
Integer.parseInt()
fails when no input is given, calculate only if there is an input.
public void onButtonClick (View v)
{
int num1 = 0,num2 = 0,sum = 0;
EditText e1 = (EditText)findViewById(R.id.num1);
EditText e2 = (EditText)findViewById(R.id.num2);
TextView t1 = (TextView)findViewById(R.id.sum);
if(!(e1.getText().toString()).equals(""))
num1 = Integer.parseInt(e1.getText().toString());
if(!(e2.getText().toString()).equals(""))
num2 = Integer.parseInt(e2.getText().toString());
sum = num1 + num2 ;
t1.setText(sum.toString());
}
Your application will crash if the given input is not a number.
To make an EditText only accept numbers
In the xml file use this
<EditText
android:inputType="number"
android:digits="0123456789."
/>
Upvotes: 2