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 trialItai Shin
9,928 PointsDon't fully understand the use of "pageText"
I don't understand how does @Ben Jakuben used the pre-entered String and entered it to a new page in the story.
String pageText = getString(page.getTextId());
pageText = String.format(pageText, name);
thanks :-)
1 Answer
Boban Talevski
24,793 PointsWell, it all starts at the strings.xml file in the res directory. That's where all the story text is entered as separate string values with appropriate names indicating the page number. Then, it "continues" in the Story.java class and the Page.java class. In the Page class, we are defining the data for a page, and in the Story class, we are making an array of Page objects named pages to represent the whole story (hence the class name :)).
Keep in mind that all that data is initiated and ready to use at the point of code you posted as we are creating a Story object in StoryActivity's onCreate() method. And if you check the Story constructor, all the Page objects of the above mentioned pages array are filled with the appropriate data there. So all of that is ready and waiting to be used in our code as we please.
So, when we enter the loadPage method we have already passed a page number as a parameter, which is used to get the appropriate page object (page0 in this case) from the pages array, and we store that object in the variable page. Now that page object already has the ID of the String resource we want to show at that page (it was assigned in the Story constructor), and it can be retrieved by the getTextId() getter method, which Ben uses at the first line of code you posted. Using the textId as a parameter to the getString method, we are getting the actual String value which is assigned in the variable pageText.
The second line is used solely for the purpose of replacing the placeholder %1$s with the name the user has entered, and if there is no such placeholder in the string pageText, nothing happens, so it's safe to use it for every page.
Also, keep in mind that we don't have to do this in multiple lines of code, including setting the text in the storyTextView. It can be also written like this:
storyTextView.setText(String.format(getString(page.getTextId()), name));
Maybe you'll understand it better this way, what Ben does is splitting it in multiple lines for better readability.