How to validate phone number in android application? - java

I am working on android. In my app users will register by entering their phone number in edittext. This phone number is then saved in database. Now when the user login with the app, I am getting the list of contacts from his mobile and comparing that with the people who register with this app. If the number in the contacts list matches with the number in the database, then I need to display those numbers in listview. Here the problem is if the user save his number with +91 or with 0 before his contact then the number in the database is not matching with the contact. At that time the numbers are not displaying.
For this issue, Do we need to keep any alert before entering the number in edit text? For example in edit text I gave, Ph no: 8923458128 and the saved it in database. Now I logged in with this number and my contacts list for suppose
9823484586
+919988334856
Lets say the above 2 numbers are stored in database. But the 2nd contact , the user entered as 9988334856 without +91. Then finally in the listview instead of 2 numbers only 1 number is displaying as the second number is not matching with database number.
How can I solve this issue? Please help me in this regard.

If you are fetching all phones from DB, then you can use below code to match entered phone with phone from DB using PhoneNumberUtils.compare()
It compares phone numbers a and b, return true if they're identical
enough for caller ID purposes.
private String getMatchedPhones(ArrayList<String> contactsFromDB, String phoneToMatch) {
// Iterate all numbers and match
for (String numberFromDb : contactsFromDB) {
if (PhoneNumberUtils.compare(numberFromDb, phoneToMatch)) {
return phoneToMatch; // Or numberFromDb
}
}
return null; // Or can custom msg. If not matched.
}

I think best way to do it create your table with 4 column-
1)id
2)name(if needed)
3)country-code
4)phone number
And now on your UI prefix country code in a spiner and give phone-number type of field in a textview. And in your database use integer value to store number.
And from matching your phone number just pass this query-
1)phoneNumber = phoneNumberEditText.getText().toString();
2)
// Reading all contacts from database
List<Contacts> number = db.getAllNumber();
for (final Contacts cn : number) {
if ((phoneNumber.equals(cn.getNumber()){
//do what you want
}
}
Thanks!Hope it will help you.

Put these two lines in your XML file at that phone number edit text field
android:inputType="numberDecimal"
android:maxLength="10"
then he could not enter more than 10 numbers and only he should enter numbers.
you can take country code in one more text field and validate with it.

For an Mobile number validation android provide InBuilt Patterns.But it only works in API level 8 and above.Try below one line code.
/* method for phone number validation */
private Boolean Number_Validate(String number)
{
return !TextUtils.isEmpty(number) && (number.length()==10) && android.util.Patterns.PHONE.matcher(number).matches();
}
you can call this mehtod by passing number in parameter,it return either true or false.
Number_Validate(number);
Hope you get your answer.
Thanks.

Use TEXT not Int in your database. When you use Int, if the first number is 0 it will disregard so just use TEXT.

private boolean phvalidator(String ph2) {
// TODO Auto-generated method stub
String expression = "^[0-9-1+]{10,15}$";
CharSequence inputStr = ph;
Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
return (matcher.matches())? true : false;

try this
final String mobile = emobile.getText().toString();
if (!isValidMobile(mobile)){
emobile.setError("Invalid Mobile");
}
private boolean isValidMobile(String mobile) {
if (!TextUtils.isEmpty(mobile)) {
return Patterns.PHONE.matcher(mobile).matches();
}
return false;
}

Related

how to prevent execution of same thing again and again

I have made an application that whenever a user types a particular word it toast a massage now I want to add a feature that if the user has typed the particular word continuously many times in a particular time it will consider it once only and toast the massage ones only.
The code
if ( string.equals("help") ) {
Toast.makeText(getApplicationContext(), "we are here to help", Toast.LENGTH_SHORT).show();
}
Use a global String variable let's name it as lastText and check whether input text is the same as last text.
UPDATE for time tracking
private String lastText = ""; // Global for all class members
private long lastTextTime = 0; // Global
//...
// May be more code goes here
//...
if ( string.equals("help") && !string.equals(lastText) ) {
// Check whether 5 min has elapsed to show the toast message
if(System.currentTimeMillis - lastTextTime > (5*60*1000)) {
Toast.makeText(getApplicationContext(), "we are here to help",
Toast.LENGTH_SHORT).show();
// If the program reach here save this string as a last text for the next check
lastText = string;
lastTextTime = System.currentTimeMillis;
}
}
You can add already typed words to a list, and when the user types a word, you can iterate through this list and check if "word" is already was typed, and then if "false" - show toast.
Alternative solution - you can create a local SQLite database (using Room persistence library), it will allow you to save values even if user restart/exit app, but it will require more coding and fixing nuances

libphonenumber - formatting phone numbers without knowing the country code

I have heard a lot of good from what appears to be an awesome library but I find myself in a delicate situation.
This is the first project I have ever worked where I am supposed to store phone numbers in a database.
I have read a bit about the E.164 format and I do intend to store all phone numbers using this format in my database.
The problem I am facing, is the data source. I have no control over the data source. All I known is that I am receiving a bunch of phone numbers and their format is not consistent. Some have the international extension, some don't. Some have parenthesis, hyphens, leading 0, etc. some don't.
How could I possibly extract the phone numbers from said source, format them into E.164 so that I can store them safely ?
I have tried using the PhoneNumberUtil#parse() method without providing the country code, since I don't have access to that information.
Have a look at the following example:
System.out.printLn("Number -> " + phoneNumberUtil.parse("00336555233634", null).toString())
Error type: INVALID_COUNTRY_CODE. Missing or invalid default region.
In my example, the number is that of french mobile phone. The two starting 0 works if you dial from outside France, I believe.
But the library cannot understand it as it is laking the country code.
Does that mean there does not exist a way to understand where that particular phone number is coming from ?
The documentation seems clear about it :
public PhoneNumber parse(CharSequence numberToParse, String defaultRegion)
#param defaultRegion region that we are expecting the number to be
from. This is only used if * the number being parsed is not
written in international format. The country_code for the *
number in this case would be stored as that of the default region
supplied. If the number * is guaranteed to start with a '+'
followed by the country calling code, then RegionCode.ZZ * or
null can be supplied.
So, if add the +33
System.out.printLn("Number -> " + phoneNumberUtil.parse("+336555233634", null).toString())
Then naturally the result is:
Number -> Country Code: 33 National Number: 336555233634
What should / can I do if the end-user supplies my app with phone numbers that do not start with + ? I cannot believe I am the only one if this situation.
Thanks for the help !
You need to use E164Format only. Here I took Norway as example
I have test case which tests and give the phone number in one format.
public static String getE164FormattedMobileNumber(String mobile, String locale)
throws PhoneNumberFormatException {
try {
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
PhoneNumber phoneProto = phoneUtil.parse(mobile, locale);
if (phoneUtil.isValidNumber(phoneProto)
&& phoneUtil.isPossibleNumberForType(phoneProto, PhoneNumberType.MOBILE)) {
return phoneUtil.format(phoneProto, PhoneNumberFormat.E164);
}
throw new PhoneNumberFormatException(
"Mobile number is invalid with the provided locale");
} catch (NumberParseException e) {
throw new PhoneNumberFormatException("Error in parsing mobile number", e);
}
}
and the test case as follows.
// this is the test mobile used
private String expectedMobileNumber = "+4746205615";
private List<String> sucessMobileNumbers;
private List<String> failMobileNumbers;
public PhoneNumberE164FormatTest() {
sucessMobileNumbers =
Arrays.asList(
"46205615",
"004746205615",
"+4746205615",
"4746205615",
"46205615",
"+47 46205615",
"462 05 615");
failMobileNumbers = Arrays.asList("abcdsds3434", "abcdsds343?#4", "21448410", "9946739087");
}
#Test
public void e164FormattedMobileNumbersSucessCase() throws PhoneNumberFormatException {
for (String mobileNumber : sucessMobileNumbers) {
Assert.assertEquals(
expectedMobileNumber,
(PhoneNumberUtils.getE164FormattedMobileNumber(mobileNumber, NO)));
}
}
#Test(expected = PhoneNumberFormatException.class)
public void e164FormattedMobileNumbersFailCase() throws PhoneNumberFormatException {
for (String mobileNumber : failMobileNumbers) {
PhoneNumberUtils.getE164FormattedMobileNumber(mobileNumber, NO);
}
}
Store the original phone numbers in a non-operational column RAW_PHONE, and the canonical E.164 standardized number in you PHONE column ("00" -> "+", "(" -> "" and such). This way you are prepared for check lists and manual corrections, and improving the conversion.
Imaginable is having two phone columns in the table, and as second value just another extension -203.
Better not to fill the strict field if the conversion fails on country code or is otherwise dubious. Is the default France, or what when the user lives in Belgium?
One might argue that the source (location) of user registration determines the default country code.

Create a boolean from a string

I am trying to create a boolean from an Edit Text field.
I've already converted it into a string but need to make a boolean from the answer. I want to assign the correct answer as 1 and 2 as the wrong answer. If you can give me a tip how to make sure they enter only 1 or 2 that would be great!
This is what i have so far:
public void EnterAnswer(Editable insertAnswer) {
EditText enterAnswer = (EditText) findViewById(R.id.editText_question_six);
String answer = enterAnswer.getText().toString().trim();
}
First and foremost, using an EditText, there is really no way of specifying the values a user can input. Best you can do is to use the input type attribute by setting the input type to "number" as shown below. This way, a user would only be able to input numbers.
android:inputType="number"
You can also use the setError() method of the EditText to display an error if the user inputs a value that is neither 0 nor 1. This is illustrated below:
if(!(editText.getText().toString().equals("0") || editText.getText().toString().equals("1"))){
editText.setError("Wrong input, you can only input 0 or 1");
}
Follow this procedure:
Get the text from your textview
Check whether the text is one or two
assign a value to your boolean variable based on the result above.
Illustration:
public boolean EnterAnswer(Editable answerView){
boolean result = false;
String answer = answerView.getText().toString().trim();
if(answer.equals("1")){
result = true;
}
return result;
}
Following the logic above, the method will only return true if the answer (from the EditText) is one.
I hope this helps... Merry coding!

Java user input validations

I'm new to Java GUI . I'm doing a project using Netbeans.There are several text fields and I need to do validations for them.
Validations should be
Want to check whether fields are empty or not.
If it's a number field it should be validated only to input numbers.
In web (Ex:contact form) validations we can validate the fields step by step when user is entering data up to down. I need to know whether it is possible or not in Java GUI programmes.
Found several methods as Documentfilter,InputVerifier and PlainDocument. Can someone please explain the differences of them and what is the best method to use for validations input data of users in Java?
depending how familiar you are with java programming in general, this helps you more or less
Retrieve the text from the JTextField (getText()) and check for emptiness
Cast the text to a number and catch a NumberFormatException in case its not a number.
for 2) its a validation after the user has entered something and not an validation during typing
You should write java method for validation .
1.Read Text from JTextField using (getText() ) and pass this string to NumberValidation Method . Sample code is shown below
String data=textFieldObject.getText().trim();
boolean validate =isValidMobile(data);//return false if the data is not a valid phone number
public boolean isValidMobile(String PhoneNumber)
{
try{
if(PhoneNumber.length()==10) //checking length.
{
for(int i=0;i<10;i++){
char c=PhoneNumber.charAt(i);
if(!Character.isDigit(c)) //return false if the character is digit
{
return false;
}
}
}else
{
return false;
}
return true;
}catch(Exception r)
{
return false;
}
}

How to check if a user inputted value is valid?

I'm working on an app in which the user has the option to input a set of coordinates in two EditText views for Latitude and Longitude. The inputted coordinate/location will then be displayed on a map, which works great. However if the user inputs an invalid value the app crashes, and I need to prevent that.
The Latitudes/Longitudes value has to be for example 35.27, and the thing that makes the app crash is when there's more then one dot "." e.g. 33.23.43. How can i check if the inputted value only has ONE dot?
I don't really have a lot of experience in this area, and I'm still new to android, so any help will be much appreciated.
I was going to suggest that you checked the length of the string that you get, but because 1.5 and 153.163 are both valid that doesn't work. I advise you to use a `try/catch statement. For example
try{
//do what ever you do with the numbers here
catch(Exception e){
//the user has inputted an invalid number deal with it here
}
Check out
Android EditText : setFilters Example : Numeric Text field Patterns and Length Restriction.
It may be what you want.
bool badInput = countChar(s, '.') > 1;
where countChar is
int countChar(string s, char c)
{
int counter = 0;
for( int i=0; i<s.length(); i++ ) {
if( s.charAt(i) == c ) {
counter++;
}
}
return counter;
}
Simply use a regexp to check the validity of the input.
Pattern p = Pattern.compile("^(-)?\d*(\.\d*)?$");
Matcher m = p.matcher(inputString);
if (m.find()) {
////Found
}
else {
//Not found
}
Now Implement a focus listener on the field to run this validity test.
OR : you can do this from xml also.
In XML add attribute to editText :
android:inputType="number|numberSigned|numberDecimal"
for signed floating point number.
Thanks.

Categories

Resources