I have three EditText controls and I need to make sure that each is the correct number input.
The first has to be a number between 0 and 23
The second has to be a number between 0 and 59
And the third has to be a number between 0 and 1500
I saw someone make a post about an easy EditText validation using setError, example:
EditText firstName = (EditText)findViewById(R.id.first_name);
if (firstName.getText().toString().length() == 0)
firstName.setError("First name is required!");
So is there an easy way to do it like above, but making sure a number isn't > 23, 59, or 1500 (individually)?
EditText firstEditText = (EditText)findViewById(R.id.first_edit_text);
EditText secondEditText = (EditText)findViewById(R.id.second_edit_text);
EditText thirdEditText= (EditText)findViewById(R.id.third_edit_text);
int value;
value = Integer.parseInt(firstEditText .getText().toString());
if (! value > 0 && value < 23)
firstEditText.setError("Error");
value = Integer.parseInt(secondEditText .getText().toString());
if (! value > 0 && value < 59)
secondEditText.setError("Error");
value = Integer.parseInt(thirdEditText.getText().toString());
if (! value > 0 && value < 1500)
thirdEditText.setError("Error");
Integer.parseInt(String s)can convert string to integer.Then, you validate it with if, else.
However, the input may not be an integer, and you have to set android:numeric="integer" in <EditText /> tag in the .xml file.
Be careful about this, if the input string is not integer, Integer.parseInt() will throw an exception, which will cause a crash.
You want to make sure you're performing some error checking since the value is coming from the user. Try something like this:
EditText firstText = (EditText) findViewById(R.id.first);
try
{
long firstVal = Long.parseLong(firstText.getText());
if (firstVal < 0 || firstVal > 23)
firstText.setError("The value must be between 0 and 23!");
}
catch (NumberFormatException e)
{
firstText.setError("Enter an integer value!");
}
// very similar for your remaining cases
String value = firstName.getText().toString();
int int_value = Integer.parseInt(value);
if (firstName.getText().toString().length() != 0)
if (int_value < 1500) {
// do what you want
}
else if (int_value < 59) {
// do what you want
}
else if (int_value < 23) {
// do what you want
}
}else {
firstName.setError("First name is required!");
}
Related
I would like to check if a filled in textfield is greater than an other filled in textfield.
So like:
if (textfield1.getText().toString().equals(""))
Toast.makeText(getActivity(), "textfield one is empty, please fill in a number", Toast.LENGTH_SHORT).show();
i would like something like this:
if (textfield1.getText().toString().less than textfield2.getText().toString())
Toast.makeText(getActivity(), "textfield one is less than textfield two, this is not allowed", Toast.LENGTH_SHORT).show();
i can't find how
I assume there are numbers in your TextViews? Make an Integer from the String and compare those numbers:
Integer input1 = Integer.parseInt(textfield1.getText().toString());
Integer input2 = Integer.parseInt(textfield2.getText().toString());
if (input1 < input2) { }
If it is input length you are talking about use String.length() like so:
if (textfield1.getText().toString().length() < textfield2.getText().toString().length()) {
}
try this
if(textfield1.getText().toString().trim().length() > 0 && textfield2.getText().toString().trim().length() > 0) {
try {
int i1 = Integer.parseInt(textfield1.getText().toString().trim());
int i2 = Integer.parseInt(textfield2.getText().toString().trim());
if(i1 > i2) {
// do needfull here
}
} catch(Exception ex) {
Log.e("tag", ex.getMessage());
// user entered some character which is not number
}
}
Have a problem with this code!
I want to check the editText values, if it is null or not...
But it gets stuck at the if segment, doesnt mather if it is a value in the editText or not.
If there is a value in the editText string it should go further and calculate the values.
Second problem I have is the toast, it doesnt show the text in the string variable, it just prints the string link.
private EditText fp;
private EditText fC;
private EditText drive;
private TextView totalcost;
public void CalcButton(View button) {
// Converting strings to float and check if each is NULL (empty)
if (!(fp.getText().equals(null)) || (fC.getText().equals(null)) || (drive.getText().equals(null)))
{
Toast.makeText(getApplicationContext(), "#string/toast", Toast.LENGTH_LONG).show();
}else {
String n1 = fp.getText().toString();
float no1 = Float.parseFloat(n1);
String n2 = fC.getText().toString();
float no2 = Float.parseFloat(n2);
String n3 = drive.getText().toString();
float no3 = Float.parseFloat(n3);
// Calculates the floats
float calc = no1 * no2 * no3;
// Converting and prints out the result
String sum = Float.toString(calc);
totalcost.setText(sum);
}
You should not do it this way, do this instead:
if (!fp.getText().toString().equals("")) {
}
To problem with Toast - use this:
Toast.makeText(getApplicationContext(), R.string.toast, Toast.LENGTH_LONG).show();
Try to use TextUtils.isEmpty() instead, it checks for null and 0-length String.
On your if statement it should look like:
if (!TextUtils.isEmpty(fp.getText().toString())) {
// Code
}
And on your Toast, change "#string/toast" to R.string.toast or getApplicationContext().getString(R.string.toast);
The code should look like:
// Converting strings to float and check if each is NULL (empty)
if (! (TextUtils.isEmpty(fp.getText().toString()) ||
(TextUtils.isEmpty(fC.getText().toString())) ||
(TextUtils.isEmpty(drive.getText().toString()))))
{
Toast.makeText(getApplicationContext(), getApplicationContext().getString(R.string.toast), Toast.LENGTH_LONG).show();
}
More on the getString() method here.
EDIT: I've seen that your code also was missing a pair of parenthesis ( ). So your "not" was only applying to the first test.
Something like:
!(test1) || test2 || test3
Instead of
!((test1) || (test2) || (test3))
To check if EditText is empty you do editText.getText().toString().equals("")
So, Your if-statement will look like this:
if (!(fp.getText().toString().equals("")) ||
(fC.getText().toString().equals("")) ||
(drive.getText().toString().equals("")))
And your Toast would be like this:
Toast.makeText(getApplicationContext(), R.string.toast, Toast.LENGTH_LONG).show();
function isNull(int resourceId, boolean getError){
EditText editText= (EditText) findViewById(resourceId);
String strEditText = String.valueOf(editText.getText());
if(TextUtils.isEmpty(strEditText)) {
if(getError) editText.setError("this is null!");
return true;
}else{
return false;
}
}
May be this block gives you a few clues about yours
about If Conditions;
In your 'IF conditions', parentheses seems less than the count it is necessary.
Try to add one more after (!)
I guess it should be like this;
for Negative
if (!(
(String.valueOf(fp.getText()).equals("")) ||
(String.valueOf(fC.getText()).equals("")) ||
(String.valueOf(drive.getText()).equals(""))
))
for Positive
if (
(String.valueOf(fp.getText()).equals("")) ||
(String.valueOf(fC.getText()).equals("")) ||
(String.valueOf(drive.getText()).equals(""))
)
I have a string (length 3-8) assigned to a variable (text). I want to check whether the 2nd and 3rd characters are NOT numeric (a letter or symbol or space..or anything other than numbers).
Elementary way to do this could be:
if(((text.charAt(1)-'0')>=0)&&(text.charAt(1)-'0')<10))||((text.charAt(2)-'0')>=0)&&(text.charAt(2)-'0')<10)))
{
//do nothing, since this means 2nd and/or 3rd characters in the string are numeric
}
else
{
// Your condition is met
}
You could also use REGEX's , if your checking is still more complicated.
Here is Another way to achieve this:
boolean isNumeric = true;
String test = "testing";
char second = test.charAt(1);
char third = test.charAt(2);
try {
Integer.parseInt(String.valueOf(second));
Integer.parseInt(String.valueOf(third));
} catch(NumberFormatException e) {
isNumeric = false;
}
System.out.println("Contains Number in 2nd and 3rd or both position: " + isNumeric);
You might make use of the String.IndexOf(String) method, like:
String digits = "0123456789";
String s2 = text.substring(2,3);
String s3 = text.substring(3,4);
boolean valid = (digits.indexOf(s2) > -1) && (digits.indexOf(s3) > -1);
I'm trying to get it to if a user doesn't enter a value in the EditText boxes, the initial value is set to 0 (to prevent the crash error NumberFormatException Invalid int: "") which is thrown assuming because there is no integer value to read, since the user didn't input one in this case.
I've tried a number of things most recently this:
String boozeAmount = boozeConsumed.getText().toString();
if (boozeAmount == "" || boozeAmount == null){
boozeConsumed.setText("0");
boozeAmount = boozeConsumed.getText().toString();
}
int boozeOz = Integer.parseInt(boozeAmount) * 12;
double beerCalc = boozeOz * 4 * 0.075;
But it seems to still throw the same error, not sure why the int values aren't being set to 0?
Throwing error on
int boozeOz = Integer.parseInt(boozeAmount) * 12;
if (boozeAmount == "" || boozeAmount == null){
It can be easily deduced from your explanation that this particular if statement is returning true, that's why your string value is not being set to "0".
Strings in Java are not primitive, i.e they cannot be compared with the comparator ==.
You need to use the method equals to compare strings, as in boozeAmount.equals("").
Apache Commons has a StringUtils utility that can check if strings are null or empty.
Check out isEmpty and isBlank.
you dont compare strings with == you compare it with .equals()
Change it to:
if (boozeAmount.equals("") || boozeAmount == null)
Although it's probably safest to also do:
if (...)
{
// just set it to zero and skip even trying to parse
}
else
{
// do the actual parsing
}
Whenever you are fetching a string value from the EditText always trim that variable to avoid any white spaces from EditText.
String boozeAmount = boozeConsumed.getText().toString().trim(); // apply Trim
// Always compare strings with `equals()` method in Java & Android
if ( boozeAmount.equals( "" ) || boozeAmount == null )
{
boozeConsumed.setText("0");
boozeAmount = boozeConsumed.getText().toString();
}
int boozeOz = Integer.parseInt(boozeAmount) * 12;
double beerCalc = boozeOz * 4 * 0.075;
You could check if it's blank and then fill it with 0 and then get the input.
Also, always compare string values with .equals and use .trim() to get rid of whitespace so that it's recognized as invalid input as well.
if (boozeConsumed.getText().toString().trim().equals("")) {
// if (boozeConsumed.length() == 0) { // doesn't consider spaces though
boozeConsumed.setText("0");
}
String boozeAmount = boozeConsumed.getText().toString();
int boozeOz = Integer.parseInt(boozeAmount) * 12;
double beerCalc = boozeOz * 4 * 0.075;
Or just do this, because you don't need to parse it to an integer if you know there's nothing there:
String boozeAmount = boozeConsumed.getText().toString();
int boozeOz = 0;
double beerCalc = 0;
if (boozeAmount.trim().equals("") || boozeAmount == null){
boozeConsumed.setText("0");
boozeAmount = boozeConsumed.getText().toString();
} else {
// only parse it if there's something there
boozeOz = Integer.parseInt(boozeAmount) * 12;
beerCalc = boozeOz * 4 * 0.075;
}
I want to check whether the entered strings length is between 3 to 8 characters. Previously I used if condition and it worked. However when I introduced some substring from the string , one of the if statements doesnt work. Can some one help me to understand why. Thanks.
My codes is
Working Code:
text = et.getText().toString();
l = text.length();
a = text.substring(0, 1);
if (l >=9) tv.setText("Invalid length!!! Please check your code");
if (l <= 2) tv.setText("Invalid length! Please check your code");
And here, the second if statement doesnt work.
text = et.getText().toString();
l = text.length();
a = text.substring(0, 1);
c = text.substring(1, 2);
d = text.substring(3, 4);
e = text.substring(4);
if (l >=9) tv.setText("Invalid length!!! Please check your code");
if (l <= 2) tv.setText("Invalid length! Please check your code");
You will want to ensure that you handle a null string as well as ensuring your string is within the limits you want. consider:
text = et.getText().toString();
if (text == null || text.length() < 3 || text.length > 8) {
tv.setText("Invalid length, should be from 3 to 8 characters. Please check your code");
} else {
a = text.substring(0,1);
b = text.substring(1,2);
c = text.substring(3,4);
if (text.length() > 3) {
d = text.substring(4);
} else {
d = null;
}
}
You need to check the length before trying to create substrings, since if the length is too short the substring indexes are invalid. Try this:
text = et.getText().toString();
l = text.length();
if (l >= 9 || l <= 2) {
tv.setText("Invalid length!!! Please check your code");
} else {
a = text.substring(0, 1);
c = text.substring(1, 2);
d = text.substring(3, 4);
e = text.substring(4);
}
You can use like this:
editText.getText().toString().length() < 3
EditText etmobile_no;
if (etmobile_no.getText().toString("") ||
etmobile_no.getText().toString().length() <3 ||
etmobile_no.getText().toString().length() >8)
{
tv.setText("Invalid length, should be from 3 to 8 characters. Please check your code");
}