Java Code Examples for android.content.res.Resources#getQuantityString()

The following examples show how to use android.content.res.Resources#getQuantityString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Utils.java    From fdroidclient with GNU General Public License v3.0 6 votes vote down vote up
public static String formatLastUpdated(@NonNull Resources res, @NonNull Date date) {
    long msDiff = Calendar.getInstance().getTimeInMillis() - date.getTime();
    long days = msDiff / DateUtils.DAY_IN_MILLIS;
    long weeks = msDiff / (DateUtils.DAY_IN_MILLIS * 7);
    long months = msDiff / (DateUtils.DAY_IN_MILLIS * 30);
    long years = msDiff / (DateUtils.DAY_IN_MILLIS * 365);

    if (days < 1) {
        return res.getString(R.string.details_last_updated_today);
    } else if (weeks < 1) {
        return res.getQuantityString(R.plurals.details_last_update_days, (int) days, days);
    } else if (months < 1) {
        return res.getQuantityString(R.plurals.details_last_update_weeks, (int) weeks, weeks);
    } else if (years < 1) {
        return res.getQuantityString(R.plurals.details_last_update_months, (int) months, months);
    } else {
        return res.getQuantityString(R.plurals.details_last_update_years, (int) years, years);
    }
}
 
Example 2
Source File: RecentTabsGroupView.java    From 365browser with Apache License 2.0 6 votes vote down vote up
private CharSequence getTimeString(ForeignSession session) {
    long timeDeltaMs = System.currentTimeMillis() - session.modifiedTime;
    if (timeDeltaMs < 0) timeDeltaMs = 0;

    int daysElapsed = (int) (timeDeltaMs / (24L * 60L * 60L * 1000L));
    int hoursElapsed = (int) (timeDeltaMs / (60L * 60L * 1000L));
    int minutesElapsed = (int) (timeDeltaMs / (60L * 1000L));

    Resources res = getResources();
    String relativeTime;
    if (daysElapsed > 0L) {
        relativeTime = res.getQuantityString(R.plurals.n_days_ago, daysElapsed, daysElapsed);
    } else if (hoursElapsed > 0L) {
        relativeTime = res.getQuantityString(R.plurals.n_hours_ago, hoursElapsed, hoursElapsed);
    } else if (minutesElapsed > 0L) {
        relativeTime = res.getQuantityString(R.plurals.n_minutes_ago, minutesElapsed,
                minutesElapsed);
    } else {
        relativeTime = res.getString(R.string.just_now);
    }

    return getResources().getString(R.string.ntp_recent_tabs_last_synced, relativeTime);
}
 
Example 3
Source File: TimeFormat.java    From echo with GNU General Public License v3.0 6 votes vote down vote up
public static void naturalLanguage(Resources resources, float secondsF, Result outResult) {
    int seconds = (int) Math.floor(secondsF);
    int minutes = seconds / 60;
    seconds %= 60;

    String out = "";

    if(minutes != 0) {
        outResult.count = minutes;
        out += resources.getQuantityString(R.plurals.minute, minutes, minutes);

        if(seconds != 0) {
            out += resources.getString(R.string.minute_second_join);
            out += resources.getQuantityString(R.plurals.second, seconds, seconds);
        }
    } else {
        outResult.count = seconds;
        out += resources.getQuantityString(R.plurals.second, seconds, seconds);
    }

    outResult.text = out + ".";
}
 
Example 4
Source File: AbstractAveragingDeviceMonitor.java    From habpanelviewer with GNU General Public License v3.0 6 votes vote down vote up
protected synchronized void addStatusItems(ApplicationStatus status) {
    if (mSensorEnabled) {
        String state = mCtx.getString(R.string.enabled);
        if (mDoAverage) {
            Resources res = mCtx.getResources();
            state += "\n" + res.getQuantityString(R.plurals.updateInterval, mInterval, mInterval);
        }
        if (!mSensorItem.isEmpty()) {
            state += "\n" + getInfoString(mValue, mSensorItem, mSensorState);
        }

        status.set(mSensorName, state);
    } else {
        status.set(mSensorName, mCtx.getString(R.string.disabled));
    }
}
 
Example 5
Source File: RecentTabsGroupView.java    From delion with Apache License 2.0 6 votes vote down vote up
private CharSequence getTimeString(ForeignSession session) {
    long timeDeltaMs = System.currentTimeMillis() - session.modifiedTime;
    if (timeDeltaMs < 0) timeDeltaMs = 0;

    int daysElapsed = (int) (timeDeltaMs / (24L * 60L * 60L * 1000L));
    int hoursElapsed = (int) (timeDeltaMs / (60L * 60L * 1000L));
    int minutesElapsed = (int) (timeDeltaMs / (60L * 1000L));

    Resources res = getResources();
    String relativeTime;
    if (daysElapsed > 0L) {
        relativeTime = res.getQuantityString(R.plurals.n_days_ago, daysElapsed, daysElapsed);
    } else if (hoursElapsed > 0L) {
        relativeTime = res.getQuantityString(R.plurals.n_hours_ago, hoursElapsed, hoursElapsed);
    } else if (minutesElapsed > 0L) {
        relativeTime = res.getQuantityString(R.plurals.n_minutes_ago, minutesElapsed,
                minutesElapsed);
    } else {
        relativeTime = res.getString(R.string.just_now);
    }

    return getResources().getString(R.string.ntp_recent_tabs_last_synced, relativeTime);
}
 
Example 6
Source File: TweetDateUtils.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
/**
 * This method is not thread safe. It has been modified from the original to not rely on global
 * time state. If a timestamp is in the future we return it as an absolute date string. Within
 * the same second we return 0s
 *
 * @param res resource
 * @param currentTimeMillis timestamp for offset
 * @param timestamp timestamp
 * @return the relative time string
 */
static String getRelativeTimeString(Resources res, long currentTimeMillis, long timestamp) {
    final long diff = currentTimeMillis - timestamp;
    if (diff >= 0) {
        if (diff < DateUtils.MINUTE_IN_MILLIS) { // Less than a minute ago
            final int secs = (int) (diff / 1000);
            return res.getQuantityString(R.plurals.tw__time_secs, secs, secs);
        } else if (diff < DateUtils.HOUR_IN_MILLIS) { // Less than an hour ago
            final int mins = (int) (diff / DateUtils.MINUTE_IN_MILLIS);
            return res.getQuantityString(R.plurals.tw__time_mins, mins, mins);
        } else if (diff < DateUtils.DAY_IN_MILLIS) { // Less than a day ago
            final int hours = (int) (diff / DateUtils.HOUR_IN_MILLIS);
            return res.getQuantityString(R.plurals.tw__time_hours, hours, hours);
        } else {
            final Calendar now = Calendar.getInstance();
            now.setTimeInMillis(currentTimeMillis);
            final Calendar c = Calendar.getInstance();
            c.setTimeInMillis(timestamp);
            final Date d = new Date(timestamp);

            if (now.get(Calendar.YEAR) == c.get(Calendar.YEAR)) {
                // Same year
                return RELATIVE_DATE_FORMAT.formatShortDateString(res, d);
            } else {
                // Outside of our year
                return RELATIVE_DATE_FORMAT.formatLongDateString(res, d);
            }
        }
    }
    return RELATIVE_DATE_FORMAT.formatLongDateString(res, new Date(timestamp));
}
 
Example 7
Source File: SetTimerActivity.java    From AndroidWearable-Samples with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    int paramLength = getIntent().getIntExtra(AlarmClock.EXTRA_LENGTH, 0);
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "SetTimerActivity:onCreate=" + paramLength);
    }
    if (paramLength > 0 && paramLength <= 86400) {
        long durationMillis = paramLength * 1000;
        setupTimer(durationMillis);
        finish();
        return;
    }

    Resources res = getResources();
    for (int i = 0; i < NUMBER_OF_TIMES; i++) {
        mTimeOptions[i] = new ListViewItem(
                res.getQuantityString(R.plurals.timer_minutes, i + 1, i + 1),
                (i + 1) * 60 * 1000);
    }

    setContentView(R.layout.timer_set_timer);

    // Initialize a simple list of countdown time options.
    mListView = (ListView) findViewById(R.id.times_list_view);
    ArrayAdapter<ListViewItem> arrayAdapter = new ArrayAdapter<ListViewItem>(this,
            android.R.layout.simple_list_item_1, mTimeOptions);
    mListView.setAdapter(arrayAdapter);
    mListView.setOnItemClickListener(this);

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Wearable.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
}
 
Example 8
Source File: UserTeamAdapter.java    From droidddle with Apache License 2.0 5 votes vote down vote up
@Override
    public void onBindContentViewHolder(RecyclerView.ViewHolder holder, int position) {
        final Team data = getItem(position);
        Holder h = (Holder) holder;

        h.mUserImageView.setImageURI(Uri.parse(data.avatarUrl));
//        Glide.with(mContext).load(data.avatarUrl).placeholder(R.drawable.person_image_empty).into(h.mUserImageView);
        if (TextUtils.isEmpty(data.location)) {
            h.mLocationView.setText(R.string.default_location);
        } else {
            h.mLocationView.setText(data.location);
        }
        h.mUserNameView.setText(data.name);

        Resources resources = mContext.getResources();
        String shots = resources.getQuantityString(R.plurals.shot_count, data.shotsCount, data.shotsCount);
        h.mShotsCountView.setText(shots);
        String followers = resources.getQuantityString(R.plurals.follower_count, data.followersCount, data.followersCount);
        h.mFollowersCountView.setText(followers);

        h.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UiUtils.launchTeam(mContext, data);
            }
        });

    }
 
Example 9
Source File: ProfileGalleryFragment.java    From deltachat-android with GNU General Public License v3.0 5 votes vote down vote up
@SuppressLint("StaticFieldLeak")
private void handleDeleteMedia(@NonNull Collection<DcMsg> mediaRecords) {
  int recordCount       = mediaRecords.size();
  Resources res         = getContext().getResources();
  String confirmMessage = res.getQuantityString(R.plurals.ask_delete_messages,
                                                recordCount,
                                                recordCount);

  AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
  builder.setMessage(confirmMessage);
  builder.setCancelable(true);

  builder.setPositiveButton(R.string.delete, (dialogInterface, i) -> {
    new ProgressDialogAsyncTask<DcMsg, Void, Void>(getContext(),
                                                                       R.string.one_moment,
                                                                       R.string.one_moment)
    {
      @Override
      protected Void doInBackground(DcMsg... records) {
        if (records == null || records.length == 0) {
          return null;
        }

        for (DcMsg record : records) {
          dcContext.deleteMsgs(new int[]{record.getId()});
        }
        return null;
      }

    }.execute(mediaRecords.toArray(new DcMsg[mediaRecords.size()]));
  });
  builder.setNegativeButton(android.R.string.cancel, null);
  builder.show();
}
 
Example 10
Source File: TimeUtils.java    From Slide with GNU General Public License v3.0 5 votes vote down vote up
public static String getTimeSince(long time, Context c) {
    if (time < 1000000000000L) {
        // if timestamp given in seconds, convert to millis
        time *= 1000;
    }

    long now = System.currentTimeMillis();
    if (time > now || time <= 0) {
        return null;
    }

    Resources res = c.getResources();

    final long diff = now - time;
    if (diff < SECOND_MILLIS) {
        return res.getQuantityString(R.plurals.time_seconds, 0, 0);
    } else if (diff < MINUTE_MILLIS) {
        int seconds = longToInt(diff / MINUTE_MILLIS);
        return res.getQuantityString(R.plurals.time_seconds, seconds, seconds);
    } else if (diff < HOUR_MILLIS) {
        int minutes = longToInt(diff / MINUTE_MILLIS);
        return res.getQuantityString(R.plurals.time_minutes, minutes, minutes);
    } else if (diff < DAY_MILLIS) {
        int hours = longToInt(diff / HOUR_MILLIS);
        return res.getQuantityString(R.plurals.time_hours, hours, hours);
    } else if (diff < MONTH_MILLIS) {
        int days = longToInt(diff / DAY_MILLIS);
        return res.getQuantityString(R.plurals.time_days, days, days);
    } else if (diff < YEAR_MILLIS) {
        int months = longToInt(diff / MONTH_MILLIS);
        return res.getQuantityString(R.plurals.time_months, months, months);
    } else {
        int years = longToInt(diff / YEAR_MILLIS);
        return res.getQuantityString(R.plurals.time_years, years, years);
    }
}
 
Example 11
Source File: NotificationHelper.java    From android with Apache License 2.0 5 votes vote down vote up
private String getReminderText(int prayer, int minutes) {
    Resources r = mContext.getResources();
    String name = mPrayerNames[prayer];

    if (minutes != 0) {
        return r.getQuantityString(R.plurals.notification_reminder, minutes, name, minutes);
    } else {
        return r.getString(R.string.notification_reminder_soon, name);
    }
}
 
Example 12
Source File: TimeUtils.java    From Slide with GNU General Public License v3.0 5 votes vote down vote up
public static String getTimeInHoursAndMins(int mins, Context c) {
    int hours = mins / 60;
    int minutes = mins - (hours * 60);
    Resources res = c.getResources();
    String hour = "";
    String minute = "";

    if (hours > 0)
        hour = res.getQuantityString(R.plurals.time_hours, hours, hours);
    if (minutes > 0)
        minute = res.getQuantityString(R.plurals.time_minutes, minutes, minutes);
    return hour.isEmpty() ? minute : hour + " " + minute ;
}
 
Example 13
Source File: X509Utils.java    From bitmask_android with GNU General Public License v3.0 5 votes vote down vote up
public static String getCertificateValidityString(X509Certificate cert, Resources res) {
    try {
        cert.checkValidity();
    } catch (CertificateExpiredException ce) {
        return "EXPIRED: ";
    } catch (CertificateNotYetValidException cny) {
        return "NOT YET VALID: ";
    }

    Date certNotAfter = cert.getNotAfter();
    Date now = new Date();
    long timeLeft = certNotAfter.getTime() - now.getTime(); // Time left in ms

    // More than 72h left, display days
    // More than 3 months display months
    if (timeLeft > 90l* 24 * 3600 * 1000) {
        long months = getMonthsDifference(now, certNotAfter);
        return res.getQuantityString(R.plurals.months_left, (int) months, months);
    } else if (timeLeft > 72 * 3600 * 1000) {
        long days = timeLeft / (24 * 3600 * 1000);
        return res.getQuantityString(R.plurals.days_left, (int) days, days);
    } else {
        long hours = timeLeft / (3600 * 1000);

        return res.getQuantityString(R.plurals.hours_left, (int)hours, hours);
    }
}
 
Example 14
Source File: SetTimerActivity.java    From android-Timer with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    int paramLength = getIntent().getIntExtra(AlarmClock.EXTRA_LENGTH, 0);
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "SetTimerActivity:onCreate=" + paramLength);
    }
    if (paramLength > 0 && paramLength <= 86400) {
        long durationMillis = paramLength * 1000;
        setupTimer(durationMillis);
        finish();
        return;
    }

    Resources res = getResources();
    for (int i = 0; i < NUMBER_OF_TIMES; i++) {
        mTimeOptions[i] = new ListViewItem(
                res.getQuantityString(R.plurals.timer_minutes, i + 1, i + 1),
                (i + 1) * 60 * 1000);
    }

    setContentView(R.layout.timer_set_timer);

    // Initialize a simple list of countdown time options.
    mWearableListView = (WearableListView) findViewById(R.id.times_list_view);
    mWearableListView.setAdapter(new TimerWearableListViewAdapter(this));
    mWearableListView.setClickListener(this);
}
 
Example 15
Source File: CardArrayMultiChoiceAdapter.java    From example with Apache License 2.0 5 votes vote down vote up
protected void onItemSelectedStateChanged(ActionMode mode) {
    int count = mCardListView.getCheckedItemCount();

    if (count > 0) {
        Resources res = mCardListView.getResources();
        String mTitleSelected = res.getQuantityString(R.plurals.card_selected_items, count, count);
        mode.setTitle(mTitleSelected);
    }
}
 
Example 16
Source File: ConnectionStatistics.java    From habpanelviewer with GNU General Public License v3.0 4 votes vote down vote up
private String toDuration(long durationMillis) {
    if (durationMillis < 1000) {
        return "-";
    }

    Resources res = mCtx.getResources();

    String retVal = "";

    // days
    if (durationMillis > 86400000) {
        long days = durationMillis / 86400000;

        retVal += res.getQuantityString(R.plurals.days, (int) days, days);
        durationMillis %= 86400000;
    }

    // hours
    if (durationMillis > 3600000) {
        long hours = durationMillis / 3600000;

        retVal += res.getQuantityString(R.plurals.hours, (int) hours, hours);
        durationMillis %= 3600000;
    }

    // minutes
    if (durationMillis > 60000) {
        long minutes = durationMillis / 60000;

        retVal += res.getQuantityString(R.plurals.minutes, (int) minutes, minutes);
        durationMillis %= 60000;
    }

    // seconds
    if (durationMillis > 1000) {
        long seconds = durationMillis / 1000;

        retVal += res.getQuantityString(R.plurals.seconds, (int) seconds, seconds);
    }

    return retVal.substring(0, retVal.length() - 1);
}
 
Example 17
Source File: ResourceUtil.java    From edx-app-android with Apache License 2.0 4 votes vote down vote up
public static CharSequence getFormattedStringForQuantity(@NonNull Resources resources,
                                                         @PluralsRes int resourceId, int quantity,
                                                         @NonNull Map<String, String> keyValMap) {
    String template = resources.getQuantityString(resourceId, quantity);
    return getFormattedString(template, keyValMap);
}
 
Example 18
Source File: MultiChoiceAdapterHelperBase.java    From MultiChoiceAdapter with Apache License 2.0 4 votes vote down vote up
public String getActionModeTitle(int count) {
    Resources res = getContext().getResources();
    return res.getQuantityString(R.plurals.selected_items, count, count);
}
 
Example 19
Source File: Utils.java    From ploggy with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Returns a human-readable form of the given date-time. It will be relative
 * to `endDate` or absolute, depending on how long ago it is.
 * @param context    The `Context` to use for resource access.
 * @param startDate  The date-time to render.
 * @param endDate    The date-time that `startDate` will be considered relative to.
 * @param ago        Add the word "ago" to relative forms.
 * @return  The formatted string representing the date-time.
 */
public static String formatRelativeDatetime(Context context, Date startDate, Date endDate, boolean ago) {
    Resources res = context.getResources();
    long diffMS = endDate.getTime() - startDate.getTime();

    // Within a minute
    if (diffMS < MILLIS_IN_MINUTE) {
        int secs = (int)(diffMS / MILLIS_IN_SEC);
        return res.getQuantityString(
                    ago ? R.plurals.period_seconds_ago_abbrev : R.plurals.period_seconds_abbrev,
                    secs, secs);
    }

    // Within an hour
    if (diffMS < MILLIS_IN_HOUR) {
        int mins = (int)(diffMS / MILLIS_IN_MINUTE);
        return res.getQuantityString(
                    ago ? R.plurals.period_minutes_ago_abbrev : R.plurals.period_minutes_abbrev,
                    mins, mins);
    }

    // If we haven't returned yet, we're going to need Calendar objects
    Calendar startCal = new GregorianCalendar();
    startCal.setTimeInMillis(startDate.getTime());

    Calendar endCal = new GregorianCalendar();
    endCal.setTimeInMillis(endDate.getTime());

    // Same day
    if (startCal.get(Calendar.YEAR) == endCal.get(Calendar.YEAR)
            && startCal.get(Calendar.DAY_OF_YEAR) == endCal.get(Calendar.DAY_OF_YEAR)) {
        return mShortTimeFormat.format(startDate);
    }

    // Same week
    if (startCal.get(Calendar.YEAR) == endCal.get(Calendar.YEAR)
            && startCal.get(Calendar.WEEK_OF_YEAR) == endCal.get(Calendar.WEEK_OF_YEAR)) {
        return res.getString(
                R.string.diff_day_same_week_datetime,
                mWeekdayFormat.format(startDate),
                mShortTimeFormat.format(startDate));
    }

    // Same year
    if (startCal.get(Calendar.YEAR) == endCal.get(Calendar.YEAR)) {
        return res.getString(
                R.string.same_year_datetime,
                mMonthFormat.format(startDate),
                mMonthDayFormat.format(startDate),
                mShortTimeFormat.format(startDate));
    }

    // Older than the same year
    return res.getString(
            R.string.older_datetime,
            mMonthFormat.format(startDate),
            mMonthDayFormat.format(startDate),
            mYearFormat.format(startDate),
            mShortTimeFormat.format(startDate));
}
 
Example 20
Source File: LiveGroup.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
private static String getMembershipDescription(@NonNull Resources resources, int invitedCount, int fullMemberCount) {
  return invitedCount > 0 ? resources.getQuantityString(R.plurals.MessageRequestProfileView_members_and_invited, fullMemberCount,
                                                        fullMemberCount, invitedCount)
                          : resources.getQuantityString(R.plurals.MessageRequestProfileView_members, fullMemberCount,
                                                        fullMemberCount);
}