Wednesday 29 April 2009

BlackBerryContact Names

Getting the name of a BlackBerryContact has been been this easy... :)

This method takes in a BlackBerryContact as the argument and would return the name as a String.

private String getDisplayName(BlackBerryContact contact) {

  StringBuffer buf = new StringBuffer();
  String[] name = contact.getStringArray(BlackBerryContact.NAME, 0);

  //Get the prefix, first and last name
  boolean found = false;
  String nameseg;

  // Catch each field separately to make sure we get any available fields
  try {
   if((nameseg = name[BlackBerryContact.NAME_PREFIX]) != null && nameseg.length() != 0) {
    buf.append(nameseg);
    found = true;
   }
  } catch(IndexOutOfBoundsException ignore) {}


  try {
   if ((nameseg = name[BlackBerryContact.NAME_GIVEN]) != null && nameseg.length() != 0) {
    if(found) {
     buf.append(' ');
     buf.append(nameseg);
     found = true;
    }
   }
  } catch(IndexOutOfBoundsException ignore) {}

  try {
   if((nameseg = name[BlackBerryContact.NAME_FAMILY]) != null && nameseg.length() != 0) {
    if (found) {
     buf.append(' ');
    }
    buf.append(nameseg);
    found = true;
   }
  } catch(IndexOutOfBoundsException ignore) {}

//This is to get the Company if no names are found under the Contact
  try {
   if (found == false) {
    buf.append(contact.getString(BlackBerryContact.ORG, 0));
   }
  } catch(IndexOutOfBoundsException ignore) {}

return buf.toString();
}

No comments: