Example usage for android.text.format DateUtils getRelativeTimeSpanString

List of usage examples for android.text.format DateUtils getRelativeTimeSpanString

Introduction

In this page you can find the example usage for android.text.format DateUtils getRelativeTimeSpanString.

Prototype

public static CharSequence getRelativeTimeSpanString(Context c, long millis, boolean withPreposition) 

Source Link

Usage

From source file:de.geeksfactory.opacclient.frontend.MainPreferenceFragment.java

private void refreshLastConfigUpdate(Preference updateLibraryConfig) {
    DateTime lastUpdate = new PreferenceDataSource(context).getLastLibraryConfigUpdate();
    if (lastUpdate != null) {
        CharSequence lastUpdateStr = DateUtils.getRelativeTimeSpanString(context, lastUpdate.getMillis(), true);
        updateLibraryConfig.setSummary(getString(R.string.library_config_last_update, lastUpdateStr));
    } else {/*from  w  w w.j av  a 2 s  . com*/
        updateLibraryConfig.setSummary(getString(R.string.library_config_last_update_never));
    }
}

From source file:org.mariotaku.twidere.fragment.support.card.CardPollFragment.java

private void displayPoll(final ParcelableCardEntity card, final ParcelableStatus status) {
    if (card == null || status == null)
        return;//from w  w  w  . j  a va  2s. c o m
    mCard = card;
    final int choicesCount = getChoicesCount(card);
    int votesSum = 0;
    final boolean countsAreFinal = card.getAsBoolean("counts_are_final", false);
    final int selectedChoice = card.getAsInteger("selected_choice", -1);
    final Date endDatetimeUtc = card.getAsDate("end_datetime_utc", new Date());
    final boolean hasChoice = selectedChoice != -1;
    final boolean isMyPoll = status.account_id == status.user_id;
    final boolean showResult = countsAreFinal || isMyPoll || hasChoice;
    for (int i = 0; i < choicesCount; i++) {
        final int choiceIndex = i + 1;
        votesSum += card.getAsInteger("choice" + choiceIndex + "_count", 0);
    }

    final View.OnClickListener clickListener = new View.OnClickListener() {
        private boolean clickedChoice;

        @Override
        public void onClick(View v) {
            if (hasChoice || clickedChoice)
                return;
            for (int i = 0, j = mPollContainer.getChildCount(); i < j; i++) {
                final View pollItem = mPollContainer.getChildAt(i);
                pollItem.setClickable(false);
                clickedChoice = true;
                final RadioButton choiceRadioButton = (RadioButton) pollItem.findViewById(R.id.choice_button);
                final boolean checked = v == pollItem;
                choiceRadioButton.setChecked(checked);
                if (checked) {
                    final CardDataMap cardData = new CardDataMap();
                    cardData.putLong("original_tweet_id", status.id);
                    cardData.putString("card_uri", card.url);
                    cardData.putString("cards_platform", TwitterAPIFactory.CARDS_PLATFORM_ANDROID_12);
                    cardData.putString("response_card_name", card.name);
                    cardData.putString("selected_choice", String.valueOf(i + 1));
                    TaskRunnable<CardDataMap, ParcelableCardEntity, CardPollFragment> task = new TaskRunnable<CardDataMap, ParcelableCardEntity, CardPollFragment>() {

                        @Override
                        public void callback(CardPollFragment handler, ParcelableCardEntity result) {
                            handler.displayPoll(result, status);
                        }

                        @Override
                        public ParcelableCardEntity doLongOperation(CardDataMap cardDataMap)
                                throws InterruptedException {
                            final TwitterCaps caps = TwitterAPIFactory.getTwitterInstance(getContext(),
                                    card.account_id, true, true, TwitterCaps.class);
                            if (caps == null)
                                return null;
                            try {
                                final CardEntity cardEntity = caps.sendPassThrough(cardDataMap).getCard();
                                return ParcelableCardEntity.fromCardEntity(cardEntity, card.account_id);
                            } catch (TwitterException e) {
                                Log.w(LOGTAG, e);
                            }
                            return null;
                        }
                    };
                    task.setParams(cardData);
                    AsyncManager.runBackgroundTask(task);
                }
            }
        }
    };

    final int color = ContextCompat.getColor(getContext(), R.color.material_light_blue_a200);
    final float radius = getResources().getDimension(R.dimen.element_spacing_small);
    for (int i = 0; i < choicesCount; i++) {
        final View pollItem = mPollContainer.getChildAt(i);

        final TextView choicePercentView = (TextView) pollItem.findViewById(R.id.choice_percent);
        final TextView choiceLabelView = (TextView) pollItem.findViewById(R.id.choice_label);
        final RadioButton choiceRadioButton = (RadioButton) pollItem.findViewById(R.id.choice_button);

        final int choiceIndex = i + 1;
        final String label = card.getAsString("choice" + choiceIndex + "_label", null);
        final int value = card.getAsInteger("choice" + choiceIndex + "_count", 0);
        if (label == null)
            throw new NullPointerException();
        final float choicePercent = votesSum == 0 ? 0 : value / (float) votesSum;
        choiceLabelView.setText(label);
        choicePercentView.setText(String.format("%d%%", Math.round(choicePercent * 100)));

        pollItem.setOnClickListener(clickListener);

        final boolean isSelected = selectedChoice == choiceIndex;

        if (showResult) {
            choicePercentView.setVisibility(View.VISIBLE);
            choiceRadioButton.setVisibility(hasChoice && isSelected ? View.VISIBLE : View.INVISIBLE);
            ViewSupport.setBackground(choiceLabelView, new PercentDrawable(choicePercent, radius, color));
        } else {
            choicePercentView.setVisibility(View.GONE);
            choiceRadioButton.setVisibility(View.VISIBLE);
            ViewSupport.setBackground(choiceLabelView, null);
        }

        choiceRadioButton.setChecked(isSelected);
        pollItem.setClickable(selectedChoice == -1);

    }

    final String nVotes = getResources().getQuantityString(R.plurals.N_votes, votesSum, votesSum);

    final CharSequence timeLeft = DateUtils.getRelativeTimeSpanString(getContext(), endDatetimeUtc.getTime(),
            true);
    mPollSummary.setText(getString(R.string.poll_summary_format, nVotes, timeLeft));
}

From source file:io.plaidapp.ui.DribbbleShot.java

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dribbble_shot);
    shot = getIntent().getParcelableExtra(EXTRA_SHOT);
    setupDribbble();//from   w ww  . j av  a 2  s  . co m
    setExitSharedElementCallback(fabLoginSharedElementCallback);
    getWindow().getSharedElementReturnTransition().addListener(shotReturnHomeListener);
    circleTransform = new CircleTransform(this);
    Resources res = getResources();

    ButterKnife.bind(this);
    View shotDescription = getLayoutInflater().inflate(R.layout.dribbble_shot_description, commentsList, false);
    shotSpacer = shotDescription.findViewById(R.id.shot_spacer);
    title = shotDescription.findViewById(R.id.shot_title);
    description = shotDescription.findViewById(R.id.shot_description);
    shotActions = (LinearLayout) shotDescription.findViewById(R.id.shot_actions);
    likeCount = (Button) shotDescription.findViewById(R.id.shot_like_count);
    viewCount = (Button) shotDescription.findViewById(R.id.shot_view_count);
    share = (Button) shotDescription.findViewById(R.id.shot_share_action);
    playerName = (TextView) shotDescription.findViewById(R.id.player_name);
    playerAvatar = (ImageView) shotDescription.findViewById(R.id.player_avatar);
    shotTimeAgo = (TextView) shotDescription.findViewById(R.id.shot_time_ago);
    commentsList = (ListView) findViewById(R.id.dribbble_comments);
    commentsList.addHeaderView(shotDescription);
    setupCommenting();
    commentsList.setOnScrollListener(scrollListener);
    back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            expandImageAndFinish();
        }
    });
    fab.setOnClickListener(fabClick);
    chromeFader = new ElasticDragDismissFrameLayout.SystemChromeFader(getWindow()) {
        @Override
        public void onDragDismissed() {
            expandImageAndFinish();
        }
    };

    // load the main image
    final int[] imageSize = shot.images.bestSize();
    Glide.with(this).load(shot.images.best()).listener(shotLoadListener)
            .diskCacheStrategy(DiskCacheStrategy.SOURCE).priority(Priority.IMMEDIATE)
            .override(imageSize[0], imageSize[1]).into(imageView);
    imageView.setOnClickListener(shotClick);
    shotSpacer.setOnClickListener(shotClick);

    postponeEnterTransition();
    imageView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        @Override
        public boolean onPreDraw() {
            imageView.getViewTreeObserver().removeOnPreDrawListener(this);
            calculateFabPosition();
            enterAnimation(savedInstanceState != null);
            startPostponedEnterTransition();
            return true;
        }
    });

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        ((FabOverlapTextView) title).setText(shot.title);
    } else {
        ((TextView) title).setText(shot.title);
    }
    if (!TextUtils.isEmpty(shot.description)) {
        final Spanned descText = shot.getParsedDescription(
                ContextCompat.getColorStateList(this, R.color.dribbble_links),
                ContextCompat.getColor(this, R.color.dribbble_link_highlight));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ((FabOverlapTextView) description).setText(descText);
        } else {
            HtmlUtils.setTextWithNiceLinks((TextView) description, descText);
        }
    } else {
        description.setVisibility(View.GONE);
    }
    NumberFormat nf = NumberFormat.getInstance();
    likeCount.setText(
            res.getQuantityString(R.plurals.likes, (int) shot.likes_count, nf.format(shot.likes_count)));
    // TODO onClick show likes
    viewCount.setText(
            res.getQuantityString(R.plurals.views, (int) shot.views_count, nf.format(shot.views_count)));
    share.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new ShareDribbbleImageTask(DribbbleShot.this, shot).execute();
        }
    });
    if (shot.user != null) {
        playerName.setText("" + shot.user.name);
        Glide.with(this).load(shot.user.avatar_url).transform(circleTransform)
                .placeholder(R.drawable.avatar_placeholder).into(playerAvatar);
        playerAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DribbbleShot.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(shot.user.html_url)));
            }
        });
        if (shot.created_at != null) {
            shotTimeAgo.setText(DateUtils.getRelativeTimeSpanString(shot.created_at.getTime(),
                    System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS));
        }
    } else {
        playerName.setVisibility(View.GONE);
        playerAvatar.setVisibility(View.GONE);
        shotTimeAgo.setVisibility(View.GONE);
    }

    if (shot.comments_count > 0) {
        loadComments();
    } else {
        commentsList.setAdapter(getNoCommentsAdapter());
    }
}

From source file:org.mariotaku.twidere.fragment.card.CardPollFragment.java

private void displayPoll(final ParcelableCardEntity card, final ParcelableStatus status) {
    final Context context = getContext();
    if (card == null || status == null || context == null)
        return;// w  ww. j ava 2s .c om
    mCard = card;
    final int choicesCount = getChoicesCount(card);
    int votesSum = 0;
    final boolean countsAreFinal = ParcelableCardEntityUtils.getAsBoolean(card, "counts_are_final", false);
    final int selectedChoice = ParcelableCardEntityUtils.getAsInteger(card, "selected_choice", -1);
    final Date endDatetimeUtc = ParcelableCardEntityUtils.getAsDate(card, "end_datetime_utc", new Date());
    final boolean hasChoice = selectedChoice != -1;
    final boolean isMyPoll = status.account_key.equals(status.user_key);
    final boolean showResult = countsAreFinal || isMyPoll || hasChoice;
    for (int i = 0; i < choicesCount; i++) {
        final int choiceIndex = i + 1;
        votesSum += ParcelableCardEntityUtils.getAsInteger(card, "choice" + choiceIndex + "_count", 0);
    }

    final View.OnClickListener clickListener = new View.OnClickListener() {
        private boolean clickedChoice;

        @Override
        public void onClick(View v) {
            if (hasChoice || clickedChoice)
                return;
            for (int i = 0, j = mPollContainer.getChildCount(); i < j; i++) {
                final View pollItem = mPollContainer.getChildAt(i);
                pollItem.setClickable(false);
                clickedChoice = true;
                final RadioButton choiceRadioButton = (RadioButton) pollItem.findViewById(R.id.choice_button);
                final boolean checked = v == pollItem;
                choiceRadioButton.setChecked(checked);
                if (checked) {
                    final CardDataMap cardData = new CardDataMap();
                    cardData.putLong("original_tweet_id", NumberUtils.toLong(status.id));
                    cardData.putString("card_uri", card.url);
                    cardData.putString("cards_platform", MicroBlogAPIFactory.CARDS_PLATFORM_ANDROID_12);
                    cardData.putString("response_card_name", card.name);
                    cardData.putString("selected_choice", String.valueOf(i + 1));
                    AbstractTask<CardDataMap, ParcelableCardEntity, CardPollFragment> task = new AbstractTask<CardDataMap, ParcelableCardEntity, CardPollFragment>() {

                        @Override
                        public void afterExecute(CardPollFragment handler, ParcelableCardEntity result) {
                            handler.displayAndReloadPoll(result, status);
                        }

                        @Override
                        public ParcelableCardEntity doLongOperation(CardDataMap cardDataMap) {
                            final Context context = getContext();
                            if (context == null)
                                return null;
                            final TwitterCaps caps = MicroBlogAPIFactory.getInstance(context, card.account_key,
                                    true, true, TwitterCaps.class);
                            if (caps == null)
                                return null;
                            try {
                                final CardEntity cardEntity = caps.sendPassThrough(cardDataMap).getCard();
                                return ParcelableCardEntityUtils.fromCardEntity(cardEntity, card.account_key);
                            } catch (MicroBlogException e) {
                                Log.w(LOGTAG, e);
                            }
                            return null;
                        }
                    };
                    task.setResultHandler(CardPollFragment.this);
                    task.setParams(cardData);
                    TaskStarter.execute(task);
                }
            }
        }
    };

    final int color = ContextCompat.getColor(context, R.color.material_light_blue_a200);
    final float radius = getResources().getDimension(R.dimen.element_spacing_small);
    for (int i = 0; i < choicesCount; i++) {
        final View pollItem = mPollContainer.getChildAt(i);

        final TextView choicePercentView = (TextView) pollItem.findViewById(R.id.choice_percent);
        final TextView choiceLabelView = (TextView) pollItem.findViewById(R.id.choice_label);
        final RadioButton choiceRadioButton = (RadioButton) pollItem.findViewById(R.id.choice_button);

        final int choiceIndex = i + 1;
        final String label = ParcelableCardEntityUtils.getAsString(card, "choice" + choiceIndex + "_label",
                null);
        final int value = ParcelableCardEntityUtils.getAsInteger(card, "choice" + choiceIndex + "_count", 0);
        if (label == null)
            throw new NullPointerException();
        final float choicePercent = votesSum == 0 ? 0 : value / (float) votesSum;
        choiceLabelView.setText(label);
        choicePercentView.setText(String.format(Locale.US, "%d%%", Math.round(choicePercent * 100)));

        pollItem.setOnClickListener(clickListener);

        final boolean isSelected = selectedChoice == choiceIndex;

        if (showResult) {
            choicePercentView.setVisibility(View.VISIBLE);
            choiceRadioButton.setVisibility(hasChoice && isSelected ? View.VISIBLE : View.INVISIBLE);
            ViewSupport.setBackground(choiceLabelView, new PercentDrawable(choicePercent, radius, color));
        } else {
            choicePercentView.setVisibility(View.GONE);
            choiceRadioButton.setVisibility(View.VISIBLE);
            ViewSupport.setBackground(choiceLabelView, null);
        }

        choiceRadioButton.setChecked(isSelected);
        pollItem.setClickable(selectedChoice == -1);

    }

    final String nVotes = getResources().getQuantityString(R.plurals.N_votes, votesSum, votesSum);

    final CharSequence timeLeft = DateUtils.getRelativeTimeSpanString(context, endDatetimeUtc.getTime(), true);
    mPollSummary.setText(getString(R.string.poll_summary_format, nVotes, timeLeft));
}

From source file:com.numenta.core.service.DataSyncService.java

/**
 * This method is execute periodically and update {@link com.numenta.core.data.CoreDatabase}
 * with new data from the/*  w w w.j av a  2  s  .  com*/
 * server.
 */
protected void synchronizeWithServer() throws IOException {
    Log.i(TAG, "synchronizeWithServer");

    if (_synchronizingWithServer) {
        return;
    }
    if (!NetUtils.isConnected()) {
        // Not connected, skip until we connect
        return;
    }

    final CoreDatabase database = HTMApplication.getDatabase();
    if (database == null) {
        return;
    }
    synchronized (this) {
        if (_synchronizingWithServer) {
            return;
        }
        _synchronizingWithServer = true;
    }
    String result = null;
    try {
        // Guard against blocking the UI Thread
        if (Looper.myLooper() == Looper.getMainLooper()) {
            throw new IllegalStateException("You should not access the database from the UI thread");
        }

        fireRefreshStateEvent(_synchronizingWithServer);

        final Context context = _service.getApplicationContext();
        final long now = System.currentTimeMillis();

        // Check if enough time has passed since we checked for new data
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        final long lastConnectedTime = prefs.getLong(PREF_LAST_CONNECTED_TIME, 0);
        if (now - lastConnectedTime < DataUtils.METRIC_DATA_INTERVAL) {
            return;
        }

        // Calculate hours since last update. This information will be
        // passed to the user together with error message
        final CharSequence hoursSinceData = DateUtils.getRelativeTimeSpanString(database.getLastTimestamp(),
                now, DateUtils.MINUTE_IN_MILLIS);

        Future<?> pendingIO = null;
        try {
            // Try to connect to server
            if (_htmClient == null) {
                _htmClient = _service.connectToServer();
            }
            if (_htmClient == null) {
                throw new IOException("Unable to connect to server");
            }

            // Update last connected time
            SharedPreferences.Editor editor = prefs.edit();
            editor.putLong(PREF_LAST_CONNECTED_TIME, now);
            editor.apply();

            // Start by downloading all the metrics available from backend
            // in a background IO thread
            pendingIO = _service.getIOThreadPool().submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {

                    try {
                        // First load metrics
                        loadAllMetrics();

                        // Load all annotations after metrics
                        loadAllAnnotations();

                        // Load all data after annotations
                        loadAllData();

                        // Synchronize notifications after data
                        synchronizeNotifications();

                        // Synchronize application data last
                        HTMApplication.getInstance().loadApplicationData(_htmClient);

                    } catch (android.database.sqlite.SQLiteFullException e) {
                        // Try to delete old records to make room if possible
                        Log.e(TAG, "Failed to save data into database", e);
                        database.deleteOldRecords();
                    }
                    return null;
                }
            });
            // Wait for metric data to finish
            pendingIO.get();
        } catch (InterruptedException e) {
            // Cancel pending tasks
            if (!pendingIO.isDone()) {
                pendingIO.cancel(true);
            }
            Log.w(TAG, "Interrupted while loading data");
        } catch (ExecutionException e) {
            // Cancel pending tasks
            if (!pendingIO.isDone()) {
                pendingIO.cancel(true);
            }
            Throwable original = e.getCause();
            if (original instanceof AuthenticationException) {
                _service.fireAuthenticationFailedEvent();
            } else if (original instanceof ObjectNotFoundException) {
                Log.e(TAG, "Error loading data", e);
                result = context.getString(R.string.refresh_update_error, hoursSinceData);
            } else if (original instanceof IOException) {
                Log.e(TAG, "Unable to connect", e);
                result = context.getString(R.string.refresh_server_unreachable, hoursSinceData);
            } else {
                Log.e(TAG, "Error loading data", e);
                result = context.getString(R.string.refresh_update_error, hoursSinceData);
            }
        } catch (AuthenticationException e) {
            _service.fireAuthenticationFailedEvent();
        } catch (HTMException e) {
            Log.e(TAG, "Error loading data", e);
            result = context.getString(R.string.refresh_update_error, hoursSinceData);
        } catch (IOException e) {
            Log.e(TAG, "Unable to connect", e);
            result = context.getString(R.string.refresh_server_unreachable, hoursSinceData);
        }
    } finally {
        _synchronizingWithServer = false;
        fireRefreshStateEvent(_synchronizingWithServer, result);
    }
}

From source file:eu.inmite.apps.smsjizdenka.adapter.TicketsAdapter.java

private String getValidToText(int status, long date) {
    if (status == Tickets.STATUS_EXPIRED) {
        return DateUtils.getRelativeTimeSpanString(date, System.currentTimeMillis(), 0).toString();
    } else {/*from w w w. j  av a2s .c  o m*/
        return "";
    }
}

From source file:com.krayzk9s.imgurholo.tools.ImageUtils.java

public static void updateInfoFont(JSONParcelable imageData, TextView infoText) {
    try {/*from   w  w  w .  ja v a2s.  c o m*/
        String albumText = "";
        if (imageData.getJSONObject().has("is_album") && imageData.getJSONObject().getBoolean("is_album"))
            albumText = "[album] ";
        if (!imageData.getJSONObject().getString("section").equals("null"))
            albumText += "/r/" + imageData.getJSONObject().getString("section") + " " + Html.fromHtml("&#8226;")
                    + " ";
        Calendar calendar = Calendar.getInstance();
        long now = calendar.getTimeInMillis();
        infoText.setText(albumText
                + DateUtils.getRelativeTimeSpanString(imageData.getJSONObject().getLong("datetime") * 1000, now,
                        DateUtils.MINUTE_IN_MILLIS)
                + " " + Html.fromHtml("&#8226;") + " ");
    } catch (JSONException e) {
        Log.e("Error!", e.toString());
    }
}

From source file:org.chromium.chrome.browser.ntp.snippets.SnippetArticleViewHolder.java

public void onBindViewHolder(SnippetArticle article) {
    super.onBindViewHolder();

    mArticle = article;/*  w  w w . j  ava  2s. c o m*/
    updateLayout();

    mHeadlineTextView.setText(mArticle.mTitle);

    // DateUtils.getRelativeTimeSpanString(...) calls through to TimeZone.getDefault(). If this
    // has never been called before it loads the current time zone from disk. In most likelihood
    // this will have been called previously and the current time zone will have been cached,
    // but in some cases (eg instrumentation tests) it will cause a strict mode violation.
    StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
    try {
        long time = SystemClock.elapsedRealtime();
        CharSequence relativeTimeSpan = DateUtils.getRelativeTimeSpanString(
                mArticle.mPublishTimestampMilliseconds, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS);
        RecordHistogram.recordTimesHistogram("Android.StrictMode.SnippetUIBuildTime",
                SystemClock.elapsedRealtime() - time, TimeUnit.MILLISECONDS);

        // We format the publisher here so that having a publisher name in an RTL language
        // doesn't mess up the formatting on an LTR device and vice versa.
        String publisherAttribution = String.format(PUBLISHER_FORMAT_STRING,
                BidiFormatter.getInstance().unicodeWrap(mArticle.mPublisher), relativeTimeSpan);
        mPublisherTextView.setText(publisherAttribution);
    } finally {
        StrictMode.setThreadPolicy(oldPolicy);
    }

    // The favicon of the publisher should match the textview height.
    int widthSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
    int heightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
    mPublisherTextView.measure(widthSpec, heightSpec);
    mPublisherFaviconSizePx = mPublisherTextView.getMeasuredHeight();

    mArticleSnippetTextView.setText(mArticle.mPreviewText);

    // If there's still a pending thumbnail fetch, cancel it.
    cancelImageFetch();

    // If the article has a thumbnail already, reuse it. Otherwise start a fetch.
    // mThumbnailView's visibility is modified in updateLayout().
    if (mThumbnailView.getVisibility() == View.VISIBLE) {
        if (mArticle.getThumbnailBitmap() != null) {
            mThumbnailView.setImageBitmap(mArticle.getThumbnailBitmap());
        } else {
            mThumbnailView.setImageResource(R.drawable.ic_snippet_thumbnail_placeholder);
            mImageCallback = new FetchImageCallback(this, mArticle);
            mNewTabPageManager.getSuggestionsSource().fetchSuggestionImage(mArticle, mImageCallback);
        }
    }

    // Set the favicon of the publisher.
    try {
        fetchFaviconFromLocalCache(new URI(mArticle.mUrl), true);
    } catch (URISyntaxException e) {
        setDefaultFaviconOnView();
    }
}

From source file:io.plaidapp.ui.DribbbleShot.java

void bindShot(final boolean postponeEnterTransition) {
    final Resources res = getResources();

    // load the main image
    final int[] imageSize = shot.images.bestSize();
    Glide.with(this).load(shot.images.best()).listener(shotLoadListener)
            .diskCacheStrategy(DiskCacheStrategy.SOURCE).priority(Priority.IMMEDIATE)
            .override(imageSize[0], imageSize[1]).into(imageView);
    imageView.setOnClickListener(shotClick);
    shotSpacer.setOnClickListener(shotClick);

    if (postponeEnterTransition)
        postponeEnterTransition();//  www.  ja v a  2  s .c o m
    imageView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        @Override
        public boolean onPreDraw() {
            imageView.getViewTreeObserver().removeOnPreDrawListener(this);
            calculateFabPosition();
            if (postponeEnterTransition)
                startPostponedEnterTransition();
            return true;
        }
    });

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        ((FabOverlapTextView) title).setText(shot.title);
    } else {
        ((TextView) title).setText(shot.title);
    }
    if (!TextUtils.isEmpty(shot.description)) {
        final Spanned descText = shot.getParsedDescription(
                ContextCompat.getColorStateList(this, R.color.dribbble_links),
                ContextCompat.getColor(this, R.color.dribbble_link_highlight));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ((FabOverlapTextView) description).setText(descText);
        } else {
            HtmlUtils.setTextWithNiceLinks((TextView) description, descText);
        }
    } else {
        description.setVisibility(View.GONE);
    }
    NumberFormat nf = NumberFormat.getInstance();
    likeCount.setText(
            res.getQuantityString(R.plurals.likes, (int) shot.likes_count, nf.format(shot.likes_count)));
    likeCount.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ((AnimatedVectorDrawable) likeCount.getCompoundDrawables()[1]).start();
            if (shot.likes_count > 0) {
                PlayerSheet.start(DribbbleShot.this, shot);
            }
        }
    });
    if (shot.likes_count == 0) {
        likeCount.setBackground(null); // clear touch ripple if doesn't do anything
    }
    viewCount.setText(
            res.getQuantityString(R.plurals.views, (int) shot.views_count, nf.format(shot.views_count)));
    viewCount.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ((AnimatedVectorDrawable) viewCount.getCompoundDrawables()[1]).start();
        }
    });
    share.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ((AnimatedVectorDrawable) share.getCompoundDrawables()[1]).start();
            new ShareDribbbleImageTask(DribbbleShot.this, shot).execute();
        }
    });
    if (shot.user != null) {
        playerName.setText(shot.user.name.toLowerCase());
        Glide.with(this).load(shot.user.getHighQualityAvatarUrl()).transform(circleTransform)
                .placeholder(R.drawable.avatar_placeholder).override(largeAvatarSize, largeAvatarSize)
                .into(playerAvatar);
        View.OnClickListener playerClick = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent player = new Intent(DribbbleShot.this, PlayerActivity.class);
                if (shot.user.shots_count > 0) { // legit user object
                    player.putExtra(PlayerActivity.EXTRA_PLAYER, shot.user);
                } else {
                    // search doesn't fully populate the user object,
                    // in this case send the ID not the full user
                    player.putExtra(PlayerActivity.EXTRA_PLAYER_NAME, shot.user.username);
                    player.putExtra(PlayerActivity.EXTRA_PLAYER_ID, shot.user.id);
                }
                ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(DribbbleShot.this,
                        playerAvatar, getString(R.string.transition_player_avatar));
                startActivity(player, options.toBundle());
            }
        };
        playerAvatar.setOnClickListener(playerClick);
        playerName.setOnClickListener(playerClick);
        if (shot.created_at != null) {
            shotTimeAgo
                    .setText(
                            DateUtils
                                    .getRelativeTimeSpanString(shot.created_at.getTime(),
                                            System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS)
                                    .toString().toLowerCase());
        }
    } else {
        playerName.setVisibility(View.GONE);
        playerAvatar.setVisibility(View.GONE);
        shotTimeAgo.setVisibility(View.GONE);
    }

    commentAnimator = new CommentAnimator();
    commentsList.setItemAnimator(commentAnimator);
    adapter = new CommentsAdapter(shotDescription, commentFooter, shot.comments_count,
            getResources().getInteger(R.integer.comment_expand_collapse_duration));
    commentsList.setAdapter(adapter);
    commentsList.addItemDecoration(new InsetDividerDecoration(CommentViewHolder.class,
            res.getDimensionPixelSize(R.dimen.divider_height), res.getDimensionPixelSize(R.dimen.keyline_1),
            ContextCompat.getColor(this, R.color.divider)));
    if (shot.comments_count != 0) {
        loadComments();
    }
    checkLiked();
}

From source file:com.andrada.sitracker.ui.fragment.PublicationInfoFragment.java

private void updateRating() {
    String ratingString = currentRecord.getRating();
    if (!TextUtils.isEmpty(ratingString) && ratingString.split("\\*").length == 2) {
        float rating = Float.valueOf(ratingString.split("\\*")[0]);
        int ratingCount = Integer.valueOf(ratingString.split("\\*")[1]);
        mRatingContainer.setVisibility(View.VISIBLE);
        mPubRating.setText(String.valueOf(rating));
        mPubRatingCount.setText(String.valueOf(ratingCount));

        //Handle personal rating
        if (!TextUtils.isEmpty(currentRecord.getVoteCookie()) && currentRecord.getVoteDate() != null) {
            mRatingBar.setRating(currentRecord.getMyVote());
            mVotedOnField.setVisibility(View.VISIBLE);
            String formattedVoteDate = DateUtils
                    .getRelativeTimeSpanString(currentRecord.getVoteDate().getTime(), new Date().getTime(),
                            DateUtils.MINUTE_IN_MILLIS)
                    .toString();//from   ww  w. j  a v a2s . c  om
            mVotedOnField.setText(getString(R.string.publication_rating_vote_date, formattedVoteDate));
        } else {
            mRatingBar.setRating(rating);
            mVotedOnField.setVisibility(View.GONE);
        }
        mRatingVisible = true;

    } else {
        mRatingContainer.setVisibility(View.GONE);
        mRatingVisible = false;
    }
}