Android Build an Interactive Story App Intents and Multiple Activities Getting Resources from the Context

bot .net
bot .net
9,766 Points

We use string resources because we dont want to hard code some values, such as the name of the app?

Hi, i dont fully understand yet why we use the strings.xml and declare :

 <string name="key_name">name</string>

instead of keeping the key as "name"?

is it because we dont want to hard code the value "name"? I mean understand the example of the name of the app, that we dont want to change each file name if we hard code it, but why we need to do this for the name as well?

i hope u understand my question

Lauren Moineau

1 Answer

Lauren Moineau
PRO
Lauren Moineau
Pro Student 8,360 Points

Hi noob developer. You're right, the golden rule is to avoid hardcoding strings. Why?

  • You could accidentally delete/modify part of the string while coding and not realise it as it wouldn't throw any error or warning (until you run the app and notice something different on the UI)
  • If a string is repeated several times in different activities in the app, then if you decide to change its value later, you'll only need to do it in one place (strings.xml)
  • Localization (= translating your app to other languages).

If you store all your strings in the string resource file (strings.xml), then in Android studio, at the click of a button, you have them all listed, can select a different language from a list and write a translation for each of them. So it makes it very easy to translate all the text in your app: text, text on buttons, user prompts, error messages, etc.. as it's all in one place.

Now, in this example, saving it in strings.xml falls in category #2 up there (centralising strings) as we also need it in StoryActivity when getting the intent.

Although, for keys (from key-value pairs), the norm is to create a constant variable:

public static final String KEY_NAME = "key_name";

So you'd write: intent.putExtra(KEY_NAME, name);. It will be introduced later in the course.

My guess is that Ben didn't want to introduce too much at once and using strings.xml was a good alternative here, and practice.

Hope that helps :)