GetText compare - android

So i have a EditText field, which i want to, check if the age is above and under my limits.
if (Integer.parseInt(age.getText().toString()) < 18 && Integer.parseInt(age.getText().toString()) >= 0)
But also, i want to simply check if the field is empty, for what i used.
else if (age.getText().toString().isEmpty())
Unluckly this one is not working, i think it sort of get in to conflict with the first one or something, because i tried with just one condition of both, and it works..
I also tried to store in String variable the method to check isEmpty(), and also in int one, to do the age comparation, but it still not working.
Thanks in advance.

The code should be:
if (age.getText().toString().trim().isEmpty()){
//The EditText field is empty
}else{
try{
if (Integer.parseInt(age.getText().toString().trim()) < 18 && Integer.parseInt(age.getText().toString().trim()) >= 0){
//Your code here
}else{
//Input value is over 18 or under 0
}
}catch(Exception ex){
//There was an error parsing the input (if your user writes letters, parseInt fails)
}
}

Related

android : app crash if user inputs two decimal points like "1..5" instead of "1.5"

i have an android program where i have successfully restricted the user to input only value after decimal.. the problem is if user inputs two decimal points like "1.." then the app crashes. i have allowed only one special character to be used i.e decimal point itself. so how can i restrict the user from entering two decimal points or else show some validation.
i need something like this
else if(txtLdays.getText().toString().trim().equals(".."))
{
txtLdays.requestFocus();
txtLdays.setError("Double decimal ?");
return false;
}
Try this..
Use contains like below
else if(txtLdays.getText().toString().trim().contains(".."))
{
txtLdays.requestFocus();
txtLdays.setError("Double decimal ?");
return false;
}
EDIT
String to double
double result = Double.parseDouble(txtLdays.getText().toString().trim());
int to double
double result = (double) 12;
If user enters 12.
then check endsWith
double result;
if(txtLdays.getText().toString().trim().endsWith("."))
result = Double.parseDouble(txtLdays.getText().toString().trim().replace("\\.", ""))
There are two possibilitites
if you want to restrict when any button pressed..
then replace all ".." characters with empty chars like..
String data=View.getText().toString().replaceAll("..", "");
2.if you restrict when the user is typing then write a TextWatcher listener for the Edittext and you need to peform some validations there...
Did you tried setting decimal input type ?
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal|number"
/>
Try this :
int count = StringUtils.countOccurrencesOf((txtLdays, ".");
if (count > 1){
txtLdays.requestFocus();
txtLdays.setError("Double decimal ?");
}
Please downlaod this jar file Commons Lang
The right way would be to match the value against a regular expression.
Here is an example that allows a string that starts/end with zero or more spaces and contains a double decimal point number:
//First make sure you avoid null pointer exception
if (txtLdays != null && txtLdays.getText() != null) {
String daysString = txtLdays.getText().toString();
String regex = "^\s*\d+\.\.\d+\s*$"
if (daysString.matches(regex)) {
txtLdays.requestFocus();
txtLdays.setError("Double decimal ?");
return false;
}
}
You can youse some kind of online regular expression tool to verify your matcher.
equals will check Object.
You need to check equalsIngnoreCase(); this ll check all the character
specially u need
else if(txtLdays.getText().toString().trim().indexOf("..") != -1 ){
txtLdays.requestFocus();
txtLdays.setError("Double decimal ?");
return false;
}

Determine if content in editText is a "." ONLY

I have written a calculator type app. My mates found that entering single decimal points only into the editText's makes the app crash. Decimal numbers and integers work fine, but I get a number format exception when .'s are entered.
I want to check if a single . has been placed in an editText, in order for me to display a toast telling the user to stop trying to crash the app.
My issue is that a . doesn't have a numerical value...
You can wrap it in a try/catch which should be done anyway when parsing text. So something like
try
{
int someInt = Integer.parseInt(et.getText().toString());
// other code
}
catch (NumberFormatException e)
{
// notify user with Toast, alert, etc...
}
This way it will protect against any number format exception and will make the code more reusable later on.
You can treat .1 as 0.1 by the following.
String text = et.getText().toString();
int len = text.length();
// Do noting if edit text just contains a "." without numbers
if(len==0 || (len==1 && text.charAt(0).equals(".")))
return;
if(text.charAt(0).equals(".") && text.length() > 1) {
text = "0" + text;
}
// Do your parsing and calculations

Parsing an integer value in Android

I am trying to get integer value entered in EditText by user.
EditText eTextValue=(EditText) findViewById(R.id.eId);
String eTextString=eTextValue.getText().toString();
int eTextValue1=Integer.parseInt(eTextString);
But unluckily I am getting,
unable to parse 9827328 as integer.
I have tried using Integer.valueOf instead of Integer.parseInt but again I am getting the same exception.
I have even used Long datatype to store value instead of int type datatype but nothing seems to be working.Any help over this will be highly appreciated.
I have gone through all these links unable to parse ' ' as integer in android , Parsing value from EditText...but nothing seems to be working all of them are landing me in exception.
You are using eTextValue as a variable name for two different things (an int and an EditText). You cant do that and expect it to work properly. Change one or the other and it should work better.
Try by entering the following in the XML File under the corresponding EditText element.
android:inputType="number"
Hope this should get you pass the exception.
You need to check whether the string you are parsing is an integer. Try this code:
if (IsInteger(eTextString)
int eTextValue1=Integer.parseInt(eTextString);
and add this function:
public static boolean IsInteger(String s)
{
if (s == null || s.length() == 0) return false;
for(int i = 0; i < s.length(); i++)
{
if (Character.digit(s.charAt(i), 10) < 0)
return false;
}
return true;
}
I hope this helps
int id;
id=Integer.parseInt(ed.getText().toString());

Else if loop doesn't validate variable from statement

I am having a problem while looping through one of my loop constructions.
I get Question instances out of my database and one of the fields of the instance is Attempts. I pulled my database from my device and inspected it and all fields of the column attempts are filled with ints greater than 0.
int initialAttempts = 0;
initialAttempts = c.getInt(6);
q.setAttempts(initialAttempts);
and in my custom array adapter:
if (mView != null) {
int attempts = getItem(position).getAttempts();
int correctAnswer = getItem(position).getAnswerCorrect();
triangle.setVisibility(View.INVISIBLE);
if(correctAnswer == 1) {
triangle.setVisibility(View.VISIBLE);
}
else if (correctAnswer != 1 && attempts > 0) {
triangle.setVisibility(View.VISIBLE);
triangle.setImageResource(R.drawable.trianglered);
}
So the problem is it never shows trianglered. If I drop the && attempts > 0, it does show the trianglered, so I assume the error is in there. The strange thing is if I initialize attempts as 1 before the getItem(position).getAttempts, it still shows no trianglereds.
Any ideas where this goes wrong?
getItem(position).getAttempts() method returns 0. There are no other variants. Why it returns 0 is the question to you. Prefer debugging instead of asking such questions.
PS. No need to check for correctAnswer != 1 in else if statement. The opposite statement has already been checked in if and it was false.

Compare two things doesn't work

I have a strange problem in my android app. I must compare two string which are equals. I tried this :
if (raspunsdata.equals(rok)) {
System.out.println("changed ");
} else
System.out.println("no change");
}
but I get always "no change". Before this I have System.out.println for both strings, and both of them have the same value.
I tried also (raspunsdata==rok) and raspunsdata.contentEquals(rok) but I have the same problem. Why? I cant understand this.,...please help...
You might have unwanted white spaces. Might need to use the trim function just to make sure.
if (raspunsdata.trim.equals(rok.trim())) {
System.out.println("changed ");
} else
System.out.println("no change");
}
Btw equals is the correct way to check whether the values are the same.
.equals - compares the values of both objects. If you have 2 Strings with the same characters sets .equals will return true;
== - compares if two objects references are equal.
For example:
String a = "lol";
String b = a;
a == b - will be true.
Try reading: http://www.devdaily.com/java/edu/qanda/pjqa00001.shtml

Categories

Resources