Search code examples
androidandroid-contentproviderandroid-contactsmobile-country-code

separating country code from mobile number if present android


I have a code which fetches phone number from mobile contacts using Content Resolver.I tested it on 2 mobiles.In one it fetches the country code and in another it doesnt.Is there a way to find out if a country code is present in a mobile number and if present I want to separate it from the number.Here is my code.Please help me

ContentResolver cr = getContentResolver();
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
            null, null, null, null);

    if ((cur != null ? cur.getCount() : 0) > 0) {
        while (cur != null && cur.moveToNext()) {
            String id = cur.getString(
                    cur.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cur.getString(cur.getColumnIndex(
                    ContactsContract.Contacts.DISPLAY_NAME));
            phoneContactName.add(name);

            if (cur.getInt(cur.getColumnIndex(
                    ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                Cursor pCur = cr.query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                        new String[]{id}, null);
                while (pCur.moveToNext()) {
                    String phoneNo = pCur.getString(pCur.getColumnIndex(
                            ContactsContract.CommonDataKinds.Phone.NUMBER));
                    String countryCode = pCur.getString(pCur.getColumnIndex(
                            ContactsContract.CommonDataKinds.Phone.NUMBER));
                    phoneContactNos.add(phoneNo);
                    dup_phoneContactNos.add(phoneNo);
                    /*if (registeredContactNos.contains(phoneNo)) {
                        Toast.makeText(getApplicationContext(), "match found", Toast.LENGTH_SHORT).show();
                        selectedContactName.add(name);
                        selectedContactNos.add(phoneNo);
                        populateList(name, phoneNo);


                    }*/
                    Log.i(TAG, "Name: " + name);
                    Log.i(TAG, "Phone Number: " + phoneNo);
                }


                pCur.close();
            }
        }
        /*for(int i=0;i<selectedContactName.size();i++)
        {
            Toast.makeText(getApplicationContext(),selectedContactName.get(i)+","+selectedContactNos.get(i),Toast.LENGTH_SHORT).show();
        }*/
    }
    if (cur != null) {
        cur.close();
    }

Solution

  • Getting telephone country code with Android This link worked for me.I am posting the link for all those looking for an answer like me