EditText Validation setError not working, getting crashed - android

I'm doing the check for my two EditText field editNumber1 and editNumber2.
I'm trying to display if the check perform fails.
I'm not able to display the error and the application crashes.
here is the sample code can any one suggest?
if ((editNumber1.getText().length() == 0) || (editNumber1.getText().toString() == " ") ||
(editNumber2.getText().length() == 0) || (editNumber2.getText().toString() == " "))
{
editNumber1.setFocusableInTouchMode(true);
editNumber1.requestFocus();
editNumber1.setError("Some inputs are empty");
}

Firs of all use this good utilities StringUtils.isNotBlank( string_to_compare );
this method return false if the string_to_compare is:
null,
empty (""),
blank (" ")
then try to use a break point in the lines below to see when the crash occurs
editNumber1.setFocusableInTouchMode(true);
editNumber1.requestFocus();
editNumber1.setError("Some inputs are empty");

Related

How to check edittext

I want to add a verification to my edit text:
check if the name is not a number
check if the tel is a number
check if the password and password2 are equals
How can I do this?
if (name.isEmpty() || name.length() < 3 || ............) {
et_name.setError("enter a valid name");
valid = false;
} else {
et_nom.setError(null);
}
if (tel.isEmpty() || ..........) {
et_tel.setError("enter a valid tel");
valid = false;
} else {
et_tel.setError(null);
}
if (password.isEmpty() || password2.isEmpty() || ..........) {
et_password.setError("enter a valid password");
valid = false;
} else {
et_password.setError(null);
}
Okey...
first :
for name you don't want allow user to enter numbers so what you can do is add two attributes to your name EditText.
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "
android:inputType="text"
This will allow user to enter only alphabets and blank space. so no need for verification on that programmatically.
Second :
Same for the telephone number. you have to add android:inputType="number" to your telephone EditText. So user will able to input numbers only.
Third
for validating if your EditText is empty or not you can do following.
if (name.getText().toString().equals("")) {
Toast.makeText(getApplicationContext(),
"Please enter your name", Toast.LENGTH_SHORT).show();
}
Fourth
For checking password equality you can do following.
if (!password1.getText().toString().equals(password2.getText().toString())) {
Toast.makeText(getApplicationContext(),
"Please enter your name", Toast.LENGTH_SHORT).show();
}
Now Hopefully you understand this whole process. for your case refer following code.
if (name.getText().toString().equals("") || name.length() < 3 ||) {
et_name.setError("enter a valid name");
valid = false;
}
if (tel.getText().toString().equals("")) {
et_tel.setError("enter a valid tel");
valid = false;
}
if (password.getText().toString().equals("") || password2.getText().toString().equals("") || !password.getText().toString().equals(password2.getText().toString())) {
et_password.setError("enter a valid password");
valid = false;
}
Happy coding.
Why not just set the inputType="number" of the EditText in the xml? If you still prefer checking it dynamically, check out this post.
TextUtils.equals() - http://developer.android.com/reference/android/text/TextUtils.html#equals(java.lang.CharSequence, java.lang.CharSequence)
Cheers! :D
Try using android.text.Utils.TextUtils class (part of android SDK)
See inputType
1. Check if name is number
if(TextUtils.isDigitsOnly(str)) {
//number
}
2. Check if name is not a number
if(!TextUtils.isDigitsOnly(str)) {
//number
}
3. Check if two password1 and password2 are equal
if(!TextUtils.isEmpty(password1) && !TextUtils.isEmpty(password2) && !password1.equals(password2)) {
//number
}

How do I recognize the initial white space/spaces in my edit text?

I am trying to recognize the initial spaces in my edit text, such that if a user enters " " (any number of spaces) ,it doesnt enable my done button.
So, far I have this code in placE:
String sendString = mSendText.getText().toString();
if(sendString.equals(" ")||sendString.isEmpty()||sendString ==null ){
//do nothing
}else {
//do my stuff
}
The thing is I want the else to work only when I have string with any characters in it as long as it is not JUST ALL whitespace in the beginning.
The code I have works for only 1 whitespace. I want to make it such that no matter how many number of whitespaces exist in the beginning it will remove them or not enable my done button as long as no characters show up.
For example :
This should go to the if loop: " "
This should go to the else loop: " Hello, it's me"
Any ideas?
Thanks!
Just replace equalsTo() to startsWith():
String sendString = mSendText.getText().toString();
if( (sendString == null) || (sendString.startsWith(" ")) || (sendString.isEmpty())){
//do nothing
}else{
//do my stuff
}
Perhaps, if you're interested only in relevant text, you can exclude white spaces in the beginning/ending just using trim()
String sendString = mSendText.getText().toString().trim();
if(sendString.isEmpty()) {
//do nothing
}else{
//do my stuff
}
Use trim() to delete odd spaces from begin and end of String.
String str = new String(" Welcome to Tutorialspoint.com ");
System.out.print("Return Value :" );
System.out.println(Str.trim() );
Returns Welcome to Tutorialspoint.com
I would remove all spaces then check to see if there is anything in the string after that.
String sendString = mSendText.getText().toString().replace(" ","");
if(sendString.isEmpty()){
// do nothing
}else{
// do something
}

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

android number format exception

I get the following exception
java.lang.NumberFormatException: Invalid int: ""
It is happening when you try to store a value into shared preferences whilst nothing has been inserted into the input field. This is because i am parsing the input as an int (as i need to do a subtraction with the figure)
This isn't much of a problem as the app will work however just incase someone using the app wants to be wierd and try and press the save button without entering any data I dont want it to insert.
I have tried the following:
else if (obj ==null || obj.currentWeight.contains("")||obj.targetWeight.contains("")){
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setTitle("No Data Stored");
builder.setMessage("Please insert your target weight and your current weight and click Store Weight")
.setPositiveButton("OK", null).show();
From what i could make out if i kept the above statement as
else if (obj ==null){
then if a null is inserted the dialog would open and display a message.
i get the number format exception.
any help would be appreciated
Generally speaking, exception processing is a good approach for this kind of undesired behavior :
if( obj != null && obj.getTargetWeight() != null ) {
try {
int i = Integer.parseInt( obj.getTargetWeight() );
//do something if target weight is a number
} catch( NumberFormatException ex ) {
//do something if target weight was not a number.
}
}
---edited to precise exception type

validating EditText input

Trying to confirm that an EditText tool is not empty when the user clicks a button. Whenever the EditText is not blank the code works. But whenever it is blank my program crashes. Any ideas what I'm doing wrong? Thanks.
if (et1.getText().toString() != null) {
inpt_weight = Integer.parseInt(et1.getText().toString());
Toast.makeText(getBaseContext(), "weight is not null", Toast.LENGTH_LONG).show();
} else {
inpt_weight = 0;
Toast.makeText(getBaseContext(), "weight is null", Toast.LENGTH_LONG).show();
};
I think its trying to parse an empty string("") to an integer which is not possible
try:
if (!et1.getText().toString().equalsIgnoreCase("") && et1.getText().toString() != null)
This will be a good way:
if(et1.getText().toString().trim().length()==0){
Log.d("No data","No text found in the edit text");
}
This also checks if the user had put nothing but only spaces.
In your code, I see you're converting the text to numbers.
In this case, either put correct IMEMethod for the edit text so that it takes only numbers, or check in your code that user has entered only numeric characters, else you'll end up with a NumberFormatException while conversion if the user has entered non numeric characters.
Try the following code please..
if(et1.getText().toString().equals("")){
Toast.makeText(getApplication(), "weight is null", Toast.LENGTH_SHORT).show();}
else{
inpt_weight = Integer.parseInt(et1.getText().toString());
Toast.makeText(getApplication(), "weight is not null & it is : "+inpt_weight,Toast.LENGTH_SHORT).show();
}

Categories

Resources