CHAPTER 3 Widget Sample Body Mass Index Calculator
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:
Severely underweight 15 16
Underweight 16 18.5
Overweight 25 30
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
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.
5
Figure 6. Settings of the weight input TextField
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:
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:
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;
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:
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:
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 = "Underweight";
else if (BMI < 25)
BMI_Cat = "Normal";
else if (BMI < 30)
BMI_Cat = "Overweight";
else if (BMI < 35)
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;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myButtonListenerMethod();
}
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);
}
});
}
}
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:
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;
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);
}
});
}
}
Figure 12. The sample BMI calculation with trimmed BMI digits
17