Getting ContactName using phone number - android

I am creating an activity which lists out recent calls from a user. The requirement is that when a user receives the call,the phone number and contact name is stored in DB to be later displayed in the activity. To retrieve the contact Name the phone number is matched with the contacts in the users contact list. I am using below code to get the contact name.
(Below code queries the Contact database and finds a match to the inputted phone number)
String getContactDisplayNameByNumber(String number) {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
String name = "";
Cursor contactLookup = context.getContentResolver().query(uri, new String[]{
ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
try {
if (contactLookup != null && contactLookup.moveToNext()) {
name = contactLookup.getString(contactLookup.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
Log.v("ranjapp", "Name is " + name + " Number is " + number);
}
} finally {
if (contactLookup != null) {
contactLookup.close();
}
}
return name;
}
Now the problem is the phonenumber is saved in the contact list as "1234567891" and the phone number retrieved from an incoming call is "01234567891"(0 prefixed).
As 0 is prefixed in the incoming number the number is not matching with the number in contact list.
There can be also other possibilities the incoming number may have the country code prefixed and saved contact does not have it.
How can i match in these scenarios.
(I am aware of PhoneNumberUtils.compare() but not able to apply it in the code mentioned).

The problem was the method was not getting called with the phone number as input. It works irrespective how the number is i.e with prefix +91 or 0. Corrected the code as below:
Bundle bundle = intent.getExtras();
String number = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
String name=getContactDisplayNameByNumber(number);

Related

How do i check if a phone number is already saved on my android phone or not?

I am building an app that enables users to save and manage a list of people, with important dates such as birthdays, anniversaries, Etc. for each person.
The goal, is to send them a personalized PDF image (with their name and details), on the important day.
The problem I am having, is what to do if the user saves a person on my app, that isn't in their contact list.
In such a case, I can't send him a whatsapp message.
So, I want to add the phone number to the phone's contacts list, only if the phone number isn't already saved in the user's regular contacts list.
How do I check if phone number XXX-XXX-XXXX exists in user's contact list or not ?
String res = null;
try {
ContentResolver resolver = ctx.getContentResolver();
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor c = resolver.query(uri, new String[]{PhoneLookup.DISPLAY_NAME}, null, null, null);
if (c != null) { // cursor not null means number is found contactsTable
if (c.moveToFirst()) { // so now find the contact Name
res = c.getString(c.getColumnIndex(CommonDataKinds.Phone.DISPLAY_NAME));
}
c.close();
}
} catch (Exception ex) {
/* Ignore */
}
return res;

Retrieve contact on Android with name matching given string and dial that contact's phone number

I've been having difficulty implementing the retrieval of the phone number of a contact whose name matches a given string and then dialing that number. I know this is possible because many existing apps include this feature. How can it be implemented?
this code getting all contacts in phone
Cursor phones = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if (phones != null) {
while (phones.moveToNext()) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
}
Compare the variable "name" or "phoneNumber" with your String
and you have add permission "android.permission.READ_CONTACTS"

Accessing contacts info without explicit permission

I am very new to app development. I am trying to read contact info without having to request permission to contacts (so I am using intents).
I get a URI with the following code in my main activity:
Intent selectContactIntent = new Intent(Intent.ACTION_PICK);
selectContactIntent.setType(ContactsContract.Contacts.CONTENT_TYPE);
if (selectContactIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(selectContactIntent, REQUEST_CODE_SELECT_CONTACT);
}
else {
showContactRequiredMessage(view);
}
In another (sub)activity, I do the following:
contactUri = intent.getParcelableExtra(MainActivity.CONTACT_URI);
String[] projection = new String[] {
ContactsContract.Contacts.Data._ID,
ContactsContract.Contacts.Data.MIMETYPE,
ContactsContract.Contacts.Data.DATA1,
ContactsContract.Contacts.Data.DATA2,
ContactsContract.Contacts.Data.DATA3,
ContactsContract.Contacts.Data.DATA4,
ContactsContract.Contacts.Data.DATA5,
ContactsContract.Contacts.Data.DATA6,
ContactsContract.Contacts.Data.DATA7,
ContactsContract.Contacts.Data.DATA8,
ContactsContract.Contacts.Data.DATA9,
ContactsContract.Contacts.Data.DATA10,
ContactsContract.Contacts.Data.DATA11,
ContactsContract.Contacts.Data.DATA12,
ContactsContract.Contacts.Data.DATA13,
ContactsContract.Contacts.Data.DATA14,
ContactsContract.Contacts.Data.DATA15
};
Cursor contactResults = getContentResolver().query(contactUri, projection, null, null, null);
The last line throws the exception java.lang.IllegalArgumentException: Invalid column <any column after _ID>
My app doesn't require all of the data in reality I just want to see what is available, I will most likely need first name, last name, phone, and email.
My issue is the MIME type that I set on the intent when I request the contact info. The documentation states ContactsContract.Contacts.CONTENT_TYPE should be used. However, if I use, something like ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE, I can get display name and phone number. I am not sure if this means I will need to make multiple queries to get everything (the information shown in the contact picker changes when changing the type requested).
TL;DR: Used the "wrong" content type when creating the intent to select a contact.
As mentioned in my comment to your answer, you should be able to get the information expected without using a specific CONTENT_TYPE like CommonDataKinds.Phone.CONTENT_TYPE.
The problem I see in your code is that you're trying to access Data table info from a Contacts table uri.
The ContactsContract api stored info on 3 main tables: Contacts, RawContacts and Data.
You were given a contactUri which points to an entry in the Contacts table, use the following code to read Data entries related to that contact:
long contactId = ContentUris.parseId(contactUri);
String projection = String[] { Data.MIMETYPE, Data.DISPLAY_NAME, Data.DATA1 };
String selection = Data.CONTACT_ID + " = " + contactId;
Cursor cursor = getContentResolver().query(Data.CONTENT_URI, projection, selection, null, null);
while (cursor != null && cursor.moveToNext()) {
String mime = cursor.getString(0);
String name = cursor.getString(1);
String info = cursor.getString(2);
if (mime.equals(CommonDataKinds.Email.CONTENT_ITEM_TYPE)) {
Log.d(TAG, name + ": email = " + info;
}
if (mime.equals(CommonDataKinds.Phone.CONTENT_ITEM_TYPE)) {
Log.d(TAG, name + ": phone = " + info;
}
// Add more mimetypes here if needed...
}
if (cursor != null) {
cursor.close();
}

Android ContactsContract.Display_Name returns contact phone number or any other available data

I'm using the code below to get contacts name from the phonebook
Uri contactUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
Cursor phones = getContentResolver().query(contactUri,null,null,null,null);
while (phones.moveToNext())
{
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
if (name != null)
{
names += name + ",";
}
}
phones.close();
I've noticed that when there is a contact that was saved without a name, the above code will return the phone number as the contact name. I understand that this is how android work in case the contact was saved without a name. But I have to prevent this behaviour and force it to return null or empty string in case there is no "Display_Name"..
is it possible?
You can add this after getting name and before the if statement.
if(text.matches("[0-9]+")) // use "[0-9\-]+" if phone number has - too
continue;
This would check if the value returned contains only numerical value. If yes then it would skip the rest of the loop code.

How to get all contact number associated with that contact name android

I've been trying to make multi contact picker list with checkbox. I already created Multi Contact Picker with contact having atleast one phone number in its contact.
Que
Now I've added contact with in ListView. But contact appear with single contact number in it, it's taking first phone number which is saved in Contact Application. I've added LinkedHashMap & Set to add indexer on the Contact List.
Did LinkedHashMap or Set is removing duplicate values from Collections?
How can i fetch all the phone number associated with that contact name?
Code Snippet:-
ContentResolver cr = getContentResolver();
String selection = Data.HAS_PHONE_NUMBER + " > '" + ("0") + "'";
Cursor cur = cr.query(Data.CONTENT_URI, new String[] { Data.CONTACT_ID, Data.MIMETYPE, Email.ADDRESS,
Contacts.DISPLAY_NAME, Phone.NUMBER }, selection, null, Contacts.DISPLAY_NAME);
Contact contact;
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(Data.CONTACT_ID));
String mimeType = cur.getString(cur.getColumnIndex(Data.MIMETYPE));
if (allContacts.containsKey(id)) {
// update contact
contact = allContacts.get(id);
} else {
contact = new Contact();
allContacts.put(id, contact);
// set photoUri
contact.setContactPhotoUri(getContactPhotoUri(Long.parseLong(id)));
}
if (mimeType.equals(StructuredName.CONTENT_ITEM_TYPE))
// set name
contact.setContactName(cur.getString(cur.getColumnIndex(Contacts.DISPLAY_NAME)));
if (mimeType.equals(Phone.CONTENT_ITEM_TYPE))
// set phone munber
contact.setContactNumber(cur.getString(cur.getColumnIndex(Phone.NUMBER)));
}
}
cur.close();
// get contacts from hashmap
contacts.clear();
contacts.addAll(allContacts.values());
These is just a temporary fix as of now, I've been trying to add all contact number associated with same contact person inside android.provider.ContactsContract.
I've added all contact number associated with same contact person inside beans by appending with delimiter(",") which i can fetch back using Tokenizer. But no idea to know which kinda contact type it is whether HOME, WORK, OFFICE , it's less important to me as of now.
Fix:
if (mimeType.equals(Phone.CONTENT_ITEM_TYPE)){
// set phone number
if (contact.getContactNumber().toString().length() == 0) {
contact.setContactNumber(cur.getString(cur.getColumnIndex(Phone.NUMBER)).replaceAll("\\D", ""));
} else {
contact.setContactNumber(contact.getContactNumber().toString().concat(", ").concat(cur.getString(cur.getColumnIndex(Phone.NUMBER)).replaceAll("\\D", "")));//One can add possible contacts "(-/,"
}
}

Categories

Resources