Android App Crashes When Nothing Is Entered And Button Is Pressed
Hi I am working on an Android App and would like to ask for some help: The user enters a numbers on a editText and presses/clicks the button to get a conversion displayed in answer
Solution 1:
You are trying to convert an empty string to a number. What you should do is a check if the string is not empty:
Change these lines:
EditTexteditText= (EditText) findViewById(R.id.editText);
Doublenum1= Double.parseDouble(editText.getText().toString());
to
EditText editText = (EditText)findViewById(R.id.editText);
Double num1 = 0.0;
finalString myStr = editText.getText().toString();
if (!myStr.isEmpty())
{
num1 = Double.parseDouble(myStr);
}
else
{
Toast.makeText(getApplicationContext(), getResources().getString(R.string.noinput),
Toast.LENGTH_LONG).show();
}
You might replace getResources().getString(R.string.noinput) (set it in your /values/strings.xml
folder) by a hardcoded string (but that's not a good practice), like "You didn't enter any value"
And this:
answer.setText(ans.toString());
should be:
answer.setText("" + ans);
Solution 2:
If i understood you weel, what you are trying to achieve is this:
String input = editText.getText().toString();
if (input.isEmpty())
textView.setText("0.00");
else{
// do whatever conversions
textView.setText(result);
}
Solution 3:
I think this is because you are calling the toString() method on a primitive. Try this:
Replace:
answer.setText(ans.toString());
With:
answer.setText(String.valueOf(ans));
Post a Comment for "Android App Crashes When Nothing Is Entered And Button Is Pressed"