How to Get the First Name and Last Name from Android Contacts

Android. Retrieve first name and last name from contact book by phone number

PhoneLookup is a nice and quick way to get contact data by a phone number, but it returns a cursor limited to the columns mentioned in the docs.

You can see there's DISPLAY_NAME you can access, but not GIVEN_NAME, FAMILY_NAME.

GIVEN_NAME & FAMILY_NAME are fields stored in the Data table, which means you need to query that table separately to get to those fields.

So, you can just add another query using the contact ID you got from PhoneLookup (note that for each looked up phone there might be multiple contacts returned).

Here's a sample method to get first/last names from contact ID:

private void addNames(MyContact contact, long contactId) {
String[] projection = new String[] {StructuredName.GIVEN_NAME, StructuredName.FAMILY_NAME};

// filter to just StructuredName rows from the data table for the given contact
String selection = Data.CONTACT_ID + "=" + contactID + " AND " + Data.MIMETYPE + "=" + StructuredName.CONTENT_ITEM_TYPE;

Cursor cursor = getContentResolver().query(Data.CONTENT_URI, projection, selection, null, null);
if (cursor.next()) {
contact.setFirstName(cursor.getString(0));
contact.setLastName(cursor.getString(1));
}
cursor.close();
}

How to get all contacts first name, last name, email, phone number, etc without duplicates

This is the complete solution

public ArrayList<HashMap<String, Object>> getContacts() {

ArrayList<HashMap<String, Object>> contacts = new ArrayList<HashMap<String, Object>>();
final String[] projection = new String[] { RawContacts.CONTACT_ID, RawContacts.DELETED };

@SuppressWarnings("deprecation")
final Cursor rawContacts = managedQuery(RawContacts.CONTENT_URI, projection, null, null, null);

final int contactIdColumnIndex = rawContacts.getColumnIndex(RawContacts.CONTACT_ID);
final int deletedColumnIndex = rawContacts.getColumnIndex(RawContacts.DELETED);

if (rawContacts.moveToFirst()) {
while (!rawContacts.isAfterLast()) {
final int contactId = rawContacts.getInt(contactIdColumnIndex);
final boolean deleted = (rawContacts.getInt(deletedColumnIndex) == 1);

if (!deleted) {
HashMap<String, Object> contactInfo = new HashMap<String, Object>() {
{
put("contactId", "");
put("name", "");
put("email", "");
put("address", "");
put("photo", "");
put("phone", "");
}
};
contactInfo.put("contactId", "" + contactId);
contactInfo.put("name", getName(contactId));
contactInfo.put("email", getEmail(contactId));
contactInfo.put("photo", getPhoto(contactId) != null ? getPhoto(contactId) : "");
contactInfo.put("address", getAddress(contactId));
contactInfo.put("phone", getPhoneNumber(contactId));
contactInfo.put("isChecked", "false");
contacts.add(contactInfo);
}
rawContacts.moveToNext();
}
}

rawContacts.close();

return contacts;
}

private String getName(int contactId) {
String name = "";
final String[] projection = new String[] { Contacts.DISPLAY_NAME };

final Cursor contact = managedQuery(Contacts.CONTENT_URI, projection, Contacts._ID + "=?", new String[] { String.valueOf(contactId) }, null);

if (contact.moveToFirst()) {
name = contact.getString(contact.getColumnIndex(Contacts.DISPLAY_NAME));
contact.close();
}
contact.close();
return name;

}

private String getEmail(int contactId) {
String emailStr = "";
final String[] projection = new String[] { Email.DATA, // use
// Email.ADDRESS
// for API-Level
// 11+
Email.TYPE };

final Cursor email = managedQuery(Email.CONTENT_URI, projection, Data.CONTACT_ID + "=?", new String[] { String.valueOf(contactId) }, null);

if (email.moveToFirst()) {
final int contactEmailColumnIndex = email.getColumnIndex(Email.DATA);

while (!email.isAfterLast()) {
emailStr = emailStr + email.getString(contactEmailColumnIndex) + ";";
email.moveToNext();
}
}
email.close();
return emailStr;

}

private Bitmap getPhoto(int contactId) {
Bitmap photo = null;
final String[] projection = new String[] { Contacts.PHOTO_ID };

final Cursor contact = managedQuery(Contacts.CONTENT_URI, projection, Contacts._ID + "=?", new String[] { String.valueOf(contactId) }, null);

if (contact.moveToFirst()) {
final String photoId = contact.getString(contact.getColumnIndex(Contacts.PHOTO_ID));
if (photoId != null) {
photo = getBitmap(photoId);
} else {
photo = null;
}
}
contact.close();

return photo;
}

private Bitmap getBitmap(String photoId) {
final Cursor photo = managedQuery(Data.CONTENT_URI, new String[] { Photo.PHOTO }, Data._ID + "=?", new String[] { photoId }, null);

final Bitmap photoBitmap;
if (photo.moveToFirst()) {
byte[] photoBlob = photo.getBlob(photo.getColumnIndex(Photo.PHOTO));
photoBitmap = BitmapFactory.decodeByteArray(photoBlob, 0, photoBlob.length);
} else {
photoBitmap = null;
}
photo.close();
return photoBitmap;
}

private String getAddress(int contactId) {
String postalData = "";
String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] addrWhereParams = new String[] { String.valueOf(contactId), ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE };

Cursor addrCur = managedQuery(ContactsContract.Data.CONTENT_URI, null, addrWhere, addrWhereParams, null);

if (addrCur.moveToFirst()) {
postalData = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS));
}
addrCur.close();
return postalData;
}

private String getPhoneNumber(int contactId) {

String phoneNumber = "";
final String[] projection = new String[] { Phone.NUMBER, Phone.TYPE, };
final Cursor phone = managedQuery(Phone.CONTENT_URI, projection, Data.CONTACT_ID + "=?", new String[] { String.valueOf(contactId) }, null);

if (phone.moveToFirst()) {
final int contactNumberColumnIndex = phone.getColumnIndex(Phone.DATA);

while (!phone.isAfterLast()) {
phoneNumber = phoneNumber + phone.getString(contactNumberColumnIndex) + ";";
phone.moveToNext();
}

}
phone.close();
return phoneNumber;
}

How to use?

ArrayList<HashMap<String, Object>> contactList = getContacts();
System.out.println("Contact List : " +contactList);

Output:

[
{
phone=992-561-1618;848-807-4440;,
contactId=1,
photo=android.graphics.Bitmap@44f40aa0,
address=Zalavadia Strret
Manavadar, Gujarat 362630
India,
email=birajzalavadia@gmail.com;biraj@tasolglobal.com;,
name=Biraj Zalavadia
},
{
phone=992-511-1418;842-827-4450;,
contactId=2,
photo=android.graphics.Bitmap@44f40aa0,
address=Makadiya Strret
Junagadh, Gujarat 364890
India,
email=niles@gmail.com;niles@tasolglobal.com;,
name=Niles patel
}
.......
]

NOTE:

You will get phone and email semicolon(;) separated if its more than one.

Retrieval of firstname and lastname from android contacts results in '1' and 'null'

The following code will help you get first name and last name:

Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
Uri dataUri = Uri.withAppendedPath(contactUri, Contacts.Data.CONTENT_DIRECTORY);
Cursor nameCursor = getActivity().getContentResolver().query(
dataUri,
null,
Data.MIMETYPE+"=?",
new String[]{ StructuredName.CONTENT_ITEM_TYPE },
null);
while (nameCursor.moveToNext())
{

String firstName = nameCursor.getString(nameCursor.getColumnIndex(Data.DATA2));
String lastName = nameCursor.getString(nameCursor.getColumnIndex(Data.DATA3));

Toast.makeText(getApplicationContext(), "First name"+firstName, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Second name"+lastName, Toast.LENGTH_LONG).show();

return new String [] {firstName , lastName};
}

nameCursor.close();

Get first and last name of a contact rather than single display name?

Take a look at ContactsContract.CommonDataKinds.StructuredName class. You have all the needed columns there, and you can probably do something like:

Cursor cursor = contentResolver.query(ContactsContract.Data.CONTENT_URI, other_query_params_for_filtering);

int indexGivenName = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
int indexFamilyName = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME);
int indexDisplayName = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME);

while (cursor.moveToNext()) {
String given = cursor.getString(indexGivenName);
String family = cursor.getString(indexFamilyName);
String display = cursor.getString(indexDisplayName);
}

Search android contacts by family name and first name and get raw_id

The "family" name as a separate field isn't part of the Contacts table.

Rows in the Contacts table are generated automatically by the provider. In general, one Contacts row aggregates one or more raw contacts in ContactsContract.RawContacts. Each raw contact has a StructuredName row that contains the family name.

To do the search you describe, search ContactsContract.CommonDataKinds.StructuredName on FAMILY_NAME and GIVEN_NAME. Provide a projection that includes LOOKUP_KEY, which is a "permanent" link to the row in ContactsContract.Contacts that you want.

Alas, this is based only on the documentation. LOOKUP_KEY is supposed to be part of the columns available to a query on StructuredName, but I've seen other cases where the documentation didn't match the implementation. Apparently, the developers sometimes include a list of implemented column names, but don't actually seem to implement returning them.

Also, the original response used getContentResolver(). Please use CursorLoader instead, whenever possible.



Related Topics



Leave a reply



Submit