6

enter image description here

I have doubt in that section. How to Remove country code, when I pick phone number from contact list?

Ex: +91 999999999 instead of 9999999999 or +020 9696854549 instead of 9696854549 Can any one know the answer about my question. please give solution to this problem

I attached my code and image here.

     private void contactPicked(Intent data) {
    Cursor cursor = null;
    try {
    String phoneNo = null ;
    // getData() method will have the Content Uri of the selected contact
    Uri uri = data.getData();
    //Query the content uri
    cursor = getContentResolver().query(uri, null, null, null, null);
    cursor.moveToFirst();
    // column index of the phone number
    int  phoneIndex =cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER
  phoneNo = cursor.getString(phoneIndex);
   String phoneNumber = phoneNo.replaceAll(" ","");
   mobile_et.setText(phoneNumber);
} catch (Exception e) {
    e.printStackTrace();
}
}
New
  • 152
  • 1
  • 2
  • 12
  • @IntelliJAmiya That will only work for countries which have a country code with three digits. The US has 1, a lot of countries have 2... – Peter Abolins Aug 03 '17 at 06:19
  • 1
    There is nothing that says that all phone numbers must have a country code (in the contact list). But, you could check this by looking for "+" and then remove the digits after it (up to the first space). – Peter Abolins Aug 03 '17 at 06:25

10 Answers10

4

My English is poor, but I will try my best to answer your question.

First of all , add this line to your build.gradle

compile 'com.googlecode.libphonenumber:libphonenumber:8.7.0'

And below is a sample write by kotlin

fun deleteCountry(phone: String) : String{
    val phoneInstance = PhoneNumberUtil.getInstance()
    try {
        val phoneNumber = phoneInstance.parse(phone, null)
        return phoneNumber?.nationalNumber?.toString()?:phone
    }catch (_ : Exception) {
    }
    return phone
}

If phone number not start with a '+' followed by the country calling code then you should pass region information, for example:

val phoneNumber = phoneInstance.parse(phone, "CN")

Omar Dhanish
  • 885
  • 7
  • 18
ijustyce
  • 328
  • 1
  • 3
  • 13
  • Update- use this for android : implementation 'io.michaelrocks:libphonenumber-android:8.12.52' – Ankit Gupta Jul 31 '22 at 13:45
  • @AnkitGupta Why do you think we should use this for Android implementation 'io.michaelrocks:libphonenumber-android:8.12.52' instead of com.googlecode.libphonenumber:libphonenumber:8.7.0 ? – Jay Rathod Jul 07 '23 at 08:06
4

You can use startsWith()

This method has two variants and tests if a string starts with the specified prefix beginning a specified index or by default at the beginning.

if(phoneNumber.startsWith("+"))
{
    if(phoneNumber.length()==13)
    {
    String str_getMOBILE=phoneNumber.substring(3);
    mobile_et.setText(str_getMOBILE);
    }
    else if(phoneNumber.length()==14)
    {
    String str_getMOBILE=phoneNumber.substring(4);
    mobile_et.setText(str_getMOBILE);
    }


}
else
{
 mobile_et.setText(phoneNumber);
}
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
  • 1
    Thanks. But your solution give to remove first 4 digits. i get that solution from your answer Ex: +917854129856 it 'll give 54129856. this is not perfect solution when i ask . i need to get 7854129845 – New Aug 03 '17 at 06:59
4

Try this....

                if(number.length()>10)
                {
                    int startidx=number.length()-10;
                    String getnumber=number.substring(startidx,number.length());
                    etEmerNumber.setText(getnumber);
                }
                else
                {
                    etEmerNumber.setText(number);
                }
3

I am just simply extending the answer that If you don't want to use any library then you can do it in this way. In order to match any prefix and since some countries could share partially the same prefix (for example 91 and 91-721), you add all possibilities to the regex in descending order and size.

Follow this Code:

public static String PhoneNumberWithoutCountryCode(String phoneNumberWithCountryCode){//+91 7698989898
        Pattern compile = Pattern.compile("\\+(?:998|996|995|994|993|992|977|976|975|974|973|972|971|970|968|967|966|965|964|963|962|961|960|886|880|856|855|853|852|850|692|691|690|689|688|687|686|685|683|682|681|680|679|678|677|676|675|674|673|672|670|599|598|597|595|593|592|591|590|509|508|507|506|505|504|503|502|501|500|423|421|420|389|387|386|385|383|382|381|380|379|378|377|376|375|374|373|372|371|370|359|358|357|356|355|354|353|352|351|350|299|298|297|291|290|269|268|267|266|265|264|263|262|261|260|258|257|256|255|254|253|252|251|250|249|248|246|245|244|243|242|241|240|239|238|237|236|235|234|233|232|231|230|229|228|227|226|225|224|223|222|221|220|218|216|213|212|211|98|95|94|93|92|91|90|86|84|82|81|66|65|64|63|62|61|60|58|57|56|55|54|53|52|51|49|48|47|46|45|44\\D?1624|44\\D?1534|44\\D?1481|44|43|41|40|39|36|34|33|32|31|30|27|20|7|1\\D?939|1\\D?876|1\\D?869|1\\D?868|1\\D?849|1\\D?829|1\\D?809|1\\D?787|1\\D?784|1\\D?767|1\\D?758|1\\D?721|1\\D?684|1\\D?671|1\\D?670|1\\D?664|1\\D?649|1\\D?473|1\\D?441|1\\D?345|1\\D?340|1\\D?284|1\\D?268|1\\D?264|1\\D?246|1\\D?242|1)\\D?");
        String number = phoneNumberWithCountryCode.replaceAll(compile.pattern(), "");
        //Log.e(tag, "number::_>" +  number);//OutPut::7698989898
        return number;
    }
Ninja
  • 678
  • 10
  • 26
2

It will work for all instances. You need not care about how much digit the country code is

String get_Mo = phoneNumber.substring(phoneNumber.lastIndexOf(' ')+1));
2

If you can use a library, this might help you:

Gradle:

repositories {
  mavenCentral()
}

dependencies {
  implementation 'io.michaelrocks:libphonenumber-android:8.12.51'
}

Java:

String getPhoneNummberWithoutCountryCode(String phoneNo)
{
    PhoneNumberUtil phoneInstance = PhoneNumberUtil.createInstance(this.getContext());
    
    Phonenumber.PhoneNumber phoneNumber = phoneInstance.parse(phoneNo, null);
    String nationalSignificantNumber = phoneInstance.getNationalSignificantNumber(phoneNumber);

    return nationalSignificantNumber;
}

nationalSignificantNumber is the required phone number

Atin Agrawal
  • 178
  • 3
  • 12
0

use this function hope it will help you out:

public String phoeNumberWithOutCountryCode(String phoneNumberWithCountryCode) {
        Pattern complie = Pattern.compile(" ");
        String[] phonenUmber = complie.split(phoneNumberWithCountryCode);
        Log.e("number is", phonenUmber[1]);
        return phonenUmber[1];
    }
Deepak Rana
  • 539
  • 4
  • 18
  • I have the phone number like +911234567890 I need to remove the +91 code. And in another pattern I have +91 1234 4567 - 897 if I use the above code aim getting only 1234 number I need to like 12344567897 – Lahari Areti Jun 29 '18 at 07:05
0
String Trimmed = s.toString().trim();
if(Trimmed.length() > 10){
char[] number = Trimmed.toCharArray();
int extra;
int dif = Trimmed.length() - 10 ;
for(int i = dif; i < Trimmed.length() ; i++){
    extra = i-dif;
    number[extra] = number[i];
}
for (int i = 10 ; i < Trimmed.length() ; i++){
    number[i]=' ';
}
String finalNumber = String.valueOf(number);
MobileNumberET.setText(finalNumber.trim());
}

//paste this in your text change listener

  • Welcome to Stack Overflow! While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please [include an explanation for your code](//meta.stackexchange.com/q/114762/269535), as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Samuel Philipp Jul 13 '19 at 13:40
0

Use a library https://groups.google.com/forum/?hl=en&fromgroups#!forum/libphonenumber-discuss

PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
// phone must begin with '+'
PhoneNumber numberProto = phoneUtil.parse(phone, "");
int countryCode = numberProto.getCountryCode();
} catch (NumberParseException e) {
System.err.println("NumberParseException was thrown: " + e.toString());
}

If you'd like to perform some extra function on a particular Sim on the mobile you can use some of the many methods below. Might not be a perfect solution but, I'll try my best. First get the country code programmatically :

TelephonyManager tm = (TelephonyManager) 
this.getSystemService(Context.TELEPHONY_SERVICE);
//get the country iso from sim e.g US, NG, FR etc
String countryIso = tm.getSimCountryIso().toUpperCase():
//get countrycode from refegion returns the code e.g +123, +1, +23 etc. 
Int countryCode = 
phoneNumberUtil.getInstance().getCountryCodeForRegion(countryIso);

Then you can remove it using your preferred way likeString PhoneNumber = phoneNo.replaceAll("countryCode ", "" );

help-info.de
  • 6,695
  • 16
  • 39
  • 41
Emmaccen
  • 488
  • 4
  • 7
  • There are other answers that provide the OP's question, and they were posted some time ago. When posting an answer [see: How do I write a good answer?](https://stackoverflow.com/help/how-to-answer), please make sure you add either a new solution, or a substantially better explanation, especially when answering older questions. – help-info.de Nov 04 '19 at 08:27
0

First of all, make sure your given phone number should be in a Normalized format like

+921234567

then use the libphonenumber google library, so, in build.gradle add this

implementation 'com.googlecode.libphonenumber:libphonenumber:8.13.4'

then follow the below code:

val phoneUtil = PhoneNumberUtil.getInstance()
                try {
                    val phoneNumberProto: Phonenumber.PhoneNumber = phoneUtil.parse(number, null)
                    val numberWithoutCountryCode = phoneUtil.getNationalSignificantNumber(phoneNumberProto)
                    Log.d(Constant.LOG_APP_DEBUG, "PhoneNumber: $numberWithoutCountryCode")
                } catch (e: NumberParseException) {
                    Log.d(Constant.LOG_APP_DEBUG, "NumberParseException was thrown: $e")
                }
Abdul Mateen
  • 1,139
  • 1
  • 14
  • 21