Example usage for android.os Bundle putParcelable

List of usage examples for android.os Bundle putParcelable

Introduction

In this page you can find the example usage for android.os Bundle putParcelable.

Prototype

public void putParcelable(@Nullable String key, @Nullable Parcelable value) 

Source Link

Document

Inserts a Parcelable value into the mapping of this Bundle, replacing any existing value for the given key.

Usage

From source file:com.android.mail.ui.AbstractActivityController.java

/**
 * Handle an intent to open the app. This method is called only when there is no saved state,
 * so we need to set state that wasn't set before. It is correct to change the viewmode here
 * since it has not been previously set.
 *
 * This method is called for a subset of the reasons mentioned in
 * {@link #onCreate(android.os.Bundle)}. Notably, this is called when launching the app from
 * notifications, widgets, and shortcuts.
 * @param intent intent passed to the activity.
 *///from  w  w  w.  j  a  v  a 2s .  com
private void handleIntent(Intent intent) {
    LogUtils.d(LOG_TAG, "IN AAC.handleIntent. action=%s", intent.getAction());
    if (Intent.ACTION_VIEW.equals(intent.getAction())) {
        if (intent.hasExtra(Utils.EXTRA_ACCOUNT)) {
            setAccount(Account.newInstance(intent.getStringExtra(Utils.EXTRA_ACCOUNT)));
        }
        if (mAccount == null) {
            return;
        }
        final boolean isConversationMode = intent.hasExtra(Utils.EXTRA_CONVERSATION);

        if (intent.getBooleanExtra(Utils.EXTRA_FROM_NOTIFICATION, false)) {
            Analytics.getInstance().setEmail(mAccount.getEmailAddress(), mAccount.getType());
            Analytics.getInstance().sendEvent("notification_click",
                    isConversationMode ? "conversation" : "conversation_list", null, 0);
        }

        if (isConversationMode && mViewMode.getMode() == ViewMode.UNKNOWN) {
            mViewMode.enterConversationMode();
        } else {
            mViewMode.enterConversationListMode();
        }
        // Put the folder and conversation, and ask the loader to create this folder.
        final Bundle args = new Bundle();

        final Uri folderUri;
        if (intent.hasExtra(Utils.EXTRA_FOLDER_URI)) {
            folderUri = intent.getParcelableExtra(Utils.EXTRA_FOLDER_URI);
        } else if (intent.hasExtra(Utils.EXTRA_FOLDER)) {
            final Folder folder = Folder.fromString(intent.getStringExtra(Utils.EXTRA_FOLDER));
            folderUri = folder.folderUri.fullUri;
        } else {
            final Bundle extras = intent.getExtras();
            LogUtils.d(LOG_TAG, "Couldn't find a folder URI in the extras: %s",
                    extras == null ? "null" : extras.toString());
            folderUri = mAccount.settings.defaultInbox;
        }

        // Check if we should load all conversations instead of using
        // the default behavior which loads an initial subset.
        mIgnoreInitialConversationLimit = intent.getBooleanExtra(Utils.EXTRA_IGNORE_INITIAL_CONVERSATION_LIMIT,
                false);

        args.putParcelable(Utils.EXTRA_FOLDER_URI, folderUri);
        args.putParcelable(Utils.EXTRA_CONVERSATION, intent.getParcelableExtra(Utils.EXTRA_CONVERSATION));
        restartOptionalLoader(LOADER_FIRST_FOLDER, mFolderCallbacks, args);
    } else if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        if (intent.hasExtra(Utils.EXTRA_ACCOUNT)) {
            mHaveSearchResults = false;
            // Save this search query for future suggestions
            final String query = intent.getStringExtra(SearchManager.QUERY);
            mSearchViewController.saveRecentQuery(query);
            setAccount((Account) intent.getParcelableExtra(Utils.EXTRA_ACCOUNT));
            fetchSearchFolder(intent);
            if (shouldEnterSearchConvMode()) {
                mViewMode.enterSearchResultsConversationMode();
            } else {
                mViewMode.enterSearchResultsListMode();
            }
        } else {
            LogUtils.e(LOG_TAG, "Missing account extra from search intent.  Finishing");
            mActivity.finish();
        }
    }
    if (mAccount != null) {
        restartOptionalLoader(LOADER_ACCOUNT_UPDATE_CURSOR, mAccountCallbacks, Bundle.EMPTY);
    }
}

From source file:com.android.launcher3.Launcher.java

@Override
protected void onSaveInstanceState(Bundle outState) {
    if (mWorkspace.getChildCount() > 0) {
        outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getCurrentPageOffsetFromCustomContent());

    }/*from w  w w . j av  a 2s.  co  m*/
    super.onSaveInstanceState(outState);

    outState.putInt(RUNTIME_STATE, mState.ordinal());
    // We close any open folder since it will not be re-opened, and we need to make sure
    // this state is reflected.
    // TODO: Move folderInfo.isOpened out of the model and make it a UI state.
    closeFolder(false);
    closeShortcutsContainer(false);

    if (mPendingRequestArgs != null) {
        outState.putParcelable(RUNTIME_STATE_PENDING_REQUEST_ARGS, mPendingRequestArgs);
    }
    if (mPendingActivityResult != null) {
        outState.putParcelable(RUNTIME_STATE_PENDING_ACTIVITY_RESULT, mPendingActivityResult);
    }

    if (mLauncherCallbacks != null) {
        mLauncherCallbacks.onSaveInstanceState(outState);
    }
}

From source file:android.app.Activity.java

/**
 * Called to retrieve per-instance state from an activity before being killed
 * so that the state can be restored in {@link #onCreate} or
 * {@link #onRestoreInstanceState} (the {@link Bundle} populated by this method
 * will be passed to both).// ww  w  .  ja  va2s . c  o  m
 *
 * <p>This method is called before an activity may be killed so that when it
 * comes back some time in the future it can restore its state.  For example,
 * if activity B is launched in front of activity A, and at some point activity
 * A is killed to reclaim resources, activity A will have a chance to save the
 * current state of its user interface via this method so that when the user
 * returns to activity A, the state of the user interface can be restored
 * via {@link #onCreate} or {@link #onRestoreInstanceState}.
 *
 * <p>Do not confuse this method with activity lifecycle callbacks such as
 * {@link #onPause}, which is always called when an activity is being placed
 * in the background or on its way to destruction, or {@link #onStop} which
 * is called before destruction.  One example of when {@link #onPause} and
 * {@link #onStop} is called and not this method is when a user navigates back
 * from activity B to activity A: there is no need to call {@link #onSaveInstanceState}
 * on B because that particular instance will never be restored, so the
 * system avoids calling it.  An example when {@link #onPause} is called and
 * not {@link #onSaveInstanceState} is when activity B is launched in front of activity A:
 * the system may avoid calling {@link #onSaveInstanceState} on activity A if it isn't
 * killed during the lifetime of B since the state of the user interface of
 * A will stay intact.
 *
 * <p>The default implementation takes care of most of the UI per-instance
 * state for you by calling {@link android.view.View#onSaveInstanceState()} on each
 * view in the hierarchy that has an id, and by saving the id of the currently
 * focused view (all of which is restored by the default implementation of
 * {@link #onRestoreInstanceState}).  If you override this method to save additional
 * information not captured by each individual view, you will likely want to
 * call through to the default implementation, otherwise be prepared to save
 * all of the state of each view yourself.
 *
 * <p>If called, this method will occur before {@link #onStop}.  There are
 * no guarantees about whether it will occur before or after {@link #onPause}.
 * 
 * @param outState Bundle in which to place your saved state.
 * 
 * @see #onCreate
 * @see #onRestoreInstanceState
 * @see #onPause
 */
protected void onSaveInstanceState(Bundle outState) {

    outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState());
    Parcelable p = mFragments.saveAllState();
    if (p != null) {
        outState.putParcelable(FRAGMENTS_TAG, p);
    }
    getApplication().dispatchActivitySaveInstanceState(this, outState);
}

From source file:com.android.soma.Launcher.java

@Override
protected void onSaveInstanceState(Bundle outState) {
    if (mWorkspace.getChildCount() > 0) {
        outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getRestorePage());
    }//from ww  w.  j a  v  a  2 s  .  com
    super.onSaveInstanceState(outState);

    outState.putInt(RUNTIME_STATE, mState.ordinal());
    // We close any open folder since it will not be re-opened, and we need to make sure
    // this state is reflected.
    closeFolder();

    if (mPendingAddInfo.container != ItemInfo.NO_ID && mPendingAddInfo.screenId > -1 && mWaitingForResult) {
        outState.putLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, mPendingAddInfo.container);
        outState.putLong(RUNTIME_STATE_PENDING_ADD_SCREEN, mPendingAddInfo.screenId);
        outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, mPendingAddInfo.cellX);
        outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, mPendingAddInfo.cellY);
        outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_X, mPendingAddInfo.spanX);
        outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y, mPendingAddInfo.spanY);
        outState.putParcelable(RUNTIME_STATE_PENDING_ADD_WIDGET_INFO, mPendingAddWidgetInfo);
    }

    if (mFolderInfo != null && mWaitingForResult) {
        outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true);
        outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID, mFolderInfo.id);
    }

    // Save the current AppsCustomize tab
    if (mAppsCustomizeTabHost != null) {
        String currentTabTag = mAppsCustomizeTabHost.getCurrentTabTag();
        if (currentTabTag != null) {
            outState.putString("apps_customize_currentTab", currentTabTag);
        }
        int currentIndex = mAppsCustomizeContent.getSaveInstanceStateIndex();
        outState.putInt("apps_customize_currentIndex", currentIndex);
    }
}

From source file:android.app.Activity.java

/**
 * Migrate the application to other device.
 * This method is called by the Android system.
 *
 * @hide/*  w  w  w.ja va2  s . c o  m*/
 * @param savedInstanceState A state the application needs to restore.
 * @return true if migration successed.
 */
private boolean systemMigrate(Bundle savedInstanceState) {
    boolean result = true;
    String cName;
    String pName;

    if (savedInstanceState == null)
        savedInstanceState = new Bundle();

    /* store Intent object this Activity has and requestCode for next Activity */
    savedInstanceState.putParcelable("MIGRATED_INTENT", getIntent());
    savedInstanceState.putInt("MIGRATED REQUEST CODE", currentCode);
    savedInstanceState.putBundle("MIGRATED REQUEST OPTIONS", currentOption);
    currentCode = -1;
    currentOption = null;

    if (mMigrator == null) {
        mMigrator = IMigratorService.Stub.asInterface(ServiceManager.getService("Migrator"));
    }

    pName = getPackageName();
    cName = mComponent.getClassName();

    try {
        /* mStartedActivity is true if this Activity calls startActivityForResult().
         * This means the next Activity exists. */
        result = mMigrator.migrate(savedInstanceState, pName, cName, mStartedActivity);
        mStartedActivity = false;
    } catch (RemoteException e) {
        Log.w("MIGRATOR", "Migrate failed");
        result = false;
        e.printStackTrace();
    }

    return result;
}

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

/**
 * Use the Exchange 2007 AutoDiscover feature to try to retrieve server information using
 * only an email address and the password
 *
 * @param userName the user's email address
 * @param password the user's password//from  w  w w  . j av  a  2 s.co  m
 * @return a HostAuth ready to be saved in an Account or null (failure)
 */
public Bundle tryAutodiscover(String userName, String password) throws RemoteException {
    XmlSerializer s = Xml.newSerializer();
    ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
    HostAuth hostAuth = new HostAuth();
    Bundle bundle = new Bundle();
    bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE, MessagingException.NO_ERROR);
    try {
        // Build the XML document that's sent to the autodiscover server(s)
        s.setOutput(os, "UTF-8");
        s.startDocument("UTF-8", false);
        s.startTag(null, "Autodiscover");
        s.attribute(null, "xmlns", AUTO_DISCOVER_SCHEMA_PREFIX + "requestschema/2006");
        s.startTag(null, "Request");
        s.startTag(null, "EMailAddress").text(userName).endTag(null, "EMailAddress");
        s.startTag(null, "AcceptableResponseSchema");
        s.text(AUTO_DISCOVER_SCHEMA_PREFIX + "responseschema/2006");
        s.endTag(null, "AcceptableResponseSchema");
        s.endTag(null, "Request");
        s.endTag(null, "Autodiscover");
        s.endDocument();
        String req = os.toString();

        // Initialize the user name and password
        mUserName = userName;
        mPassword = password;
        // Make sure the authentication string is recreated and cached
        cacheAuthAndCmdString();

        // Split out the domain name
        int amp = userName.indexOf('@');
        // The UI ensures that userName is a valid email address
        if (amp < 0) {
            throw new RemoteException();
        }
        String domain = userName.substring(amp + 1);

        // There are up to four attempts here; the two URLs that we're supposed to try per the
        // specification, and up to one redirect for each (handled in postAutodiscover)
        // Note: The expectation is that, of these four attempts, only a single server will
        // actually be identified as the autodiscover server.  For the identified server,
        // we may also try a 2nd connection with a different format (bare name).

        // Try the domain first and see if we can get a response
        HttpPost post = new HttpPost("https://" + domain + AUTO_DISCOVER_PAGE);
        setHeaders(post, false);
        post.setHeader("Content-Type", "text/xml");
        post.setEntity(new StringEntity(req));
        HttpClient client = getHttpClient(COMMAND_TIMEOUT);
        HttpResponse resp;
        try {
            resp = postAutodiscover(client, post, true /*canRetry*/);
        } catch (IOException e1) {
            userLog("IOException in autodiscover; trying alternate address");
            // We catch the IOException here because we have an alternate address to try
            post.setURI(URI.create("https://autodiscover." + domain + AUTO_DISCOVER_PAGE));
            // If we fail here, we're out of options, so we let the outer try catch the
            // IOException and return null
            resp = postAutodiscover(client, post, true /*canRetry*/);
        }

        // Get the "final" code; if it's not 200, just return null
        int code = resp.getStatusLine().getStatusCode();
        userLog("Code: " + code);
        if (code != HttpStatus.SC_OK)
            return null;

        // At this point, we have a 200 response (SC_OK)
        HttpEntity e = resp.getEntity();
        InputStream is = e.getContent();
        try {
            // The response to Autodiscover is regular XML (not WBXML)
            // If we ever get an error in this process, we'll just punt and return null
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser parser = factory.newPullParser();
            parser.setInput(is, "UTF-8");
            int type = parser.getEventType();
            if (type == XmlPullParser.START_DOCUMENT) {
                type = parser.next();
                if (type == XmlPullParser.START_TAG) {
                    String name = parser.getName();
                    if (name.equals("Autodiscover")) {
                        hostAuth = new HostAuth();
                        parseAutodiscover(parser, hostAuth);
                        // On success, we'll have a server address and login
                        if (hostAuth.mAddress != null) {
                            // Fill in the rest of the HostAuth
                            // We use the user name and password that were successful during
                            // the autodiscover process
                            hostAuth.mLogin = mUserName;
                            hostAuth.mPassword = mPassword;
                            hostAuth.mPort = 443;
                            hostAuth.mProtocol = "eas";
                            hostAuth.mFlags = HostAuth.FLAG_SSL | HostAuth.FLAG_AUTHENTICATE;
                            bundle.putParcelable(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_HOST_AUTH, hostAuth);
                        } else {
                            bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE,
                                    MessagingException.UNSPECIFIED_EXCEPTION);
                        }
                    }
                }
            }
        } catch (XmlPullParserException e1) {
            // This would indicate an I/O error of some sort
            // We will simply return null and user can configure manually
        }
        // There's no reason at all for exceptions to be thrown, and it's ok if so.
        // We just won't do auto-discover; user can configure manually
    } catch (IllegalArgumentException e) {
        bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE,
                MessagingException.UNSPECIFIED_EXCEPTION);
    } catch (IllegalStateException e) {
        bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE,
                MessagingException.UNSPECIFIED_EXCEPTION);
    } catch (IOException e) {
        userLog("IOException in Autodiscover", e);
        bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE, MessagingException.IOERROR);
    } catch (MessagingException e) {
        bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE,
                MessagingException.AUTHENTICATION_FAILED);
    }
    return bundle;
}

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//www  .j a  va2s .  c  o  m
 * @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);
}