lamudi-gmbh / android-phone-field

A small library that allows you to create phone fields with corresponding country flags, and validate the phone number using libphonenumber from google.
Apache License 2.0
227 stars 67 forks source link

How to get the "Phone Number region" after user entering phone number? #17

Open dimitrihartt opened 5 years ago

dimitrihartt commented 5 years ago

How can I get the "Phone Number region" after the user having entered the number. Ie: If the user enters: +49 9876543210 I could get: phone.country.region = "DE" Is it possible?

vzahradnik commented 5 years ago

It it possible to get the region, however not directly. This library uses another library called libphonenumber by Google. For you its internals are hidden.

However if you add libphonenumber as a dependency to your project, you can get the region as follows:

final private PhoneNumberUtil mPhoneUtil = PhoneNumberUtil.getInstance();
Phonenumber.PhoneNumber number = mPhoneUtil.parseAndKeepRawInput("+499876543210", "DE");

// After the number is parsed, you can get region code as follows:
final String phoneRegion = mPhoneUtil.getRegionCodeForNumber(number)

Also check this great online parser. It pretty much demonstrates all the capabilities which the parsing library provides.

lilia-sensiati commented 4 years ago

This is my solution with Kotlin

val loc = Locale("", getRegion(id_mobile_edittext.phoneNumber))
Log.d("region", loc.displayCountry)

This is the function getRegion that takes the mobileNumber as parameter

private fun getRegion(mobileNumber: String): String {
        val util = PhoneNumberUtil.getInstance()
        val numberRegion = util.parse(mobileNumber, null)
        return util.getRegionCodeForNumber(numberRegion)
    }
dimitrihartt commented 4 years ago

Thank you very much ❤️ I really needed that!

lilia-sensiati commented 4 years ago

Thank you very much ❤️ I really needed that!

I'm glad I could help !