Friday, February 11, 2011

Android using R.string resource in TextView and ArrayList

Here are few examples of getting R.string resource in code of your application.
It all comes down to using getText() and getString() functions when needed.

Example 1
If you have an array list like this:
      private List<String> categories = new ArrayList<String>();
and you want to add a string from strings.xml to that list.

Let's say string is saved in strings.xml like this:
            <string name="first_category">The first category</string>

To add this string from strings.xml to categories list you need to use getString() function.
It goes like this:
            categories.add(getString(R.string.first_category));
If you try this without getString() function Eclipse will show an error.

Example 2
If you have a TextView like this:
      private TextView txtViewExample;
and you want to set its text to a string from string.xml.

The string you want to add is saved in strings.xml like this:
            <string name="stringExample">String Example</string>

  
If you try code like this:
txtViewExample.setText(R.string.stringExample);
TextView will show the correct text.

But, if you have a similar situation that needs you to add a text from strings.xml plus a string from a variable you might get into trouble.

Let's say you have a string variable:
      private String tempString="XX";
and you want txtViewExample to show text like this:
         String Example XX

If you try something like this:
txtViewExample.setText(R.string.stringExample + " " + tempString);

txtViewExample will show something like this:
         2131034177 XX
As you can see instead of text from strings.xml  --> stringExample
a number od R.string.stringExample resource is shown.

To do things right you need to use getText() function:

txtViewExample.setText(getText(R.string.stringExample) + " " + tempString);

Then you will get the right text displayed.

Hope this helps! ;-)