When to use getString()

roiberg picture roiberg · Dec 12, 2013 · Viewed 7.2k times · Source

I am wondering about the getString(). I can see that doing getString(R.string.some_text) works. Also getResources().getString(R.string.connection_error) works. So my question is why should we use the getString or when? Thanks!

Answer

Martin Marconcini picture Martin Marconcini · Dec 12, 2013

The question is easy to misinterpret.

If you are in a valid context (like an Activity), there is no difference, because the context has a reference to the resources, so it can resolve a getString(int); directly, which returns a String.

Adding more information for your peace of mind.

If you can use getString directly, go ahead and do it. Now sometimes you might need to use getResources() because it contains a lot of helper methods.

This is the Android source code for getResources.getString():

/**
     * Return the string value associated with a particular resource ID.  It
     * will be stripped of any styled text information.
     * {@more}
     *
     * @param id The desired resource identifier, as generated by the aapt
     *           tool. This integer encodes the package, type, and resource
     *           entry. The value 0 is an invalid identifier.
     *
     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
     *
     * @return String The string data associated with the resource,
     * stripped of styled text information.
     */
    public String getString(int id) throws NotFoundException {
        CharSequence res = getText(id);
        if (res != null) {
            return res.toString();
        }
        throw new NotFoundException("String resource ID #0x"
                                    + Integer.toHexString(id));
    }

Neat huh? :)

The truth is that the Resources object does a lot more than just "get strings", you can take a look here.

Now compare with the Activity version of getString():

Return a localized string from the application's package's default string table.

So in summary, other than the fact that the Resources object will be stripped of any styled text information. and that the Resources object can do a lot more, the end result is the same. The Activity version is a convenient shortcut :)