Issue With Empty Edittext
I have an Activity with an EditText, Button and TextView. If I write some numbers and click the button, the TextView shows the result of the calculation. If the EditText is empty
Solution 1:
You just need to do a check on what the user has typed:
String input = editText.getText().toString();
if(input == null || input.trim().equals("")){
Toast.makeText(context, "Sorry you did't type anything"), Toast.LENGTH_SHORT).show();
}
EDIT
If you have a float, you have to do the check before you parse the float:
String input = editText.getText().toString();
if(input == null || input.trim().equals("")){
// Toast messagereturn;
}
float num1 = Float.parseFloat(input);
or
try{
float num1 = Float.parseFloat(numA.getText().toString());
} catch (NumberFormatException e) {
// Toast message - you cannot get a float from that inputreturn;
}
Solution 2:
You need to make sure that the EditText isn't empty. Try using something like:
EditTexteditText= (EditText) findViewById(R.id.edittext);
Stringtext= editText.getText().toString();
if (text == null || text.equals("")) {
Toast.makeText(this, "You did not enter a number", Toast.LENGTH_SHORT).show();
return;
}
Solution 3:
Pretty simple. Before you start calculations you should call the following code:
if (editText.getText().length() > 0) {
// do the calculations
}
This way you'll know whether there is something in your EditText
or not. If it's empty you can show an AlertDialog
or a Toast
to help your users. Hope this helps.
Post a Comment for "Issue With Empty Edittext"