Java Code Examples for com.google.i18n.phonenumbers.Phonenumber#PhoneNumber

The following examples show how to use com.google.i18n.phonenumbers.Phonenumber#PhoneNumber . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ProjectUtil.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
public static boolean validatePhone(String phNumber, String countryCode) {
  PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
  String contryCode = countryCode;
  if (!StringUtils.isBlank(countryCode) && (countryCode.charAt(0) != '+')) {
    contryCode = "+" + countryCode;
  }
  Phonenumber.PhoneNumber phoneNumber = null;
  try {
    if (StringUtils.isBlank(countryCode)) {
      contryCode = PropertiesCache.getInstance().getProperty("sunbird_default_country_code");
    }
    String isoCode = phoneNumberUtil.getRegionCodeForCountryCode(Integer.parseInt(contryCode));
    phoneNumber = phoneNumberUtil.parse(phNumber, isoCode);
    return phoneNumberUtil.isValidNumber(phoneNumber);
  } catch (NumberParseException e) {
    ProjectLogger.log("Exception occurred while validating phone number : ", e);
    ProjectLogger.log(phNumber + "this phone no. is not a valid one.");
  }
  return false;
}
 
Example 2
Source File: BaseFlagFragment.java    From android-phone-number-with-flags with Apache License 2.0 6 votes vote down vote up
protected String validate() {
    String region = null;
    String phone = null;
    if (mLastEnteredPhone != null) {
        try {
            Phonenumber.PhoneNumber p = mPhoneNumberUtil.parse(mLastEnteredPhone, null);
            StringBuilder sb = new StringBuilder(16);
            sb.append('+').append(p.getCountryCode()).append(p.getNationalNumber());
            phone = sb.toString();
            region = mPhoneNumberUtil.getRegionCodeForNumber(p);
        } catch (NumberParseException ignore) {
        }
    }
    if (region != null) {
        return phone;
    } else {
        return null;
    }
}
 
Example 3
Source File: E164PhoneNumberWithExtension.java    From jadira with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a instance from the given PhoneNumber
 * @param prototype The PhoneNumber to construct the instance from
 */
public E164PhoneNumberWithExtension(Phonenumber.PhoneNumber prototype) {

    StringBuilder e164Builder = new StringBuilder();
    PHONE_NUMBER_UTIL.format(prototype, PhoneNumberFormat.E164, e164Builder);
    
	try {
        this.number = PHONE_NUMBER_UTIL.parse(e164Builder.toString(), "GB");
    } catch (NumberParseException e) {
        throw new PhoneNumberParseException(
                EX_PARSE_MSG_PREFIX + prototype.getNationalNumber() +"}", e);
    }
	
	if (prototype.hasExtension()) {
		this.number.setExtension(prototype.getExtension());
	}
}
 
Example 4
Source File: MainPresenter.java    From YaMvp with MIT License 6 votes vote down vote up
private String validateThenFormatMobileNumber(String phone) {
    try {
        PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
        Phonenumber.PhoneNumber phoneNumber = phoneNumberUtil.parse(phone, "+86");
        if (phoneNumberUtil.isValidNumber(phoneNumber) && (
                phoneNumberUtil.getNumberType(phoneNumber)
                == PhoneNumberUtil.PhoneNumberType.MOBILE
                || phoneNumberUtil.getNumberType(phoneNumber)
                   == PhoneNumberUtil.PhoneNumberType.FIXED_LINE_OR_MOBILE)) {
            return phoneNumberUtil.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164);
        } else {
            return "";
        }
    } catch (NumberParseException e) {
        return "";
    }
}
 
Example 5
Source File: ContactFragment.java    From customview-samples with Apache License 2.0 6 votes vote down vote up
private void displayContactData(){
    List<PhoneInfo> phoneInfoList = MobileContactSingleton.getInstance().getMobileContact();

    PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
    for(PhoneInfo phoneInfo: phoneInfoList) {
        try {
            String phoneNum = phoneInfo.getPhoneNum();
            Phonenumber.PhoneNumber phoneNumProto = phoneUtil.parse(phoneNum, "CN");
            boolean isValid = phoneUtil.isValidNumber(phoneNumProto);
            Log.d("hyh", "ContactFragment: displayContactData: isValid="+isValid+" ,phoneNum="+phoneNum);
            if (isValid) {
                String formatPhoneNum = phoneUtil.format(phoneNumProto,
                    PhoneNumberUtil.PhoneNumberFormat.E164);
                Log.d("hyh", "ContactMgr: run: formatPhoneNum=" + formatPhoneNum);
            }
        } catch (NumberParseException e) {
            Log.d("hyh", "ContactFragment: displayContactData: phone="+phoneInfo.getPhoneNum());
            e.printStackTrace();
        }
    }

    ContactListAdapter contactListAdapter = new ContactListAdapter(getContext(),phoneInfoList);
    mRvContactList.setLayoutManager(new LinearLayoutManager(getContext()));
    mRvContactList.setAdapter(contactListAdapter);
}
 
Example 6
Source File: ShortCodeUtil.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public static boolean isShortCode(@NonNull String localNumber, @NonNull String number) {
  try {
    PhoneNumberUtil         util              = PhoneNumberUtil.getInstance();
    Phonenumber.PhoneNumber localNumberObject = util.parse(localNumber, null);
    String                  localCountryCode  = util.getRegionCodeForNumber(localNumberObject);
    String                  bareNumber        = number.replaceAll("[^0-9+]", "");

    // libphonenumber seems incorrect for Russia and a few other countries with 4 digit short codes.
    if (bareNumber.length() <= 4 && !SHORT_COUNTRIES.contains(localCountryCode)) {
      return true;
    }

    Phonenumber.PhoneNumber shortCode = util.parse(number, localCountryCode);
    return ShortNumberInfo.getInstance().isPossibleShortNumberForRegion(shortCode, localCountryCode);
  } catch (NumberParseException e) {
    Log.w(TAG, e);
    return false;
  }
}
 
Example 7
Source File: PhoneUtils.java    From android-phone-number-with-flags with Apache License 2.0 6 votes vote down vote up
private static String parseNumber(String paramString) {
    if (paramString == null) {
        return null;
    }
    PhoneNumberUtil numberUtil = PhoneNumberUtil.getInstance();
    String result;
    try {
        Phonenumber.PhoneNumber localPhoneNumber = numberUtil.parse(paramString, null);
        result = numberUtil.getRegionCodeForNumber(localPhoneNumber);
        if (result == null) {
            return null;
        }
    } catch (NumberParseException localNumberParseException) {
        return null;
    }
    return result;
}
 
Example 8
Source File: MobileValidation.java    From keycloak-extension-playground with Apache License 2.0 6 votes vote down vote up
static boolean isPhoneNumberValid(String phoneNumber) {

        String formattedPhoneNumber = convertInternationalPrefix(phoneNumber);

        String region;
        if (isPossibleNationalNumber(formattedPhoneNumber)) {
            region = "DE";
        } else if (isInternationalNumber(formattedPhoneNumber)) {
            region = null;
        } else {
            return true; // If the number cannot be interpreted as an international or possible DE phone number, do not attempt to validate it.
        }

        try {
            Phonenumber.PhoneNumber parsedPhoneNumber = PhoneNumberUtil.getInstance().parse(formattedPhoneNumber, region);
            return PhoneNumberUtil.getInstance().isValidNumber(parsedPhoneNumber);
        } catch (NumberParseException e) {
            return false;
        }
    }
 
Example 9
Source File: Utilities.java    From call_manage with MIT License 6 votes vote down vote up
/**
 * Format a given phone number to a readable string for the user
 *
 * @param phoneNumber the number to format
 * @return the formatted number
 */
public static String formatPhoneNumber(String phoneNumber) {
    if (phoneNumber == null) return null;
    phoneNumber = normalizePhoneNumber(phoneNumber);
    Phonenumber.PhoneNumber formattedNumber = null;
    PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();

    try {
        formattedNumber = phoneUtil.parse(phoneNumber, sLocale.getCountry());
    } catch (NumberParseException e) {
        Timber.w(e);
        return phoneNumber;
    }

    PhoneNumberUtil.PhoneNumberFormat format;
    if (phoneUtil.getRegionCodeForCountryCode(formattedNumber.getCountryCode()).equals(sLocale.getCountry()))
        format = PhoneNumberUtil.PhoneNumberFormat.NATIONAL;
    else
        format = PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL;

    return phoneUtil.format(formattedNumber, format);
}
 
Example 10
Source File: MessagesDatabase.java    From weMessage with GNU Affero General Public License v3.0 6 votes vote down vote up
public Handle getHandleByAccount(String account) throws SQLException {
    try {
        PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
        Phonenumber.PhoneNumber numberOne = phoneNumberUtil.parse(account, Locale.getDefault().getCountry());
        String numberStringOne = phoneNumberUtil.format(numberOne, PhoneNumberUtil.PhoneNumberFormat.E164);

        Handle handle = getHandleById(numberStringOne);

        if (handle == null){
            Phonenumber.PhoneNumber numberTwo = numberOne.clearCountryCode();
            String numberStringTwo = phoneNumberUtil.format(numberTwo, PhoneNumberUtil.PhoneNumberFormat.E164).substring(2);

            return getHandleById(numberStringTwo);
        }else {
            return handle;
        }
    }catch(Exception ex){
        return getHandleById(account);
    }
}
 
Example 11
Source File: SessionPhoneTokenRequestJson.java    From mxisd with GNU Affero General Public License v3.0 5 votes vote down vote up
public String getValue() {
    try {
        Phonenumber.PhoneNumber num = phoneUtil.parse(phone_number, country);
        return phoneUtil.format(num, PhoneNumberUtil.PhoneNumberFormat.E164).replace("+", "");
    } catch (NumberParseException e) {
        throw new IllegalArgumentException("Invalid phone number");
    }
}
 
Example 12
Source File: LoginForPhoneActivity.java    From Android with MIT License 5 votes vote down vote up
@Override
public void afterTextChanged(Editable s) {
    try {
        PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
        Phonenumber.PhoneNumber swissNumberProto = phoneUtil.parse(s.toString(), countryBean.getCountryCode());
        if(phoneUtil.isValidNumberForRegion(swissNumberProto, countryBean.getCountryCode())){
            setBtnEnabled(true);
        }else{
            setBtnEnabled(false);
        }
    } catch (Exception e) {
        e.printStackTrace();
        setBtnEnabled(false);
    }
}
 
Example 13
Source File: PhoneField.java    From android-phone-field with Apache License 2.0 5 votes vote down vote up
/**
 * Sets phone number.
 *
 * @param rawNumber the raw number
 */
public void setPhoneNumber(String rawNumber) {
  try {
    Phonenumber.PhoneNumber number = parsePhoneNumber(rawNumber);
    if (mCountry == null || mCountry.getDialCode() != number.getCountryCode()) {
      selectCountry(number.getCountryCode());
    }
    mEditText.setText(mPhoneUtil.format(number, PhoneNumberUtil.PhoneNumberFormat.NATIONAL));
  } catch (NumberParseException ignored) {
  }
}
 
Example 14
Source File: MessagesDatabase.java    From weMessage with GNU Affero General Public License v3.0 5 votes vote down vote up
public PeerChat getChatByAccount(String handle) throws SQLException {
    ChatBase chatBase;

    try {
        PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
        Phonenumber.PhoneNumber phoneNumberOne = phoneNumberUtil.parse(handle, Locale.getDefault().getCountry());

        String phoneNumberString = phoneNumberUtil.format(phoneNumberOne, PhoneNumberUtil.PhoneNumberFormat.E164);
        ChatBase attemptOne = getChatByIdentifier(phoneNumberString);

        if (attemptOne == null){
            Phonenumber.PhoneNumber phoneNumberTwo = phoneNumberOne.clearCountryCode();
            String phoneNumberStringTwo = phoneNumberUtil.format(phoneNumberTwo, PhoneNumberUtil.PhoneNumberFormat.E164).substring(2);
            ChatBase attemptTwo = getChatByIdentifier(phoneNumberStringTwo);

            if (attemptTwo == null){
                return null;
            }else {
                chatBase = attemptTwo;
            }
        }else {
            chatBase = attemptOne;
        }
    }catch(Exception ex){
        chatBase = getChatByIdentifier(handle);
    }

    if (chatBase == null) return null;
    if (chatBase instanceof GroupChat) return null;

    return (PeerChat) chatBase;
}
 
Example 15
Source File: PhoneNumberFormatter.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
PhoneNumberFormatter(@NonNull String localNumberString) {
  try {
    Phonenumber.PhoneNumber libNumber   = phoneNumberUtil.parse(localNumberString, null);
    int                     countryCode = libNumber.getCountryCode();

    this.localNumber       = Optional.of(new PhoneNumber(localNumberString, countryCode, parseAreaCode(localNumberString, countryCode)));
    this.localCountryCode  = phoneNumberUtil.getRegionCodeForNumber(libNumber);
  } catch (NumberParseException e) {
    throw new AssertionError(e);
  }
}
 
Example 16
Source File: NumberViewState.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private static String formatNumber(@NonNull PhoneNumberUtil util, @NonNull String e164Number) {
  try {
    Phonenumber.PhoneNumber number = getPhoneNumber(util, e164Number);
    return util.format(number, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL);
  } catch (NumberParseException e) {
    return e164Number;
  }
}
 
Example 17
Source File: NumberViewState.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Finds actual name of region from a valid number. So for example +1 might map to US or Canada or other territories.
 */
private static @Nullable String getActualCountry(@NonNull PhoneNumberUtil util, @NonNull String e164Number) {
  try {
    Phonenumber.PhoneNumber phoneNumber = getPhoneNumber(util, e164Number);
    String                  regionCode  = util.getRegionCodeForNumber(phoneNumber);

    if (regionCode != null) {
      return PhoneNumberFormatter.getRegionDisplayName(regionCode);
    }

  } catch (NumberParseException e) {
    return null;
  }
  return null;
}
 
Example 18
Source File: PhoneField.java    From android-phone-field with Apache License 2.0 5 votes vote down vote up
/**
 * Gets phone number.
 *
 * @return the phone number
 */
public String getPhoneNumber() {
  try {
    Phonenumber.PhoneNumber number = parsePhoneNumber(getRawInput());
    return mPhoneUtil.format(number, PhoneNumberUtil.PhoneNumberFormat.E164);
  } catch (NumberParseException ignored) {
  }
  return getRawInput();
}
 
Example 19
Source File: NumberViewState.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
private static Phonenumber.PhoneNumber getPhoneNumber(@NonNull PhoneNumberUtil util, @NonNull String e164Number)
  throws NumberParseException
{
  return util.parse(e164Number, null);
}
 
Example 20
Source File: PhoneNumberFormatter.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
public String format(@Nullable String number) {
  if (number == null)                       return "Unknown";
  if (GroupId.isEncodedGroup(number))     return number;
  if (ALPHA_PATTERN.matcher(number).find()) return number.trim();

  String bareNumber = number.replaceAll("[^0-9+]", "");

  if (bareNumber.length() == 0) {
    if (number.trim().length() == 0) return "Unknown";
    else                             return number.trim();
  }

  // libphonenumber doesn't seem to be correct for Germany and Finland
  if (bareNumber.length() <= 6 && ("DE".equals(localCountryCode) || "FI".equals(localCountryCode) || "SK".equals(localCountryCode))) {
    return bareNumber;
  }

  // libphonenumber seems incorrect for Russia and a few other countries with 4 digit short codes.
  if (bareNumber.length() <= 4 && !SHORT_COUNTRIES.contains(localCountryCode)) {
    return bareNumber;
  }

  if (isShortCode(bareNumber, localCountryCode)) {
    return bareNumber;
  }

  String processedNumber = applyAreaCodeRules(localNumber, bareNumber);

  try {
    Phonenumber.PhoneNumber parsedNumber = phoneNumberUtil.parse(processedNumber, localCountryCode);
    return phoneNumberUtil.format(parsedNumber, PhoneNumberUtil.PhoneNumberFormat.E164);
  } catch (NumberParseException e) {
    Log.w(TAG, e);
    if (bareNumber.charAt(0) == '+')
      return bareNumber;

    String localNumberImprecise = localNumber.isPresent() ? localNumber.get().getE164Number() : "";

    if (localNumberImprecise.charAt(0) == '+')
      localNumberImprecise = localNumberImprecise.substring(1);

    if (localNumberImprecise.length() == bareNumber.length() || bareNumber.length() > localNumberImprecise.length())
      return "+" + number;

    int difference = localNumberImprecise.length() - bareNumber.length();

    return "+" + localNumberImprecise.substring(0, difference) + bareNumber;
  }
}