/*
ADDING NUMBERS TO ArrayLIST AND IF NEW NUMBER ENTERED SAME AS already EXISTING NUMBER
RESAULT IS DUBLICATE;
*/
private String[] phoneNumbers;
public String addPhoneNumber(String newPhoneNumber) throws SMSDataModelFullException {
String result;
if (numPhoneNumbers == phoneNumbers.length) {
result = FULL;
} else {
boolean exists;
exists = findPhoneNumberIndex(newPhoneNumber) != -1;
if (exists) {
result = DUPLICATE;
} else {
phoneNumbers[numPhoneNumbers] = newPhoneNumber;
numPhoneNumbers++;
result = newPhoneNumber;
}
}
return result;
}
This one is working perfectly to Array. I need some help with Duplicate in existing number only to List
private List<String> phoneNumber;
public String addPhoneNumber(String newPhoneNumber) throws SMSDataModelFullException {
String result;
if (maxNumPhoneNumbers!=0 && phoneNumber.size() >= maxNumPhoneNumbers) {
throw new SMSDataModelFullException(newPhoneNumber);
}
else{
boolean exist;
exist =findPhoneNumberIndex(newPhoneNumber)!= -1;
if(exist)
{
result = DUPLICATE;
}
else{
phoneNumber.add(newPhoneNumber);
}
return newPhoneNumber;
}
}
This one is not working, what I'm doing wrong? The Duplicate in List not showing some reason.
public String addPhoneNumber(String newPhoneNumber) {
String result = newPhoneNumber;
if(!phoneNumber.contains(newPhoneNumber)){ // if it is not already in the list
phoneNumber.add(newPhoneNumber); // add it to the list
}else{
result = "DUPLICATE"; // if number was already in the list result = DUPLICATE
}
return result;
}
You return newPhoneNumber always
return newPhoneNumber;
Do the same as in the first case
...
if (exists) {
result = DUPLICATE;
} else {
phoneNumber.add(newPhoneNumber);
result = newPhoneNumber;
}
}
return result;
Also your findPhoneNumberIndex() can be replaced with phoneNumber.contains(newPhoneNumber)
I have a String and sometimes value changed:
String str1 = "+25"; // only have "+" sign and number
String str2 = "+Name"; // only have "+" sign and text
How can I distinguish these String because I want to do something like that:
if (isString1Type) { // both strings also have "+" sign
// do something
}
Do String have any functions for this case.
Can anyone give me suggestions?
Yes, you could do something like this:
String str = "+Name";
boolean hasPlusSign = str.contains("+");
boolean isNumber = tryParseInt(str.replace("+", ""));
if(hasPlusSign && isNumber){ //if the string is +25 for example here will be true, else it will go to the else statement
//do something
} else {
//something else
}
boolean tryParseInt(String value) {
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException e) {
return false;
}
}
You can use the simple regex "[+][0-9]+". It more simple and easy.
Here is example code
String str1 = "+25";
if (str1.matches("[+][0-9]+")){
// your string contains plus "+" and number
// do something
}eles{
}
Hope this help
You can use regex like this:
[0-9]+ here + means more than one digits from 0-9
String str1 = "+25";
String str2 = "+Name";
String regex = "[0-9]+";
if(isDigit(str1.replace("+",""))){
Log.d("str1","Integer");
}else{
Log.d("str1","Not Integer");
}
if(isDigit(str2.replace("+",""))){
Log.d("str2","Integer");
}else{
Log.d("str2","Not Integer");
}
boolean isDigit(String str){
if(str.matches(regex)){
return true;
}else {
return false;
}
}
I have a registration form in my application which I am trying to validate. I'm facing some problems with my validation while validating the phone number and email fields.
Here is my code:
private boolean validate() {
String MobilePattern = "[0-9]{10}";
//String email1 = email.getText().toString().trim();
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if (name.length() > 25) {
Toast.makeText(getApplicationContext(), "pls enter less the 25 character in user name", Toast.LENGTH_SHORT).show();
return true;
} else if (name.length() == 0 || number.length() == 0 || email.length() ==
0 || subject.length() == 0 || message.length() == 0) {
Toast.makeText(getApplicationContext(), "pls fill the empty fields", Toast.LENGTH_SHORT).show();
return false;
} else if (email.getText().toString().matches(emailPattern)) {
//Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
return true;
} else if(!email.getText().toString().matches(emailPattern)) {
Toast.makeText(getApplicationContext(),"Please Enter Valid Email Address",Toast.LENGTH_SHORT).show();
return false;
} else if(number.getText().toString().matches(MobilePattern)) {
Toast.makeText(getApplicationContext(), "phone number is valid", Toast.LENGTH_SHORT).show();
return true;
} else if(!number.getText().toString().matches(MobilePattern)) {
Toast.makeText(getApplicationContext(), "Please enter valid 10 digit phone number", Toast.LENGTH_SHORT).show();
return false;
}
return false;
}
I have used this code above for the validation. The problem I'm facing is in the phone number and email validation, only one validation is working. For example, if I comment out the phone number validation, the email validation is working properly. If I comment out the email validation, the phone number validation is working. If use both validations, it's not working.
For Email Address Validation
private boolean isValidMail(String email) {
String EMAIL_STRING = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
return Pattern.compile(EMAIL_STRING).matcher(email).matches();
}
OR
private boolean isValidMail(String email) {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
For Mobile Validation
For Valid Mobile You need to consider 7 digit to 13 digit because some country have 7 digit mobile number. If your main target is your own country then you can match with the length. Assuming India has 10 digit mobile number. Also we can not check like mobile number must starts with 9 or 8 or anything.
For mobile number I used this two Function:
private boolean isValidMobile(String phone) {
if(!Pattern.matches("[a-zA-Z]+", phone)) {
return phone.length() > 6 && phone.length() <= 13;
}
return false;
}
OR
private boolean isValidMobile(String phone) {
return android.util.Patterns.PHONE.matcher(phone).matches();
}
Use Pattern package in Android to match the input validation for email and phone
Do like
android.util.Patterns.EMAIL_ADDRESS.matcher(input).matches();
android.util.Patterns.PHONE.matcher(input).matches();
Android has build-in patterns for email, phone number, etc, that you can use if you are building for Android API level 8 and above.
private boolean isValidEmail(CharSequence email) {
if (!TextUtils.isEmpty(email)) {
return Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
return false;
}
private boolean isValidPhoneNumber(CharSequence phoneNumber) {
if (!TextUtils.isEmpty(phoneNumber)) {
return Patterns.PHONE.matcher(phoneNumber).matches();
}
return false;
}
Try this
public class Validation {
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
public static final boolean isValidPhoneNumber(CharSequence target) {
if (target.length()!=10) {
return false;
} else {
return android.util.Patterns.PHONE.matcher(target).matches();
}
}
}
He want an elegant and proper solution try this small regex pattern matcher.
This is specifically for India.(First digit can't be zero and and then can be any 9 digits)
return mobile.matches("[1-9][0-9]{9}");
Pattern Breakdown:-
[1-9] matches first digit and checks if number(integer) lies between(inclusive) 1 to 9
[0-9]{9} matches the same thing but {9} tells the pattern that it has to check for upcoming all 9 digits.
Now the {9} part may vary for different countries so you may have array which tells the number of digits allowed in phone number. Some countries also have significance for zero ahead of number, so you may have exception for those and design a separate regex patterns for those countries phone numbers.
in Kotlin you can use Extension function to validate input
// for Email validation
fun String.isValidEmail(): Boolean =
this.isNotEmpty() && Patterns.EMAIL_ADDRESS.matcher(this).matches()
// for Phone validation
fun String.isValidMobile(phone: String): Boolean {
return Patterns.PHONE.matcher(phone).matches()
}
try this:
extMobileNo.addTextChangedListener(new MyTextWatcher(extMobileNo));
private boolean validateMobile() {
String mobile =extMobileNo.getText().toString().trim();
if(mobile.isEmpty()||!isValidMobile(mobile)||extMobileNo.getText().toString().toString().length()<10 || mobile.length()>13 )
{
inputLayoutMobile.setError(getString(R.string.err_msg_mobile));
requestFocus(extMobileNo);
return false;
}
else {
inputLayoutMobile.setErrorEnabled(false);
}
return true;
}
private static boolean isValidMobile(String mobile)
{
return !TextUtils.isEmpty(mobile)&& Patterns.PHONE.matcher(mobile).matches();
}
The built in PHONE pattern matcher does not work in all cases.
So far, this is the best solution I have found to validate a phone number (code in Kotlin, extension of String)
fun String.isValidPhoneNumber() : Boolean {
val patterns = "^\\s*(?:\\+?(\\d{1,3}))?[-. (]*(\\d{3})[-. )]*(\\d{3})[-. ]*(\\d{4})(?: *x(\\d+))?\\s*$"
return Pattern.compile(patterns).matcher(this).matches()
}
//validation class
public class EditTextValidation {
public static boolean isValidText(CharSequence target) {
return target != null && target.length() != 0;
}
public static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
public static boolean isValidPhoneNumber(CharSequence target) {
if (target.length() != 10) {
return false;
} else {
return android.util.Patterns.PHONE.matcher(target).matches();
}
}
//activity or fragment
val userName = registerNameET.text?.trim().toString()
val mobileNo = registerMobileET.text?.trim().toString()
val emailID = registerEmailIDET.text?.trim().toString()
when {
!EditTextValidation.isValidText(userName) -> registerNameET.error = "Please provide name"
!EditTextValidation.isValidEmail(emailID) -> registerEmailIDET.error =
"Please provide email"
!EditTextValidation.isValidPhoneNumber(mobileNo) -> registerMobileET.error =
"Please provide mobile number"
else -> {
showToast("Hello World")
}
}
**Hope it will work for you... It is a working example.
I am always using this methode for Email Validation:
public boolean checkForEmail(Context c, EditText edit) {
String str = edit.getText().toString();
if (android.util.Patterns.EMAIL_ADDRESS.matcher(str).matches()) {
return true;
}
Toast.makeText(c, "Email is not valid...", Toast.LENGTH_LONG).show();
return false;
}
public boolean checkForEmail() {
Context c;
EditText mEtEmail=(EditText)findViewById(R.id.etEmail);
String mStrEmail = mEtEmail.getText().toString();
if (android.util.Patterns.EMAIL_ADDRESS.matcher(mStrEmail).matches()) {
return true;
}
Toast.makeText(this,"Email is not valid", Toast.LENGTH_LONG).show();
return false;
}
public boolean checkForMobile() {
Context c;
EditText mEtMobile=(EditText)findViewById(R.id.etMobile);
String mStrMobile = mEtMobile.getText().toString();
if (android.util.Patterns.PHONE.matcher(mStrMobile).matches()) {
return true;
}
Toast.makeText(this,"Phone No is not valid", Toast.LENGTH_LONG).show();
return false;
}
For check email and phone number you need to do that
public static boolean isValidMobile(String phone) {
boolean check = false;
if (!Pattern.matches("[a-zA-Z]+", phone)) {
if (phone.length() < 9 || phone.length() > 13) {
// if(phone.length() != 10) {
check = false;
// txtPhone.setError("Not Valid Number");
} else {
check = android.util.Patterns.PHONE.matcher(phone).matches();
}
} else {
check = false;
}
return check;
}
public static boolean isEmailValid(String email) {
boolean check;
Pattern p;
Matcher m;
String EMAIL_STRING = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
p = Pattern.compile(EMAIL_STRING);
m = p.matcher(email);
check = m.matches();
return check;
}
String enter_mob_or_email="";//1234567890 or test#gmail.com
if (isValidMobile(enter_mob_or_email)) {// Phone number is valid
}else isEmailValid(enter_mob_or_email){//Email is valid
}else{// Not valid email or phone number
}
XML
<android.support.v7.widget.AppCompatEditText
android:id="#+id/et_email_contact"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:maxLines="1"
android:hint="Enter Email or Phone Number"/>
Java
private AppCompatEditText et_email_contact;
private boolean validEmail = false, validPhone = false;
et_email_contact = findViewById(R.id.et_email_contact);
et_email_contact.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
String regex = "^[+]?[0-9]{10,13}$";
String emailContact = s.toString();
if (TextUtils.isEmpty(emailContact)) {
Log.e("Validation", "Enter Mobile No or Email");
} else {
if (emailContact.matches(regex)) {
Log.e("Validation", "Valid Mobile No");
validPhone = true;
validEmail = false;
} else if (Patterns.EMAIL_ADDRESS.matcher(emailContact).matches()) {
Log.e("Validation", "Valid Email Address");
validPhone = false;
validEmail = true;
} else {
validPhone = false;
validEmail = false;
Log.e("Validation", "Invalid Mobile No or Email");
}
}
}
});
if (validPhone || validEmail) {
Toast.makeText(this, "Valid Email or Phone no", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "InValid Email or Phone no", Toast.LENGTH_SHORT).show();
}
private fun isValidMobileNumber(s: String): Boolean {
// 1) Begins with 0 or 91
// 2) Then contains 6 or 7 or 8 or 9.
// 3) Then contains 9 digits
val p: Pattern = Pattern.compile("(0|91)?[6-9][0-9]{9}")
// Pattern class contains matcher() method
// to find matching between given number
val m: Matcher = p.matcher(s)
return m.find() && m.group().equals(s)
}
I am using following function which uses boolean value.
int recFound=0;
public Boolean CheckUser(String uName,String password)
{
try
{
statement=conn.createStatement();
resultSet=statement.executeQuery("select count(*) from UserMaster where username LIKE'"+uName+"' and password LIKE'"+password+"'");
if(resultSet.getRow()>0)
{
recFound=1;
}
else
{
recFound=0;
}
}
catch (Exception e) {
e.printStackTrace();
recFound=0;
}
if(recFound == 0)
{
return false;
}
else
{
return true;
}
}
I am calling this function through:
boolean isValidUser=con.CheckUser(etLoginID.getText().toString(), etPassword.getText().toString());
if(isValidUser)
{
Intent i= new Intent(getApplicationContext(),Messages.class);
startActivity(i);
}
When i pass this function proper values its not making recFound=1;
And in last condition although recFound==0 it enters in else condition and returns true.
But while assigning this value to caller functions return value it assigns false.
Means it makes , boolean isValidUser=con.CheckUser(etLoginID.getText().toString(), etPassword.getText().toString()); to be false.
isValidUser should get true in such case.
Please help me.
Hi Shrimant Bajirao Peshawe - I,
change the statement "if(resultSet.getRow()>0)" to "if(resultSet. next ())" then try it.
Reference : Refer
you are calling a boolean function in your CheckUser method so its returns true or false value..
Jo just returns true value in that function.
you can also check it with:
if(isValidUser==true)
{
Intent i= new Intent(getApplicationContext(),Messages.class);
startActivity(i);
}
and print a value isValidUser in log that which value it is getting
Try Follwing code...
int recFound = 0;
public boolean CheckUser(String uName, String password) {
try {
statement = conn.createStatement();
resultSet = statement.executeQuery("select count(*) from UserMaster where username LIKE '" + uName + "' and password LIKE '" + password + "'");
if (resultSet.getRow() > 0) {
recFound = 1;
} else {
recFound = 0;
}
if (recFound > 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
and
if(con.CheckUser(etLoginID.getText().toString(), etPassword.getText().toString())) {
Intent i= new Intent(getApplicationContext(),Messages.class);
startActivity(i);
}
Change:
if(resultSet.getRow()>0)
{
recFound=1;
}
else
{
recFound=0;
}
to:
if(resultSet.getRow()>0)
{
return true;
}
else
{
return false;
}
Remove conditions checking recFound in catch()
This should solve your problem.
Replace code
if(resultSet.getRow()>0){
recFound=1;
} else {
recFound=0;
}
to
if(resultSet.next()){
return true;
} else {
return false;
}
Try to initialize the
isValidUser to false at the begining
also log the value of resultSet.getRow() and recFound before returning it caller.
you can also try to use cusrsor like below
int recFound=0;
private SQLiteDatabase mDb;
public Boolean CheckUser(String uName,String password)
{
try
{
String sql="select count(*) from UserMaster where username LIKE'"+uName+"' and password LIKE'"+password+"'";
Log.i(TAG,"Executing Query : "+sql);
mCur = mDb.rawQuery(sql, null);
Log.i(TAG,"Query Executed Successfully");
if(mCur!=null)
{
recFound=1;
}
else
{
recFound=0;
}
}
catch (Exception e) {
e.printStackTrace();
recFound=0;
}
if(recFound == 0)
{
return false;
}
else
{
return true;
}
}
Been stuck on this all night and there just doesn't seem to be an easy solution to it. I'm trying to validate all 4 of my fields to ensure that there is a value in each one of them, if there's a value in each one of them after I click the Calculate button a total will be calculated. If any of them don't have a value in them it'll return an error at every EditText which doesn't have a value and a total will not be calculated.
cal.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
if( eLoan.getText().toString().length() == 0 )
{
eLoan.setError( "A value is required" );
}
else if( eWage.getText().toString().length() == 0 )
{
eWage.setError( "A value is required" );
}
else if( eGrant.getText().toString().length() == 0 )
{
eGrant.setError( "A value is required" );
}
else if( eOther.getText().toString().length() == 0 )
{
eOther.setError( "A value is required" );
}
else
convertToString();
converToDouble();
inTotal = inLoan + inWage + inGrant + inOther;
DecimalFormat currency = new DecimalFormat(".00");
TotalInNum.setText("£" + currency.format(inTotal));
}
});
I can't get my head around it, I've tried to incorporate a boolean statement to check each EditText but it didn't work either. I'm convinced there's an easier method to do this.
I'm quite new to android, self teaching myself it so I would appreciate it if people could advise me on what I'm doing wrong and maybe give me an example of what I should do.
Thanks to all who respond.
Just to build on what others have said. You can do something like this...
Make a validation method that loops through your EditTexts, checks if they're empty, if true set error and then returns true or false...
public boolean validateEditText(int[] ids)
{
boolean isEmpty = false;
for(int id: ids)
{
EditText et = (EditText)findViewById(id);
if(TextUtils.isEmpty(et.getText().toString()))
{
et.setError("Must enter Value");
isEmpty = true;
}
}
return isEmpty;
}
Make a list of you EditText id's..
int[] ids = new int[]
{
R.id.section1_item1_textfield,
R.id.section1_item2_textfield,
R.id.section1_item3_textfield
};
Now use your validation method to check if empty...
if(!validateEditText(ids))
{
//if not empty do something
}else{
//if empty do somethingelse
}
To use the method above you will need to...
import android.text.TextUtils;
The good thing about doing it this way is that you can simply chuck all of your EditTexts into the list and it does the rest for you. Maintaining a huge chunk of if statements can be annoying and time consuming.
I think the problem is you're missing curlies at the last else, where the logic sits. As it is right now, only convertToString(); is part of that last else and the last four statements will execute no matter what error you're setting.
Try this:
cal.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
boolean failFlag = false;
// TODO Auto-generated method stub
if( eLoan.getText().toString().trim().length() == 0 )
{
failFlag = true;
eLoan.setError( "A value is required" );
}
if( eWage.getText().toString().trim().length() == 0 )
{
failFlag = true;
eWage.setError( "A value is required" );
}
if( eGrant.getText().toString().trim().length() == 0 )
{
failFlag = true;
eGrant.setError( "A value is required" );
}
if( eOther.getText().toString().trim().length() == 0 )
{
failFlag = true;
eOther.setError( "A value is required" );
}
// if all are fine
if (failFlag == false) {
convertToString();
converToDouble();
inTotal = inLoan + inWage + inGrant + inOther;
DecimalFormat currency = new DecimalFormat(".00");
TotalInNum.setText("£" + currency.format(inTotal));
}
}
});
This code will set more than one error, if more exist. Yours will signal only the first found error.
I think the best way to solve this problem is the example below:
private boolean verifyIfEditTextIsFilled(EditText... editText) {
boolean result = true;
for (EditText text : editText) {
if (text.getText().toString().isEmpty()) {
final View focusView = text;
text.setError(getString(R.string.error_required));
focusView.requestFocus();
result = false;
}
}
return result;
}
late answer But may Help someone in need.
Simplest way -->
Create method as below
public Boolean validateUserInput()
{
Boolean isAnyFieldsEmpty=false;
if (position.getText().toString()==null || position.getText().toString().equalsIgnoreCase(""))
{
position.setError("Empty postion");
isAnyFieldsEmpty=true;
}
else{
position.setError(null);
isAnyFieldsEmpty=false;
}
if (eligiblity.getText().toString()==null || eligiblity.getText().toString().equalsIgnoreCase(""))
{
eligiblity.setError("Empty postion");
isAnyFieldsEmpty=true;
}
else{
eligiblity.setError(null);
isAnyFieldsEmpty=false;
}
if (skillsRequired.getText().toString()==null || skillsRequired.getText().toString().equalsIgnoreCase(""))
{
skillsRequired.setError("Empty postion");
isAnyFieldsEmpty=true;
}
else{
skillsRequired.setError(null);
isAnyFieldsEmpty=false;
}
if (desc.getText().toString()==null || desc.getText().toString().equalsIgnoreCase(""))
{
desc.setError("Empty postion");
isAnyFieldsEmpty=true;
}
else{
desc.setError(null);
isAnyFieldsEmpty=false;
}
if (interviewFrmDate.getText().toString()==null || interviewFrmDate.getText().toString().equalsIgnoreCase(""))
{
interviewFrmDate.setError("choose date");
isAnyFieldsEmpty=true;
}else{
interviewFrmDate.setError(null);
isAnyFieldsEmpty=false;
}
if (interviewToDate.getText().toString()==null || interviewToDate.getText().toString().equalsIgnoreCase(""))
{
interviewToDate.setError("choose date");
isAnyFieldsEmpty=true;
}else{
interviewToDate.setError(null);
isAnyFieldsEmpty=false;
}
if (interviewToTime.getText().toString()==null || interviewToTime.getText().toString().equalsIgnoreCase(""))
{
interviewToTime.setError("choose date");
isAnyFieldsEmpty=true;
}else{
interviewToTime.setError(null);
isAnyFieldsEmpty=false;
}
return isAnyFieldsEmpty;
}
Now on your Button click
call that method as below and validate
#overide
public void onclick
{
Boolean isinputEmpty=validateUserInput()
if(isinputEmpty==false)
{
///process your save or whatever processing it is
}
}