askIT

Android BMI calculator tutorial

01_bmi_kalkulator_i_android_java.jpg
Figure: Finished app

This tutorial shows you how to get started with Android programming. The goal for the tutorial is to create a simple BMI calculator.

In this project we will use text fields EditText, simple mathematics and update of TextView.

You will need Android Studio and Java Development Kit installed on your computer. These can be downloaded for free from the links below.

android_studio.jpg Android studio: developer.android.com

java.png Java Development Kit: oracle.com

It is easy to calculate BMI. The mathematics is not complicated. You need the weight and height of the user. Divide the weight with height * height. This gives the following formula:

BMI =
m
h2

Where m is mass in kg and h is height in meters. BMI is messured in kg/m2.

Download Download source code

01 Create project

Start up Android Studio and select New Project.

02_nytt_prosjekt_welcome.jpg

03_configure_your_new_project.jpg
Figur: Appliaction name = BMI Calculator
Company domain = yourname.com

Use API 15 (Android 4.0.3).This works on most mobile phones.

04_api_15.jpg

Select Empty Activity.

05_empty_activity.jpg

06_customize_the_activity_mainactivity.jpg

02 Design activity_main.xml

It is easiest to design application before writing any code. To start the designer go to.

app > res > layout > activity_main.xml

Drag en drop this items to your application.

Add 7 TextView.:
07_design_bmi_kalkulator.jpg

Add 2 Number (Decimal):
07_design_bmi_calculator_number.jpg

If you run the app it should look like this:
07_run.jpg

Change text of TextView:
You can change the text on a item by clicking on it. You can also change the apperance. Change the text for all TextView elements.

08_endre_tekst.jpg

Change ID of Number (Decimal) and TextView:
The code need to get the correct elemements. To make it easy to write the code you need to give elements IDs that are understandeble. Click on the Number Decimal items and one of the TextView items. Give them a new ID in the "Properties" on the right side.

09_id_height.jpg

09_id_wiehgt.jpg

09_id_textveiw.jpg

If you are having problems then you can copy the source code from the window below. Go to XML view by clicking on "Text".
12_text.jpg.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.nettport.bmicalculator.MainActivity">

    <TextView
        android:text="Your Information:"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="10dp"
        android:id="@+id/textView"
        android:textAppearance="@style/TextAppearance.AppCompat.Large" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal"
        android:ems="10"
        android:layout_below="@+id/textView3"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:id="@+id/editTextHeight"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium" />

    <TextView
        android:text="Height:"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:id="@+id/textView3"
        android:layout_below="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium" />

    <TextView
        android:text="Weight:"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="17dp"
        android:id="@+id/textView5"
        android:layout_below="@+id/editTextHeight"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal"
        android:ems="10"
        android:id="@+id/editTextWeight"
        android:layout_below="@+id/textView5"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium" />

    <TextView
        android:text="TextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView6"
        android:layout_marginTop="15dp"
        android:id="@+id/textViewResult"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium" />

    <TextView
        android:text="kg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/editTextWeight"
        android:layout_alignLeft="@+id/textView8"
        android:layout_alignStart="@+id/textView8"
        android:id="@+id/textView9"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium" />

    <TextView
        android:text="cm"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="33dp"
        android:layout_marginStart="33dp"
        android:id="@+id/textView8"
        android:layout_alignBottom="@+id/editTextHeight"
        android:layout_toRightOf="@+id/editTextHeight"
        android:layout_toEndOf="@+id/editTextHeight"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium" />

    <TextView
        android:text="Result:"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView6"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

</RelativeLayout>

You can start your application by clicking on Run.
11_kjor_app_i_emulator.jpg.

03 MainActivity

The code for your application is located in MainActivity.java

app > java > com.nettport.bmicalculator > MainActivity

We will start by making a method for calcualteBMI. This method will be the code for calculation of BMI.

void calcualteBMI(){
}

Try to run you app now to make sure it still works!

The next thing we need to do is create two listeners. When there are changes in height or weight EditText the listners code will run. The listners code is going to be placed inside the onCreate method. When ever there is changes in EditText the listners will record it and call on the method calcualteBMI().

/* EditText Height listener */
EditText editTextHeight = (EditText)findViewById(R.id.editTextHeight);
editTextHeight.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
                if (!(s.toString().equals(""))) {
                        // My code here
                        calcualteBMI();
                }
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
});

/* EditText Weight listener */
EditText editTextWeight = (EditText)findViewById(R.id.editTextWeight);
editTextWeight.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
                if (!(s.toString().equals(""))) {
                        // My code here
                        calcualteBMI();
                }
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
});

If you get error message "Cannot resolve symbol ..." then go to the error and click ALT+Enter. You need to import the libary.

12_cannot_resolve_symbol.jpg

Height

We can now code the method calcualteBMI(). We want to get the height and weight. After we have got the values we want to calculate and finally print the result on the screen of your mobile phone.

// Get Height
EditText editTextHeight = (EditText)findViewById(R.id.editTextHeight);
String heightString = editTextHeight.getText().toString();

double height = 0;
try {
        height = Double.parseDouble(heightString);
}
catch (NumberFormatException nfe){
        //Toast.makeText(this, "Enter number", Toast.LENGTH_SHORT).show();
}
height = height * 1/100;
height = height*height;

Weight

The weight is approximately equal to the height. The only diffrent is that we dont multiply it with itself.

// Get Weight
EditText editTextWeight = (EditText)findViewById(R.id.editTextWeight);
String weightString = editTextWeight.getText().toString();

double weight = 0;
try {
        weight = Double.parseDouble(weightString);
}
catch (NumberFormatException nfe){
        //Toast.makeText(this, "Enter a number", Toast.LENGTH_SHORT).show();
}

Calculate result

We will get the result by dividing weight with height.

// Calculate result
double result = Math.round(weight/height);

Print result

We use if and else for writing the result to a TextView in the design that got the ID TextViewResult.

// Print result
TextView TextViewResult = (TextView)findViewById(R.id.textViewResult);


// If or else for values

if(result < 18.5){
        TextViewResult.setText("Your BMI is " + result + "\nYou are categorized as underweight.");
}
else{
        if(result < 24.9){
                TextViewResult.setText("Your BMI is " + result + "\nYou are categorized as normal weight.");
        }
        else {
                if (result < 29.9) {
                        TextViewResult.setText("Your BMI is " + result + "\nYou are categorized as overweight.");
                }
                else{
                        if(result > 30 && result < 34.9){
                                TextViewResult.setText("Your BMI is " + result + "\nYou are categorized as obese class I (Moderately obese).");
                        }
                        else {
                                if(result < 39.9){
                                        TextViewResult.setText("Your BMI is " + result + "\nYou are categorized as obese class II (Severely obese).");
                                }
                                else{
                                        if(result < 40){
                                                TextViewResult.setText("Your BMI is " + result + "\nYou are categorized as obese class III (Very severely obese).");
                                        }
                                        else{
                                                TextViewResult.setText("");
                                        }
                                }
                        }
                }
        }
}

04 MainActivity code

If you didnt get the code to run then dont worry. You can look at the source code for MainActivity.java by following the link below.

_img/java.png MainActivity

05 Start application

The application is finished and is ready to run in your emulator.

11_kjor_app_i_emulator.jpg

12_app.jpg

Now you can work with the design. Try to make the EditText fields width smaller. Move the result to top right.

13_design.jpg

Add comment

avatar_blank_60.png

Comment:

Name:

Email:

Comments

No comments yet. You can be the first one to comment. Just write your comment in the form and click on the submit button.