0% found this document useful (0 votes)
209 views

CHAPTER 3 Widget Sample Body Mass Index Calculator

This document describes the development of a body mass index (BMI) calculator mobile app. It includes: 1) Placing text views and labels to display instructions for entering weight and height, as well as labels for displaying the calculated BMI and category. 2) Adding edit text fields for entering weight and height. A third field is included for displaying the calculated BMI. 3) Positioning a button between height and BMI labels to trigger the BMI calculation. 4) Outlining the main code steps: getting user input values, converting to doubles, performing BMI calculation, displaying result in BMI field, and using if/else statements to determine BMI category based on a provided table.

Uploaded by

wahyyyuu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
209 views

CHAPTER 3 Widget Sample Body Mass Index Calculator

This document describes the development of a body mass index (BMI) calculator mobile app. It includes: 1) Placing text views and labels to display instructions for entering weight and height, as well as labels for displaying the calculated BMI and category. 2) Adding edit text fields for entering weight and height. A third field is included for displaying the calculated BMI. 3) Positioning a button between height and BMI labels to trigger the BMI calculation. 4) Outlining the main code steps: getting user input values, converting to doubles, performing BMI calculation, displaying result in BMI field, and using if/else statements to determine BMI category based on a provided table.

Uploaded by

wahyyyuu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

CHAPTER 3: Widget Sample : Body Mass Index Calculator

General Information
Body mass index (BMI) is a figure of merit that is used for assessing the thickness-
thinness of a person. BMI is defined as the ratio of the mass and height-squared
with the formula below:

After the calculation of the BMI, the following table is the used for assessing the
weight category:

Weight category from BMI to BMI


Very severely underweight 0 15

Severely underweight 15 16
Underweight 16 18.5

Normal (healthy weight) 18.5 25

Overweight 25 30

Obese Class I (Moderately obese) 30 35

Obese Class II (Severely obese) 35 40

Obese Class III (Very severely obese) 40 ∞

Table 1. BMI categories


(source: https://en.wikipedia.org/wiki/Body_mass_index)

In this chapter, we‟ll develop a BMI calculator app and learn to read user inputs,
make calculations inside our code and display results to the user.
Adding and Positioning TextViews
In order to calculate the BMI in our app, we obviously need the weight and height
inputs. Our Java code will calculate the BMI using the given BMI formula and then
it will decide the category according to Table 1. First of all, let‟s create the user
interface of our app. In Android Studio, create a new project called “BMI
Calculator” and save it anywhere you want on your computer (I‟ll not repeat myself
1
about these things, we explained in detail in previous chapters). Please select the
“Phone and Tablet” platforms with minimum SDK of API 15 as we did for the
previous app. The default layout can be chosen as “Empty activity” with the main
class being “MainActivity.java” and the layout file as “activity_main.xml”. Please
don‟t delete the default TextView of “Hello World” so that we can modify it to
show our app title. Click on it and then it will be selected. Now, change its text as
BMI Calculator, set its font size as 24sp and make the text bold as indicated by
the numbers 1, 2 and 3 in Figure 1.
Let‟s position this title text so that it is positioned in the middle horizontally and
has a distance of something like 50~60 dp from the top. (dp stands for Density
Independent Pixel which is automatically adjusted when the display resolution is
changed). For this, click on the View all properties as shown by 4 in Figure 1 and
adjust the position of this TextView as shown in Figure 2. Please note that the
horizontal middle guiding line is displayed automatically so that we can slide this
widget on this line which will help us keep it in the middle horizontally. As you
move the widget, observe the parameter named layout_marginT which indicates its
distance from the top. I set it as 60 dp.
We‟ll take height and weight inputs from the user and show the BMI result as a
number and its category. We‟ll need to place four TextViews which will show
Enter your weight (kg): , Enter your height (m): , Your BMI: and BMI
category. Please find the widget TextView from the Palette and drag and drop four
TextViews as shown in Figure 3.

Figure 1. Setting the basic properties of the TextView (You can download full
resolution colour images from the book‟s website)
2
Figure 2. Positio ning the title label

Figure 3. Placing four TextViews

3
Once the first TextView is placed, the next one is positioned relative to the previous
one. For out BMI Calculator app, the exact positions are not strict and I am not
giving the exact positions here in order to confuse you. You can download the
project files from the book‟s companion website if you‟d like to see which
positions I exactly used but it is not mandatory of course. However, we need to
leave a space between the second and the third TextViews for placing the button
that will initiate the calculation.
I have changed the text font sizes to 18 sp and made the text type bold. The layout
seems like in Figure 4 after changing the texts of these TextViews per our aim.

Figure 4. The app‟s GUI layout after setting up the TextViews


Adding the EditText Widgets
We now need to place two editable text boxes to let the user input his/her weight
and height, another textbox to display the BMI as a number and a button to initiate
the calculation of the BMI.
The positioning of the Text Fields (text boxes) are shown in Figure 5. I‟ve placed
Text Fields which can be used to input decimal numbers (numbers with fractional
part) rather than general input types because the user is supposed to enter only
numeric values in this app. It is worth noting that the calculation result will be
displayed next to the Your BMI: label and a Text Field is placed there to display
4
the BMI result. We could use a static text (TextView) for this aim however I
wanted to show you how we can set the contents of the TextField
programmatically.

Figure 5. Placing the TextFields


Please note that Text Fields do not have borders by default therefore after they are
placed, we can only see them by selecting them.
Let‟s set their IDs so that we can access them programmatically and also set their
default texts. For this, select the respective TextField and then set the ID and text
properties as shown in Figure 6 for the weight input
Text Field. I also positioned its default text in the middle as we did before.

5
Figure 6. Settings of the weight input TextField

Figure 7. The GUI of the app after setting up all TextFields

6
Please set the IDs and default texts of the height input and BMI result Text Fields
as heightInput and 1.80; BMIResult and ……., respectively. Bu setting the
default text of the BMI result Text Field as
……., we make the user to see ……. in that box before calculating his/her BMI.
After these settings, the GUI seems as in Figure 7.
Adding and Positioning the Button
There are two steps remaining to complete our GUI design. The first one is the
button that will initiate the calculation. Please drag and drop a button widget from
the Palette between the height input TextView and the YourBMI TextView and
then position it horizontally in the middle as shown below:

Figure 8. Placing the button on the screen

7
Now, please set the text of the button as Calculate my BMI! Note that the default
ID of the button is button which is OK.
Our GUI is almost complete however there‟s one step remaining. The ID of the
BMI category TextView (the one with the text Your BMI category appears
here.). Please set its ID as BMICategory and then we are finished. After these
steps, the GUI of our app is ready as shown below:

Figure 9. The GUI of our BMI Calculator app


Developing the Main Code of the App
We are now ready to continue with programming. We will implement the following
steps in MainActivity.java for the BMI calculation:
Firstly, the values entered in the weight input and height input text fields will be
taken. These will be String type variables.
Convert these Strings to double type variables so that the BMI calculation can be
performed using the BMI equation given at the beginning of the chapter.
Perform the body mass index calculation.

8
Display the BMI value in the text field next to the “Your BMI:” label after
converting to String type.
Use if–else statements to determine the BMI category from the BMI value using
Table 1.
Display the BMI category in the text view which shows “BMI category appears
here.” by default.
Please open the MainActivity.java file from the file explorer of Android Studio.
The default contents of this file are as follows:

package com.helloworld.quantum.bmicalculator;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity


{
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Code 1
The calculation will be done when the user taps the button therefore we need to
write a listener method for the button and then call this method inside the
onCreate() function (as we explained in the previous chapter). Code 2 shows the
general template of the button listener method.

public void myButtonListenerMethod() {


Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// code those will be run when the button‟s clicked
}
});
}

Code 2
9
We have analysed the structure of this listener method in Chapter 5. In short, the
button is accessed by the button object created in the second line and all the
operations those will be done when the button is clicked will go inside the method
onClick(View v).
First of all we need to take the height and weight inputs from their respective
EditTexts (TextFields). This is simply done with the following code snippet:

final EditText heightText = (EditText)


findViewById(R.id.heightInput);

String heightStr = heightText.getText().toString();


double height = Double.parseDouble(heightStr);
Code 3
The explanation of this code is as follows:
In the first line, we access the height input textbox using its ID (R.id.heightInput)
and then create an EditText object called heightText.
In the second line, the string inside this EditText is extracted and assigned to a new
String object called heightStr.
And in the last line, the String value of the height is converted to
double type and assigned to a newly created variable height.
In the end, we have the height value stored in the height variable which is of double
type.
We need to implement these steps because there‟s no other way to directly take the
EditText value as a Stringor double.
The following code does a similar job and in the end the weight value is stored in
the weightvariable.

final EditText weightText =


findViewById(R.id.weightInput);
String weightStr = weightText.getText().toString();
double weight = Double.parseDouble(heightStr);

Code 4

10
We now have weight and height data in double type variables so we can do the BMI
calculation using the equation given in the beginning of the chapter as follows:
double BMI = (weight)/(height*height);
Code 5
In this code, the * operator does the multiplication while the / operator divides the
weight to the height squared.
We will display this BMI value in the EditText box next to the You BMI label in
the GUI. We did set its ID as BMIResult when we laid out the user interface before.
Therefore, the following code does this job:

final EditText BMIResult = (EditText)


findViewById(R.id.BMIResult);

BMIResult.setText(Double.toString(BMI));
Code 6
In this code, the widget with the ID BMIResult is found in the first line and then
the double type BMI variable is converted to String by the code
Double.toString(BMI)for displaying inside the EditText. Note that the texts
written inside the EditText widgets can only be read and written as Strings.
We now have the BMI stored as a double type variable. We now have to use if–else
statements to check this numeric value according to Table 1
and determine the BMI category. For this, let‟s define a String that will hold the
BMI category:
String BMI_Cat;
Code 7
We‟ll set this String according to the BMI value using if–else statements as follows:

11
if (BMI < 15)
BMI_Cat = "Very severely underweight";
else if (BMI < 16)

BMI_Cat = "Severely underweight";


else if (BMI < 18.5)

BMI_Cat = "Underweight";
else if (BMI < 25)

BMI_Cat = "Normal";
else if (BMI < 30)

BMI_Cat = "Overweight";
else if (BMI < 35)

BMI_Cat = "Obese Class Code


1 - 8Moderately Obese";
else if (BMI < 40)
The only thing remaining is setting the TextView to the BMI_Cat String so that
BMI_Cat = "Obese Class 2 - Severely Obese";
the BMI category is displayed in the user interface:
else

BMI_Cat = "Obese Class 3 - Very Severely Obese";


final TextView BMICategory = (TextView)
findViewById(R.id.BMICategory);
BMICategory.setText(BMI_Cat);
Code 9
Sticking all these code lines together, we reach the complete MainActivity.java
given in Code 10. (You can download these codes from the book’s website:
www.android-java.website)
Please note that the library import directives at the beginning of this file are
automatically placed by Android Studio according to the methods and classes we
used in our code.

12
package com.helloworld.quantum.bmicalculator;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity{

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myButtonListenerMethod();
}

public void myButtonListenerMethod() {


Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final EditText heightText = findViewById(R.id.heightInput);
String heightStr = heightText.getText().toString();
double height = Double.parseDouble(heightStr);
final EditText weightText = findViewById(R.id.weightInput);
String weightStr = weightText.getText().toString();
double weight = Double.parseDouble(weightStr);
double BMI = (weight)/(height*height);
final EditText BMIResult =findViewById(R.id.BMIResult);
BMIResult.setText(Double.toString(BMI)); String BMI_Cat;
if (BMI < 15)
BMI_Cat = "Very severely underweight";
else if (BMI < 16)
BMI_Cat = "Severely underweight"; else if (BMI <
18.5)

13
BMI_Cat = "Underweight";
else if (BMI < 25)
BMI_Cat = "Normal";
else if (BMI < 30)
BMI_Cat = "Overweight";
else if (BMI < 35)
BMI_Cat = "Obese Class 1 – Moderately Obese";
else if (BMI < 40)
BMI_Cat = "Obese Class 2 - Severely Obese";
else
BMI_Cat = "Obese Class 3 - Very Severely Obese";
final TextView BMICategory = (TextView)
findViewById(R.id.BMICategory);
BMICategory.setText(BMI_Cat);
}
});
}
}

Code 10 (cont‟d from the previous page)


Building and Running the App
Let‟s now try our app in the Nexus 4 emulator. Just press the “Run” button in
Android Studio and select the Nexus 4 emulator. You should see the app screen
shown in Figure 10.
Enter weight and height values (in kg and metres) and then tap the CALCULATE
MY BMI! button. If you followed all steps correctly, you should see the BMI value
and the BMI category on your app screen as in Figure 11.

Figure 10. The app screen

14
Figure 11. A sample BMI calculation
Final Notes
As you can see from Figure 11, the BMI value is displayed with a lot of unnecessary
floating point digits. Probably only a single decimal digit is enough. We can use
the following code to trim the decimal digits of the BMI variable and assign the
trimmed value to a new double type variable BMI_trimmed:

DecimalFormat df = new DecimalFormat("#.#");


double BMI_trimmed =

Double.parseDouble(df.format(BMI));
Code 11
The DecimalFormat class is used for these types of operations. Android Studio
automatically adds the required library by the code line:

import android.icu.text.DecimalFormat;

Code 12
The modified complete MainActivity.java is also given as follows:

15
package com.helloworld.quantum.bmicalculator;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity{


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myButtonListenerMethod();
}

public void myButtonListenerMethod() {


Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {

final EditText heightText = findViewById(R.id.heightInput);


String heightStr = heightText.getText().toString();
double height = Double.parseDouble(heightStr);
final EditText weightText = findViewById(R.id.weightInput);
String weightStr = weightText.getText().toString();
double weight = Double.parseDouble(weightStr);
double BMI = (weight)/(height*height);
DecimalFormat df = new DecimalFormat("#.#");
double BMI_trimmed = Double.parseDouble(df.format(BMI));
final EditText BMIResult = findViewById(R.id.BMIResult);
BMIResult.setText(Double.toString(BMI_trimmed));
String BMI_Cat;
if (BMI < 15)
BMI_Cat = "Very severely underweight";
else if (BMI < 16)
BMI_Cat = "Severely underweight";
else if (BMI < 18.5)
BMI_Cat = "Underweight";
else if (BMI < 25)
BMI_Cat = "Normal";
else if (BMI < 30)
BMI_Cat = "Overweight";

16
else if (BMI < 35)
BMI_Cat = "Obese Class 1 - Moderately Obese";
else if (BMI < 40)
BMI_Cat = "Obese Class 2 - Severely Obese";
else
BMI_Cat = "Obese Class 3 - Very Severely Obese";
final TextView BMICategory =
findViewById(R.id.BMICategory);
BMICategory.setText(BMI_Cat);
}
});
}
}

Code 13 (cont‟d from the previous page)


When the modified code is used, the calculation result is displayed in the emulator
as follows:

Figure 12. The sample BMI calculation with trimmed BMI digits
17

You might also like