问题
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 field text.
Unfortunately if nothing is entered and the user clicks the button the application crashes.
Could anyone help me put it into code:
If editText is empty and button is clicked display 0.00 in the answer text field.
or the other way if editText is empty and button is pressed display toast message
?
If anyone understands what I am talking about and can help I would greatly appreciate it as I want to improve my applications for users before publishing ;-)
my updated code:
EditText editText = (EditText)findViewById(R.id.editText);
Double num1 = 0.0;
final String myStr = editText.getText().toString();
if (!myStrisEmpty())
{
num1 = Double.parseDouble(myStr);
}
else
{
Toast.makeText(getApplicationContext(), getResources().getString(R.string.noinput),
Toast.LENGTH_LONG).show();
}
Problem is this: final String myStr = editText.getText().toString(); //editText is in red if (!myStrisEmpty()) //(!myStrisEmpty()) is in red
Ive been trying for hours and days to acomplish this task. simply have made a app where the user enters a number then clicks the button to convert the number and display it below into a textview answer. If i dont enter anything and click the button the app crashes. I would like a toast message instead of it crashing saying "Please Enter a Number"
回答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:
EditText editText = (EditText) findViewById(R.id.editText);
Double num1 = Double.parseDouble(editText.getText().toString());
to
EditText editText = (EditText)findViewById(R.id.editText);
Double num1 = 0.0;
final String 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);
回答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);
}
回答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));
来源:https://stackoverflow.com/questions/23029262/android-app-crashes-when-nothing-is-entered-and-button-is-pressed