Example usage for android.content.res Resources getQuantityString

List of usage examples for android.content.res Resources getQuantityString

Introduction

In this page you can find the example usage for android.content.res Resources getQuantityString.

Prototype

@NonNull
public String getQuantityString(@PluralsRes int id, int quantity, Object... formatArgs)
        throws NotFoundException 

Source Link

Document

Formats the string necessary for grammatically correct pluralization of the given resource ID for the given quantity, using the given arguments.

Usage

From source file:com.ichi2.libanki.Utils.java

/**
 * Return a string representing a time//  w  w w. j  ava2s  .co m
 * (If you want a certain unit, use the strings directly)
 *
 * @param context The application's environment.
 * @param time_s The time to format, in seconds
 * @return The formatted, localized time string. The time is always an integer.
 */
public static String timeSpan(Context context, int time_s) {
    int time_x; // Time in unit x
    Resources res = context.getResources();
    if (Math.abs(time_s) < TIME_MINUTE) {
        return res.getQuantityString(R.plurals.time_span_seconds, time_s, time_s);
    } else if (Math.abs(time_s) < TIME_HOUR) {
        time_x = (int) Math.round(time_s / TIME_MINUTE);
        return res.getQuantityString(R.plurals.time_span_minutes, time_x, time_x);
    } else if (Math.abs(time_s) < TIME_DAY) {
        time_x = (int) Math.round(time_s / TIME_HOUR);
        return res.getQuantityString(R.plurals.time_span_hours, time_x, time_x);
    } else if (Math.abs(time_s) < TIME_MONTH) {
        time_x = (int) Math.round(time_s / TIME_DAY);
        return res.getQuantityString(R.plurals.time_span_days, time_x, time_x);
    } else if (Math.abs(time_s) < TIME_YEAR) {
        time_x = (int) Math.round(time_s / TIME_MONTH);
        return res.getQuantityString(R.plurals.time_span_months, time_x, time_x);
    } else {
        time_x = (int) Math.round(time_s / TIME_YEAR);
        return res.getQuantityString(R.plurals.time_span_years, time_x, time_x);
    }
}

From source file:com.quarterfull.newsAndroid.services.OwnCloudSyncService.java

private void finishedSync() {
    TeslaUnreadManager.PublishUnreadCount(this);
    WidgetProvider.UpdateWidget(this);

    syncRunning = false;/* ww  w .j  a va  2s.  c o m*/
    syncStopWatch.stop();
    Log.v(TAG, "Time needed (synchronization): " + syncStopWatch.toString());

    SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(OwnCloudSyncService.this);
    int newItemsCount = mPrefs.getInt(Constants.LAST_UPDATE_NEW_ITEMS_COUNT_STRING, 0);
    if (newItemsCount > 0) {
        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTaskInfo = am.getRunningTasks(1);

        ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
        if (!componentInfo.getPackageName().equals("com.quarterfull.newsAndroid")) {
            Resources res = getResources();
            String tickerText = res.getQuantityString(R.plurals.notification_new_items_ticker, newItemsCount,
                    newItemsCount);
            String contentText = res.getQuantityString(R.plurals.notification_new_items_text, newItemsCount,
                    newItemsCount);
            String title = getString(R.string.app_name);

            if (mPrefs.getBoolean(SettingsActivity.CB_SHOW_NOTIFICATION_NEW_ARTICLES_STRING, true))//Default is true
                NotificationManagerNewsReader.getInstance(OwnCloudSyncService.this).ShowMessage(title,
                        tickerText, contentText);
        }
    }

    EventBus.getDefault().post(new SyncFinishedEvent());
}

From source file:physical_web.org.physicalweb.DeviceDiscoveryService.java

/**
 * Update the notification that displays
 * the number of nearby devices.//from   ww  w  . j ava  2 s.c  o  m
 * If there are no devices the notification
 * is removed.
 */
private void updateNearbyDevicesNotification() {
    // Create the notification builder
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    // Set the notification icon
    builder.setSmallIcon(R.drawable.ic_notification);

    // Set the title
    String contentTitle = "";
    // Get the number of current nearby devices
    int numNearbyDevices = mDeviceAddressesFound.size();

    // If there are no nearby devices
    if (numNearbyDevices == 0) {
        // Remove the notification
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                Context.NOTIFICATION_SERVICE);
        mNotificationManager.cancel(ID_NOTIFICATION);
        return;
    }

    // Add the ending part of the title
    // which is either singular or plural
    // based on the number of devices
    contentTitle += String.valueOf(numNearbyDevices) + " ";
    Resources resources = getResources();
    contentTitle += resources.getQuantityString(R.plurals.numFoundBeacons, numNearbyDevices, numNearbyDevices);
    builder.setContentTitle(contentTitle);

    // Have the app launch when the user taps the notification
    Intent resultIntent = new Intent(this, MainActivity.class);
    int requestID = (int) System.currentTimeMillis();
    PendingIntent resultPendingIntent = PendingIntent.getActivity(this, requestID, resultIntent, 0);

    // Build the notification
    builder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(ID_NOTIFICATION, builder.build());
}

From source file:de.luhmer.owncloudnewsreader.services.OwnCloudSyncService.java

private void finishedSync() {
    TeslaUnreadManager.PublishUnreadCount(this);
    WidgetProvider.UpdateWidget(this);

    syncRunning = false;/*w w  w .ja v  a2  s. c o  m*/
    syncStopWatch.stop();
    Log.v(TAG, "Time needed (synchronization): " + syncStopWatch.toString());

    SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(OwnCloudSyncService.this);
    int newItemsCount = mPrefs.getInt(Constants.LAST_UPDATE_NEW_ITEMS_COUNT_STRING, 0);
    if (newItemsCount > 0) {
        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTaskInfo = am.getRunningTasks(1);

        ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
        if (!componentInfo.getPackageName().equals("de.luhmer.owncloudnewsreader")) {
            Resources res = getResources();
            String tickerText = res.getQuantityString(R.plurals.notification_new_items_ticker, newItemsCount,
                    newItemsCount);
            String contentText = res.getQuantityString(R.plurals.notification_new_items_text, newItemsCount,
                    newItemsCount);
            String title = getString(R.string.app_name);

            if (mPrefs.getBoolean(SettingsActivity.CB_SHOW_NOTIFICATION_NEW_ARTICLES_STRING, true))//Default is true
                NotificationManagerNewsReader.getInstance(OwnCloudSyncService.this).ShowMessage(title,
                        tickerText, contentText);
        }
    }

    List<IOwnCloudSyncServiceCallback> callbackList = getCallBackItemsAndBeginBroadcast();
    for (IOwnCloudSyncServiceCallback icb : callbackList) {
        try {
            icb.finishedSync();
            //icb.finishedSyncOfItems();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
    callbacks.finishBroadcast();
}

From source file:com.stasbar.knowyourself.timer.TimerSetupView.java

private CharSequence createContentDescription(int hours, int minutes, int seconds) {
    final Resources r = getResources();
    final String hoursFormatted = r.getQuantityString(R.plurals.Nhours_description, hours, hours);
    final String minutesFormatted = r.getQuantityString(R.plurals.Nminutes_description, minutes, minutes);
    final String secondsFormatted = r.getQuantityString(R.plurals.Nseconds_description, seconds, seconds);
    return (hours == 0 ? "" : hoursFormatted + ", ") + (minutes == 0 ? "" : minutesFormatted + ", ")
            + secondsFormatted;//from   w  w  w .java2  s  .  c  o m
}

From source file:com.example.android.wearable.timer.SetTimerActivity.java

@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);
    }//from ww  w  . j a v a2 s .  c om
    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();
}

From source file:at.florian_lentsch.expirysync.NotifyChecker.java

private void createExpiryNotification(Context appContext, List<String> expiringProducts) {
    Resources res = appContext.getResources();
    NotificationCompat.Builder builder = new NotificationCompat.Builder(appContext)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(res.getQuantityString(R.plurals.numberOfItemsToBeEaten, expiringProducts.size(),
                    expiringProducts.size()))
            .setContentText(StringUtils.join(expiringProducts, System.getProperty("line.separator")))
            .setSound(Settings.System.DEFAULT_NOTIFICATION_URI).setAutoCancel(true);
    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(appContext, ProductListActivity.class);

    // set stack (for the back button to work correctly):
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(appContext);
    stackBuilder.addParentStack(ProductListActivity.class);
    stackBuilder.addNextIntent(resultIntent);

    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(resultPendingIntent);
    NotificationManager notificationManager = (NotificationManager) appContext
            .getSystemService(Context.NOTIFICATION_SERVICE);

    // display the notification:
    notificationManager.notify(WASTE_NOTIFICATION, builder.build());
}

From source file:com.androidinspain.deskclock.timer.TimerSetupView.java

private void updateTime() {
    final int seconds = mInput[1] * 10 + mInput[0];
    final int minutes = mInput[3] * 10 + mInput[2];
    final int hours = mInput[5] * 10 + mInput[4];

    final UiDataModel uidm = UiDataModel.getUiDataModel();
    mTimeView.setText(TextUtils.expandTemplate(mTimeTemplate, uidm.getFormattedNumber(hours, 2),
            uidm.getFormattedNumber(minutes, 2), uidm.getFormattedNumber(seconds, 2)));

    final Resources r = getResources();
    mTimeView.setContentDescription(/*from   w w  w  . jav  a2 s . c o  m*/
            r.getString(R.string.timer_setup_description, r.getQuantityString(R.plurals.hours, hours, hours),
                    r.getQuantityString(R.plurals.minutes, minutes, minutes),
                    r.getQuantityString(R.plurals.seconds, seconds, seconds)));
}

From source file:com.bluros.updater.service.UpdateCheckService.java

private void recordAvailableUpdates(LinkedList<UpdateInfo> availableUpdates, Intent finishedIntent) {

    if (availableUpdates == null) {
        sendBroadcast(finishedIntent);/*from w ww.  j  a  va  2 s . com*/
        return;
    }

    // Store the last update check time and ensure boot check completed is true
    Date d = new Date();
    PreferenceManager.getDefaultSharedPreferences(UpdateCheckService.this).edit()
            .putLong(Constants.LAST_UPDATE_CHECK_PREF, d.getTime())
            .putBoolean(Constants.BOOT_CHECK_COMPLETED, true).apply();

    int realUpdateCount = finishedIntent.getIntExtra(EXTRA_REAL_UPDATE_COUNT, 0);
    UpdateApplication app = (UpdateApplication) getApplicationContext();

    // Write to log
    Log.i(TAG, "The update check successfully completed at " + d + " and found " + availableUpdates.size()
            + " updates (" + realUpdateCount + " newer than installed)");

    if (realUpdateCount != 0 && !app.isMainActivityActive()) {
        // There are updates available
        // The notification should launch the main app
        Intent i = new Intent(this, UpdatesSettings.class);
        i.putExtra(UpdatesSettings.EXTRA_UPDATE_LIST_UPDATED, true);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_ONE_SHOT);

        Resources res = getResources();
        String text = res.getQuantityString(R.plurals.not_new_updates_found_body, realUpdateCount,
                realUpdateCount);

        // Get the notification ready
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_system_update).setWhen(System.currentTimeMillis())
                .setTicker(res.getString(R.string.not_new_updates_found_ticker))
                .setContentTitle(res.getString(R.string.not_new_updates_found_title)).setContentText(text)
                .setContentIntent(contentIntent).setLocalOnly(true).setAutoCancel(true);

        LinkedList<UpdateInfo> realUpdates = new LinkedList<UpdateInfo>();
        for (UpdateInfo ui : availableUpdates) {
            if (ui.isNewerThanInstalled()) {
                realUpdates.add(ui);
            }
        }

        Collections.sort(realUpdates, new Comparator<UpdateInfo>() {
            @Override
            public int compare(UpdateInfo lhs, UpdateInfo rhs) {
                /* sort by date descending */
                long lhsDate = lhs.getDate();
                long rhsDate = rhs.getDate();
                if (lhsDate == rhsDate) {
                    return 0;
                }
                return lhsDate < rhsDate ? 1 : -1;
            }
        });

        NotificationCompat.InboxStyle inbox = new NotificationCompat.InboxStyle(builder)
                .setBigContentTitle(text);
        int added = 0, count = realUpdates.size();

        for (UpdateInfo ui : realUpdates) {
            if (added < EXPANDED_NOTIF_UPDATE_COUNT) {
                inbox.addLine(ui.getName());
                added++;
            }
        }
        if (added != count) {
            inbox.setSummaryText(
                    res.getQuantityString(R.plurals.not_additional_count, count - added, count - added));
        }
        builder.setStyle(inbox);
        builder.setNumber(availableUpdates.size());

        if (count == 1) {
            i = new Intent(this, DownloadReceiver.class);
            i.setAction(DownloadReceiver.ACTION_START_DOWNLOAD);
            i.putExtra(DownloadReceiver.EXTRA_UPDATE_INFO, (Parcelable) realUpdates.getFirst());
            PendingIntent downloadIntent = PendingIntent.getBroadcast(this, 0, i,
                    PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);

            builder.addAction(R.drawable.ic_tab_download, res.getString(R.string.not_action_download),
                    downloadIntent);
        }

        // Trigger the notification
        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        nm.notify(R.string.not_new_updates_found_title, builder.build());
    }

    sendBroadcast(finishedIntent);
}

From source file:com.ichi2.anki.stats.OverviewStatsBuilder.java

private void appendTodaysStats(StringBuilder stringBuilder) {
    Stats stats = new Stats(mCol, mWholeCollection);
    int[] todayStats = stats.calculateTodayStats();
    stringBuilder.append(_title(mWebView.getResources().getString(R.string.stats_today)));
    Resources res = mWebView.getResources();
    final int minutes = (int) Math.round(todayStats[THETIME_INDEX] / 60.0);
    final String span = res.getQuantityString(R.plurals.time_span_minutes, minutes, minutes);
    stringBuilder.append(res.getQuantityString(R.plurals.stats_today_cards, todayStats[CARDS_INDEX],
            todayStats[CARDS_INDEX], span));
    stringBuilder.append("<br>");
    stringBuilder.append(res.getString(R.string.stats_today_again_count, todayStats[FAILED_INDEX]));
    if (todayStats[CARDS_INDEX] > 0) {
        stringBuilder.append(" ");
        stringBuilder.append(res.getString(R.string.stats_today_correct_count,
                (((1 - todayStats[FAILED_INDEX] / (float) (todayStats[CARDS_INDEX])) * 100.0))));
    }//from w  w  w.j ava2  s .  co  m
    stringBuilder.append("<br>");
    stringBuilder.append(res.getString(R.string.stats_today_type_breakdown, todayStats[LRN_INDEX],
            todayStats[REV_INDEX], todayStats[RELRN_INDEX], todayStats[FILT_INDEX]));
    stringBuilder.append("<br>");
    if (todayStats[MCNT_INDEX] != 0) {
        stringBuilder.append(res.getString(R.string.stats_today_mature_cards, todayStats[MSUM_INDEX],
                todayStats[MCNT_INDEX], (todayStats[MSUM_INDEX] / (float) (todayStats[MCNT_INDEX]) * 100.0)));
    } else {
        stringBuilder.append(res.getString(R.string.stats_today_no_mature_cards));
    }
}