2
Android and Model-View-Controller

In this chapter, you are going to upgrade GeoQuiz to present more than one question, as shown in Figure 2.1.

Figure 2.1  Next!

Next!

To make this happen, you are going to add a class named Question to the GeoQuiz project. An instance of this class will encapsulate a single true-false question.

Then, you will create an array of Question objects for QuizActivity to manage.

In the project tool window, right-click the com.bignerdranch.android.geoquiz package and select NewJava Class. Name the class Question and click OK (Figure 2.2).

In Question.java, add two member variables and a constructor.

The Question class holds two pieces of data: the question text and the question answer (true or false).

Why is mTextResId an int and not a String? The mTextResId variable will hold the resource ID (always an int) of a string resource for the question. You will create the question string resources in a later section.

These variables need getter and setter methods. Rather than typing them in yourself, you can have Android Studio generate the implementations for you.

The first step is to configure Android Studio to recognize the m prefix for member variables.

Open Android Studio’s preferences (from the Android Studio menu on Mac and from FileSettings on Windows). Expand Editor and then expand Code Style. Select Java, then choose the Code Generation tab.

In the Naming table, select the Field row and add m as the name prefix for fields (Figure 2.3). Then add s as the name prefix for static fields. (You will not be using the s prefix in the GeoQuiz project, but it will be useful in later projects.)

Click OK.

What is the point of setting these prefixes? Now, when you ask Android Studio to generate a getter for mTextResId, it will create getTextResId() rather than getMTextResId() and isAnswerTrue() rather than isMAnswerTrue().

Back in Question.java, right-click after the constructor and select Generate... and then Getter and Setter. Select mTextResId and mAnswerTrue and click OK to create a getter and setter for each variable. The results are shown in Listing 2.2.

Your Question class is now complete. In a moment, you will modify QuizActivity to work with Question. First, let’s take a look at how the pieces of GeoQuiz will work together.

You are going to have QuizActivity create an array of Question objects. It will then interact with the TextView and the three Buttons to display questions and provide feedback. Figure 2.4 diagrams these relationships.