Reputation: 31
I have a problem trying to check if a EditText is empty or not. I have found a lot of solutions but all of them reffer to a string variable. I wanna check if a value that is Integer between 0 and 10 is empty or not.
Here is my code:
int value = Integer.parseInt(instances.getText().toString());;
if (value > 10)
Toast.makeText(getApplicationContext(), "Enter a value between 0 and 10!", Toast.LENGTH_SHORT).show();
else if (value < 0)
Toast.makeText(getApplicationContext(), "Enter a value between 0 and 10!", Toast.LENGTH_SHORT).show();
else if (value >= 0 && value <= 10) {
schimba(v);
}
If I enter a number > 10 I get the toast, same if I enter a negative number.The function work great when I enter the number between 0 and 10 but if I let empty I get an error and I need to create the condition but I can't find something to integer.
Any help would be great, thank you in advance.
Upvotes: 0
Views: 5939
Reputation: 10414
A simplified sample code
int value = instances.getText().toString()!=null && !instances.getText().toString().equals("") ? Integer.parseInt(instances.getText().toString()) : -1;
if (value < 0 || value > 10){
Toast.makeText(getApplicationContext(), "Enter a value between 0 and 10!", Toast.LENGTH_SHORT).show();
}else{
schimba(v);
}
Upvotes: 0
Reputation: 10274
String _data = instances.getText().toString().lenght()
if (_data > 0){
int value = Integer.parseInt(_data );;
if(value > 10)
Toast.makeText(getApplicationContext(), "Enter a value between 0 and 10!", Toast.LENGTH_SHORT).show();
else if(value<0)
Toast.makeText(getApplicationContext(), "Enter a value between 0 and 10!", Toast.LENGTH_SHORT).show();
else if(value >= 0 && value <=10)
{
schimba(v);
}
}else{
Toast.makeText(getApplicationContext(), "msg you want to display!", Toast.LENGTH_SHORT).show();
}
Upvotes: 0
Reputation: 9700
You can use matches()
method to check that your EditText
is empty or not.
String stringValue = usernameEditText.getText().toString();
if (!stringValue.matches("")) {
int value = Integer.parseInt(stringValue);
if(value > 10)
Toast.makeText(getApplicationContext(), "Enter a value between 0 and 10!", Toast.LENGTH_SHORT).show();
else if(value<0)
Toast.makeText(getApplicationContext(), "Enter a value between 0 and 10!", Toast.LENGTH_SHORT).show();
else if(value >= 0 && value <=10) {
schimba(v);
}
}
Upvotes: 0
Reputation: 722
How about doing:
if (instances.getText().toString().lenght() > 0)
{
int value = Integer.parseInt(instances.getText().toString());;
if(value > 10)
Toast.makeText(getApplicationContext(), "Enter a value between 0 and 10!", Toast.LENGTH_SHORT).show();
else
if(value<0)
Toast.makeText(getApplicationContext(), "Enter a value between 0 and 10!", Toast.LENGTH_SHORT).show();
else
if(value >= 0 && value <=10)
{
schimba(v);
}
}
else
{
// HANDLE EMPTY VALUE HERE
}
Upvotes: 3