I am working on android app that receives a broadcast intent for incoming calls and incoming text messages.
It then is supposed to get the incoming number and perform a search on the users contacts using the incoming number.
This is more a less working, but I am having a slight problem. I have it working so that the number is searched in the contact list by, if it starts with + strips the first 3 characters and puts a 0 on the beginning, or just a does a search if it doesn’t contain the +. However, I have a slight problem, that if the user enters spaces in the number then the app doesn’t find the contact. For example, if I have a contact number saved as 07412xxxxxx and the incoming number comes in as 07412xxxxxx or +447412xxxxxx. However, if the contact number is saved as `07412 xxx xxxand the incoming number is07412xxxxxx“ then the number doesn’t get recognised so it doesn’t find the contacts name.
How can I perform the search to take all considerations of the number format. Below is the code I am currently using.
public String getContactNameFromNumber(String number)
{
if (number.startsWith("+"))
{
number = "0" + number.substring(3);
}
String contactName = null;
ContentResolver contentResolver = context.getContentResolver();
Uri uri = Data.CONTENT_URI;
String[] projection = new String[] {PhoneLookup._ID, PhoneLookup.DISPLAY_NAME};
String selection = ContactsContract.CommonDataKinds.Phone.NUMBER + " = ?";
String[] selectionArgs = { number };
Cursor cursor = contentResolver.query(uri, projection, selection, selectionArgs, null);
if (cursor.moveToFirst())
{
contactName = cursor.getString(cursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
cursor.close();
return contactName;
}
else
{
cursor.close();
return null;
}
}
Try:
See replace function.