Example usage for android.content Intent getType

List of usage examples for android.content Intent getType

Introduction

In this page you can find the example usage for android.content Intent getType.

Prototype

public @Nullable String getType() 

Source Link

Document

Retrieve any explicit MIME type included in the intent.

Usage

From source file:com.fa.mastodon.activity.ComposeActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_compose);
    ButterKnife.bind(this);

    // Setup the toolbar.
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);/*from  www . j av a  2s.c  o  m*/
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setTitle(null);
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setDisplayShowHomeEnabled(true);
        Drawable closeIcon = AppCompatResources.getDrawable(this, R.drawable.ic_close_24dp);
        ThemeUtils.setDrawableTint(this, closeIcon, R.attr.compose_close_button_tint);
        actionBar.setHomeAsUpIndicator(closeIcon);
    }

    // Setup the interface buttons.
    floatingBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onSendClicked();
        }
    });
    pickBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onMediaPick();
        }
    });
    takeBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            initiateCameraApp();
        }
    });
    nsfwBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            toggleNsfw();
        }
    });
    visibilityBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showComposeOptions();
        }
    });

    /* Initialise all the state, or restore it from a previous run, to determine a "starting"
     * state. */
    SharedPreferences preferences = getPrivatePreferences();

    String startingVisibility;
    boolean startingHideText;
    String startingContentWarning = null;
    ArrayList<SavedQueuedMedia> savedMediaQueued = null;
    if (savedInstanceState != null) {
        showMarkSensitive = savedInstanceState.getBoolean("showMarkSensitive");
        startingVisibility = savedInstanceState.getString("statusVisibility");
        statusMarkSensitive = savedInstanceState.getBoolean("statusMarkSensitive");
        startingHideText = savedInstanceState.getBoolean("statusHideText");
        // Keep these until everything needed to put them in the queue is finished initializing.
        savedMediaQueued = savedInstanceState.getParcelableArrayList("savedMediaQueued");
        // These are for restoring an in-progress commit content operation.
        InputContentInfoCompat previousInputContentInfo = InputContentInfoCompat
                .wrap(savedInstanceState.getParcelable("commitContentInputContentInfo"));
        int previousFlags = savedInstanceState.getInt("commitContentFlags");
        if (previousInputContentInfo != null) {
            onCommitContentInternal(previousInputContentInfo, previousFlags);
        }
    } else {
        showMarkSensitive = false;
        startingVisibility = preferences.getString("rememberedVisibility", "public");
        statusMarkSensitive = false;
        startingHideText = false;
    }

    /* If the composer is started up as a reply to another post, override the "starting" state
     * based on what the intent from the reply request passes. */
    Intent intent = getIntent();

    String[] mentionedUsernames = null;
    inReplyToId = null;
    if (intent != null) {
        inReplyToId = intent.getStringExtra("in_reply_to_id");
        String replyVisibility = intent.getStringExtra("reply_visibility");

        if (replyVisibility != null && startingVisibility != null) {
            // Lowest possible visibility setting in response
            if (startingVisibility.equals("private") || replyVisibility.equals("private")) {
                startingVisibility = "private";
            } else if (startingVisibility.equals("unlisted") || replyVisibility.equals("unlisted")) {
                startingVisibility = "unlisted";
            } else {
                startingVisibility = replyVisibility;
            }
        }

        mentionedUsernames = intent.getStringArrayExtra("mentioned_usernames");

        if (inReplyToId != null) {
            startingHideText = !intent.getStringExtra("content_warning").equals("");
            if (startingHideText) {
                startingContentWarning = intent.getStringExtra("content_warning");
            }
        }
    }

    /* If the currently logged in account is locked, its posts should default to private. This
     * should override even the reply settings, so this must be done after those are set up. */
    if (preferences.getBoolean("loggedInAccountLocked", false)) {
        startingVisibility = "private";
    }

    // After the starting state is finalised, the interface can be set to reflect this state.
    setStatusVisibility(startingVisibility);
    postProgress.setVisibility(View.INVISIBLE);
    updateNsfwButtonColor();

    // Setup the main text field.
    setEditTextMimeTypes(null); // new String[] { "image/gif", "image/webp" }
    final int mentionColour = ThemeUtils.getColor(this, R.attr.compose_mention_color);
    SpanUtils.highlightSpans(textEditor.getText(), mentionColour);
    textEditor.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            updateVisibleCharactersLeft();
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            SpanUtils.highlightSpans(editable, mentionColour);
        }
    });

    // Add any mentions to the text field when a reply is first composed.
    if (mentionedUsernames != null) {
        StringBuilder builder = new StringBuilder();
        for (String name : mentionedUsernames) {
            builder.append('@');
            builder.append(name);
            builder.append(' ');
        }
        textEditor.setText(builder);
        textEditor.setSelection(textEditor.length());
    }

    // Initialise the content warning editor.
    contentWarningEditor.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            updateVisibleCharactersLeft();
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });
    showContentWarning(startingHideText);
    if (startingContentWarning != null) {
        contentWarningEditor.setText(startingContentWarning);
    }

    // Initialise the empty media queue state.
    mediaQueued = new ArrayList<>();
    waitForMediaLatch = new CountUpDownLatch();
    statusAlreadyInFlight = false;

    // These can only be added after everything affected by the media queue is initialized.
    if (savedMediaQueued != null) {
        for (SavedQueuedMedia item : savedMediaQueued) {
            addMediaToQueue(item.type, item.preview, item.uri, item.mediaSize);
        }
    } else if (intent != null && savedInstanceState == null) {
        /* Get incoming images being sent through a share action from another app. Only do this
         * when savedInstanceState is null, otherwise both the images from the intent and the
         * instance state will be re-queued. */
        String type = intent.getType();
        if (type != null) {
            if (type.startsWith("image/")) {
                List<Uri> uriList = new ArrayList<>();
                switch (intent.getAction()) {
                case Intent.ACTION_SEND: {
                    Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
                    if (uri != null) {
                        uriList.add(uri);
                    }
                    break;
                }
                case Intent.ACTION_SEND_MULTIPLE: {
                    ArrayList<Uri> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
                    if (list != null) {
                        for (Uri uri : list) {
                            if (uri != null) {
                                uriList.add(uri);
                            }
                        }
                    }
                    break;
                }
                }
                for (Uri uri : uriList) {
                    long mediaSize = getMediaSize(getContentResolver(), uri);
                    pickMedia(uri, mediaSize);
                }
            } else if (type.equals("text/plain")) {
                String action = intent.getAction();
                if (action != null && action.equals(Intent.ACTION_SEND)) {
                    String text = intent.getStringExtra(Intent.EXTRA_TEXT);
                    if (text != null) {
                        int start = Math.max(textEditor.getSelectionStart(), 0);
                        int end = Math.max(textEditor.getSelectionEnd(), 0);
                        int left = Math.min(start, end);
                        int right = Math.max(start, end);
                        textEditor.getText().replace(left, right, text, 0, text.length());
                    }
                }
            }
        }
    }
}

From source file:net.maa123.tatuky.ComposeActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_compose);
    ButterKnife.bind(this);

    // Setup the toolbar.
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);/*from   w  w  w.  ja v  a2 s.c  om*/
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setTitle(null);
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setDisplayShowHomeEnabled(true);
        Drawable closeIcon = AppCompatResources.getDrawable(this, R.drawable.ic_close_24dp);
        ThemeUtils.setDrawableTint(this, closeIcon, R.attr.compose_close_button_tint);
        actionBar.setHomeAsUpIndicator(closeIcon);
    }

    // Setup the interface buttons.
    floatingBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onSendClicked();
        }
    });
    pickBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onMediaPick();
        }
    });
    takeBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            initiateCameraApp();
        }
    });
    nsfwBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            toggleNsfw();
        }
    });
    visibilityBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showComposeOptions();
        }
    });

    /* Initialise all the state, or restore it from a previous run, to determine a "starting"
     * state. */
    SharedPreferences preferences = getPrivatePreferences();

    String startingVisibility;
    boolean startingHideText;
    String startingContentWarning = null;
    ArrayList<SavedQueuedMedia> savedMediaQueued = null;
    if (savedInstanceState != null) {
        showMarkSensitive = savedInstanceState.getBoolean("showMarkSensitive");
        startingVisibility = savedInstanceState.getString("statusVisibility");
        statusMarkSensitive = savedInstanceState.getBoolean("statusMarkSensitive");
        startingHideText = savedInstanceState.getBoolean("statusHideText");
        // Keep these until everything needed to put them in the queue is finished initializing.
        savedMediaQueued = savedInstanceState.getParcelableArrayList("savedMediaQueued");
        // These are for restoring an in-progress commit content operation.
        InputContentInfoCompat previousInputContentInfo = InputContentInfoCompat
                .wrap(savedInstanceState.getParcelable("commitContentInputContentInfo"));
        int previousFlags = savedInstanceState.getInt("commitContentFlags");
        if (previousInputContentInfo != null) {
            onCommitContentInternal(previousInputContentInfo, previousFlags);
        }
    } else {
        showMarkSensitive = false;
        startingVisibility = preferences.getString("rememberedVisibility", "public");
        statusMarkSensitive = false;
        startingHideText = false;
    }

    /* If the composer is started up as a reply to another post, override the "starting" state
     * based on what the intent from the reply request passes. */
    Intent intent = getIntent();

    String[] mentionedUsernames = null;
    inReplyToId = null;
    if (intent != null) {
        inReplyToId = intent.getStringExtra("in_reply_to_id");
        String replyVisibility = intent.getStringExtra("reply_visibility");

        if (replyVisibility != null && startingVisibility != null) {
            // Lowest possible visibility setting in response
            if (startingVisibility.equals("direct") || replyVisibility.equals("direct")) {
                startingVisibility = "direct";
            } else if (startingVisibility.equals("private") || replyVisibility.equals("private")) {
                startingVisibility = "private";
            } else if (startingVisibility.equals("unlisted") || replyVisibility.equals("unlisted")) {
                startingVisibility = "unlisted";
            } else {
                startingVisibility = replyVisibility;
            }
        }

        mentionedUsernames = intent.getStringArrayExtra("mentioned_usernames");

        if (inReplyToId != null) {
            startingHideText = !intent.getStringExtra("content_warning").equals("");
            if (startingHideText) {
                startingContentWarning = intent.getStringExtra("content_warning");
            }
        }
    }

    /* If the currently logged in account is locked, its posts should default to private. This
     * should override even the reply settings, so this must be done after those are set up. */
    if (preferences.getBoolean("loggedInAccountLocked", false)) {
        startingVisibility = "private";
    }

    // After the starting state is finalised, the interface can be set to reflect this state.
    setStatusVisibility(startingVisibility);
    postProgress.setVisibility(View.INVISIBLE);
    updateNsfwButtonColor();

    // Setup the main text field.
    setEditTextMimeTypes(null); // new String[] { "image/gif", "image/webp" }
    final int mentionColour = ThemeUtils.getColor(this, R.attr.compose_mention_color);
    SpanUtils.highlightSpans(textEditor.getText(), mentionColour);
    textEditor.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            updateVisibleCharactersLeft();
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            SpanUtils.highlightSpans(editable, mentionColour);
        }
    });

    // Add any mentions to the text field when a reply is first composed.
    if (mentionedUsernames != null) {
        StringBuilder builder = new StringBuilder();
        for (String name : mentionedUsernames) {
            builder.append('@');
            builder.append(name);
            builder.append(' ');
        }
        textEditor.setText(builder);
        textEditor.setSelection(textEditor.length());
    }

    // Initialise the content warning editor.
    contentWarningEditor.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            updateVisibleCharactersLeft();
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });
    showContentWarning(startingHideText);
    if (startingContentWarning != null) {
        contentWarningEditor.setText(startingContentWarning);
    }

    // Initialise the empty media queue state.
    mediaQueued = new ArrayList<>();
    waitForMediaLatch = new CountUpDownLatch();
    statusAlreadyInFlight = false;

    // These can only be added after everything affected by the media queue is initialized.
    if (savedMediaQueued != null) {
        for (SavedQueuedMedia item : savedMediaQueued) {
            addMediaToQueue(item.type, item.preview, item.uri, item.mediaSize);
        }
    } else if (intent != null && savedInstanceState == null) {
        /* Get incoming images being sent through a share action from another app. Only do this
         * when savedInstanceState is null, otherwise both the images from the intent and the
         * instance state will be re-queued. */
        String type = intent.getType();
        if (type != null) {
            if (type.startsWith("image/")) {
                List<Uri> uriList = new ArrayList<>();
                switch (intent.getAction()) {
                case Intent.ACTION_SEND: {
                    Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
                    if (uri != null) {
                        uriList.add(uri);
                    }
                    break;
                }
                case Intent.ACTION_SEND_MULTIPLE: {
                    ArrayList<Uri> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
                    if (list != null) {
                        for (Uri uri : list) {
                            if (uri != null) {
                                uriList.add(uri);
                            }
                        }
                    }
                    break;
                }
                }
                for (Uri uri : uriList) {
                    long mediaSize = getMediaSize(getContentResolver(), uri);
                    pickMedia(uri, mediaSize);
                }
            } else if (type.equals("text/plain")) {
                String action = intent.getAction();
                if (action != null && action.equals(Intent.ACTION_SEND)) {
                    String text = intent.getStringExtra(Intent.EXTRA_TEXT);
                    if (text != null) {
                        int start = Math.max(textEditor.getSelectionStart(), 0);
                        int end = Math.max(textEditor.getSelectionEnd(), 0);
                        int left = Math.min(start, end);
                        int right = Math.max(start, end);
                        textEditor.getText().replace(left, right, text, 0, text.length());
                    }
                }
            }
        }
    }
}

From source file:com.if3games.chessonline.DroidFish.java

/**
 * Return PGN/FEN data or filename from the Intent. Both can not be non-null.
 * @return Pair of PGN/FEN data and filename.
 *///from w  ww .  j  av  a  2  s  .c  o  m
private final Pair<String, String> getPgnOrFenIntent() {
    String pgnOrFen = null;
    String filename = null;
    try {
        Intent intent = getIntent();
        Uri data = intent.getData();
        if (data == null) {
            Bundle b = intent.getExtras();
            if (b != null) {
                Object strm = b.get(Intent.EXTRA_STREAM);
                if (strm instanceof Uri) {
                    data = (Uri) strm;
                    if ("file".equals(data.getScheme())) {
                        filename = data.getEncodedPath();
                        if (filename != null)
                            filename = Uri.decode(filename);
                    }
                }
            }
        }
        if (data == null) {
            if ((Intent.ACTION_SEND.equals(intent.getAction()) || Intent.ACTION_VIEW.equals(intent.getAction()))
                    && ("application/x-chess-pgn".equals(intent.getType())
                            || "application/x-chess-fen".equals(intent.getType())))
                pgnOrFen = intent.getStringExtra(Intent.EXTRA_TEXT);
        } else {
            String scheme = intent.getScheme();
            if ("file".equals(scheme)) {
                filename = data.getEncodedPath();
                if (filename != null)
                    filename = Uri.decode(filename);
            }
            if ((filename == null) && ("content".equals(scheme) || "file".equals(scheme))) {
                ContentResolver resolver = getContentResolver();
                InputStream in = resolver.openInputStream(intent.getData());
                StringBuilder sb = new StringBuilder();
                while (true) {
                    byte[] buffer = new byte[16384];
                    int len = in.read(buffer);
                    if (len <= 0)
                        break;
                    sb.append(new String(buffer, 0, len));
                }
                pgnOrFen = sb.toString();
            }
        }
    } catch (IOException e) {
        Toast.makeText(getApplicationContext(), R.string.failed_to_read_pgn_data, Toast.LENGTH_SHORT).show();
    }
    return new Pair<String, String>(pgnOrFen, filename);
}

From source file:com.keylesspalace.tusky.ComposeActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    String theme = preferences.getString("appTheme", ThemeUtils.APP_THEME_DEFAULT);
    if (theme.equals("black")) {
        setTheme(R.style.TuskyDialogActivityBlackTheme);
    }//  w  w  w  . ja  va  2  s  .  co  m
    setContentView(R.layout.activity_compose);

    replyTextView = findViewById(R.id.composeReplyView);
    replyContentTextView = findViewById(R.id.composeReplyContentView);
    textEditor = findViewById(R.id.composeEditField);
    mediaPreviewBar = findViewById(R.id.compose_media_preview_bar);
    contentWarningBar = findViewById(R.id.composeContentWarningBar);
    contentWarningEditor = findViewById(R.id.composeContentWarningField);
    charactersLeft = findViewById(R.id.composeCharactersLeftView);
    tootButton = findViewById(R.id.composeTootButton);
    pickButton = findViewById(R.id.composeAddMediaButton);
    visibilityButton = findViewById(R.id.composeToggleVisibilityButton);
    contentWarningButton = findViewById(R.id.composeContentWarningButton);
    emojiButton = findViewById(R.id.composeEmojiButton);
    hideMediaToggle = findViewById(R.id.composeHideMediaButton);
    emojiView = findViewById(R.id.emojiView);
    emojiList = Collections.emptyList();

    saveTootHelper = new SaveTootHelper(database.tootDao(), this);

    // Setup the toolbar.
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setTitle(null);
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setDisplayShowHomeEnabled(true);
        Drawable closeIcon = AppCompatResources.getDrawable(this, R.drawable.ic_close_24dp);
        ThemeUtils.setDrawableTint(this, closeIcon, R.attr.compose_close_button_tint);
        actionBar.setHomeAsUpIndicator(closeIcon);
    }

    // setup the account image
    final AccountEntity activeAccount = accountManager.getActiveAccount();

    if (activeAccount != null) {
        ImageView composeAvatar = findViewById(R.id.composeAvatar);

        if (TextUtils.isEmpty(activeAccount.getProfilePictureUrl())) {
            composeAvatar.setImageResource(R.drawable.avatar_default);
        } else {
            Picasso.with(this).load(activeAccount.getProfilePictureUrl()).error(R.drawable.avatar_default)
                    .placeholder(R.drawable.avatar_default).into(composeAvatar);
        }

        composeAvatar.setContentDescription(
                getString(R.string.compose_active_account_description, activeAccount.getFullName()));

        mastodonApi.getInstance().enqueue(new Callback<Instance>() {
            @Override
            public void onResponse(@NonNull Call<Instance> call, @NonNull Response<Instance> response) {
                if (response.isSuccessful() && response.body().getMaxTootChars() != null) {
                    maximumTootCharacters = response.body().getMaxTootChars();
                    updateVisibleCharactersLeft();
                    cacheInstanceMetadata(activeAccount);
                }
            }

            @Override
            public void onFailure(@NonNull Call<Instance> call, @NonNull Throwable t) {
                Log.w(TAG, "error loading instance data", t);
                loadCachedInstanceMetadata(activeAccount);
            }
        });

        mastodonApi.getCustomEmojis().enqueue(new Callback<List<Emoji>>() {
            @Override
            public void onResponse(@NonNull Call<List<Emoji>> call, @NonNull Response<List<Emoji>> response) {
                emojiList = response.body();
                setEmojiList(emojiList);
                cacheInstanceMetadata(activeAccount);
            }

            @Override
            public void onFailure(@NonNull Call<List<Emoji>> call, @NonNull Throwable t) {
                Log.w(TAG, "error loading custom emojis", t);
                loadCachedInstanceMetadata(activeAccount);
            }
        });
    } else {
        // do not do anything when not logged in, activity will be finished in super.onCreate() anyway
        return;
    }

    composeOptionsView = findViewById(R.id.composeOptionsBottomSheet);
    composeOptionsView.setListener(this);

    composeOptionsBehavior = BottomSheetBehavior.from(composeOptionsView);
    composeOptionsBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);

    addMediaBehavior = BottomSheetBehavior.from(findViewById(R.id.addMediaBottomSheet));

    emojiBehavior = BottomSheetBehavior.from(emojiView);

    emojiView.setLayoutManager(new GridLayoutManager(this, 3, GridLayoutManager.HORIZONTAL, false));

    enableButton(emojiButton, false, false);

    // Setup the interface buttons.
    tootButton.setOnClickListener(v -> onSendClicked());
    pickButton.setOnClickListener(v -> openPickDialog());
    visibilityButton.setOnClickListener(v -> showComposeOptions());
    contentWarningButton.setOnClickListener(v -> onContentWarningChanged());
    emojiButton.setOnClickListener(v -> showEmojis());
    hideMediaToggle.setOnClickListener(v -> toggleHideMedia());

    TextView actionPhotoTake = findViewById(R.id.action_photo_take);
    TextView actionPhotoPick = findViewById(R.id.action_photo_pick);

    int textColor = ThemeUtils.getColor(this, android.R.attr.textColorTertiary);

    Drawable cameraIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_camera_alt).color(textColor)
            .sizeDp(18);
    TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(actionPhotoTake, cameraIcon, null, null,
            null);

    Drawable imageIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_image).color(textColor).sizeDp(18);
    TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(actionPhotoPick, imageIcon, null, null,
            null);

    actionPhotoTake.setOnClickListener(v -> initiateCameraApp());
    actionPhotoPick.setOnClickListener(v -> onMediaPick());

    thumbnailViewSize = getResources().getDimensionPixelSize(R.dimen.compose_media_preview_size);

    /* Initialise all the state, or restore it from a previous run, to determine a "starting"
     * state. */
    Status.Visibility startingVisibility = Status.Visibility.UNKNOWN;
    boolean startingHideText;
    ArrayList<SavedQueuedMedia> savedMediaQueued = null;
    if (savedInstanceState != null) {
        startingVisibility = Status.Visibility
                .byNum(savedInstanceState.getInt("statusVisibility", Status.Visibility.PUBLIC.getNum()));
        statusMarkSensitive = savedInstanceState.getBoolean("statusMarkSensitive");
        startingHideText = savedInstanceState.getBoolean("statusHideText");
        // Keep these until everything needed to put them in the queue is finished initializing.
        savedMediaQueued = savedInstanceState.getParcelableArrayList("savedMediaQueued");
        // These are for restoring an in-progress commit content operation.
        InputContentInfoCompat previousInputContentInfo = InputContentInfoCompat
                .wrap(savedInstanceState.getParcelable("commitContentInputContentInfo"));
        int previousFlags = savedInstanceState.getInt("commitContentFlags");
        if (previousInputContentInfo != null) {
            onCommitContentInternal(previousInputContentInfo, previousFlags);
        }
        photoUploadUri = savedInstanceState.getParcelable("photoUploadUri");
    } else {
        statusMarkSensitive = false;
        startingHideText = false;
        photoUploadUri = null;
    }

    /* If the composer is started up as a reply to another post, override the "starting" state
     * based on what the intent from the reply request passes. */
    Intent intent = getIntent();

    String[] mentionedUsernames = null;
    ArrayList<String> loadedDraftMediaUris = null;
    inReplyToId = null;
    if (intent != null) {

        if (startingVisibility == Status.Visibility.UNKNOWN) {
            Status.Visibility preferredVisibility = Status.Visibility.byString(
                    preferences.getString("defaultPostPrivacy", Status.Visibility.PUBLIC.serverString()));
            Status.Visibility replyVisibility = Status.Visibility
                    .byNum(intent.getIntExtra(REPLY_VISIBILITY_EXTRA, Status.Visibility.UNKNOWN.getNum()));

            startingVisibility = Status.Visibility
                    .byNum(Math.max(preferredVisibility.getNum(), replyVisibility.getNum()));
        }

        inReplyToId = intent.getStringExtra(IN_REPLY_TO_ID_EXTRA);

        mentionedUsernames = intent.getStringArrayExtra(MENTIONED_USERNAMES_EXTRA);

        String contentWarning = intent.getStringExtra(CONTENT_WARNING_EXTRA);
        if (contentWarning != null) {
            startingHideText = !contentWarning.isEmpty();
            if (startingHideText) {
                startingContentWarning = contentWarning;
            }
        }

        // If come from SavedTootActivity
        String savedTootText = intent.getStringExtra(SAVED_TOOT_TEXT_EXTRA);
        if (!TextUtils.isEmpty(savedTootText)) {
            startingText = savedTootText;
            textEditor.setText(savedTootText);
        }

        String savedJsonUrls = intent.getStringExtra(SAVED_JSON_URLS_EXTRA);
        if (!TextUtils.isEmpty(savedJsonUrls)) {
            // try to redo a list of media
            loadedDraftMediaUris = new Gson().fromJson(savedJsonUrls, new TypeToken<ArrayList<String>>() {
            }.getType());
        }

        int savedTootUid = intent.getIntExtra(SAVED_TOOT_UID_EXTRA, 0);
        if (savedTootUid != 0) {
            this.savedTootUid = savedTootUid;
        }

        if (intent.hasExtra(REPLYING_STATUS_AUTHOR_USERNAME_EXTRA)) {
            replyTextView.setVisibility(View.VISIBLE);
            String username = intent.getStringExtra(REPLYING_STATUS_AUTHOR_USERNAME_EXTRA);
            replyTextView.setText(getString(R.string.replying_to, username));
            Drawable arrowDownIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_arrow_drop_down)
                    .sizeDp(12);

            ThemeUtils.setDrawableTint(this, arrowDownIcon, android.R.attr.textColorTertiary);
            TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(replyTextView, null, null,
                    arrowDownIcon, null);

            replyTextView.setOnClickListener(v -> {
                TransitionManager.beginDelayedTransition((ViewGroup) replyContentTextView.getParent());

                if (replyContentTextView.getVisibility() != View.VISIBLE) {
                    replyContentTextView.setVisibility(View.VISIBLE);
                    Drawable arrowUpIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_arrow_drop_up)
                            .sizeDp(12);

                    ThemeUtils.setDrawableTint(this, arrowUpIcon, android.R.attr.textColorTertiary);
                    TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(replyTextView, null, null,
                            arrowUpIcon, null);
                } else {
                    replyContentTextView.setVisibility(View.GONE);

                    TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(replyTextView, null, null,
                            arrowDownIcon, null);
                }
            });
        }

        if (intent.hasExtra(REPLYING_STATUS_CONTENT_EXTRA)) {
            replyContentTextView.setText(intent.getStringExtra(REPLYING_STATUS_CONTENT_EXTRA));
        }
    }

    // After the starting state is finalised, the interface can be set to reflect this state.
    setStatusVisibility(startingVisibility);

    updateHideMediaToggle();
    updateVisibleCharactersLeft();

    // Setup the main text field.
    textEditor.setOnCommitContentListener(this);
    final int mentionColour = textEditor.getLinkTextColors().getDefaultColor();
    SpanUtilsKt.highlightSpans(textEditor.getText(), mentionColour);
    textEditor.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            SpanUtilsKt.highlightSpans(editable, mentionColour);
            updateVisibleCharactersLeft();
        }
    });

    textEditor.setAdapter(new MentionAutoCompleteAdapter(this, R.layout.item_autocomplete, this));
    textEditor.setTokenizer(new MentionTokenizer());

    // Add any mentions to the text field when a reply is first composed.
    if (mentionedUsernames != null) {
        StringBuilder builder = new StringBuilder();
        for (String name : mentionedUsernames) {
            builder.append('@');
            builder.append(name);
            builder.append(' ');
        }
        startingText = builder.toString();
        textEditor.setText(startingText);
        textEditor.setSelection(textEditor.length());
    }

    // work around Android platform bug -> https://issuetracker.google.com/issues/67102093
    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O || Build.VERSION.SDK_INT == Build.VERSION_CODES.O_MR1) {
        textEditor.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    // Initialise the content warning editor.
    contentWarningEditor.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            updateVisibleCharactersLeft();
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });
    showContentWarning(startingHideText);
    if (startingContentWarning != null) {
        contentWarningEditor.setText(startingContentWarning);
    }

    // Initialise the empty media queue state.
    waitForMediaLatch = new CountUpDownLatch();

    // These can only be added after everything affected by the media queue is initialized.
    if (!ListUtils.isEmpty(loadedDraftMediaUris)) {
        for (String uriString : loadedDraftMediaUris) {
            Uri uri = Uri.parse(uriString);
            long mediaSize = MediaUtils.getMediaSize(getContentResolver(), uri);
            pickMedia(uri, mediaSize);
        }
    } else if (savedMediaQueued != null) {
        for (SavedQueuedMedia item : savedMediaQueued) {
            Bitmap preview = MediaUtils.getImageThumbnail(getContentResolver(), item.uri, thumbnailViewSize);
            addMediaToQueue(item.id, item.type, preview, item.uri, item.mediaSize, item.readyStage,
                    item.description);
        }
    } else if (intent != null && savedInstanceState == null) {
        /* Get incoming images being sent through a share action from another app. Only do this
         * when savedInstanceState is null, otherwise both the images from the intent and the
         * instance state will be re-queued. */
        String type = intent.getType();
        if (type != null) {
            if (type.startsWith("image/")) {
                List<Uri> uriList = new ArrayList<>();
                if (intent.getAction() != null) {
                    switch (intent.getAction()) {
                    case Intent.ACTION_SEND: {
                        Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
                        if (uri != null) {
                            uriList.add(uri);
                        }
                        break;
                    }
                    case Intent.ACTION_SEND_MULTIPLE: {
                        ArrayList<Uri> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
                        if (list != null) {
                            for (Uri uri : list) {
                                if (uri != null) {
                                    uriList.add(uri);
                                }
                            }
                        }
                        break;
                    }
                    }
                }
                for (Uri uri : uriList) {
                    long mediaSize = MediaUtils.getMediaSize(getContentResolver(), uri);
                    pickMedia(uri, mediaSize);
                }
            } else if (type.equals("text/plain")) {
                String action = intent.getAction();
                if (action != null && action.equals(Intent.ACTION_SEND)) {
                    String text = intent.getStringExtra(Intent.EXTRA_TEXT);
                    if (text != null) {
                        int start = Math.max(textEditor.getSelectionStart(), 0);
                        int end = Math.max(textEditor.getSelectionEnd(), 0);
                        int left = Math.min(start, end);
                        int right = Math.max(start, end);
                        textEditor.getText().replace(left, right, text, 0, text.length());
                    }
                }
            }
        }
    }

    textEditor.requestFocus();
}

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//w ww  .  j a  v a 2 s . co  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);
}