Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.Start your free trial
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 :
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
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 :)