Home > Articles > Mobile Application Development & Programming

This chapter is from the book

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 importexpand1.jpg to its left. You can click the importexpand1.jpg 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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020