Search code examples
androidtelephonymanagerlibphonenumberphonenumberutils

Getting the Wrong Mobile Prefix in Android


I am making an app where I will get user's complete phone number from the sim - including the country and mobile prefixes. The phone number I have is 061555555, so when I save it to server it should look like this: +38761555555.

And here is my problem - when I use the code from below I get the following: +387218900032555555, ie. instead of 061 becoming 61, it becomes 218900032. This line number gives the wrong number:

MyPhoneNumber = tMgr.getLine1Number(); 

I have also tried this and this.

This is my code:

// Get users phone number
private String getMyPhoneNumber() {
    TelephonyManager tMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

    // Get the SIM country ISO code
    String simCountry = tMgr.getSimCountryIso().toUpperCase();
    // Get the operator code of the active SIM (MCC + MNC)
    String simOperatorCode = tMgr.getSimOperator();
    // Get the name of the SIM operator
    String simOperatorName = tMgr.getSimOperatorName();
    // Get the SIM’s serial number
    String simSerial = tMgr.getSimSerialNumber();

    String MyPhoneNumber = "0000000000";

    try {
        MyPhoneNumber = tMgr.getLine1Number();
    } catch (NullPointerException ex) {
    }

    if (MyPhoneNumber.equals("")) {
        MyPhoneNumber = tMgr.getSubscriberId();
    }

    PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
    Phonenumber.PhoneNumber countryNumberProto = null;
    try {
        countryNumberProto = phoneUtil.parse(MyPhoneNumber, simCountry);
    } catch (NumberParseException e) {
        System.err.println("NumberParseException was thrown: " + e.toString());
    }

    String myPhone = phoneUtil.format(countryNumberProto, PhoneNumberUtil.PhoneNumberFormat.E164);
    // I tried INTERNATIONAL and NATIONAL as well

    return myPhone;
}

Solution

  • I think you are parsing "national_number" instead of "country_code". Check your JSON parsing code fields logic

    {
      "country_code": 41,
      "national_number": 446681800
    }
    

    https://github.com/googlei18n/libphonenumber