3.6 Adding the App’s Logic
Class MainActivity (Figs. 3.12–3.18) implements the Tip Calculator app’s logic. It calculates the tip and total bill amounts, then displays them in locale-specific currency format. To view the file, in the Project window, expand the app/Java/com.deitel.tipcalculator node and double click MainActivity.java. You’ll need to enter most of the code in Figs. 3.12–3.18.
Fig. 3.12 | MainActivity’s package and import statements.
1 // MainActivity.java
2 // Calculates a bill total based on a tip percentage
3 package com.deitel.tipcalculator;
4
5 import android.os.Bundle; // for saving state information
6 import android.support.v7.app.AppCompatActivity; // base class
7 import android.text.Editable; // for EditText event handling
8 import android.text.TextWatcher; // EditText listener
9 import android.widget.EditText; // for bill amount input
10 import android.widget.SeekBar; // for changing the tip percentage
11 import android.widget.SeekBar.OnSeekBarChangeListener; // SeekBar listener
12 import android.widget.TextView; // for displaying text
13
14 import java.text.NumberFormat; // for currency formatting
15
3.6.1 package and import Statements
Figure 3.12 shows the package statement and import statements in MainActivity.java. The package statement in line 3 was inserted when you created the project. When you open a Java file in the IDE, the import statements are collapsed—one is displayed with a to its left. You can click the to see the complete list of import statements.
Lines 5–14 import the classes and interfaces the app uses:
- Class Bundle of package android.os (line 5) stores key–value pairs of information—typically representing an app’s state or data that needs to be passed between activities. When another app is about to appear on the screen—e.g., when the user receives a phone call or launches another app—Android gives the currently executing app the opportunity to save its state in a Bundle. The Android runtime might subsequently kill the app—e.g., to reclaim its memory. When the app returns to the screen, the Android runtime passes the Bundle of the previously saved state to Activity method onCreate (Section 3.6.4). Then, the app can use the saved state to return the app to the state it was in when another app became active. We’ll use Bundles in Chapter 8 to pass data between activities.
- Class AppCompatActivity of package android.support.v7.app (line 6) provides the basic lifecycle methods of an app—we’ll discuss these shortly. AppCompatActivity is an indirect subclass of Activity (package android.app) that supports using newer Android features apps running on current and older Android platforms.
- Interface Editable of package android.text (line 7) allows you to modify the content and markup of text in a GUI.
- You implement interface TextWatcher of package android.text (line 8) to respond to events when the user changes the text in an EditText.
- Package android.widget (lines 9, 10 and 12) contains the widgets (i.e., views) and layouts that are used in Android GUIs. This app uses EditText (line 9), SeekBar (line 10) and TextView (line 12) widgets.
- You implement interface SeekBar.OnSeekBarChangeListener of package android.widget (line 11) to respond to the user moving the SeekBar’s thumb.
- Class NumberFormat of package java.text (line 14) provides numeric formatting capabilities, such as locale-specific currency and percentage formats.
3.6.2 MainActivity Subclass of AppCompatActivity
Class MainActivity (Figs. 3.13–3.18) is the Tip Calculator app’s Activity subclass. When you created the TipCalculator project, the IDE generated this class as a subclass of AppCompatActivity (an indirect subclass of Activity) and provided an override of class Activity’s inherited onCreate method (Fig. 3.15). Every Activity subclass must override this method. We’ll discuss onCreate shortly.
Fig. 3.13 | Class MainActivity is a subclass of Activity.
16 // MainActivity class for the Tip Calculator app
17 public class MainActivity extends Activity
{
18
3.6.3 Class Variables and Instance Variables
Figure 3.14 declares class MainActivity’s variables. The NumberFormat objects (lines 20–23) are used to format currency values and percentages, respectively. NumberFormat’s static method getCurrencyInstance returns a NumberFormat object that formats values as currency using the device’s locale. Similarly, static method getPercentInstance formats values as percentages using the device’s locale.
Fig. 3.14 | MainActivity class’s instance variables.
19 // currency and percent formatter objects
20 private static final NumberFormat currencyFormat =
21 NumberFormat.getCurrencyInstance();
22 private static final NumberFormat percentFormat =
23 NumberFormat.getPercentInstance();
24
25 private double billAmount = 0.0; // bill amount entered by the user
26 private double percent = 0.15; // initial tip percentage
27 private TextView amountTextView; // shows formatted bill amount
28 private TextView percentTextView; // shows tip percentage
29 private TextView tipTextView; // shows calculated tip amount
30 private TextView totalTextView; // shows calculated total bill amount
31
The bill amount entered by the user into amountEditText will be read and stored as a double in billAmount (line 25). The tip percentage (an integer in the range 0–30) that the user sets by moving the Seekbar thumb will be divided by 100.0 to create a double for use in calculations, then stored in percent (line 26). For example, if you select 25 with the SeekBar, percent will store 0.25, so the app will multiply the bill amount by 0.25 to calculate the 25% tip.
Line 27 declares the TextView that displays the currency-formatted bill amount. Line 28 declares the TextView that displays the tip percentage, based on the SeekBar thumb’s position (see the 15% in Fig. 3.1(a)). The variables in line 29–30 will refer to the TextViews in which the app displays the calculated tip and total.
3.6.4 Overriding Activity Method onCreate
The onCreate method (Fig. 3.15)—which is autogenerated with lines 33–36 when you create the app’s project—is called by the system when an Activity is started. Method onCreate typically initializes the Activity’s instance variables and views. This method should be as simple as possible so that the app loads quickly. In fact, if the app takes longer than five seconds to load, the operating system will display an ANR (Application Not Responding) dialog—giving the user the option to forcibly terminate the app. You’ll learn how to prevent this problem in Chapter 9.
Fig. 3.15 | Overriding Activity method onCreate.
32 // called when the activity is first created
33 @Override
34 protected void onCreate(Bundle savedInstanceState) {
35 super.onCreate(savedInstanceState); // call superclass's version
36 setContentView(R.layout.activity_main); // inflate the GUI
37
38 // get references to programmatically manipulated TextViews
39 amountTextView = (TextView) findViewById(R.id.amountTextView);
40 percentTextView = (TextView) findViewById(R.id.percentTextView);
41 tipTextView = (TextView) findViewById(R.id.tipTextView);
42 totalTextView = (TextView) findViewById(R.id.totalTextView);
43 tipTextView.setText(currencyFormat.format(0)); // set text to 0
44 totalTextView.setText(currencyFormat.format(0)); // set text to 0
45
46 // set amountEditText's TextWatcher
47 EditText amountEditText =
48 (EditText) findViewById(R.id.amountEditText);
49 amountEditText.addTextChangedListener(amountEditTextWatcher);
50
51 // set percentSeekBar's OnSeekBarChangeListener
52 SeekBar percentSeekBar =
53 (SeekBar) findViewById(R.id.percentSeekBar);
54 percentSeekBar.setOnSeekBarChangeListener(seekBarListener);
55 }
56
onCreate’s Bundle Parameter
During the app’s execution, the user could change the device’s configuration—for example, by rotating the device, connecting to a Bluetooth keyboard or sliding out a hard keyboard. For a good user experience, the app should continue operating smoothly through such configuration changes. When the system calls onCreate, it passes a Bundle argument containing the Activity’s saved state, if any. Typically, you save state in Activity methods onPause or onSaveInstanceState (demonstrated in later apps). Line 35 calls the superclass’s onCreate method, which is required when overriding onCreate.
Generated R Class Contains Resource IDs
As you build your app’s GUI and add resources (such as strings in the strings.xml file or views in the activity_main.xml file) to your app, the IDE generates a class named R that contains nested classes representing each type of resource in your project’s res folder. The nested classes are declared static, so that you can access them in your code with R.ClassName. Within class R’s nested classes, the IDE creates static final int constants that enable you to refer to your app’s resources programmatically (as we’ll discuss momentarily). Some of the nested classes in class R include
- class R.drawable—contains constants for any drawable items, such as images, that you put in the various drawable folders in your app’s res folder
- class R.id—contains constants for the views in your XML layout files
- class R.layout—contains constants that represent each layout file in your project (such as, activity_main.xml), and
- class R.string—contains constants for each String in the strings.xml file.
Inflating the GUI
The call to setContentView (line 36) receives the constant R.layout.activity_main which indicates the XML file that represents MainActivity’s GUI—in this case, the constant represents the activity_main.xml file. Method setContentView uses this constant to load the corresponding XML document, which Android parses and converts into the app’s GUI. This process is known as inflating the GUI.
Getting References to the Widgets
Once the layout is inflated, you can get references to the individual widgets so that you can interact with them programmatically. To do so, you use class Activity’s findViewById method. This method takes an int constant representing a specific view’s Id and returns a reference to the view. The name of each view’s R.id constant is determined by the component’s Id property that you specified when designing the GUI. For example, amountEditText’s constant is R.id.amountEditText.
Lines 39–42 obtain references to the TextViews that we change programmatically in the app. Line 39 obtains a reference to the amountTextView that’s updated when the user enters the bill amount. Line 40 obtains a reference to the percentTextView that’s updated when the user changes the tip percentage. Lines 41–42 obtain references to the TextViews where the calculated tip and total are displayed.
Displaying Initial Values in the TextView
Lines 43–44 set tipTextView’s and totalTextView’s text to 0 in a locale-specific currency format by calling the currencyFormat object’s format method. The text in each of these TextViews will change as the user enters the bill amount.
Registering the Event Listeners
Lines 47–49 get the amountEditText and call its addTextChangedListener method to register the TextWatcher object that responds to events generated when the user changes the EditText’s contents. We define this listener (Fig. 3.18) as an anonymous-inner-class object and assign it to the amountEditTextWatcher instance variable. Though we could have defined the anonymous inner class in place of amountEditTextWatcher in line 49, we chose to define it later in the class so that the code is easier to read.
Lines 52–53 get a reference to the percentSeekBar. Line 54 calls the SeekBar’s setOnSeekBarChangeListener method to register the OnSeekBarChangeListener object that responds to events generated when the user moves the SeekBar’s thumb. Figure 3.17 defines this listener as an anonymous-inner-class object that’s assigned to the instance variable seekBarListener.
Note Regarding Android 6 Data Binding
Android now has a Data Binding support library that you can use with Android apps targeting Android 2.1 (API level 7) and higher. You now can include in your layout XML files data-binding expressions that manipulate Java objects and dynamically update data in your apps’ user interfaces.
In addition, each layout XML file that contains views with ids has a corresponding autogenerated class. For each view with an id, the class has a public final instance variable referencing that view. You can create an instance of this “Binding” class to replace all calls to findViewById, which can greatly simplify your onCreate methods in Activity and Fragment classes with complex user interfaces. Each instance variable’s name is the id specified in the layout for the corresponding view. The “Binding” class’s name is based on the layout’s name—for activity_main.xml, the class name is ActivityMainBinding.
At the time of this writing, the Data Binding library is an early beta release that’s subject to substantial changes, both in the syntax of data-binding expressions and in the Android Studio tool support. You can learn more about Android data binding at
https://developer.android.com/tools/data-binding/guide.html
3.6.5 MainActivity Method calculate
Method calculate (Fig. 3.16) is called by the EditText’s and SeekBar’s listeners to update the tip and total TextViews each time the user changes the bill amount. Line 60 displays the tip percentage in the percentTextView. Lines 63–64 calculate the tip and total, based on the billAmount. Lines 67–68 display the amounts in currency format.
Fig. 3.16 | MainActivity Method calculate.
57 // calculate and display tip and total amounts
58 private void calculate() {
59 // format percent and display in percentTextView
60 percentTextView.setText(percentFormat.format(percent));
61
62 // calculate the tip and total
63 double tip = billAmount * percent;
64 double total = billAmount + tip;
65
66 // display tip and total formatted as currency
67 tipTextView.setText(currencyFormat.format(tip));
68 totalTextView.setText(currencyFormat.format(total));
69 }
70
3.6.6 Anonymous Inner Class That Implements Interface OnSeekBarChangeListener
Lines 72–87 (Fig. 3.17) create the anonymous-inner-class object that responds to percentSeekBar’s events. The object is assigned to the instance variable seekBarListener. Line 54 (Fig. 3.15) registered seekBarListener as percentSeekBar’s OnSeekBarChangeListener event-handling object. For clarity, we define all but the simplest event-handling objects in this manner so that we do not clutter the onCreate method with this code.
Fig. 3.17 | Anonymous inner class that implements interface OnSeekBarChangeListener.
71 // listener object for the SeekBar's progress changed events
72 private final OnSeekBarChangeListener seekBarListener =
73 new OnSeekBarChangeListener() {
74 // update percent, then call calculate
75 @Override
76 public void onProgressChanged(SeekBar seekBar, int progress,
77 boolean fromUser) {
78 percent = progress
/ 100.0;// set percent based on progress
79 calculate(); // calculate and display tip and total
80 }
81
82 @Override
83 public void onStartTrackingTouch(SeekBar seekBar) { }
84
85 @Override
86 public void onStopTrackingTouch(SeekBar seekBar) { }
87 };
88
Overriding Method onProgressChanged of Interface OnSeekBarChangeListener
Lines 75–86 (Fig. 3.17) implement interface OnSeekBarChangeListener’s methods. Method onProgressChanged is called whenever the SeekBar’s thumb position changes. Line 78 calculates the percent value using the method’s progress parameter—an int representing the SeekBar’s thumb position. We divide this by 100.0 to get the percentage. Line 79 calls method calculate to recalculate and display the tip and total.
Overriding Methods onStartTrackingTouch and onStopTrackingTouch of Interface OnSeekBarChangeListener
Java requires that you override every method in an interface that you implement. This app does not need to know when the user starts moving the SeekBar’s thumb (onStartTrackingTouch) or stops moving it (onStopTrackingTouch), so we simply provide an empty body for each (lines 82–86) to fulfill the interface contract.
Android Studio Tools for Overriding Methods
Android Studio can create for you empty methods that override inherited methods from the class’s superclasses or that implement interface methods. When you place the cursor in a class’s body, then select the Code > Override Methods menu option, the IDE displays a Select Methods to Override/Implement dialog that lists every method you can override in the current class. This list includes all the inherited methods in the class’s hierarchy and the methods of any interfaces implemented throughout the class’s hierarchy.
3.6.7 Anonymous Inner Class That Implements Interface TextWatcher
Lines 90–114 of Fig. 3.18 create an anonymous-inner-class object that responds to amountEditText’s events and assign it to the instance variable amountEditTextWatcher. Line 49 (Fig. 3.15) registered this object to listen for amountEditText’s events that occur when the text changes.
Fig. 3.18 | Anonymous inner class that implements interface TextWatcher.
89 // listener object for the EditText's text-changed events
90 private final TextWatcher amountEditTextWatcher = new TextWatcher() {
91 // called when the user modifies the bill amount
92 @Override
93 public void onTextChanged(CharSequence s, int start,
94 int before, int count) {
95
96 try { // get bill amount and display currency formatted value
97 billAmount = Double.parseDouble(s.toString()) / 100.0;
98 amountTextView.setText(currencyFormat.format(billAmount));
99 }
100 catch (NumberFormatException e) { // if s is empty or non-numeric
101 amountTextView.setText("");
102 billAmount = 0.0;
103 }
104
105 calculate(); // update the tip and total TextViews
106 }
107
108 @Override
109 public void afterTextChanged(Editable s) { }
110
111 @Override
112 public void beforeTextChanged(
113 CharSequence s, int start, int count, int after) { }
114 };
115 }
Overriding Method onTextChanged of Interface TextWatcher
The onTextChanged method (lines 92–106) is called whenever the text in the amountEditText is modified. The method receives four parameters. In this example, we use only CharSequence s, which contains a copy of amountEditText’s text. The other parameters indicate that the count characters starting at start replaced previous text of length before.
Line 97 converts the user input from amountEditText to a double. We allow users to enter only whole numbers in pennies, so we divide the converted value by 100.0 to get the actual bill amount—e.g., if the user enters 2495, the bill amount is 24.95. Line 98 displays the updated bill amount. If an exception occurs, lines 101–102 clear the amountTextView and set the billAmount to 0.0. Lines 105 calls calculate to recalculate and display the tip and total, based on the current bill amount.
Other Methods of the amountEditTextWatcher TextWatcher
This app does not need to know what changes are about to be made to the text (beforeTextChanged) or that the text has already been changed (afterTextChanged), so we simply override each of these TextWatcher interface methods with an empty body (lines 108–113) to fulfill the interface contract.