List of usage examples for android.text.format DateUtils getRelativeTimeSpanString
public static CharSequence getRelativeTimeSpanString(Context c, long millis, boolean withPreposition)
From source file:com.appjma.appdeployer.adapter.AppVersionsAdapter.java
@Override public void bindView(View view, Context context, Cursor cursor) { ViewHolder holder = (ViewHolder) view.getTag(); String version = cursor.getString(PROJECTION_VERSION); long updatedAt = cursor.getLong(PROJECTION_UPDATED_AT); long id = cursor.getLong(PROJECTION_APP_VERSION_ID); String downloadManagerId = cursor.getString(PROJECTION_DOWNLOAD_MANAGER_ID); int status = -1; if (downloadManagerId != null) { DownloadItem downloadItem = mMap.get(downloadManagerId); if (downloadItem != null) { status = downloadItem.mStatus; }/*from www . j a v a2 s . co m*/ } if (status == DownloadManager.STATUS_PENDING || status == DownloadManager.STATUS_RUNNING) { holder.mButton.setBackgroundResource(R.drawable.ic_list_item_downloading); } else if (status == DownloadManager.STATUS_SUCCESSFUL) { holder.mButton.setBackgroundResource(R.drawable.ic_list_item_downloaded); } else { holder.mButton.setBackgroundResource(R.drawable.ic_list_item_download); } holder.mPosition = cursor.getPosition(); holder.mText1.setText(String.format(mVersionFormat, version)); CharSequence updatedAtText = DateUtils.getRelativeTimeSpanString(updatedAt, mNow, DateUtils.MINUTE_IN_MILLIS); holder.mText2.setText(updatedAtText); holder.mId = id; }
From source file:org.microg.gms.ui.GcmFragment.java
private void updateContent() { PreferenceScreen root = getPreferenceScreen(); if (McsService.isConnected()) { root.findPreference(PREF_GCM_STATUS).setSummary(getString(R.string.gcm_state_connected, DateUtils .getRelativeTimeSpanString(McsService.getStartTimestamp(), System.currentTimeMillis(), 0))); } else {/*from ww w. j a v a 2 s. c om*/ root.findPreference(PREF_GCM_STATUS).setSummary(getString(R.string.gcm_state_disconnected)); } PreferenceCategory appList = (PreferenceCategory) root.findPreference(PREF_GCM_APPS); appList.removeAll(); List<GcmDatabase.App> list = database.getAppList(); if (!list.isEmpty()) { List<Preference> appListPrefs = new ArrayList<>(); PackageManager pm = getContext().getPackageManager(); for (GcmDatabase.App app : list) { try { pm.getApplicationInfo(app.packageName, 0); appListPrefs.add(new GcmAppPreference(getPreferenceManager().getContext(), app)); } catch (PackageManager.NameNotFoundException e) { final List<GcmDatabase.Registration> registrations = database .getRegistrationsByApp(app.packageName); if (registrations.isEmpty()) { database.removeApp(app.packageName); } else { appListPrefs.add(new GcmAppPreference(getPreferenceManager().getContext(), app)); } } } addPreferencesSorted(appListPrefs, appList); } else { // If there's no item to display, add a "None" item. Preference banner = new Preference(getPreferenceManager().getContext()); banner.setLayoutResource(R.layout.list_no_item); banner.setTitle(R.string.list_no_item_none); banner.setSelectable(false); appList.addPreference(banner); } }
From source file:ro.expectations.expenses.ui.accounts.AccountsAdapter.java
@Override public void onBindViewHolder(ViewHolder holder, int position) { mCursor.moveToPosition(position);/*from ww w. ja v a 2 s . co m*/ // Set the row background ListHelper.setItemBackground(mContext, holder.itemView, isItemSelected(position), holder.mAccountIconBackground, holder.mSelectedIconBackground); // Set the icon String type = mCursor.getString(mCursor.getColumnIndex(ExpensesContract.Accounts.TYPE)); AccountType accountType = AccountType.valueOf(type); if (accountType == AccountType.CREDIT_CARD || accountType == AccountType.DEBIT_CARD) { String issuer = mCursor.getString(mCursor.getColumnIndex(ExpensesContract.Accounts.SUBTYPE)); CardIssuer cardIssuer; if (issuer == null) { cardIssuer = CardIssuer.OTHER; } else { try { cardIssuer = CardIssuer.valueOf(issuer); } catch (final IllegalArgumentException ex) { cardIssuer = CardIssuer.OTHER; } } holder.mAccountIcon .setImageDrawable(DrawableHelper.tint(mContext, cardIssuer.iconId, R.color.colorWhite)); } else if (accountType == AccountType.ELECTRONIC) { String paymentType = mCursor.getString(mCursor.getColumnIndex(ExpensesContract.Accounts.SUBTYPE)); ElectronicPaymentType electronicPaymentType; if (paymentType == null) { electronicPaymentType = ElectronicPaymentType.OTHER; } else { try { electronicPaymentType = ElectronicPaymentType.valueOf(paymentType); } catch (IllegalArgumentException ex) { electronicPaymentType = ElectronicPaymentType.OTHER; } } holder.mAccountIcon.setImageDrawable( DrawableHelper.tint(mContext, electronicPaymentType.iconId, R.color.colorWhite)); } else { holder.mAccountIcon .setImageDrawable(DrawableHelper.tint(mContext, accountType.iconId, R.color.colorWhite)); } // Set the icon background color GradientDrawable bgShape = (GradientDrawable) holder.mAccountIconBackground.getBackground(); bgShape.setColor(0xFF000000 | ContextCompat.getColor(mContext, accountType.colorId)); // Set the description holder.mAccountDescription.setText(accountType.titleId); // Set the title String title = mCursor.getString(mCursor.getColumnIndex(ExpensesContract.Accounts.TITLE)); holder.mAccountTitle.setText(title); // Set the date long now = System.currentTimeMillis(); long lastTransactionAt = mCursor .getLong(mCursor.getColumnIndex(ExpensesContract.Accounts.LAST_TRANSACTION_AT)); if (lastTransactionAt == 0) { lastTransactionAt = mCursor.getLong(mCursor.getColumnIndex(ExpensesContract.Accounts.CREATED_AT)); } holder.mAccountLastTransactionAt .setText(DateUtils.getRelativeTimeSpanString(lastTransactionAt, now, DateUtils.DAY_IN_MILLIS)); // Set the account balance double balance = NumberUtils.roundToTwoPlaces( mCursor.getLong(mCursor.getColumnIndex(ExpensesContract.Accounts.BALANCE)) / 100.0); String currencyCode = mCursor.getString(mCursor.getColumnIndex(ExpensesContract.Accounts.CURRENCY)); Currency currency = Currency.getInstance(currencyCode); NumberFormat format = NumberFormat.getCurrencyInstance(); format.setCurrency(currency); format.setMaximumFractionDigits(currency.getDefaultFractionDigits()); holder.mAccountBalance.setText(format.format(balance)); if (balance > 0) { holder.mAccountBalance.setTextColor(ContextCompat.getColor(mContext, R.color.colorGreen700)); } else if (balance < 0) { holder.mAccountBalance.setTextColor(ContextCompat.getColor(mContext, R.color.colorRed700)); } }
From source file:com.davidmiguel.gobees.apiary.ApiaryInfoFragment.java
@SuppressWarnings("ConstantConditions") @Override/*from w w w . j a v a 2 s . c o m*/ public void showInfo(Apiary apiary, Date lastRevisionDate) { // GENERAL INFO // Location if (apiary.hasLocation()) { String latLetter = (apiary.getLocationLat() > 0) ? "N" : "S"; String lonLetter = (apiary.getLocationLong() > 0) ? "E" : "W"; location.setText(apiary.getLocationLat() + latLetter + " / " + apiary.getLocationLong() + lonLetter); } // Num hives int num = apiary.getHives().size(); numHives.setText(getResources().getQuantityString(R.plurals.num_hives_plurals, num, num)); // Last revision if (lastRevisionDate != null) { lastRevision.setText(DateUtils.getRelativeTimeSpanString(lastRevisionDate.getTime(), (new Date()).getTime(), DateUtils.MINUTE_IN_MILLIS)); } // Notes if (Strings.isNullOrEmpty(apiary.getNotes())) { notes.setText(getString(R.string.no_notes)); } else { notes.setText(apiary.getNotes()); } // WEATHER // Hide card if no weather data exists if (apiary.getCurrentWeather() == null) { weatherCard.setVisibility(View.GONE); return; } // Weather Icon String iconId = apiary.getCurrentWeather().getWeatherConditionIcon(); weatherIcon.setImageResource(WeatherUtils.getWeatherIconResourceId(iconId)); // Temperature double temp = apiary.getCurrentWeather().getTemperature(); temperature.setText(WeatherUtils.formatTemperature(getContext(), temp)); // City String cityName = apiary.getCurrentWeather().getCityName(); city.setText(cityName); // Weather condition String weatherCondition = WeatherUtils.getStringForWeatherCondition(getContext(), apiary.getCurrentWeather().getWeatherCondition()); condition.setText(weatherCondition); // Humidity double hum = apiary.getCurrentWeather().getHumidity(); humidity.setText(WeatherUtils.formatHumidity(getContext(), hum)); // Pressure double pre = apiary.getCurrentWeather().getPressure(); pressure.setText(WeatherUtils.formatPressure(getContext(), pre)); // Wind double windSpeed = apiary.getCurrentWeather().getWindSpeed(); double windDegrees = apiary.getCurrentWeather().getWindDegrees(); wind.setText(WeatherUtils.formatWind(getContext(), windSpeed, windDegrees)); // Rain double rainVol = apiary.getCurrentWeather().getRain(); rain.setText(WeatherUtils.formatRainSnow(getContext(), rainVol)); // Snow double snowVol = apiary.getCurrentWeather().getSnow(); snow.setText(WeatherUtils.formatRainSnow(getContext(), snowVol)); // Last update String date = (String) DateUtils.getRelativeTimeSpanString( apiary.getCurrentWeather().getTimestamp().getTime(), (new Date()).getTime(), DateUtils.MINUTE_IN_MILLIS); updated.setText(date); }
From source file:ro.expectations.expenses.ui.transactions.TransactionsAdapter.java
@Override public void onBindViewHolder(ViewHolder holder, int position) { mCursor.moveToPosition(position);/*from ww w .j av a2s. c o m*/ long fromAccountId = mCursor.getLong(TransactionsFragment.COLUMN_FROM_ACCOUNT_ID); long toAccountId = mCursor.getLong(TransactionsFragment.COLUMN_TO_ACCOUNT_ID); if (fromAccountId > 0 && toAccountId > 0) { processTransfer(holder, position); } else { if (fromAccountId > 0) { processDebit(holder, position); } else { processCredit(holder, position); } } // Set the row background ListHelper.setItemBackground(mContext, holder.itemView, isItemSelected(position), holder.mTransactionIconBackground, holder.mSelectedIconBackground); // Set the description StringBuilder description = new StringBuilder(); long categoryId = mCursor.getLong(TransactionsFragment.COLUMN_CATEGORY_ID); if (categoryId == -1) { description.append(mContext.getString(R.string.multiple_categories)); } else { String category = mCursor.getString(TransactionsFragment.COLUMN_CATEGORY_NAME); if (category != null && !category.isEmpty()) { description.append(category); } } String parentCategory = mCursor.getString(TransactionsFragment.COLUMN_PARENT_CATEGORY_NAME); if (parentCategory != null && !parentCategory.isEmpty()) { description.insert(0, " "); description.insert(0, parentCategory); } StringBuilder additionalDescription = new StringBuilder(); String payeeName = mCursor.getString(TransactionsFragment.COLUMN_PAYEE_NAME); if (payeeName != null && !payeeName.isEmpty()) { additionalDescription.append(payeeName); } String note = mCursor.getString(TransactionsFragment.COLUMN_NOTE); if (note != null && !note.isEmpty()) { if (additionalDescription.length() > 0) { additionalDescription.append(": "); } additionalDescription.append(note); } if (description.length() > 0 && additionalDescription.length() > 0) { additionalDescription.insert(0, " ("); additionalDescription.append(")"); } if (additionalDescription.length() > 0) { description.append(additionalDescription.toString()); } if (description.length() == 0) { if (fromAccountId > 0 && toAccountId > 0) { description.append(mContext.getString(R.string.default_transfer_description)); } else { long fromAmount = mCursor.getLong(TransactionsFragment.COLUMN_FROM_AMOUNT); if (fromAmount > 0) { description.append(mContext.getString(R.string.default_debit_description)); } else { description.append(mContext.getString(R.string.default_credit_description)); } } } holder.mDescription.setText(description.toString()); // Set the transaction date long transactionDate = mCursor.getLong(TransactionsFragment.COLUMN_OCCURED_AT); if (transactionDate == 0) { transactionDate = mCursor.getLong(TransactionsFragment.COLUMN_CREATED_AT); } holder.mDate.setText(DateUtils.getRelativeTimeSpanString(transactionDate, System.currentTimeMillis(), DateUtils.DAY_IN_MILLIS)); // Set the icon if (fromAccountId > 0 && toAccountId > 0) { holder.mTransactionIcon.setImageDrawable( DrawableHelper.tint(mContext, R.drawable.ic_transfer_black_24dp, R.color.colorWhite)); } else { holder.mTransactionIcon.setImageDrawable( DrawableHelper.tint(mContext, R.drawable.ic_question_mark_black_24dp, R.color.colorWhite)); } GradientDrawable bgShape = (GradientDrawable) holder.mTransactionIconBackground.getBackground(); bgShape.setColor(0xFF000000 | ContextCompat.getColor(mContext, R.color.colorPrimary)); }
From source file:de.badaix.snapcast.ClientSettingsFragment.java
public void update() { if (client == null) return;/*ww w.j av a 2s . com*/ prefName.setSummary(client.getConfig().getName()); prefName.setText(client.getConfig().getName()); prefMac.setSummary(client.getHost().getMac()); prefIp.setSummary(client.getHost().getIp()); prefHost.setSummary(client.getHost().getName()); prefOS.setSummary(client.getHost().getOs() + "@" + client.getHost().getArch()); prefVersion.setSummary(client.getSnapclient().getVersion()); String lastSeen = getText(R.string.online).toString(); if (!client.isConnected()) { long lastSeenTs = Math.min(client.getLastSeen().getSec() * 1000, System.currentTimeMillis()); lastSeen = DateUtils .getRelativeTimeSpanString(lastSeenTs, System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS) .toString(); } prefLastSeen.setSummary(lastSeen); prefLatency.setSummary(client.getConfig().getLatency() + "ms"); prefLatency.setText(client.getConfig().getLatency() + ""); }
From source file:com.android.gpstest.GpsStatusFragment.java
private void updateFixTime() { if (mFixTime == 0 || !GpsTestActivity.getInstance().mStarted) { mFixTimeView.setText(""); } else {//ww w . jav a2 s . c o m mFixTimeView.setText(DateUtils.getRelativeTimeSpanString(mFixTime, System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS)); } }
From source file:com.sonaive.v2ex.ui.ReviewsFragment.java
private void initHeader(View header) { if (mFeed != null) { ImageLoader imageLoader = new ImageLoader(getActivity(), R.drawable.person_image_empty); TextView title = (TextView) header.findViewById(R.id.title); HtmlTextView content = (HtmlTextView) header.findViewById(R.id.content); ImageView avatar = (ImageView) header.findViewById(R.id.avatar); TextView name = (TextView) header.findViewById(R.id.name); TextView time = (TextView) header.findViewById(R.id.time); TextView replies = (TextView) header.findViewById(R.id.replies); TextView nodeTitle = (TextView) header.findViewById(R.id.node_title); title.setText(mFeed.title);//from www .ja v a 2s . c o m content.setVisibility(View.VISIBLE); content.setText( Html.fromHtml(mFeed.content_rendered, new URLImageParser(getActivity(), content), null)); if (mFeed.member != null) { String avatarUrl = mFeed.member.avatar_large; if (avatarUrl != null) { avatarUrl = avatarUrl.startsWith("http:") ? avatarUrl : "http:" + avatarUrl; } else { avatarUrl = ""; } imageLoader.loadImage(avatarUrl, avatar); name.setText(mFeed.member.username); } if (mFeed.member != null) { nodeTitle.setText(mFeed.node.title); } time.setText(DateUtils.getRelativeTimeSpanString(mFeed.created * 1000, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS)); replies.setText(mFeed.replies + getString(R.string.noun_reply)); } }
From source file:de.schildbach.wallet.ui.backup.RestoreWalletDialogFragment.java
@Override public Dialog onCreateDialog(final Bundle savedInstanceState) { final View view = LayoutInflater.from(activity).inflate(R.layout.restore_wallet_dialog, null); messageView = (TextView) view.findViewById(R.id.restore_wallet_dialog_message); fileView = (Spinner) view.findViewById(R.id.import_keys_from_storage_file); passwordView = (EditText) view.findViewById(R.id.import_keys_from_storage_password); showView = (CheckBox) view.findViewById(R.id.import_keys_from_storage_show); replaceWarningView = view.findViewById(R.id.restore_wallet_from_storage_dialog_replace_warning); final DialogBuilder builder = new DialogBuilder(activity); builder.setTitle(R.string.import_keys_dialog_title); builder.setView(view);/*w ww .j a va 2 s .c om*/ builder.setPositiveButton(R.string.import_keys_dialog_button_import, new OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { final File file = (File) fileView.getSelectedItem(); final String password = passwordView.getText().toString().trim(); passwordView.setText(null); // get rid of it asap if (WalletUtils.BACKUP_FILE_FILTER.accept(file)) restoreWalletFromProtobuf(file); else if (WalletUtils.KEYS_FILE_FILTER.accept(file)) restorePrivateKeysFromBase58(file); else if (Crypto.OPENSSL_FILE_FILTER.accept(file)) restoreWalletFromEncrypted(file, password); } }); builder.setNegativeButton(R.string.button_cancel, new OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { passwordView.setText(null); // get rid of it asap } }); builder.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(final DialogInterface dialog) { passwordView.setText(null); // get rid of it asap } }); fileView.setAdapter(new FileAdapter(activity) { @Override public View getDropDownView(final int position, View row, final ViewGroup parent) { final File file = getItem(position); final boolean isExternal = Constants.Files.EXTERNAL_WALLET_BACKUP_DIR.equals(file.getParentFile()); final boolean isEncrypted = Crypto.OPENSSL_FILE_FILTER.accept(file); if (row == null) row = inflater.inflate(R.layout.restore_wallet_file_row, null); final TextView filenameView = (TextView) row .findViewById(R.id.wallet_import_keys_file_row_filename); filenameView.setText(file.getName()); final TextView securityView = (TextView) row .findViewById(R.id.wallet_import_keys_file_row_security); final String encryptedStr = context .getString(isEncrypted ? R.string.import_keys_dialog_file_security_encrypted : R.string.import_keys_dialog_file_security_unencrypted); final String storageStr = context .getString(isExternal ? R.string.import_keys_dialog_file_security_external : R.string.import_keys_dialog_file_security_internal); securityView.setText(encryptedStr + ", " + storageStr); final TextView createdView = (TextView) row.findViewById(R.id.wallet_import_keys_file_row_created); createdView.setText(context.getString( isExternal ? R.string.import_keys_dialog_file_created_manual : R.string.import_keys_dialog_file_created_automatic, DateUtils.getRelativeTimeSpanString(context, file.lastModified(), true))); return row; } }); final AlertDialog dialog = builder.create(); dialog.setOnShowListener(new OnShowListener() { @Override public void onShow(final DialogInterface d) { final ImportDialogButtonEnablerListener dialogButtonEnabler = new ImportDialogButtonEnablerListener( passwordView, dialog) { @Override protected boolean hasFile() { return fileView.getSelectedItem() != null; } @Override protected boolean needsPassword() { final File selectedFile = (File) fileView.getSelectedItem(); return selectedFile != null ? Crypto.OPENSSL_FILE_FILTER.accept(selectedFile) : false; } }; passwordView.addTextChangedListener(dialogButtonEnabler); fileView.setOnItemSelectedListener(dialogButtonEnabler); updateView(); viewModel.balance.observe(RestoreWalletDialogFragment.this, new Observer<Coin>() { @Override public void onChanged(final Coin balance) { final boolean hasCoins = balance.signum() > 0; replaceWarningView.setVisibility(hasCoins ? View.VISIBLE : View.GONE); } }); } }); return dialog; }
From source file:com.markupartist.sthlmtraveling.utils.DateTimeUtil.java
public static CharSequence routeToTimeDisplay(Context context, Route route) { java.text.DateFormat format = android.text.format.DateFormat.getTimeFormat(context); BidiFormatter bidiFormatter = BidiFormatter.getInstance(RtlUtils.isRtl(Locale.getDefault())); Pair<Date, RealTimeState> departsAt = route.departsAt(true); Pair<Date, RealTimeState> arrivesAt = route.arrivesAt(true); String departsAtStr = format.format(departsAt.first); String arrivesAtStr = format.format(arrivesAt.first); CharSequence displayTime;//from w w w . j a va 2 s . c om if (!DateUtils.isToday(departsAt.first.getTime())) { displayTime = String.format("%s %s %s", bidiFormatter.unicodeWrap(DateUtils.getRelativeTimeSpanString(departsAt.first.getTime(), System.currentTimeMillis(), DateUtils.DAY_IN_MILLIS).toString()), bidiFormatter.unicodeWrap(departsAtStr), bidiFormatter.unicodeWrap(arrivesAtStr)); } else { displayTime = String.format("%s %s", bidiFormatter.unicodeWrap(departsAtStr), bidiFormatter.unicodeWrap(arrivesAtStr)); } ForegroundColorSpan spanDepartsAt = new ForegroundColorSpan( ContextCompat.getColor(context, ViewHelper.getTextColorByRealtimeState(departsAt.second))); Pattern patternDepartsAt = Pattern.compile(departsAtStr); displayTime = SpanUtils.createSpannable(displayTime, patternDepartsAt, spanDepartsAt); ForegroundColorSpan spanArrivessAt = new ForegroundColorSpan( ContextCompat.getColor(context, ViewHelper.getTextColorByRealtimeState(arrivesAt.second))); Pattern patternArrivesAt = Pattern.compile(arrivesAtStr); displayTime = SpanUtils.createSpannable(displayTime, patternArrivesAt, spanArrivessAt); return displayTime; }