Example usage for android.content ContentUris withAppendedId

List of usage examples for android.content ContentUris withAppendedId

Introduction

In this page you can find the example usage for android.content ContentUris withAppendedId.

Prototype

public static Uri withAppendedId(Uri contentUri, long id) 

Source Link

Document

Appends the given ID to the end of the path.

Usage

From source file:com.sonetel.ui.dialpad.DialerFragment.java

public void placeVMCall() {
    Long accountToUse = SipProfile.INVALID_ID;
    SipProfile acc = null;//from  w w w. j a  v a 2s  .  c  om
    acc = accountChooserButton.getSelectedAccount();
    if (acc != null) {
        accountToUse = acc.id;
    }

    if (accountToUse >= 0) {
        SipProfile vmAcc = SipProfile.getProfileFromDbId(getActivity(), acc.id,
                new String[] { SipProfile.FIELD_VOICE_MAIL_NBR });
        if (!TextUtils.isEmpty(vmAcc.vm_nbr)) {
            // Account already have a VM number
            try {
                service.makeCall(vmAcc.vm_nbr, (int) acc.id);
            } catch (RemoteException e) {
                Log.e(THIS_FILE, "Service can't be called to make the call");
            }
        } else {
            // Account has no VM number, propose to create one
            final long editedAccId = acc.id;
            LayoutInflater factory = LayoutInflater.from(getActivity());
            final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);

            missingVoicemailDialog = new AlertDialog.Builder(getActivity()).setTitle(acc.display_name)
                    .setView(textEntryView)
                    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {

                            if (missingVoicemailDialog != null) {
                                TextView tf = (TextView) missingVoicemailDialog.findViewById(R.id.vmfield);
                                if (tf != null) {
                                    String vmNumber = tf.getText().toString();
                                    if (!TextUtils.isEmpty(vmNumber)) {
                                        ContentValues cv = new ContentValues();
                                        cv.put(SipProfile.FIELD_VOICE_MAIL_NBR, vmNumber);

                                        int updated = getActivity().getContentResolver()
                                                .update(ContentUris.withAppendedId(
                                                        SipProfile.ACCOUNT_ID_URI_BASE, editedAccId), cv, null,
                                                        null);
                                        Log.d(THIS_FILE, "Updated accounts " + updated);
                                    }
                                }
                                missingVoicemailDialog.hide();
                            }
                        }
                    }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (missingVoicemailDialog != null) {
                                missingVoicemailDialog.hide();
                            }
                        }
                    }).create();

            // When the dialog is up, completely hide the in-call UI
            // underneath (which is in a partially-constructed state).
            missingVoicemailDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);

            missingVoicemailDialog.show();
        }
    } /**else if (accountToUse == CallHandlerPlugin.getAccountIdForCallHandler(getActivity(),
          (new ComponentName(getActivity(), com.sonetel.plugins.telephony.CallHandler.class).flattenToString()))) {
      // Case gsm voice mail
      TelephonyManager tm = (TelephonyManager) getActivity().getSystemService(
              Context.TELEPHONY_SERVICE);
      String vmNumber = tm.getVoiceMailNumber();
              
      if (!TextUtils.isEmpty(vmNumber)) {
          if(service != null) {
              try {
                  service.ignoreNextOutgoingCallFor(vmNumber);
              } catch (RemoteException e) {
                  Log.e(THIS_FILE, "Not possible to ignore next");
              }
          }
          Intent intent = new Intent(Intent.ACTION_CALL, Uri.fromParts("tel", vmNumber, null));
          intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          startActivity(intent);
      } else {
              
          missingVoicemailDialog = new AlertDialog.Builder(getActivity())
                  .setTitle(R.string.gsm)
                  .setMessage(R.string.no_voice_mail_configured)
                  .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                      public void onClick(DialogInterface dialog, int which) {
                          if (missingVoicemailDialog != null) {
                              missingVoicemailDialog.hide();
                          }
                      }
                  })
                  .create();
              
          // When the dialog is up, completely hide the in-call UI
          // underneath (which is in a partially-constructed state).
          missingVoicemailDialog.getWindow().addFlags(
                  WindowManager.LayoutParams.FLAG_DIM_BEHIND);
              
          missingVoicemailDialog.show();
      }
      }*/
    // TODO : manage others ?... for now, no way to do so cause no vm stored
}

From source file:com.android.mms.ui.ComposeMessageActivity.java

/**
 * Returns true if all drm'd parts are forwardable.
 * @param msgId/*from  w w w.  j  a v a  2  s. co m*/
 * @return true if all drm'd parts are forwardable.
 */
private boolean isForwardable(long msgId) {
    PduBody body = null;
    try {
        body = SlideshowModel.getPduBody(this, ContentUris.withAppendedId(Mms.CONTENT_URI, msgId));
    } catch (MmsException e) {
        Log.e(TAG, "getDrmMimeType can't load pdu body: " + msgId);
    }
    if (body == null) {
        return false;
    }

    int partNum = body.getPartsNum();
    for (int i = 0; i < partNum; i++) {
        PduPart part = body.getPart(i);
        String type = new String(part.getContentType());

        if (DrmUtils.isDrmType(type)
                && !DrmUtils.haveRightsForAction(part.getDataUri(), DrmStore.Action.TRANSFER)) {
            return false;
        }
    }
    return true;
}

From source file:com.android.exchange.EasSyncService.java

/**
 * Performs FolderSync//from   www. j a  v  a  2  s  . c  o m
 *
 * @throws IOException
 * @throws EasParserException
 */
public void runAccountMailbox() throws IOException, EasParserException {
    // Initialize exit status to success
    mExitStatus = EmailServiceStatus.SUCCESS;
    try {
        try {
            SyncManager.callback().syncMailboxListStatus(mAccount.mId, EmailServiceStatus.IN_PROGRESS, 0);
        } catch (RemoteException e1) {
            // Don't care if this fails
        }

        if (mAccount.mSyncKey == null) {
            mAccount.mSyncKey = "0";
            userLog("Account syncKey INIT to 0");
            ContentValues cv = new ContentValues();
            cv.put(AccountColumns.SYNC_KEY, mAccount.mSyncKey);
            mAccount.update(mContext, cv);
        }

        boolean firstSync = mAccount.mSyncKey.equals("0");
        if (firstSync) {
            userLog("Initial FolderSync");
        }

        // When we first start up, change all mailboxes to push.
        ContentValues cv = new ContentValues();
        cv.put(Mailbox.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PUSH);
        if (mContentResolver.update(Mailbox.CONTENT_URI, cv, WHERE_ACCOUNT_AND_SYNC_INTERVAL_PING,
                new String[] { Long.toString(mAccount.mId) }) > 0) {
            SyncManager.kick("change ping boxes to push");
        }

        // Determine our protocol version, if we haven't already and save it in the Account
        // Also re-check protocol version at least once a day (in case of upgrade)
        if (mAccount.mProtocolVersion == null || ((System.currentTimeMillis() - mMailbox.mSyncTime) > DAYS)) {
            userLog("Determine EAS protocol version");
            HttpResponse resp = sendHttpClientOptions();
            int code = resp.getStatusLine().getStatusCode();
            userLog("OPTIONS response: ", code);
            if (code == HttpStatus.SC_OK) {
                Header header = resp.getFirstHeader("MS-ASProtocolCommands");
                userLog(header.getValue());
                header = resp.getFirstHeader("ms-asprotocolversions");
                try {
                    setupProtocolVersion(this, header);
                } catch (MessagingException e) {
                    // Since we've already validated, this can't really happen
                    // But if it does, we'll rethrow this...
                    throw new IOException();
                }
                // Save the protocol version
                cv.clear();
                // Save the protocol version in the account
                cv.put(Account.PROTOCOL_VERSION, mProtocolVersion);
                mAccount.update(mContext, cv);
                cv.clear();
                // Save the sync time of the account mailbox to current time
                cv.put(Mailbox.SYNC_TIME, System.currentTimeMillis());
                mMailbox.update(mContext, cv);
            } else {
                errorLog("OPTIONS command failed; throwing IOException");
                throw new IOException();
            }
        }

        // Change all pushable boxes to push when we start the account mailbox
        if (mAccount.mSyncInterval == Account.CHECK_INTERVAL_PUSH) {
            cv.clear();
            cv.put(Mailbox.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PUSH);
            if (mContentResolver.update(Mailbox.CONTENT_URI, cv, SyncManager.WHERE_IN_ACCOUNT_AND_PUSHABLE,
                    new String[] { Long.toString(mAccount.mId) }) > 0) {
                userLog("Push account; set pushable boxes to push...");
            }
        }

        while (!mStop) {
            userLog("Sending Account syncKey: ", mAccount.mSyncKey);
            Serializer s = new Serializer();
            s.start(Tags.FOLDER_FOLDER_SYNC).start(Tags.FOLDER_SYNC_KEY).text(mAccount.mSyncKey).end().end()
                    .done();
            HttpResponse resp = sendHttpClientPost("FolderSync", s.toByteArray());
            if (mStop)
                break;
            int code = resp.getStatusLine().getStatusCode();
            if (code == HttpStatus.SC_OK) {
                HttpEntity entity = resp.getEntity();
                int len = (int) entity.getContentLength();
                if (len != 0) {
                    InputStream is = entity.getContent();
                    // Returns true if we need to sync again
                    if (new FolderSyncParser(is, new AccountSyncAdapter(mMailbox, this)).parse()) {
                        continue;
                    }
                }
            } else if (isProvisionError(code)) {
                // If the sync error is a provisioning failure (perhaps the policies changed),
                // let's try the provisioning procedure
                // Provisioning must only be attempted for the account mailbox - trying to
                // provision any other mailbox may result in race conditions and the creation
                // of multiple policy keys.
                if (!tryProvision()) {
                    // Set the appropriate failure status
                    mExitStatus = EXIT_SECURITY_FAILURE;
                    return;
                } else {
                    // If we succeeded, try again...
                    continue;
                }
            } else if (isAuthError(code)) {
                mExitStatus = EXIT_LOGIN_FAILURE;
                return;
            } else {
                userLog("FolderSync response error: ", code);
            }

            // Change all push/hold boxes to push
            cv.clear();
            cv.put(Mailbox.SYNC_INTERVAL, Account.CHECK_INTERVAL_PUSH);
            if (mContentResolver.update(Mailbox.CONTENT_URI, cv, WHERE_PUSH_HOLD_NOT_ACCOUNT_MAILBOX,
                    new String[] { Long.toString(mAccount.mId) }) > 0) {
                userLog("Set push/hold boxes to push...");
            }

            try {
                SyncManager.callback().syncMailboxListStatus(mAccount.mId, mExitStatus, 0);
            } catch (RemoteException e1) {
                // Don't care if this fails
            }

            // Before each run of the pingLoop, if this Account has a PolicySet, make sure it's
            // active; otherwise, clear out the key/flag.  This should cause a provisioning
            // error on the next POST, and start the security sequence over again
            String key = mAccount.mSecuritySyncKey;
            if (!TextUtils.isEmpty(key)) {
                PolicySet ps = new PolicySet(mAccount);
                SecurityPolicy sp = SecurityPolicy.getInstance(mContext);
                if (!sp.isActive(ps)) {
                    cv.clear();
                    cv.put(AccountColumns.SECURITY_FLAGS, 0);
                    cv.putNull(AccountColumns.SECURITY_SYNC_KEY);
                    long accountId = mAccount.mId;
                    mContentResolver.update(ContentUris.withAppendedId(Account.CONTENT_URI, accountId), cv,
                            null, null);
                    sp.policiesRequired(accountId);
                }
            }

            // Wait for push notifications.
            String threadName = Thread.currentThread().getName();
            try {
                runPingLoop();
            } catch (StaleFolderListException e) {
                // We break out if we get told about a stale folder list
                userLog("Ping interrupted; folder list requires sync...");
            } catch (IllegalHeartbeatException e) {
                // If we're sending an illegal heartbeat, reset either the min or the max to
                // that heartbeat
                resetHeartbeats(e.mLegalHeartbeat);
            } finally {
                Thread.currentThread().setName(threadName);
            }
        }
    } catch (IOException e) {
        // We catch this here to send the folder sync status callback
        // A folder sync failed callback will get sent from run()
        try {
            if (!mStop) {
                SyncManager.callback().syncMailboxListStatus(mAccount.mId, EmailServiceStatus.CONNECTION_ERROR,
                        0);
            }
        } catch (RemoteException e1) {
            // Don't care if this fails
        }
        throw e;
    }
}

From source file:org.openintents.shopping.ui.ShoppingActivity.java

/**
 * Picks an item and returns to calling activity.
 *///from w  ww  . j  av  a2  s.co  m
private void pickItem(Cursor c) {
    long itemId = c.getLong(mStringItemsITEMID);
    Uri url = ContentUris.withAppendedId(ShoppingContract.Items.CONTENT_URI, itemId);

    Intent intent = new Intent();
    intent.setData(url);
    setResult(RESULT_OK, intent);
    finish();
}

From source file:com.android.mms.ui.ComposeMessageActivity.java

/**
 * Copies media from an Mms to the "download" directory on the SD card. If any of the parts
 * are audio types, drm'd or not, they're copied to the "Ringtones" directory.
 * @param msgId//  ww  w  .  j a  va  2  s .  c o m
 */
private boolean copyMedia(long msgId) {
    boolean result = true;
    PduBody body = null;
    try {
        body = SlideshowModel.getPduBody(this, ContentUris.withAppendedId(Mms.CONTENT_URI, msgId));
    } catch (MmsException e) {
        Log.e(TAG, "copyMedia can't load pdu body: " + msgId);
    }
    if (body == null) {
        return false;
    }

    int partNum = body.getPartsNum();
    for (int i = 0; i < partNum; i++) {
        PduPart part = body.getPart(i);

        // all parts have to be successful for a valid result.
        result &= copyPart(part, Long.toHexString(msgId));
    }
    return result;
}

From source file:com.android.exchange.EasSyncService.java

private void pushFallback(long mailboxId) {
    Mailbox mailbox = Mailbox.restoreMailboxWithId(mContext, mailboxId);
    if (mailbox == null) {
        return;//from  w w  w.ja v a  2  s  . c om
    }
    ContentValues cv = new ContentValues();
    int mins = PING_FALLBACK_PIM;
    if (mailbox.mType == Mailbox.TYPE_INBOX) {
        mins = PING_FALLBACK_INBOX;
    }
    cv.put(Mailbox.SYNC_INTERVAL, mins);
    mContentResolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, mailboxId), cv, null, null);
    errorLog("*** PING ERROR LOOP: Set " + mailbox.mDisplayName + " to " + mins + " min sync");
    SyncManager.kick("push fallback");
}

From source file:com.android.calendar.EventInfoFragment.java

private void updateCustomAppButton() {
    buttonSetup: {//from   w ww. ja  v  a  2  s .co  m
        final Button launchButton = (Button) mView.findViewById(R.id.launch_custom_app_button);
        if (launchButton == null)
            break buttonSetup;

        final String customAppPackage = mEventCursor.getString(EVENT_INDEX_CUSTOM_APP_PACKAGE);
        final String customAppUri = mEventCursor.getString(EVENT_INDEX_CUSTOM_APP_URI);

        if (TextUtils.isEmpty(customAppPackage) || TextUtils.isEmpty(customAppUri))
            break buttonSetup;

        PackageManager pm = mContext.getPackageManager();
        if (pm == null)
            break buttonSetup;

        ApplicationInfo info;
        try {
            info = pm.getApplicationInfo(customAppPackage, 0);
            if (info == null)
                break buttonSetup;
        } catch (NameNotFoundException e) {
            break buttonSetup;
        }

        Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, mEventId);
        final Intent intent = new Intent(CalendarContract.ACTION_HANDLE_CUSTOM_EVENT, uri);
        intent.setPackage(customAppPackage);
        intent.putExtra(CalendarContract.EXTRA_CUSTOM_APP_URI, customAppUri);
        intent.putExtra(EXTRA_EVENT_BEGIN_TIME, mStartMillis);

        // See if we have a taker for our intent
        if (pm.resolveActivity(intent, 0) == null)
            break buttonSetup;

        Drawable icon = pm.getApplicationIcon(info);
        if (icon != null) {

            Drawable[] d = launchButton.getCompoundDrawables();
            icon.setBounds(0, 0, mCustomAppIconSize, mCustomAppIconSize);
            launchButton.setCompoundDrawables(icon, d[1], d[2], d[3]);
        }

        CharSequence label = pm.getApplicationLabel(info);
        if (label != null && label.length() != 0) {
            launchButton.setText(label);
        } else if (icon == null) {
            // No icon && no label. Hide button?
            break buttonSetup;
        }

        // Launch custom app
        launchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    startActivityForResult(intent, 0);
                } catch (ActivityNotFoundException e) {
                    // Shouldn't happen as we checked it already
                    setVisibilityCommon(mView, R.id.launch_custom_app_container, View.GONE);
                }
            }
        });

        setVisibilityCommon(mView, R.id.launch_custom_app_container, View.VISIBLE);
        return;

    }

    setVisibilityCommon(mView, R.id.launch_custom_app_container, View.GONE);
    return;
}

From source file:org.cryptsecure.Utility.java

/**
 * Get the contact photo for a contact id.
 * //from w  w w  .j  a v a  2  s . c  om
 * @param contentResolver
 *            the content resolver
 * @param contactId
 *            the contact id
 * @return the bitmap
 */
public static Bitmap getContactPhoto(ContentResolver contentResolver, String contactId) {
    Bitmap bitmap = null;
    try {
        InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(contentResolver,
                ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(contactId)));
        if (inputStream != null) {
            bitmap = BitmapFactory.decodeStream(inputStream);
            inputStream.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bitmap;
}

From source file:com.android.mail.utils.NotificationUtils.java

public static ContactIconInfo getContactInfo(final Context context, final String senderAddress,
        final int idealIconWidth, final int idealIconHeight, final int idealWearableBgWidth,
        final int idealWearableBgHeight) {
    final ContactIconInfo contactIconInfo = new ContactIconInfo();
    final List<Long> contactIds = findContacts(context, Arrays.asList(new String[] { senderAddress }));

    if (contactIds != null) {
        for (final long id : contactIds) {
            final Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
            final InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(
                    context.getContentResolver(), contactUri, true /*preferHighres*/);

            if (inputStream != null) {
                try {
                    final Bitmap source = BitmapFactory.decodeStream(inputStream);
                    if (source != null) {
                        // We should scale this image to fit the intended size
                        contactIconInfo.icon = Bitmap.createScaledBitmap(source, idealIconWidth,
                                idealIconHeight, true);

                        contactIconInfo.wearableBg = Bitmap.createScaledBitmap(source, idealWearableBgWidth,
                                idealWearableBgHeight, true);
                    }/*w w  w . j  a  v a2 s .c o m*/

                    if (contactIconInfo.icon != null) {
                        break;
                    }
                } finally {
                    Closeables.closeQuietly(inputStream);
                }
            }
        }
    }

    return contactIconInfo;
}

From source file:com.android.contacts.quickcontact.QuickContactActivity.java

/**
 * Converts a {@link DataItem} into an {@link ExpandingEntryCardView.Entry} for display.
 * If the {@link ExpandingEntryCardView.Entry} has no visual elements, null is returned.
 *
 * This runs on a background thread. This is set as static to avoid accidentally adding
 * additional dependencies on unsafe things (like the Activity).
 *
 * @param dataItem The {@link DataItem} to convert.
 * @param secondDataItem A second {@link DataItem} to help build a full entry for some
 *  mimetypes/*from ww w .  j a  va 2  s . c  om*/
 * @return The {@link ExpandingEntryCardView.Entry}, or null if no visual elements are present.
 */
private static Entry dataItemToEntry(DataItem dataItem, DataItem secondDataItem, Context context,
        Contact contactData, final MutableString aboutCardName) {
    Drawable icon = null;
    String header = null;
    String subHeader = null;
    Drawable subHeaderIcon = null;
    String text = null;
    Drawable textIcon = null;
    StringBuilder primaryContentDescription = new StringBuilder();
    Spannable phoneContentDescription = null;
    Spannable smsContentDescription = null;
    Intent intent = null;
    boolean shouldApplyColor = true;
    Drawable alternateIcon = null;
    Intent alternateIntent = null;
    StringBuilder alternateContentDescription = new StringBuilder();
    final boolean isEditable = false;
    EntryContextMenuInfo entryContextMenuInfo = null;
    Drawable thirdIcon = null;
    Intent thirdIntent = null;
    int thirdAction = Entry.ACTION_NONE;
    String thirdContentDescription = null;
    Bundle thirdExtras = null;
    int iconResourceId = 0;

    context = context.getApplicationContext();
    final Resources res = context.getResources();
    DataKind kind = dataItem.getDataKind();

    if (dataItem instanceof ImDataItem) {
        final ImDataItem im = (ImDataItem) dataItem;
        intent = ContactsUtils.buildImIntent(context, im).first;
        final boolean isEmail = im.isCreatedFromEmail();
        final int protocol;
        if (!im.isProtocolValid()) {
            protocol = Im.PROTOCOL_CUSTOM;
        } else {
            protocol = isEmail ? Im.PROTOCOL_GOOGLE_TALK : im.getProtocol();
        }
        if (protocol == Im.PROTOCOL_CUSTOM) {
            // If the protocol is custom, display the "IM" entry header as well to distinguish
            // this entry from other ones
            header = res.getString(R.string.header_im_entry);
            subHeader = Im.getProtocolLabel(res, protocol, im.getCustomProtocol()).toString();
            text = im.getData();
        } else {
            header = Im.getProtocolLabel(res, protocol, im.getCustomProtocol()).toString();
            subHeader = im.getData();
        }
        entryContextMenuInfo = new EntryContextMenuInfo(im.getData(), header, dataItem.getMimeType(),
                dataItem.getId(), dataItem.isSuperPrimary());
    } else if (dataItem instanceof OrganizationDataItem) {
        final OrganizationDataItem organization = (OrganizationDataItem) dataItem;
        header = res.getString(R.string.header_organization_entry);
        subHeader = organization.getCompany();
        entryContextMenuInfo = new EntryContextMenuInfo(subHeader, header, dataItem.getMimeType(),
                dataItem.getId(), dataItem.isSuperPrimary());
        text = organization.getTitle();
    } else if (dataItem instanceof NicknameDataItem) {
        final NicknameDataItem nickname = (NicknameDataItem) dataItem;
        // Build nickname entries
        final boolean isNameRawContact = (contactData.getNameRawContactId() == dataItem.getRawContactId());

        final boolean duplicatesTitle = isNameRawContact
                && contactData.getDisplayNameSource() == DisplayNameSources.NICKNAME;

        if (!duplicatesTitle) {
            header = res.getString(R.string.header_nickname_entry);
            subHeader = nickname.getName();
            entryContextMenuInfo = new EntryContextMenuInfo(subHeader, header, dataItem.getMimeType(),
                    dataItem.getId(), dataItem.isSuperPrimary());
        }
    } else if (dataItem instanceof NoteDataItem) {
        final NoteDataItem note = (NoteDataItem) dataItem;
        header = res.getString(R.string.header_note_entry);
        subHeader = note.getNote();
        entryContextMenuInfo = new EntryContextMenuInfo(subHeader, header, dataItem.getMimeType(),
                dataItem.getId(), dataItem.isSuperPrimary());
    } else if (dataItem instanceof WebsiteDataItem) {
        final WebsiteDataItem website = (WebsiteDataItem) dataItem;
        header = res.getString(R.string.header_website_entry);
        subHeader = website.getUrl();
        entryContextMenuInfo = new EntryContextMenuInfo(subHeader, header, dataItem.getMimeType(),
                dataItem.getId(), dataItem.isSuperPrimary());
        try {
            final WebAddress webAddress = new WebAddress(website.buildDataStringForDisplay(context, kind));
            intent = new Intent(Intent.ACTION_VIEW, Uri.parse(webAddress.toString()));
        } catch (final ParseException e) {
            Log.e(TAG, "Couldn't parse website: " + website.buildDataStringForDisplay(context, kind));
        }
    } else if (dataItem instanceof EventDataItem) {
        final EventDataItem event = (EventDataItem) dataItem;
        final String dataString = event.buildDataStringForDisplay(context, kind);
        final Calendar cal = DateUtils.parseDate(dataString, false);
        if (cal != null) {
            final Date nextAnniversary = DateUtils.getNextAnnualDate(cal);
            final Uri.Builder builder = CalendarContract.CONTENT_URI.buildUpon();
            builder.appendPath("time");
            ContentUris.appendId(builder, nextAnniversary.getTime());
            intent = new Intent(Intent.ACTION_VIEW).setData(builder.build());
        }
        header = res.getString(R.string.header_event_entry);
        if (event.hasKindTypeColumn(kind)) {
            subHeader = EventCompat.getTypeLabel(res, event.getKindTypeColumn(kind), event.getLabel())
                    .toString();
        }
        text = DateUtils.formatDate(context, dataString);
        entryContextMenuInfo = new EntryContextMenuInfo(text, header, dataItem.getMimeType(), dataItem.getId(),
                dataItem.isSuperPrimary());
    } else if (dataItem instanceof RelationDataItem) {
        final RelationDataItem relation = (RelationDataItem) dataItem;
        final String dataString = relation.buildDataStringForDisplay(context, kind);
        if (!TextUtils.isEmpty(dataString)) {
            intent = new Intent(Intent.ACTION_SEARCH);
            intent.putExtra(SearchManager.QUERY, dataString);
            intent.setType(Contacts.CONTENT_TYPE);
        }
        header = res.getString(R.string.header_relation_entry);
        subHeader = relation.getName();
        entryContextMenuInfo = new EntryContextMenuInfo(subHeader, header, dataItem.getMimeType(),
                dataItem.getId(), dataItem.isSuperPrimary());
        if (relation.hasKindTypeColumn(kind)) {
            text = Relation.getTypeLabel(res, relation.getKindTypeColumn(kind), relation.getLabel()).toString();
        }
    } else if (dataItem instanceof PhoneDataItem) {
        final PhoneDataItem phone = (PhoneDataItem) dataItem;
        String phoneLabel = null;
        if (!TextUtils.isEmpty(phone.getNumber())) {
            primaryContentDescription.append(res.getString(R.string.call_other)).append(" ");
            header = sBidiFormatter.unicodeWrap(phone.buildDataStringForDisplay(context, kind),
                    TextDirectionHeuristics.LTR);
            entryContextMenuInfo = new EntryContextMenuInfo(header, res.getString(R.string.phoneLabelsGroup),
                    dataItem.getMimeType(), dataItem.getId(), dataItem.isSuperPrimary());
            if (phone.hasKindTypeColumn(kind)) {
                final int kindTypeColumn = phone.getKindTypeColumn(kind);
                final String label = phone.getLabel();
                phoneLabel = label;
                if (kindTypeColumn == Phone.TYPE_CUSTOM && TextUtils.isEmpty(label)) {
                    text = "";
                } else {
                    text = Phone.getTypeLabel(res, kindTypeColumn, label).toString();
                    phoneLabel = text;
                    primaryContentDescription.append(text).append(" ");
                }
            }
            primaryContentDescription.append(header);
            phoneContentDescription = com.android.contacts.common.util.ContactDisplayUtils
                    .getTelephoneTtsSpannable(primaryContentDescription.toString(), header);
            icon = res.getDrawable(R.drawable.ic_phone_24dp);
            iconResourceId = R.drawable.ic_phone_24dp;
            if (PhoneCapabilityTester.isPhone(context)) {
                intent = CallUtil.getCallIntent(phone.getNumber());
            }
            alternateIntent = new Intent(Intent.ACTION_SENDTO,
                    Uri.fromParts(ContactsUtils.SCHEME_SMSTO, phone.getNumber(), null));

            alternateIcon = res.getDrawable(R.drawable.ic_message_24dp);
            alternateContentDescription.append(res.getString(R.string.sms_custom, header));
            smsContentDescription = com.android.contacts.common.util.ContactDisplayUtils
                    .getTelephoneTtsSpannable(alternateContentDescription.toString(), header);

            int videoCapability = CallUtil.getVideoCallingAvailability(context);
            boolean isPresenceEnabled = (videoCapability & CallUtil.VIDEO_CALLING_PRESENCE) != 0;
            boolean isVideoEnabled = (videoCapability & CallUtil.VIDEO_CALLING_ENABLED) != 0;

            if (CallUtil.isCallWithSubjectSupported(context)) {
                thirdIcon = res.getDrawable(R.drawable.ic_call_note_white_24dp);
                thirdAction = Entry.ACTION_CALL_WITH_SUBJECT;
                thirdContentDescription = res.getString(R.string.call_with_a_note);
                // Create a bundle containing the data the call subject dialog requires.
                thirdExtras = new Bundle();
                thirdExtras.putLong(CallSubjectDialog.ARG_PHOTO_ID, contactData.getPhotoId());
                thirdExtras.putParcelable(CallSubjectDialog.ARG_PHOTO_URI,
                        UriUtils.parseUriOrNull(contactData.getPhotoUri()));
                thirdExtras.putParcelable(CallSubjectDialog.ARG_CONTACT_URI, contactData.getLookupUri());
                thirdExtras.putString(CallSubjectDialog.ARG_NAME_OR_NUMBER, contactData.getDisplayName());
                thirdExtras.putBoolean(CallSubjectDialog.ARG_IS_BUSINESS, false);
                thirdExtras.putString(CallSubjectDialog.ARG_NUMBER, phone.getNumber());
                thirdExtras.putString(CallSubjectDialog.ARG_DISPLAY_NUMBER, phone.getFormattedPhoneNumber());
                thirdExtras.putString(CallSubjectDialog.ARG_NUMBER_LABEL, phoneLabel);
            } else if (isVideoEnabled) {
                // Check to ensure carrier presence indicates the number supports video calling.
                int carrierPresence = dataItem.getCarrierPresence();
                boolean isPresent = (carrierPresence & Phone.CARRIER_PRESENCE_VT_CAPABLE) != 0;

                if ((isPresenceEnabled && isPresent) || !isPresenceEnabled) {
                    thirdIcon = res.getDrawable(R.drawable.ic_videocam);
                    thirdAction = Entry.ACTION_INTENT;
                    thirdIntent = CallUtil.getVideoCallIntent(phone.getNumber(),
                            CALL_ORIGIN_QUICK_CONTACTS_ACTIVITY);
                    thirdContentDescription = res.getString(R.string.description_video_call);
                }
            }
        }
    } else if (dataItem instanceof EmailDataItem) {
        final EmailDataItem email = (EmailDataItem) dataItem;
        final String address = email.getData();
        if (!TextUtils.isEmpty(address)) {
            primaryContentDescription.append(res.getString(R.string.email_other)).append(" ");
            final Uri mailUri = Uri.fromParts(ContactsUtils.SCHEME_MAILTO, address, null);
            intent = new Intent(Intent.ACTION_SENDTO, mailUri);
            header = email.getAddress();
            entryContextMenuInfo = new EntryContextMenuInfo(header, res.getString(R.string.emailLabelsGroup),
                    dataItem.getMimeType(), dataItem.getId(), dataItem.isSuperPrimary());
            if (email.hasKindTypeColumn(kind)) {
                text = Email.getTypeLabel(res, email.getKindTypeColumn(kind), email.getLabel()).toString();
                primaryContentDescription.append(text).append(" ");
            }
            primaryContentDescription.append(header);
            icon = res.getDrawable(R.drawable.ic_email_24dp);
            iconResourceId = R.drawable.ic_email_24dp;
        }
    } else if (dataItem instanceof StructuredPostalDataItem) {
        StructuredPostalDataItem postal = (StructuredPostalDataItem) dataItem;
        final String postalAddress = postal.getFormattedAddress();
        if (!TextUtils.isEmpty(postalAddress)) {
            primaryContentDescription.append(res.getString(R.string.map_other)).append(" ");
            intent = StructuredPostalUtils.getViewPostalAddressIntent(postalAddress);
            header = postal.getFormattedAddress();
            entryContextMenuInfo = new EntryContextMenuInfo(header, res.getString(R.string.postalLabelsGroup),
                    dataItem.getMimeType(), dataItem.getId(), dataItem.isSuperPrimary());
            if (postal.hasKindTypeColumn(kind)) {
                text = StructuredPostal.getTypeLabel(res, postal.getKindTypeColumn(kind), postal.getLabel())
                        .toString();
                primaryContentDescription.append(text).append(" ");
            }
            primaryContentDescription.append(header);
            alternateIntent = StructuredPostalUtils.getViewPostalAddressDirectionsIntent(postalAddress);
            alternateIcon = res.getDrawable(R.drawable.ic_directions_24dp);
            alternateContentDescription.append(res.getString(R.string.content_description_directions))
                    .append(" ").append(header);
            icon = res.getDrawable(R.drawable.ic_place_24dp);
            iconResourceId = R.drawable.ic_place_24dp;
        }
    } else if (dataItem instanceof SipAddressDataItem) {
        final SipAddressDataItem sip = (SipAddressDataItem) dataItem;
        final String address = sip.getSipAddress();
        if (!TextUtils.isEmpty(address)) {
            primaryContentDescription.append(res.getString(R.string.call_other)).append(" ");
            if (PhoneCapabilityTester.isSipPhone(context)) {
                final Uri callUri = Uri.fromParts(PhoneAccount.SCHEME_SIP, address, null);
                intent = CallUtil.getCallIntent(callUri);
            }
            header = address;
            entryContextMenuInfo = new EntryContextMenuInfo(header, res.getString(R.string.phoneLabelsGroup),
                    dataItem.getMimeType(), dataItem.getId(), dataItem.isSuperPrimary());
            if (sip.hasKindTypeColumn(kind)) {
                text = SipAddress.getTypeLabel(res, sip.getKindTypeColumn(kind), sip.getLabel()).toString();
                primaryContentDescription.append(text).append(" ");
            }
            primaryContentDescription.append(header);
            icon = res.getDrawable(R.drawable.ic_dialer_sip_black_24dp);
            iconResourceId = R.drawable.ic_dialer_sip_black_24dp;
        }
    } else if (dataItem instanceof StructuredNameDataItem) {
        // If the name is already set and this is not the super primary value then leave the
        // current value. This way we show the super primary value when we are able to.
        if (dataItem.isSuperPrimary() || aboutCardName.value == null || aboutCardName.value.isEmpty()) {
            final String givenName = ((StructuredNameDataItem) dataItem).getGivenName();
            if (!TextUtils.isEmpty(givenName)) {
                aboutCardName.value = res.getString(R.string.about_card_title) + " " + givenName;
            } else {
                aboutCardName.value = res.getString(R.string.about_card_title);
            }
        }
    } else {
        // Custom DataItem
        header = dataItem.buildDataStringForDisplay(context, kind);
        text = kind.typeColumn;
        intent = new Intent(Intent.ACTION_VIEW);
        final Uri uri = ContentUris.withAppendedId(Data.CONTENT_URI, dataItem.getId());
        intent.setDataAndType(uri, dataItem.getMimeType());

        if (intent != null) {
            final String mimetype = intent.getType();

            // Build advanced entry for known 3p types. Otherwise default to ResolveCache icon.
            switch (mimetype) {
            case MIMETYPE_GPLUS_PROFILE:
                // If a secondDataItem is available, use it to build an entry with
                // alternate actions
                if (secondDataItem != null) {
                    icon = res.getDrawable(R.drawable.ic_google_plus_24dp);
                    alternateIcon = res.getDrawable(R.drawable.ic_add_to_circles_black_24);
                    final GPlusOrHangoutsDataItemModel itemModel = new GPlusOrHangoutsDataItemModel(intent,
                            alternateIntent, dataItem, secondDataItem, alternateContentDescription, header,
                            text, context);

                    populateGPlusOrHangoutsDataItemModel(itemModel);
                    intent = itemModel.intent;
                    alternateIntent = itemModel.alternateIntent;
                    alternateContentDescription = itemModel.alternateContentDescription;
                    header = itemModel.header;
                    text = itemModel.text;
                } else {
                    if (GPLUS_PROFILE_DATA_5_ADD_TO_CIRCLE.equals(intent.getDataString())) {
                        icon = res.getDrawable(R.drawable.ic_add_to_circles_black_24);
                    } else {
                        icon = res.getDrawable(R.drawable.ic_google_plus_24dp);
                    }
                }
                break;
            case MIMETYPE_HANGOUTS:
                // If a secondDataItem is available, use it to build an entry with
                // alternate actions
                if (secondDataItem != null) {
                    icon = res.getDrawable(R.drawable.ic_hangout_24dp);
                    alternateIcon = res.getDrawable(R.drawable.ic_hangout_video_24dp);
                    final GPlusOrHangoutsDataItemModel itemModel = new GPlusOrHangoutsDataItemModel(intent,
                            alternateIntent, dataItem, secondDataItem, alternateContentDescription, header,
                            text, context);

                    populateGPlusOrHangoutsDataItemModel(itemModel);
                    intent = itemModel.intent;
                    alternateIntent = itemModel.alternateIntent;
                    alternateContentDescription = itemModel.alternateContentDescription;
                    header = itemModel.header;
                    text = itemModel.text;
                } else {
                    if (HANGOUTS_DATA_5_VIDEO.equals(intent.getDataString())) {
                        icon = res.getDrawable(R.drawable.ic_hangout_video_24dp);
                    } else {
                        icon = res.getDrawable(R.drawable.ic_hangout_24dp);
                    }
                }
                break;
            default:
                entryContextMenuInfo = new EntryContextMenuInfo(header, mimetype, dataItem.getMimeType(),
                        dataItem.getId(), dataItem.isSuperPrimary());
                icon = ResolveCache.getInstance(context).getIcon(dataItem.getMimeType(), intent);
                // Call mutate to create a new Drawable.ConstantState for color filtering
                if (icon != null) {
                    icon.mutate();
                }
                shouldApplyColor = false;
            }
        }
    }

    if (intent != null) {
        // Do not set the intent is there are no resolves
        if (!PhoneCapabilityTester.isIntentRegistered(context, intent)) {
            intent = null;
        }
    }

    if (alternateIntent != null) {
        // Do not set the alternate intent is there are no resolves
        if (!PhoneCapabilityTester.isIntentRegistered(context, alternateIntent)) {
            alternateIntent = null;
        } else if (TextUtils.isEmpty(alternateContentDescription)) {
            // Attempt to use package manager to find a suitable content description if needed
            alternateContentDescription.append(getIntentResolveLabel(alternateIntent, context));
        }
    }

    // If the Entry has no visual elements, return null
    if (icon == null && TextUtils.isEmpty(header) && TextUtils.isEmpty(subHeader) && subHeaderIcon == null
            && TextUtils.isEmpty(text) && textIcon == null) {
        return null;
    }

    // Ignore dataIds from the Me profile.
    final int dataId = dataItem.getId() > Integer.MAX_VALUE ? -1 : (int) dataItem.getId();

    return new Entry(dataId, icon, header, subHeader, subHeaderIcon, text, textIcon,
            phoneContentDescription == null ? new SpannableString(primaryContentDescription.toString())
                    : phoneContentDescription,
            intent, alternateIcon, alternateIntent,
            smsContentDescription == null ? new SpannableString(alternateContentDescription.toString())
                    : smsContentDescription,
            shouldApplyColor, isEditable, entryContextMenuInfo, thirdIcon, thirdIntent, thirdContentDescription,
            thirdAction, thirdExtras, iconResourceId);
}