Example usage for android.content.res Resources getString

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

Introduction

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

Prototype

@NonNull
public String getString(@StringRes int id) throws NotFoundException 

Source Link

Document

Return the string value associated with a particular resource ID.

Usage

From source file:com.androzic.Androzic.java

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    Resources resources = getResources();

    if (getString(R.string.pref_folder_data).equals(key)) {
        setDataPath(Androzic.PATH_DATA,//  ww  w . j a v  a  2s . co  m
                sharedPreferences.getString(key, resources.getString(R.string.def_folder_data)));
    } else if (getString(R.string.pref_folder_icon).equals(key)) {
        setDataPath(Androzic.PATH_ICONS,
                sharedPreferences.getString(key, resources.getString(R.string.def_folder_icon)));
    } else if (getString(R.string.pref_unitcoordinate).equals(key)) {
        StringFormatter.coordinateFormat = Integer.parseInt(sharedPreferences.getString(key, "0"));
    } else if (getString(R.string.pref_unitdistance).equals(key)) {
        int distanceIdx = Integer.parseInt(sharedPreferences.getString(key, "0"));
        StringFormatter.distanceFactor = Double
                .parseDouble(resources.getStringArray(R.array.distance_factors)[distanceIdx]);
        StringFormatter.distanceAbbr = resources.getStringArray(R.array.distance_abbrs)[distanceIdx];
        StringFormatter.distanceShortFactor = Double
                .parseDouble(resources.getStringArray(R.array.distance_factors_short)[distanceIdx]);
        StringFormatter.distanceShortAbbr = resources.getStringArray(R.array.distance_abbrs_short)[distanceIdx];
    } else if (getString(R.string.pref_unitspeed).equals(key)) {
        int speedIdx = Integer.parseInt(sharedPreferences.getString(key, "0"));
        StringFormatter.speedFactor = Double
                .parseDouble(resources.getStringArray(R.array.speed_factors)[speedIdx]);
        StringFormatter.speedAbbr = resources.getStringArray(R.array.speed_abbrs)[speedIdx];
    } else if (getString(R.string.pref_unitelevation).equals(key)) {
        int elevationIdx = Integer.parseInt(sharedPreferences.getString(key, "0"));
        StringFormatter.elevationFactor = Double
                .parseDouble(resources.getStringArray(R.array.elevation_factors)[elevationIdx]);
        StringFormatter.elevationAbbr = resources.getStringArray(R.array.elevation_abbrs)[elevationIdx];
    } else if (getString(R.string.pref_unitangle).equals(key)) {
        int angleIdx = Integer.parseInt(sharedPreferences.getString(key, "0"));
        StringFormatter.angleFactor = Double
                .parseDouble(resources.getStringArray(R.array.angle_factors)[angleIdx]);
        StringFormatter.angleAbbr = resources.getStringArray(R.array.angle_abbrs)[angleIdx];
    } else if (getString(R.string.pref_unitanglemagnetic).equals(key)) {
        angleMagnetic = sharedPreferences.getBoolean(key, resources.getBoolean(R.bool.def_unitanglemagnetic));
    } else if (getString(R.string.pref_unitsunrise).equals(key)) {
        sunriseType = Integer.parseInt(sharedPreferences.getString(key, "0"));
    } else if (getString(R.string.pref_unitprecision).equals(key)) {
        boolean precision = sharedPreferences.getBoolean(key, resources.getBoolean(R.bool.def_unitprecision));
        StringFormatter.precisionFormat = precision ? "%.1f" : "%.0f";
    } else if (getString(R.string.pref_grid_mapshow).equals(key)) {
        overlayManager.mapGrid = sharedPreferences.getBoolean(key, false);
        if (currentMap instanceof OzfMap)
            overlayManager.initGrids((OzfMap) currentMap);
    } else if (getString(R.string.pref_grid_usershow).equals(key)) {
        overlayManager.userGrid = sharedPreferences.getBoolean(key, false);
        if (currentMap instanceof OzfMap)
            overlayManager.initGrids((OzfMap) currentMap);
    } else if (getString(R.string.pref_grid_preference).equals(key)) {
        overlayManager.gridPrefer = Integer.parseInt(sharedPreferences.getString(key, "0"));
        if (currentMap instanceof OzfMap)
            overlayManager.initGrids((OzfMap) currentMap);
    } else if (getString(R.string.pref_grid_userscale).equals(key)
            || getString(R.string.pref_grid_userunit).equals(key)
            || getString(R.string.pref_grid_usermpp).equals(key)) {
        if (currentMap instanceof OzfMap)
            overlayManager.initGrids((OzfMap) currentMap);
    } else if (getString(R.string.pref_vectormap_theme).equals(key)
            || getString(R.string.pref_vectormap_poi).equals(key)) {
        initializeRenderTheme();
        ForgeMap.onRenderThemeChanged();
    } else if (getString(R.string.pref_vectormap_textscale).equals(key)) {
        ForgeMap.textScale = Float
                .parseFloat(sharedPreferences.getString(getString(R.string.pref_vectormap_textscale), "1.0"));
        ForgeMap.onRenderThemeChanged();
    } else if (getString(R.string.pref_onlinemap).equals(key)
            || getString(R.string.pref_onlinemapscale).equals(key)) {
        setOnlineMaps(sharedPreferences.getString(getString(R.string.pref_onlinemap),
                resources.getString(R.string.def_onlinemap)));
    } else if (getString(R.string.pref_mapadjacent).equals(key)) {
        adjacentMaps = sharedPreferences.getBoolean(key, resources.getBoolean(R.bool.def_mapadjacent));
    } else if (getString(R.string.pref_onlinemapprescalefactor).equals(key)) {
        onlineMapPrescaleFactor = sharedPreferences.getInt(key,
                resources.getInteger(R.integer.def_onlinemapprescalefactor));
        if (maps != null)
            for (BaseMap map : maps.getMaps())
                if (map instanceof OnlineMap)
                    ((OnlineMap) map).setPrescaleFactor(onlineMapPrescaleFactor);
        // Hack to recalculate cache and mpp
        if (currentMap != null && currentMap instanceof OnlineMap)
            currentMap.setZoom(currentMap.getZoom());
    } else if (getString(R.string.pref_onlinemapexpiration).equals(key)) {
        // in weeks
        onlineMapTileExpiration = sharedPreferences.getInt(key,
                resources.getInteger(R.integer.def_onlinemapexpiration));
        // in milliseconds
        onlineMapTileExpiration *= 1000 * 3600 * 24 * 7;
        if (onlineMaps != null) {
            for (TileProvider provider : onlineMaps)
                provider.tileExpiration = onlineMapTileExpiration;
        }
    } else if (getString(R.string.pref_mapcropborder).equals(key)) {
        cropMapBorder = sharedPreferences.getBoolean(key, resources.getBoolean(R.bool.def_mapcropborder));
    } else if (getString(R.string.pref_mapdrawborder).equals(key)) {
        drawMapBorder = sharedPreferences.getBoolean(key, resources.getBoolean(R.bool.def_mapdrawborder));
    } else if (getString(R.string.pref_showwaypoints).equals(key)) {
        overlayManager.setWaypointsOverlayEnabled(sharedPreferences.getBoolean(key, true));
    } else if (getString(R.string.pref_showcurrenttrack).equals(key)) {
        overlayManager.setCurrentTrackOverlayEnabled(sharedPreferences.getBoolean(key, true));
    } else if (getString(R.string.pref_showaccuracy).equals(key)) {
        overlayManager.setAccuracyOverlayEnabled(sharedPreferences.getBoolean(key, true));
    } else if (getString(R.string.pref_showdistance_int).equals(key)) {
        int showDistance = Integer
                .parseInt(sharedPreferences.getString(key, getString(R.string.def_showdistance)));
        overlayManager.setDistanceOverlayEnabled(showDistance > 0);
    }
    overlayManager.onPreferencesChanged(sharedPreferences);
    if (mapHolder != null)
        mapHolder.refreshMap();
}

From source file:com.android.contacts.quickcontact.QuickContactActivity.java

/**
 * Converts a {@link DataItem} into an {@link ExpandingEntryCardView.Entry} for display.
 * If the {@link ExpandingEntryCardView.Entry} has no visual elements, null is returned.
 *
 * This runs on a background thread. This is set as static to avoid accidentally adding
 * additional dependencies on unsafe things (like the Activity).
 *
 * @param dataItem The {@link DataItem} to convert.
 * @param secondDataItem A second {@link DataItem} to help build a full entry for some
 *  mimetypes// w  w  w  .  j a  v a 2 s. c om
 * @return The {@link ExpandingEntryCardView.Entry}, or null if no visual elements are present.
 */
private static Entry dataItemToEntry(DataItem dataItem, DataItem secondDataItem, Context context,
        Contact contactData, final MutableString aboutCardName) {
    Drawable icon = null;
    String header = null;
    String subHeader = null;
    Drawable subHeaderIcon = null;
    String text = null;
    Drawable textIcon = null;
    StringBuilder primaryContentDescription = new StringBuilder();
    Spannable phoneContentDescription = null;
    Spannable smsContentDescription = null;
    Intent intent = null;
    boolean shouldApplyColor = true;
    Drawable alternateIcon = null;
    Intent alternateIntent = null;
    StringBuilder alternateContentDescription = new StringBuilder();
    final boolean isEditable = false;
    EntryContextMenuInfo entryContextMenuInfo = null;
    Drawable thirdIcon = null;
    Intent thirdIntent = null;
    int thirdAction = Entry.ACTION_NONE;
    String thirdContentDescription = null;
    Bundle thirdExtras = null;
    int iconResourceId = 0;

    context = context.getApplicationContext();
    final Resources res = context.getResources();
    DataKind kind = dataItem.getDataKind();

    if (dataItem instanceof ImDataItem) {
        final ImDataItem im = (ImDataItem) dataItem;
        intent = ContactsUtils.buildImIntent(context, im).first;
        final boolean isEmail = im.isCreatedFromEmail();
        final int protocol;
        if (!im.isProtocolValid()) {
            protocol = Im.PROTOCOL_CUSTOM;
        } else {
            protocol = isEmail ? Im.PROTOCOL_GOOGLE_TALK : im.getProtocol();
        }
        if (protocol == Im.PROTOCOL_CUSTOM) {
            // If the protocol is custom, display the "IM" entry header as well to distinguish
            // this entry from other ones
            header = res.getString(R.string.header_im_entry);
            subHeader = Im.getProtocolLabel(res, protocol, im.getCustomProtocol()).toString();
            text = im.getData();
        } else {
            header = Im.getProtocolLabel(res, protocol, im.getCustomProtocol()).toString();
            subHeader = im.getData();
        }
        entryContextMenuInfo = new EntryContextMenuInfo(im.getData(), header, dataItem.getMimeType(),
                dataItem.getId(), dataItem.isSuperPrimary());
    } else if (dataItem instanceof OrganizationDataItem) {
        final OrganizationDataItem organization = (OrganizationDataItem) dataItem;
        header = res.getString(R.string.header_organization_entry);
        subHeader = organization.getCompany();
        entryContextMenuInfo = new EntryContextMenuInfo(subHeader, header, dataItem.getMimeType(),
                dataItem.getId(), dataItem.isSuperPrimary());
        text = organization.getTitle();
    } else if (dataItem instanceof NicknameDataItem) {
        final NicknameDataItem nickname = (NicknameDataItem) dataItem;
        // Build nickname entries
        final boolean isNameRawContact = (contactData.getNameRawContactId() == dataItem.getRawContactId());

        final boolean duplicatesTitle = isNameRawContact
                && contactData.getDisplayNameSource() == DisplayNameSources.NICKNAME;

        if (!duplicatesTitle) {
            header = res.getString(R.string.header_nickname_entry);
            subHeader = nickname.getName();
            entryContextMenuInfo = new EntryContextMenuInfo(subHeader, header, dataItem.getMimeType(),
                    dataItem.getId(), dataItem.isSuperPrimary());
        }
    } else if (dataItem instanceof NoteDataItem) {
        final NoteDataItem note = (NoteDataItem) dataItem;
        header = res.getString(R.string.header_note_entry);
        subHeader = note.getNote();
        entryContextMenuInfo = new EntryContextMenuInfo(subHeader, header, dataItem.getMimeType(),
                dataItem.getId(), dataItem.isSuperPrimary());
    } else if (dataItem instanceof WebsiteDataItem) {
        final WebsiteDataItem website = (WebsiteDataItem) dataItem;
        header = res.getString(R.string.header_website_entry);
        subHeader = website.getUrl();
        entryContextMenuInfo = new EntryContextMenuInfo(subHeader, header, dataItem.getMimeType(),
                dataItem.getId(), dataItem.isSuperPrimary());
        try {
            final WebAddress webAddress = new WebAddress(website.buildDataStringForDisplay(context, kind));
            intent = new Intent(Intent.ACTION_VIEW, Uri.parse(webAddress.toString()));
        } catch (final ParseException e) {
            Log.e(TAG, "Couldn't parse website: " + website.buildDataStringForDisplay(context, kind));
        }
    } else if (dataItem instanceof EventDataItem) {
        final EventDataItem event = (EventDataItem) dataItem;
        final String dataString = event.buildDataStringForDisplay(context, kind);
        final Calendar cal = DateUtils.parseDate(dataString, false);
        if (cal != null) {
            final Date nextAnniversary = DateUtils.getNextAnnualDate(cal);
            final Uri.Builder builder = CalendarContract.CONTENT_URI.buildUpon();
            builder.appendPath("time");
            ContentUris.appendId(builder, nextAnniversary.getTime());
            intent = new Intent(Intent.ACTION_VIEW).setData(builder.build());
        }
        header = res.getString(R.string.header_event_entry);
        if (event.hasKindTypeColumn(kind)) {
            subHeader = EventCompat.getTypeLabel(res, event.getKindTypeColumn(kind), event.getLabel())
                    .toString();
        }
        text = DateUtils.formatDate(context, dataString);
        entryContextMenuInfo = new EntryContextMenuInfo(text, header, dataItem.getMimeType(), dataItem.getId(),
                dataItem.isSuperPrimary());
    } else if (dataItem instanceof RelationDataItem) {
        final RelationDataItem relation = (RelationDataItem) dataItem;
        final String dataString = relation.buildDataStringForDisplay(context, kind);
        if (!TextUtils.isEmpty(dataString)) {
            intent = new Intent(Intent.ACTION_SEARCH);
            intent.putExtra(SearchManager.QUERY, dataString);
            intent.setType(Contacts.CONTENT_TYPE);
        }
        header = res.getString(R.string.header_relation_entry);
        subHeader = relation.getName();
        entryContextMenuInfo = new EntryContextMenuInfo(subHeader, header, dataItem.getMimeType(),
                dataItem.getId(), dataItem.isSuperPrimary());
        if (relation.hasKindTypeColumn(kind)) {
            text = Relation.getTypeLabel(res, relation.getKindTypeColumn(kind), relation.getLabel()).toString();
        }
    } else if (dataItem instanceof PhoneDataItem) {
        final PhoneDataItem phone = (PhoneDataItem) dataItem;
        String phoneLabel = null;
        if (!TextUtils.isEmpty(phone.getNumber())) {
            primaryContentDescription.append(res.getString(R.string.call_other)).append(" ");
            header = sBidiFormatter.unicodeWrap(phone.buildDataStringForDisplay(context, kind),
                    TextDirectionHeuristics.LTR);
            entryContextMenuInfo = new EntryContextMenuInfo(header, res.getString(R.string.phoneLabelsGroup),
                    dataItem.getMimeType(), dataItem.getId(), dataItem.isSuperPrimary());
            if (phone.hasKindTypeColumn(kind)) {
                final int kindTypeColumn = phone.getKindTypeColumn(kind);
                final String label = phone.getLabel();
                phoneLabel = label;
                if (kindTypeColumn == Phone.TYPE_CUSTOM && TextUtils.isEmpty(label)) {
                    text = "";
                } else {
                    text = Phone.getTypeLabel(res, kindTypeColumn, label).toString();
                    phoneLabel = text;
                    primaryContentDescription.append(text).append(" ");
                }
            }
            primaryContentDescription.append(header);
            phoneContentDescription = com.android.contacts.common.util.ContactDisplayUtils
                    .getTelephoneTtsSpannable(primaryContentDescription.toString(), header);
            icon = res.getDrawable(R.drawable.ic_phone_24dp);
            iconResourceId = R.drawable.ic_phone_24dp;
            if (PhoneCapabilityTester.isPhone(context)) {
                intent = CallUtil.getCallIntent(phone.getNumber());
            }
            alternateIntent = new Intent(Intent.ACTION_SENDTO,
                    Uri.fromParts(ContactsUtils.SCHEME_SMSTO, phone.getNumber(), null));

            alternateIcon = res.getDrawable(R.drawable.ic_message_24dp);
            alternateContentDescription.append(res.getString(R.string.sms_custom, header));
            smsContentDescription = com.android.contacts.common.util.ContactDisplayUtils
                    .getTelephoneTtsSpannable(alternateContentDescription.toString(), header);

            int videoCapability = CallUtil.getVideoCallingAvailability(context);
            boolean isPresenceEnabled = (videoCapability & CallUtil.VIDEO_CALLING_PRESENCE) != 0;
            boolean isVideoEnabled = (videoCapability & CallUtil.VIDEO_CALLING_ENABLED) != 0;

            if (CallUtil.isCallWithSubjectSupported(context)) {
                thirdIcon = res.getDrawable(R.drawable.ic_call_note_white_24dp);
                thirdAction = Entry.ACTION_CALL_WITH_SUBJECT;
                thirdContentDescription = res.getString(R.string.call_with_a_note);
                // Create a bundle containing the data the call subject dialog requires.
                thirdExtras = new Bundle();
                thirdExtras.putLong(CallSubjectDialog.ARG_PHOTO_ID, contactData.getPhotoId());
                thirdExtras.putParcelable(CallSubjectDialog.ARG_PHOTO_URI,
                        UriUtils.parseUriOrNull(contactData.getPhotoUri()));
                thirdExtras.putParcelable(CallSubjectDialog.ARG_CONTACT_URI, contactData.getLookupUri());
                thirdExtras.putString(CallSubjectDialog.ARG_NAME_OR_NUMBER, contactData.getDisplayName());
                thirdExtras.putBoolean(CallSubjectDialog.ARG_IS_BUSINESS, false);
                thirdExtras.putString(CallSubjectDialog.ARG_NUMBER, phone.getNumber());
                thirdExtras.putString(CallSubjectDialog.ARG_DISPLAY_NUMBER, phone.getFormattedPhoneNumber());
                thirdExtras.putString(CallSubjectDialog.ARG_NUMBER_LABEL, phoneLabel);
            } else if (isVideoEnabled) {
                // Check to ensure carrier presence indicates the number supports video calling.
                int carrierPresence = dataItem.getCarrierPresence();
                boolean isPresent = (carrierPresence & Phone.CARRIER_PRESENCE_VT_CAPABLE) != 0;

                if ((isPresenceEnabled && isPresent) || !isPresenceEnabled) {
                    thirdIcon = res.getDrawable(R.drawable.ic_videocam);
                    thirdAction = Entry.ACTION_INTENT;
                    thirdIntent = CallUtil.getVideoCallIntent(phone.getNumber(),
                            CALL_ORIGIN_QUICK_CONTACTS_ACTIVITY);
                    thirdContentDescription = res.getString(R.string.description_video_call);
                }
            }
        }
    } else if (dataItem instanceof EmailDataItem) {
        final EmailDataItem email = (EmailDataItem) dataItem;
        final String address = email.getData();
        if (!TextUtils.isEmpty(address)) {
            primaryContentDescription.append(res.getString(R.string.email_other)).append(" ");
            final Uri mailUri = Uri.fromParts(ContactsUtils.SCHEME_MAILTO, address, null);
            intent = new Intent(Intent.ACTION_SENDTO, mailUri);
            header = email.getAddress();
            entryContextMenuInfo = new EntryContextMenuInfo(header, res.getString(R.string.emailLabelsGroup),
                    dataItem.getMimeType(), dataItem.getId(), dataItem.isSuperPrimary());
            if (email.hasKindTypeColumn(kind)) {
                text = Email.getTypeLabel(res, email.getKindTypeColumn(kind), email.getLabel()).toString();
                primaryContentDescription.append(text).append(" ");
            }
            primaryContentDescription.append(header);
            icon = res.getDrawable(R.drawable.ic_email_24dp);
            iconResourceId = R.drawable.ic_email_24dp;
        }
    } else if (dataItem instanceof StructuredPostalDataItem) {
        StructuredPostalDataItem postal = (StructuredPostalDataItem) dataItem;
        final String postalAddress = postal.getFormattedAddress();
        if (!TextUtils.isEmpty(postalAddress)) {
            primaryContentDescription.append(res.getString(R.string.map_other)).append(" ");
            intent = StructuredPostalUtils.getViewPostalAddressIntent(postalAddress);
            header = postal.getFormattedAddress();
            entryContextMenuInfo = new EntryContextMenuInfo(header, res.getString(R.string.postalLabelsGroup),
                    dataItem.getMimeType(), dataItem.getId(), dataItem.isSuperPrimary());
            if (postal.hasKindTypeColumn(kind)) {
                text = StructuredPostal.getTypeLabel(res, postal.getKindTypeColumn(kind), postal.getLabel())
                        .toString();
                primaryContentDescription.append(text).append(" ");
            }
            primaryContentDescription.append(header);
            alternateIntent = StructuredPostalUtils.getViewPostalAddressDirectionsIntent(postalAddress);
            alternateIcon = res.getDrawable(R.drawable.ic_directions_24dp);
            alternateContentDescription.append(res.getString(R.string.content_description_directions))
                    .append(" ").append(header);
            icon = res.getDrawable(R.drawable.ic_place_24dp);
            iconResourceId = R.drawable.ic_place_24dp;
        }
    } else if (dataItem instanceof SipAddressDataItem) {
        final SipAddressDataItem sip = (SipAddressDataItem) dataItem;
        final String address = sip.getSipAddress();
        if (!TextUtils.isEmpty(address)) {
            primaryContentDescription.append(res.getString(R.string.call_other)).append(" ");
            if (PhoneCapabilityTester.isSipPhone(context)) {
                final Uri callUri = Uri.fromParts(PhoneAccount.SCHEME_SIP, address, null);
                intent = CallUtil.getCallIntent(callUri);
            }
            header = address;
            entryContextMenuInfo = new EntryContextMenuInfo(header, res.getString(R.string.phoneLabelsGroup),
                    dataItem.getMimeType(), dataItem.getId(), dataItem.isSuperPrimary());
            if (sip.hasKindTypeColumn(kind)) {
                text = SipAddress.getTypeLabel(res, sip.getKindTypeColumn(kind), sip.getLabel()).toString();
                primaryContentDescription.append(text).append(" ");
            }
            primaryContentDescription.append(header);
            icon = res.getDrawable(R.drawable.ic_dialer_sip_black_24dp);
            iconResourceId = R.drawable.ic_dialer_sip_black_24dp;
        }
    } else if (dataItem instanceof StructuredNameDataItem) {
        // If the name is already set and this is not the super primary value then leave the
        // current value. This way we show the super primary value when we are able to.
        if (dataItem.isSuperPrimary() || aboutCardName.value == null || aboutCardName.value.isEmpty()) {
            final String givenName = ((StructuredNameDataItem) dataItem).getGivenName();
            if (!TextUtils.isEmpty(givenName)) {
                aboutCardName.value = res.getString(R.string.about_card_title) + " " + givenName;
            } else {
                aboutCardName.value = res.getString(R.string.about_card_title);
            }
        }
    } else {
        // Custom DataItem
        header = dataItem.buildDataStringForDisplay(context, kind);
        text = kind.typeColumn;
        intent = new Intent(Intent.ACTION_VIEW);
        final Uri uri = ContentUris.withAppendedId(Data.CONTENT_URI, dataItem.getId());
        intent.setDataAndType(uri, dataItem.getMimeType());

        if (intent != null) {
            final String mimetype = intent.getType();

            // Build advanced entry for known 3p types. Otherwise default to ResolveCache icon.
            switch (mimetype) {
            case MIMETYPE_GPLUS_PROFILE:
                // If a secondDataItem is available, use it to build an entry with
                // alternate actions
                if (secondDataItem != null) {
                    icon = res.getDrawable(R.drawable.ic_google_plus_24dp);
                    alternateIcon = res.getDrawable(R.drawable.ic_add_to_circles_black_24);
                    final GPlusOrHangoutsDataItemModel itemModel = new GPlusOrHangoutsDataItemModel(intent,
                            alternateIntent, dataItem, secondDataItem, alternateContentDescription, header,
                            text, context);

                    populateGPlusOrHangoutsDataItemModel(itemModel);
                    intent = itemModel.intent;
                    alternateIntent = itemModel.alternateIntent;
                    alternateContentDescription = itemModel.alternateContentDescription;
                    header = itemModel.header;
                    text = itemModel.text;
                } else {
                    if (GPLUS_PROFILE_DATA_5_ADD_TO_CIRCLE.equals(intent.getDataString())) {
                        icon = res.getDrawable(R.drawable.ic_add_to_circles_black_24);
                    } else {
                        icon = res.getDrawable(R.drawable.ic_google_plus_24dp);
                    }
                }
                break;
            case MIMETYPE_HANGOUTS:
                // If a secondDataItem is available, use it to build an entry with
                // alternate actions
                if (secondDataItem != null) {
                    icon = res.getDrawable(R.drawable.ic_hangout_24dp);
                    alternateIcon = res.getDrawable(R.drawable.ic_hangout_video_24dp);
                    final GPlusOrHangoutsDataItemModel itemModel = new GPlusOrHangoutsDataItemModel(intent,
                            alternateIntent, dataItem, secondDataItem, alternateContentDescription, header,
                            text, context);

                    populateGPlusOrHangoutsDataItemModel(itemModel);
                    intent = itemModel.intent;
                    alternateIntent = itemModel.alternateIntent;
                    alternateContentDescription = itemModel.alternateContentDescription;
                    header = itemModel.header;
                    text = itemModel.text;
                } else {
                    if (HANGOUTS_DATA_5_VIDEO.equals(intent.getDataString())) {
                        icon = res.getDrawable(R.drawable.ic_hangout_video_24dp);
                    } else {
                        icon = res.getDrawable(R.drawable.ic_hangout_24dp);
                    }
                }
                break;
            default:
                entryContextMenuInfo = new EntryContextMenuInfo(header, mimetype, dataItem.getMimeType(),
                        dataItem.getId(), dataItem.isSuperPrimary());
                icon = ResolveCache.getInstance(context).getIcon(dataItem.getMimeType(), intent);
                // Call mutate to create a new Drawable.ConstantState for color filtering
                if (icon != null) {
                    icon.mutate();
                }
                shouldApplyColor = false;
            }
        }
    }

    if (intent != null) {
        // Do not set the intent is there are no resolves
        if (!PhoneCapabilityTester.isIntentRegistered(context, intent)) {
            intent = null;
        }
    }

    if (alternateIntent != null) {
        // Do not set the alternate intent is there are no resolves
        if (!PhoneCapabilityTester.isIntentRegistered(context, alternateIntent)) {
            alternateIntent = null;
        } else if (TextUtils.isEmpty(alternateContentDescription)) {
            // Attempt to use package manager to find a suitable content description if needed
            alternateContentDescription.append(getIntentResolveLabel(alternateIntent, context));
        }
    }

    // If the Entry has no visual elements, return null
    if (icon == null && TextUtils.isEmpty(header) && TextUtils.isEmpty(subHeader) && subHeaderIcon == null
            && TextUtils.isEmpty(text) && textIcon == null) {
        return null;
    }

    // Ignore dataIds from the Me profile.
    final int dataId = dataItem.getId() > Integer.MAX_VALUE ? -1 : (int) dataItem.getId();

    return new Entry(dataId, icon, header, subHeader, subHeaderIcon, text, textIcon,
            phoneContentDescription == null ? new SpannableString(primaryContentDescription.toString())
                    : phoneContentDescription,
            intent, alternateIcon, alternateIntent,
            smsContentDescription == null ? new SpannableString(alternateContentDescription.toString())
                    : smsContentDescription,
            shouldApplyColor, isEditable, entryContextMenuInfo, thirdIcon, thirdIntent, thirdContentDescription,
            thirdAction, thirdExtras, iconResourceId);
}

From source file:com.hichinaschool.flashcards.async.DeckTask.java

private TaskData doInBackgroundImportAdd(TaskData... params) {
    // Log.i(AnkiDroidApp.TAG, "doInBackgroundImportAdd");
    Resources res = AnkiDroidApp.getInstance().getBaseContext().getResources();
    Collection col = params[0].getCollection();
    String path = params[0].getString();
    boolean sharedDeckImport = params[0].getBoolean();

    ProgressCallback pc = null;//from w  w  w .j  a v a2  s.co  m
    // don't report progress on shared deck import (or maybe should we?)
    if (!sharedDeckImport) {
        pc = new ProgressCallback(this, res);
    }

    int addedCount = -1;
    try {
        Anki2Importer imp = new Anki2Importer(col, path, pc);
        AnkiDb ankiDB = col.getDb();
        ankiDB.getDatabase().beginTransaction();
        try {
            addedCount = imp.run();
            ankiDB.getDatabase().setTransactionSuccessful();
        } finally {
            ankiDB.getDatabase().endTransaction();
            if (sharedDeckImport) {
                File tmpFile = new File(path);
                tmpFile.delete();
            }
        }
        if (addedCount >= 0) {
            ankiDB.execute("VACUUM");
            ankiDB.execute("ANALYZE");
        }

        publishProgress(new TaskData(res.getString(R.string.import_update_counts)));
        // Update the counts
        DeckTask.TaskData result = doInBackgroundLoadDeckCounts(new TaskData(col));
        if (result == null) {
            return null;
        }
        return new TaskData(addedCount, result.getObjArray(), true);
    } catch (RuntimeException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundImportAdd - RuntimeException on importing cards: ", e);
        AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportAdd");
        return new TaskData(false);
    } catch (IOException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundImportAdd - IOException on importing cards: ", e);
        AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportAdd");
        return new TaskData(false);
    }
}

From source file:com.ichi2.async.DeckTask.java

private TaskData doInBackgroundImportAdd(TaskData... params) {
    Timber.d("doInBackgroundImportAdd");
    Resources res = AnkiDroidApp.getInstance().getBaseContext().getResources();
    Collection col = CollectionHelper.getInstance().getCol(mContext);
    String path = params[0].getString();
    boolean sharedDeckImport = params[0].getBoolean();

    ProgressCallback pc = null;/*from   w w  w.  j av  a  2  s. c o  m*/
    // don't report progress on shared deck import (or maybe should we?)
    if (!sharedDeckImport) {
        pc = new ProgressCallback(this, res);
    }

    int addedCount = -1;
    try {
        Anki2Importer imp = new Anki2Importer(col, path, pc);
        AnkiDb ankiDB = col.getDb();
        ankiDB.getDatabase().beginTransaction();
        try {
            addedCount = imp.run();
            // Rollback db transaction if an error occured (TODO: doesn't appear to be working)
            if (addedCount >= 0) {
                ankiDB.getDatabase().setTransactionSuccessful();
            }
        } finally {
            ankiDB.getDatabase().endTransaction();
            if (sharedDeckImport) {
                File tmpFile = new File(path);
                tmpFile.delete();
            }
        }
        if (addedCount >= 0) {
            ankiDB.execute("VACUUM");
            ankiDB.execute("ANALYZE");
        }

        publishProgress(new TaskData(res.getString(R.string.import_update_counts)));
        return new TaskData(addedCount, null, true);
    } catch (RuntimeException e) {
        Timber.e(e, "doInBackgroundImportAdd - RuntimeException on importing cards");
        AnkiDroidApp.sendExceptionReport(e, "doInBackgroundImportAdd");
        return new TaskData(false);
    } catch (IOException e) {
        Timber.e(e, "doInBackgroundImportAdd - IOException on importing cards: ");
        AnkiDroidApp.sendExceptionReport(e, "doInBackgroundImportAdd");
        return new TaskData(false);
    }
}

From source file:com.android.mms.ui.MessageUtils.java

public static String getMmsDetail(Context context, Uri uri, int size, int msgBox) {
    Resources res = context.getResources();
    MultimediaMessagePdu msg;/*from w w  w  . j  av  a 2  s  .  c om*/
    try {
        msg = (MultimediaMessagePdu) PduPersister.getPduPersister(context).load(uri);
    } catch (MmsException e) {
        Log.e(TAG, "Failed to load the message: " + uri, e);
        return res.getString(R.string.cannot_get_details);
    }

    StringBuilder details = new StringBuilder();
    // Message Type: Text message.
    initializeMsgDetails(context, details, res, msg);

    // SentDate: ***
    if (msg.getDateSent() > 0 && msgBox == Mms.MESSAGE_BOX_INBOX) {
        details.append('\n');
        details.append(res.getString(R.string.sent_label));
        details.append(MessageUtils.formatTimeStampString(context, msg.getDateSent() * 1000L, true));
    }

    // Date: ***
    details.append('\n');
    if (msgBox == Mms.MESSAGE_BOX_DRAFTS) {
        details.append(res.getString(R.string.saved_label));
    } else if (msgBox == Mms.MESSAGE_BOX_INBOX) {
        details.append(res.getString(R.string.received_label));
    } else {
        details.append(res.getString(R.string.sent_label));
    }

    details.append(MessageUtils.formatTimeStampString(context, msg.getDate() * 1000L, true));

    // Subject: ***
    details.append('\n');
    details.append(res.getString(R.string.subject_label));

    EncodedStringValue subject = msg.getSubject();
    if (subject != null) {
        String subStr = subject.getString();
        // Message size already include size of subject.
        //            size += subStr.length();
        details.append(subStr);
    }
    // Priority: High/Normal/Low
    return formatDetails(details, context, msg, size, res);
}

From source file:com.nit.async.DeckTask.java

private TaskData doInBackgroundImportAdd(TaskData... params) {
    // Log.i(AnkiDroidApp.TAG, "doInBackgroundImportAdd");
    Resources res = AnkiDroidApp.getInstance().getBaseContext().getResources();
    Collection col = params[0].getCollection();
    String path = params[0].getString();
    boolean currDeckImport = params[0].getBoolean();

    ProgressCallback pc = null;/*from  ww w . j a v a 2 s  .  c  om*/
    //        // don't report progress on shared deck import (or maybe should we?)
    //        if (!sharedDeckImport) {
    //            pc = new ProgressCallback(this, res);
    //        }

    int addedCount = -1;
    try {
        Anki2Importer imp = new Anki2Importer(col, path, pc);
        AnkiDb ankiDB = col.getDb();
        ankiDB.getDatabase().beginTransaction();
        try {
            addedCount = imp.run(currDeckImport);
            ankiDB.getDatabase().setTransactionSuccessful();
        } finally {
            ankiDB.getDatabase().endTransaction();
            //                if (sharedDeckImport) {
            //                    File tmpFile = new File(path);
            //                    tmpFile.delete();
            //                }
        }
        if (addedCount >= 0) {
            ankiDB.execute("VACUUM");
            ankiDB.execute("ANALYZE");
        }

        publishProgress(new TaskData(res.getString(R.string.import_update_counts)));
        // Update the counts
        DeckTask.TaskData result = doInBackgroundLoadDeckCounts(new TaskData(col));
        if (result == null) {
            return null;
        }
        return new TaskData(addedCount, result.getObjArray(), true);
    } catch (RuntimeException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundImportAdd - RuntimeException on importing cards: ", e);
        AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportAdd");
        return new TaskData(false);
    } catch (IOException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundImportAdd - IOException on importing cards: ", e);
        AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportAdd");
        return new TaskData(false);
    }
}

From source file:com.ichi2.anki.DeckPicker.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Resources res = getResources();
    switch (item.getItemId()) {

    case R.id.action_undo:
        Timber.i("DeckPicker:: Undo button pressed");
        undo();//  ww  w.j a va2 s .  c  om
        return true;

    case R.id.action_sync:
        Timber.i("DeckPicker:: Sync button pressed");
        sync();
        return true;

    case R.id.action_import:
        Timber.i("DeckPicker:: Import button pressed");
        showImportDialog(ImportDialog.DIALOG_IMPORT_HINT);
        return true;

    case R.id.action_new_filtered_deck:
        Timber.i("DeckPicker:: New filtered deck button pressed");
        mDialogEditText = new EditText(DeckPicker.this);
        ArrayList<String> names = getCol().getDecks().allNames();
        int n = 1;
        String name = String.format("%s %d", res.getString(R.string.filtered_deck_name), n);
        while (names.contains(name)) {
            n++;
            name = String.format("%s %d", res.getString(R.string.filtered_deck_name), n);
        }
        mDialogEditText.setText(name);
        // mDialogEditText.setFilters(new InputFilter[] { mDeckNameFilter });
        new MaterialDialog.Builder(DeckPicker.this).title(res.getString(R.string.new_deck))
                .customView(mDialogEditText, true).positiveText(res.getString(R.string.create))
                .negativeText(res.getString(R.string.dialog_cancel))
                .callback(new MaterialDialog.ButtonCallback() {
                    @Override
                    public void onPositive(MaterialDialog dialog) {
                        String filteredDeckName = mDialogEditText.getText().toString();
                        Timber.i("DeckPicker:: Creating filtered deck...");
                        getCol().getDecks().newDyn(filteredDeckName);
                        openStudyOptions(true);
                    }
                }).show();
        return true;

    case R.id.action_check_database:
        Timber.i("DeckPicker:: Check database button pressed");
        showDatabaseErrorDialog(DatabaseErrorDialog.DIALOG_CONFIRM_DATABASE_CHECK);
        return true;

    case R.id.action_check_media:
        Timber.i("DeckPicker:: Check media button pressed");
        showMediaCheckDialog(MediaCheckDialog.DIALOG_CONFIRM_MEDIA_CHECK);
        return true;

    case R.id.action_empty_cards:
        Timber.i("DeckPicker:: Empty cards button pressed");
        handleEmptyCards();
        return true;

    case R.id.action_model_browser_open:
        Timber.i("DeckPicker:: Model browser button pressed");
        Intent noteTypeBrowser = new Intent(this, ModelBrowser.class);
        startActivityForResultWithAnimation(noteTypeBrowser, 0, ActivityTransitionAnimation.LEFT);
        return true;

    case R.id.action_restore_backup:
        Timber.i("DeckPicker:: Restore from backup button pressed");
        showDatabaseErrorDialog(DatabaseErrorDialog.DIALOG_CONFIRM_RESTORE_BACKUP);
        return true;

    case R.id.action_export:
        Timber.i("DeckPicker:: Export collection button pressed");
        String msg = getResources().getString(R.string.confirm_apkg_export);
        showDialogFragment(ExportDialog.newInstance(msg));
        return true;
    default:
        return super.onOptionsItemSelected(item);

    }
}

From source file:com.google.android.apps.forscience.whistlepunk.RunReviewOverlay.java

private void init() {
    Resources res = getResources();

    mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mPaint.setStyle(Paint.Style.FILL);

    mDotPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mDotPaint.setStyle(Paint.Style.FILL);

    mDotBackgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mDotBackgroundPaint.setColor(res.getColor(R.color.chart_margins_color));
    mDotBackgroundPaint.setStyle(Paint.Style.FILL);

    Typeface valueTypeface = Typeface.create("sans-serif-medium", Typeface.NORMAL);
    Typeface timeTimeface = Typeface.create("sans-serif", Typeface.NORMAL);

    mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mTextPaint.setTypeface(valueTypeface);
    mTextPaint.setTextSize(res.getDimension(R.dimen.run_review_overlay_label_text_size));
    mTextPaint.setColor(res.getColor(R.color.text_color_white));

    mTimePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mTimePaint.setTypeface(timeTimeface);
    mTimePaint.setTextSize(res.getDimension(R.dimen.run_review_overlay_label_text_size));
    mTimePaint.setColor(res.getColor(R.color.text_color_white));

    mCenterLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mCenterLinePaint.setStrokeWidth(res.getDimensionPixelSize(R.dimen.chart_grid_line_width));
    mCenterLinePaint.setStyle(Paint.Style.STROKE);
    mCenterLinePaint.setColor(res.getColor(R.color.text_color_white));

    mLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mLinePaint.setStrokeWidth(res.getDimensionPixelSize(R.dimen.recording_overlay_bar_width));
    int dashSize = res.getDimensionPixelSize(R.dimen.run_review_overlay_dash_size);
    mLinePaint.setPathEffect(new DashPathEffect(new float[] { dashSize, dashSize }, dashSize));
    mLinePaint.setColor(res.getColor(R.color.note_overlay_line_color));
    mLinePaint.setStyle(Paint.Style.STROKE);

    mPath = new Path();

    // TODO: Need to make sure this is at least as detailed as the SensorAppearance number
    // format!/*from  ww  w.  ja  va2  s . c  o m*/
    mTextFormat = res.getString(R.string.run_review_chart_label_format);
    mTimeFormat = ElapsedTimeAxisFormatter.getInstance(getContext());

    mCropBackgroundPaint = new Paint();
    mCropBackgroundPaint.setStyle(Paint.Style.FILL);
    mCropBackgroundPaint.setColor(res.getColor(R.color.text_color_black));
    mCropBackgroundPaint.setAlpha(40);

    mCropVerticalLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mCropVerticalLinePaint.setStyle(Paint.Style.STROKE);
    mCropVerticalLinePaint.setStrokeWidth(res.getDimensionPixelSize(R.dimen.chart_grid_line_width));
}

From source file:com.android.mail.compose.ComposeActivity.java

/**
 * Returns a formatted subject string with the appropriate prefix for the action type.
 * E.g., "FWD: " is prepended if action is {@link ComposeActivity#FORWARD}.
 *///from  w ww  .j a  v  a2  s.c o m
public static String buildFormattedSubject(Resources res, String subject, int action) {
    final String prefix;
    final String correctedSubject;
    if (action == ComposeActivity.COMPOSE) {
        prefix = "";
    } else if (action == ComposeActivity.FORWARD) {
        prefix = res.getString(R.string.forward_subject_label);
    } else {
        prefix = res.getString(R.string.reply_subject_label);
    }

    if (TextUtils.isEmpty(subject)) {
        correctedSubject = prefix;
    } else {
        // Don't duplicate the prefix
        if (subject.toLowerCase().startsWith(prefix.toLowerCase())) {
            correctedSubject = subject;
        } else {
            correctedSubject = String.format(res.getString(R.string.formatted_subject), prefix, subject);
        }
    }

    return correctedSubject;
}

From source file:com.aliyun.homeshell.Folder.java

/**
 * Used to inflate the Workspace from XML.
 *
 * @param context The application's context.
 * @param attrs The attribtues set containing the Workspace's customization values.
 *///from   w  w w  .  j a  v a2  s . c  o  m
public Folder(Context context, AttributeSet attrs) {
    super(context, attrs);
    setAlwaysDrawnWithCacheEnabled(false);
    mInflater = LayoutInflater.from(context);

    /* YUNOS BEGIN */
    //##date:2014/04/16 ##author:nater.wg ##BugID:110407
    // Enhance ConfigManager.
    /*
            Resources res = getResources();
            mMaxCountX = res.getInteger(R.integer.folder_max_count_x);
            mMaxCountY = res.getInteger(R.integer.folder_max_count_y);
            mMaxNumItems = res.getInteger(R.integer.folder_max_num_items);
            if (mMaxCountX < 0 || mMaxCountY < 0 || mMaxNumItems < 0) {
    mMaxCountX = LauncherModel.getCellCountX();
    mMaxCountY = LauncherModel.getCellCountY();
    mMaxNumItems = mMaxCountX * mMaxCountY;
            }
    */
    mLauncher = (Launcher) context;
    mIconManager = mLauncher.getIconManager();
    mMaxCountX = ConfigManager.getFolderMaxCountX();
    mMaxCountY = mIconManager.supprtCardIcon() ? ConfigManager.getCardFolderMaxCountY()
            : ConfigManager.getFolderMaxCountY();
    mMaxNumItems = mMaxCountX * mMaxCountY;
    /* YUNOS END */

    Resources res = getResources();
    mInputMethodManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);

    mExpandDuration = res.getInteger(R.integer.config_folderAnimDuration);

    if (sDefaultFolderName == null) {
        sDefaultFolderName = res.getString(R.string.folder_name);
    }
    /*
     * if (sHintText == null) { sHintText =
     * res.getString(R.string.folder_hint_text); }
     */
    // We need this view to be focusable in touch mode so that when text editing of the folder
    // name is complete, we have something to focus on, thus hiding the cursor and giving
    // reliable behvior when clicking the text field (since it will always gain focus on click).
    setFocusableInTouchMode(true);

    mShortcutInfoCache = new ShortcutInfo();
    mIconManager = mLauncher.getIconManager();
    /* YUNOS BEGIN */
    //##date:2014/09/23 ##author:andy.zx ##BugID:5244732
    Display display = mLauncher.getWindowManager().getDefaultDisplay();
    display.getSize(mDisplaySize);
    /* YUNOS END */
}