Fetching Phone Number from Contacts based on Name Android - android

I am developing an application, where I need to fetch the phone number from the contacts corresponding to the name provided. I have tried many codes but none of them seem to work.
Here is the code I'm currently using now
public static String getContactPhoneNumber(Context context, String contactName, int type) {
String phoneNumber = null;
String[] whereArgs = new String[] { contactName, String.valueOf(type) };
Log.d(TAG, String.valueOf(contactName));
Cursor cursor = context.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.Contacts.DISPLAY_NAME + " = ? and "
+ ContactsContract.CommonDataKinds.Phone.TYPE + " = ?", whereArgs, null);
int phoneNumberIndex = cursor
.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER);
Log.d(TAG, String.valueOf(cursor.getCount()));
if (cursor != null) {
Log.v(TAG, "Cursor Not null");
try {
if (cursor.moveToNext()) {
Log.v(TAG, "Moved to first");
Log.v(TAG, "Cursor Moved to first and checking");
phoneNumber = cursor.getString(phoneNumberIndex);
}
} finally {
Log.v(TAG, "In finally");
cursor.close();
}
}
Log.v(TAG, "Returning phone number");
return phoneNumber;
}
On passing Contact Name (say: John Doe) and type (2 which is int value for Mobile Type), the phone number returned is null even though the contact "John Doe" exists in my contact list.
Please help!!!

Try this
instead of ContactsContract.CommonDataKinds.Phone.CONTENT_URI Pass
ContactsContract.Contacts.CONTENT_URI parameter to query method.

Related

Method to return contacts phone number always returns null - Android [duplicate]

I am able to retrieve the contact ID, but then later I wish to separately retrieve the phone number based on the contact ID. The code below is returning a null result for the phone number. (I do wish later to retrieve the name and phone number together and populate a view, but I am just trying to get the phone number to work first).
In my onCreate I have this code
String phoneNum = getPhoneNumber(myID);
TextView phoneTextView = (TextView) findViewById(R.id.textViewPhone);
phoneTextView.setText(phoneNum);
This is the method for getPhoneNumber()
protected String getPhoneNumber(String id) {
ArrayList<String> phones = new ArrayList<String>();
Cursor cursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (cursor.moveToNext()) {
phones.add(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
cursor.close();
String phoneNum;
phoneNum = phones.get(0);
return phoneNum;
}//end getPhoneNumber();
}
This produces the error java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0, which I plan on creating some error handling for. But still, I am certain I have the ID from the previous code, so I don't know why the ArrayList returns null. If you would like to see that code, it is also in my onCreate:
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if (cursor.getCount() != 0) {
int numContacts = cursor.getCount();
ArrayList<String> idList = new ArrayList<>();
Random rand = new Random();
int randomNum = rand.nextInt(numContacts);
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
idList.add(id);
}
myID = idList.get(randomNum);
String myString = Integer.toString(randomNum);
TextView myTextView = (TextView) findViewById(R.id.textViewID);
myTextView.setText(myString);
if (myID != null) {
myTextView.setText(myID);
} else {
myTextView.setText("Try Again!");
}
} else {
Toast.makeText(getApplicationContext(), "Your have no contacts.", Toast.LENGTH_SHORT).show();
}
cursor.close();
// You can fetch the Contact Number and Email With Following Methods.
String phone = getPhoneNumber(ContactId);
String email = getEmail("" + ContactId);
private String getPhoneNumber(long id) {
String phone = null;
Cursor phonesCursor = null;
phonesCursor = queryPhoneNumbers(id);
if (phonesCursor == null || phonesCursor.getCount() == 0) {
// No valid number
//signalError();
return null;
} else if (phonesCursor.getCount() == 1) {
// only one number, call it.
phone = phonesCursor.getString(phonesCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
} else {
phonesCursor.moveToPosition(-1);
while (phonesCursor.moveToNext()) {
// Found super primary, call it.
phone = phonesCursor.getString(phonesCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
break;
}
}
return phone;
}
private Cursor queryPhoneNumbers(long contactId) {
ContentResolver cr = getContentResolver();
Uri baseUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,
contactId);
Uri dataUri = Uri.withAppendedPath(baseUri,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY);
Cursor c = cr.query(dataUri, new String[]{ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.IS_SUPER_PRIMARY, ContactsContract.RawContacts.ACCOUNT_TYPE,
ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.LABEL},
ContactsContract.Data.MIMETYPE + "=?",
new String[]{ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE}, null);
if (c != null && c.moveToFirst()) {
return c;
}
return null;
}
private String getEmail(String id) {
String email = "";
ContentResolver cr = getContentResolver();
Cursor emailCur = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
// String emailType = emailCur.getString(
// emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
}
emailCur.close();
return email;
}
I have not been able to successfully retrieve code based on the Contact ID - but this post gave me a clue: Retrieving a phone number with ContactsContract in Android - function doesn't work
I have altered my original code to query on DISPLAY_NAME instead and things are working now. Here is the method I am using to retrieve the phone number:
private String retrieveContactNumber(String contactName) {
Log.d(TAG, "Contact Name: " + contactName);
Cursor cursorPhone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{contactName},
null);
if (cursorPhone.moveToFirst()) {
contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
cursorPhone.close();
Log.d(TAG, "Contact Phone Number: " + contactNumber);
return contactNumber;
}

How to use call log for copy incoming number in android

I just want to copy the incoming number and paste it to a text box. How can I do that?
Use a cursor to get any call log information you want.
String[] projection = {android.provider.CallLog.Calls._ID,
android.provider.CallLog.Calls.NUMBER,
CallLog.Calls.TYPE, CallLog.Calls.DATE};
final Cursor cursor = getActivity().getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, projection,
"type = " + CallLog.Calls.INCOMING_TYPE, null,
android.provider.CallLog.Calls.DATE + " DESC" + " LIMIT 200");
The cursor will result the number and time of call.
if (cursor.moveToFirst()) {
do {
try {
String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
String date = cursor.getString(cursor.getColumnIndex(CallLog.Calls.DATE));
// Do anything with number and name
} catch (Exception e) {
}
} while (cursor.moveToNext());
}
cursor.close();

How to get the connectivity of user from contact list of device?

Is it possible to get the connections of any contact from contact list of device? Connection like email id of google+ account, and other third party api,I am searching the query of it. But did not get the proper solution. So please friends help me to sort out from these problem. Thanks in advance
In the Contacts provider, the "connections" of a Contact are just all the entries in RawContacts for that particular CONTACT_ID. And their data is stored in the Data table.
Therefore, to get all the info on all the connections of a contact, it's enough to query the Data table with the appropriate filter. For example:
private static void getConnections(Context context, int contactId)
{
// Read all data for contactId
String selection = RawContacts.CONTACT_ID + " = ?";
String[] selectionArgs = new String[] { String.valueOf(contactId) };
Cursor c = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, selection, selectionArgs, null);
while (c.moveToNext())
{
String accountType = c.getString(c.getColumnIndexOrThrow(ContactsContract.RawContacts.ACCOUNT_TYPE));
String accountName = c.getString(c.getColumnIndexOrThrow(ContactsContract.RawContacts.ACCOUNT_NAME));
String dataMimeType = c.getString(c.getColumnIndexOrThrow(ContactsContract.Data.MIMETYPE));
String dataValue = c.getString(c.getColumnIndexOrThrow(ContactsContract.Data.DATA1));
Log.d("contactInfo", accountName + " (" + accountType + ") - " + dataMimeType + " - " + dataValue);
}
c.close();
}
You can filter this data by using more restrictive selection / selectionArgs arguments (such as for a specific ACCOUNT_TYPE, MIMETYPE, and so forth).
Of course, you need the appropriate permission in AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_CONTACTS" />
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
Cursor cur1 = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (cur1.moveToNext()) {
//to get the contact names
String name=cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
Log.e("Name :", name);
String email = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
Log.e("Email", email);
if(email!=null){
names.add(name);
}
}
cur1.close();
}
}
This is the solution, it's using a Whatsapp-like third party API:
Cursor connectionCur = cr.query(ContactsContract.RawContacts.CONTENT_URI,
new String[]{ContactsContract.RawContacts.ACCOUNT_NAME, ContactsContract.RawContacts.ACCOUNT_TYPE},
ContactsContract.RawContacts.CONTACT_ID +"=?",
new String[]{String.valueOf(id)},
null);
System.out.println("TOTAL NUMBERS OF COUNTS====================="+connectionCur.getCount());
if (connectionCur != null && connectionCur.getCount() >0)
{
while (connectionCur.moveToNext())
{
String accountName = connectionCur.getString(connectionCur.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_NAME));
String accountType = connectionCur.getString(connectionCur.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_TYPE));
if(accountType.contains("whatsapp"))
{
Toast.makeText(LoginScreen.this, "whatsapp == "+accountType, Toast.LENGTH_SHORT).show();
}
else if(accountType.contains("google"))
{
Toast.makeText(LoginScreen.this, "google == "+accountType, Toast.LENGTH_SHORT).show();
}
else if(accountType.contains("facebook"))
{
Toast.makeText(LoginScreen.this, "facebook == "+accountType, Toast.LENGTH_SHORT).show();
}
else if(accountType.contains("twitter"))
{
Toast.makeText(LoginScreen.this, "twitter == "+accountType, Toast.LENGTH_SHORT).show();
}
else if(accountType.contains("linkedin"))
{
Toast.makeText(LoginScreen.this, "linkedin == "+accountType, Toast.LENGTH_SHORT).show();
}
System.out.println("a========="+accountName+" b====="+accountType);
}
}

Android 4.1+/ContactContract: Lookup group to given contactId (derived from lookup a number)

The following function has a phone number as input parameter (e.g. +436641234567 or +436641234567) and performs two lookups in the Contacts database: first, identify the user belonging to this number (this already works) and then to use the id of the user to get all groups this contact is assigned to (and this does not work). Test gives back the correct id (again), however, the group is "null".
public String getNameGroupByNumber(Context context, String number) {
String name = "?";
String contactId = "0";
String group = "0";
String test = "0";
// Step 1: LookUp Name to given Number
ContentResolver contentResolver = context.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
String[] contactProjection = new String[] {BaseColumns._ID, ContactsContract.PhoneLookup.DISPLAY_NAME };
Cursor contactLookup = contentResolver.query(uri, contactProjection, null, null, null);
try {
if (contactLookup != null && contactLookup.getCount() > 0) {
contactLookup.moveToNext();
name = contactLookup.getString(contactLookup.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
contactId = contactLookup.getString(contactLookup.getColumnIndex(BaseColumns._ID));
}
} finally {
if (contactLookup != null) {
contactLookup.close();
}
}
Log.d(TAG, "Name: " +name + " ContactId: " + contactId); // works as expected
// Step 2: Lookup group memberships of the contact found in step one
Uri groupURI = ContactsContract.Data.CONTENT_URI;
String[] groupProjection = new String[]{ ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID , ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID};
Cursor groupLookup = contentResolver.query(groupURI, groupProjection, ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID+"="+contactId, null, null);
try {
if (groupLookup != null && groupLookup.getCount() > 0) {
groupLookup.moveToNext();
test = groupLookup.getString(groupLookup.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID));
group = groupLookup.getString(groupLookup.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID));
Log.d(TAG, "Group found with Id: " + test + " and GroupId: " + group); // test is again the contactID from above but group is null
}
} finally {
if (groupLookup != null) {
groupLookup.close();
}
}
return name;
}
Cursor groupLookup = getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
new String[]{
ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID ,
ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID
},
ContactsContract.Data.MIMETYPE + "=? AND " + ContactContract.Data.CONTACT_ID + "=?",
new String[]{
ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE,
contact_id
}, null
);
Use this groupLookup cursor instead.
Cursor groupCursor = getContentResolver().query(
ContactsContract.Groups.CONTENT_URI,
new String[]{
ContactsContract.Groups._ID,
ContactsContract.Groups.TITLE
}, ContactsContract.Groups._ID + "=" + _id, null, null
);
groupCursor helps to get Group title from _id.

To retrieve contact list with number in android

Hi i want to retrieve name and numbers from contact list in android ,am using following code, it will give me name but not number it gives null value for number
NOTE: am using android emulator
public void demo(){
String phoneNumber;
String [] item = new String[]{ People._ID,
People.NAME,
People.NUMBER};
Cursor cur = getContentResolver().query(People.CONTENT_URI ,item , null, null, null);
int phoneNumberIndex = cur.getColumnIndexOrThrow(People.NUMBER);
if (cur != null) {
Log.v("cur not null", "Cursor Not null");
if (cur.moveToNext()) {
Log.v("moveToNext", "Moved to first");
Log.v("moveToNext", "Cursor Moved to first and checking");
phoneNumber = cur.getString(phoneNumberIndex);
System.out.println("****** from_number "+phoneNumber +" *****************");
}
}
}
It gives null because u r trying to retrieve only one number.. this should work..
if (cur.moveToNext()) {
Log.v("moveToNext", "Moved to first");
Log.v("moveToNext", "Cursor Moved to first and checking");
while(cur.moveToNext())
{
phoneNumber = cur.getString(phoneNumberIndex);
System.out.println("****** from_number "+phoneNumber +" *****************");
}
}

Categories

Resources