dr_rk
dr_rk

Reputation: 4565

Random phone number generator for any country

I am trying to create synthetic data around phone numbers, from a list of countries.

I found Google's libphonenumber Java library with ports in Python, C++, etc. a good resource.

Is it possible to generate valid random phone numbers from a list of countries, with this library?

With this code I've written, I am using their getExampleNumber function but it is generating the same number each time:

import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberType;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import com.google.i18n.phonenumbers.Phonemetadata.PhoneNumberDesc;
import com.google.i18n.phonenumbers.NumberParseException;

public class Driver {
    public static void main(String[] args) {
       // Prints "Hello, World" in the terminal window.
       for (int i=0;i<10;i++)
       {
          System.out.println(Generator());
       }
    }


    public static PhoneNumber  Generator() 
    {
       String regionCode = new String("GB");
       PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
       PhoneNumber exampleNumber =phoneNumberUtil.getExampleNumber(regionCode);
       return exampleNumber;
    }

}

Upvotes: 0

Views: 11569

Answers (3)

Thinh Trinh
Thinh Trinh

Reputation: 29

You can use the minimal regex version from libphonenumber-js library's metadata and this tool to generate valid random phone number for any country.

If this is too complicated, you can take a look at this Random phone number generator to simplify all of these stuffs.

Upvotes: 0

android developer
android developer

Reputation: 116362

The best way would be to use the REGEX that the library has, somehow, but it's a lot of work.

As the function of getExampleNumber will return you the exact same value, always, you can still use it, to randomize (or iterate) numbers in it.

Here's an example (sample here) of how to do it, getting 10 random mobile phone numbers of each supported region :

class MainActivity : AppCompatActivity() {
    @WorkerThread
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val phoneNumbersToRandomize = 10
        var regionsThatFoundMobilePhonesFor = 0
        if (savedInstanceState == null)
            thread {
                val phoneNumberUtil = PhoneNumberUtil.getInstance()
                val startTime = System.currentTimeMillis()
                val supportedRegions = phoneNumberUtil.supportedRegions
                for (region in supportedRegions) {
                    val validPhoneNumbers = HashSet<String>()
                    val exampleNumber = phoneNumberUtil.getExampleNumberForType(region, PhoneNumberUtil.PhoneNumberType.MOBILE)
                    if (exampleNumber == null) {
                        Log.w("AppLog", "region:$region no exampleNumber")
                        continue
                    }
                    Log.d("AppLog", "region:$region exampleNumber:${phoneNumberUtil.format(exampleNumber, PhoneNumberUtil.PhoneNumberFormat.E164)}")
                    val countryCode = phoneNumberUtil.getCountryCodeForRegion(region)
                    val nationalSignificantNumber = phoneNumberUtil.getNationalSignificantNumber(exampleNumber)
                    //                    Log.d("AppLog", "finding $phoneNumbersToRandomize random mobile phone numbers for $region example phone number:" +
                    //                            phoneNumberUtil.format(exampleNumber, PhoneNumberUtil.PhoneNumberFormat.E164) + " countryCode:$countryCode nationalSignificantNumber:$nationalSignificantNumber ")
                    val randomDigitsLength = nationalSignificantNumber.length
                    while (validPhoneNumbers.size < phoneNumbersToRandomize) {
                        val inputPhone = "+$countryCode${getRandomStringOfDigits(randomDigitsLength)}"
                        if (validPhoneNumbers.contains(inputPhone))
                            continue
                        val phoneNumber = phoneNumberUtil.parse(inputPhone, region)
                        val nationalSignificantNumberFromGeneratedNumber = phoneNumberUtil.getNationalSignificantNumber(phoneNumber)
                        if (nationalSignificantNumberFromGeneratedNumber.length != randomDigitsLength)
                            continue
                        val isValidMobilePhoneNumber = phoneNumberUtil.isValidNumberForRegion(phoneNumber, region)
                                && phoneNumberUtil.isPossibleNumberForType(phoneNumber, PhoneNumberUtil.PhoneNumberType.MOBILE)
                        if (isValidMobilePhoneNumber) {
                            validPhoneNumbers.add(inputPhone)
                        }
                    }
                    ++regionsThatFoundMobilePhonesFor
                }
                Log.d("AppLog", "done regionsThatFoundMobilePhonesFor:$regionsThatFoundMobilePhonesFor out of ${supportedRegions.size}" +
                        "timeTaken:${System.currentTimeMillis() - startTime}ms")
            }

    }

    companion object {
        private fun getRandomStringOfDigits(numberOfDigitsToGenerate: Int): String {
            val sb = StringBuilder(numberOfDigitsToGenerate)
            for (i in 0 until numberOfDigitsToGenerate)
                sb.append(Random.nextInt(10).toString())
            return sb.toString()
        }
    }
}

gradle dependencies:

    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'androidx.core:core-ktx:1.3.2'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    api 'com.googlecode.libphonenumber:libphonenumber:8.12.13'

Upvotes: 1

Pablo AM
Pablo AM

Reputation: 314

This library does not provide you with random numbers, no matter how many times you run your code you will always get:

Country Code: 44 National Number: 1212345678

You can take a look to their github project:

https://github.com/googlei18n/libphonenumber/

And you will see a lot of proto files inside this folder:

https://github.com/googlei18n/libphonenumber/tree/master/java/libphonenumber/src/com/google/i18n/phonenumbers/data

From those files is where they get that number, so it is hardcoded in there. No way to get it randomly.

Upvotes: 1

Related Questions