Make your own BMI Calculator Android App

Make your own BMI Calculator Android App

The easiest way to learn the basics of Java and Android development is to dive head first into coding, of course you’ll need some basic understanding of Java, or programming in general. In this article I’m going to guide you through making a simple app which can calculate your Body Mass Index. In this tutorial we will use some elements to get you familiar with the absolute basics.

This is a great practice for people who’ve just begun their Android or even Java coding. If you haven’t used Android Studio, which is the IDE I’m using, and I highly recommend it, and it’s pretty easy to get started with.

The Strings of your Android Application

A good place to start is to set up the strings we’ll need in our app. When calculating BMI you will need two values from the user, their height and their weight. So we’re going to need two TextView strings, and one string for our button and of course we’ll need the name of the App – lets name it BMI Calculator.

<!-- res/values/strings.xml -->
<resources>
    <string name="app_name">BMI Calculator</string>
    <string name="bmi_weight">Weight in KG:</string>
    <string name="bmi_height">Height in CM:</string>
    <string name="bmi_calc_button">Calculate BMI</string>
</resources>

Making your app beautiful, kind of

Lets get our layout design out of our way, it doesn’t have to be to complicated to fit our needs. We’ll just use a simple RelativeLayout, and put everything below each item. I know it’s not fancy, but hey – it’s functional!

<!-- res/layout/activity_main.xml" -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    >

    <!-- The app name -->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:textSize="30sp" />
    <!-- Height in CM text -->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/bmi_height"
        android:id="@+id/bmi_height"
        android:layout_below="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:textSize="20sp" />
    <!-- Height in CM input -->
    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:ems="10"
        android:id="@+id/height_input"
        android:layout_below="@+id/bmi_height"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />
    <!-- Weight in KG text -->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/bmi_weight"
        android:id="@+id/bmi_weight"
        android:layout_below="@+id/height_input"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:textSize="20sp" />
    <!-- Weight in KG input -->
    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:ems="10"
        android:id="@+id/weight_input"
        android:layout_below="@+id/bmi_weight"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />
    <!-- Calculate BMI Button -->
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/bmi_calc_button"
        android:id="@+id/bmi_calc_button"
        android:layout_below="@+id/weight_input"
        android:layout_centerHorizontal="true" />
    <!-- The TextView that will be updated with the Value -->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="0"
        android:id="@+id/bmi_result"
        android:textSize="50sp"
        android:layout_below="@+id/bmi_calc_button"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

This is how our Android app looks when rendered, as I said – it’s not the fanciest app you’ve seen but that is for another article, it’s functional and that’s the point of this tutorial. As you can see we have four TextViews, two number EditTexts and one Button, and we’ve made use of our previously made strings for easy editing.

How our Android app will look

Finally some Java code

Finally we’re ready to begin with the actual Java coding for our application, are you excited? Good, you should be – coding is fun! We’ll begin by declaring some of our variables we’ll need, and then find the view items by their id.

// Find UI elements by ID and save to variable
EditText height = (EditText) findViewById(R.id.height_input);
EditText weight = (EditText) findViewById(R.id.weight_input);
TextView bmi_result = (TextView) findViewById(R.id.bmi_result);
Button button = (Button) findViewById(R.id.bmi_calc_button);

Now we have setup our variables, and we will need to write a Listener for our button, since we only have one button to listen for we can keep it simple and stick everything in our main class. We do need to check for null values though, and we’re going to use Toast to tell the user that they need to enter the missing values.

Make a send Toast method

To make it easy on us we will make a method in our main class below our onCreate() method, let’s call it sendToast(). Let’s begin with the sendToast() method, preferably this should be put into a separate helpers class but since this is a basic Android app, there is no need for that. First things first, we need context – well Toast needs context, so let’s define that first at the top of our class.

// Toast needs context
final Context context = this;

I’ve chosen to put this helper method at the bottom of our class, and it takes one String argument, which is the message we’re sending.

/***
 * This method will send the user a Toast
 * which is a small black popup that is 
 * only visible for a few seconds.
 * 
 * Our method takes one argument of a
 * String with the message.
 * 
 * @param msg
 */
public void sendToast(String msg)
{
    // Get the message from our method call
    CharSequence text = msg;
    int duration = Toast.LENGTH_SHORT;

    Toast toast = Toast.makeText(context, text, duration);
    toast.show();
}

Looks neat right? When we’re coding we always need to be thinking and following the DRY principles. As I mentioned above, we need to listen to the button click and then check for null values, or else our Android app will crash on launch – let’s do that now in our onCreate() method below our variables we set earlier.

// Listen for our click event
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        // Check for null
        if (height.getText().toString().length() < 1)
        {
            sendToast("You must enter your height!");
            // Abort the onClick if null
            return;
        }
        if (weight.getText().toString().length() < 1)
        {
            sendToast("You must enter your weight, sorry!");
            // Abort the onClick if null
            return;
        }
        // Passed the null checks, let's do some math!

        /***
         * Android is funny this way, but you have
         * to convert it back and forth from integer/float
         * to strings, you'll get used to it. 😉
         */
        // Convert height from string to float
        float h = Float.valueOf(height.getText().toString());
        float w = Float.valueOf(weight.getText().toString());

        /***
         * Time for math!
         * BMI is calculated
         * (weigth in kg / (height in meter * height in meter)
         * But since we want the user to input in CM, we just
         * multiply it with 10 000 to get the correct value.
         */
        float BMI = w / (h * h) * 10000;

        // Set the bmi_result view item of the value of our BMI
        bmi_result.setText(String.valueOf(BMI));
    }
});

Not many lines of code and you’ve made a simple Android app that gets input from the user and then updates the textview from zero to the users BMI. I know that this app needs a lot of refinement, for example if the user enters zero as height or weight the result will be NaN (Not a Number) and more checking is needed, but for this short tutorial it’s overkill. Just below here is our full code of our MainActivity.java – everything put together.

package net.jejje.java.bmicalculatortutorial;

import android.content.Context;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity {

    // Toast needs context
    final Context context = this;

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

        // Find UI elements by ID and save to variable
        final EditText height = (EditText) findViewById(R.id.height_input);
        final EditText weight = (EditText) findViewById(R.id.weight_input);
        final TextView bmi_result = (TextView) findViewById(R.id.bmi_result);
        Button button = (Button) findViewById(R.id.bmi_calc_button);

        // Listen for our click event
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // Check for null
                if (height.getText().toString().length() < 1)
                {
                    sendToast("You must enter your height!");
                    // Abort the onClick if null
                    return;
                }
                if (weight.getText().toString().length() < 1)
                {
                    sendToast("You must enter your weight, sorry!");
                    // Abort the onClick if null
                    return;
                }
                // Passed the null checks, let's do some math!

                /***
                 * Android is funny this way, but you have
                 * to convert it back and forth from integer/float
                 * to strings, you'll get used to it. 😉
                 */
                // Convert height from string to float
                float h = Float.valueOf(height.getText().toString());
                float w = Float.valueOf(weight.getText().toString());

                /***
                 * Time for math!
                 * BMI is calculated
                 * (weigth in kg / (height in meter * height in meter)
                 * But since we want the user to input in CM, we just
                 * multiply it with 10 000 to get the correct value.
                 */
                float BMI = w / (h * h) * 10000;

                // Set the bmi_result view item of the value of our BMI
                bmi_result.setText(String.valueOf(BMI));
            }
        });


    }

    /***
     * This method will send the user a Toast
     * which is a small black popup that is
     * only visible for a few seconds.
     *
     * Our method takes one argument of a
     * String with the message.
     *
     * @param msg
     */
    public void sendToast(String msg)
    {
        // Get the message from our method call
        CharSequence text = msg;
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
    }

}

If you’re not a Copy and paste kind of guy or gal, you can find the code for this Tutorial at my GitHub page, BMI Calculator Tutorial at GitHub.

Jimmy Nelsing's Picture

About Jimmy Nelsing

I'm a computer enthusiast who loves the web and web development, I've used Wordpress for a long time on and off for different web pages for many years. I also like to develop in PHP, especially with Laravel and have also started with Java programming as side projects - testing out Bukkit and Android.

http://jejje.net/

Comments