I am working on an app where have a login activity, in which, when the user logs in, it automatically saves contacts from their phone to the server. This works, but I have one issue, when I save the numbers they are saved in the format the user entered in their phone. For example if the user entered this number: +15555555 it will be saved like that, but if he entered it without country code it will look like this: 5555555, without the +1, or any other country code depending on the country.
What I want to is to return all of my contacts with their country code, even those that user have entered without the country code.
Some apps like Viber can recognize the format it is in, so if it doesn't start with +1, or starts with 05.., it is recognized and it automatically adds the country code, so that 05.. becomes +15...
public void updateContacts() {
String[] PROJECTION = new String[]{
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
};
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, null, null, null);
HashMap<String, String> user = db.getUserDetails();
String userId = user.get("uid");
if (phones != null) {
while (phones.moveToNext()) {
if (phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER) != -1) {
final String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<ContactsResponse> call = apiService.contactExists(phoneNumber, userId);
call.enqueue(new Callback<ContactsResponse>() {
@Override
public void onResponse(Call<ContactsResponse> call, retrofit2.Response<ContactsResponse> response) {
Log.e(TAG, "abc");
}
@Override
public void onFailure(Call<ContactsResponse> call, Throwable t) {
Log.e(TAG, t.toString());
}
});
}
}
}
if (phones != null) {
phones.close();
}
}
I am using libphonenumber, so I was wondering if there is a way to use this and get the country code, then add it to the number without it.
Not possible. If a user does not type in a country code or area code, then when that number is called the service provider will automatically assume that they are using the country code/area code that they are currently in. If you have 518-222-2345 saved and you call this number in the US, the service provider will add a +1 to the beginning. If the user then takes a trip to the UK and tries calling the same number(contact-entry), the service provider will add a +44 code to the front. Long story short the data that you see is all the data that is stored on the device and when that specific data(country-code/area-code) is not there, the service provider assumes the codes of where they currently are.