Sunday, January 22, 2012

Writing Your First Android App - Body Mass Index Calculator

This tutorial will guide you to write a simple Android app using the available button and text widgets. What our app will do is ask user for his weight and the height and calculate the Body Mass Index (BMI) for him with the information that whether the user is underweight, normal or overweight.

1. Create the Eclipse Project for the Android App

First make sure you have installed the Android Development Tools by following my previous blog post, Installing Android Development Tools in Windows. After the setup, start eclipse, and click the menu File->New->Android Project.

Creating an Eclipse Project for Android Developments

In the "New Android Project" wizard, give a name to your project.

Giving a project name for the Android App

I'm giving the name "". Note my name forms from the package name convention of Java, starts with the opposite sequence of my url parts and then the name for the project. This will uniquely identify my project. Click 'Next' to continue.

Select the Android version you want to run the app. I will keep the Android 4.0 checked.
Selecting the Target Android SDK version

From the next window fill the information as following and click 'Finish' to finalize creating the project.

Adding Your Application Information

2. Design the User Interface (UI)
Designing a (UI) for an android app is very easy. You can do that by simply drag and drop of widgets like text box, buttons into the form in the WYSIWYG editor in Eclipse. To get to the UI Designer double click the res/main.xml file (shown below) under your project from Package Explorer window.
Locating the XML file to design the UI

When you open that file by double clicking, you will get to the WYSIWYG (Graphical Layout) editor. You will see there is a hello world greeting has been added by default. Just select the "Hello Wold, BMICalculatorActivity" label and delete it (by pressing the 'delete' button) to clean the form.

Get Familiar with the UI Editor

Now drag a medium size label widgets from the Platte to the form to get the following look for the UI.

Drag and Drop a Label (TextView Widget)

To edit the text of the label, right click on it and select "Edit Text...". That will give you the "Resource Chooser" form.

The resource selection panel
From there, Click 'New String.." at the bottom of the form to declare a new string. This label should contain the String "Your Weight (lbs)". So in the new form put "Your Weight (lbs)" as the String and "weightLabel" as the R.String and click "OK".
Adding a new string

Click 'OK' in the Resource Chooser dialog box (make sure the string "weightLabel" is selected) and make sure your label contain the desired string value.

Next Drag a text field to allow user to input the weight. That should be a text field that allow user type decimal numbers (As users enter weight as decimal numbers). For that drag the text field labeled as 42.0 in the Palette to the form.
Drag and Drop a Text field (EditText widget)

Right click on the newly added text field and click "Edit ID". That allows you to provide a meaningful names to the text field. (So it is easier to refer them from your code). Give the ID "weightText" and click "OK".

Now add the following widgets to the form in the same order mentioned.
  1. A "Medium size label" and label with string value "Your Height (feets)" and R.String as "heightLabel". (You have to create a new string resource similar to the "Your Weight (lbs)" label mentioned above.)
  2. A text field with decimal numbers. Give it the id "heightText". (By right clicking the text field and clicking "Edit ID".)
  3. A Button. Right click and from the menu click "Other Properties" -> "All By Name" -> "Text" and add a new String Resource (String: Calculate and R.String: calculateButton). Similarly set the "onClick" property (You can choose it by right clicking and selecting "Other Properties" -> "All By Name"->onClick) to "calculateClickHandler". Set the button's id as "calculateButton".
  4. a Large Label. Give it the id "resultLabel". Set the text property of the label to a empty string. (with the R.String: emptyString)
That is the UI for the BMI Calculator app. Check whether you get the UI similar to this one.

The final UI for the App

If you click the main.xml tab in the bottom of the window, you can review or edit the strings and IDs you have associated with widgets. Check whether you got one similar to this one.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""

    android:orientation="vertical" >


        android:textAppearance="?android:attr/textAppearanceMedium" />

        android:inputType="numberDecimal" >
        <requestFocus />


        android:textAppearance="?android:attr/textAppearanceMedium" />

        android:inputType="numberDecimal" />


        android:text="@string/calculateButton" />

        android:textAppearance="?android:attr/textAppearanceLarge" />


3. Writing Code for Your App

After designing the UI, we have to write a small piece of code, that trigger BMI calculation when user click the "Calculate" button. This is written in the src/ file.

Check the below code and make sure you understand each step properly, specially on how to get references to the widgets in the UI and how to manipulate their texts.

import android.os.Bundle;
import android.view.View;

import android.widget.EditText;
import android.widget.TextView;
public class BMICalculatorActivity extends Activity {
    /** Called when the activity is first created. */

    public void onCreate(Bundle savedInstanceState) {

    public void calculateClickHandler(View view) {
     // make sure we handle the click of the calculator button

     if (view.getId() == {

      // get the references to the widgets
      EditText weightText = (EditText)findViewById(;
      EditText heightText = (EditText)findViewById(;
      TextView resultText = (TextView)findViewById(;
      // get the users values from the widget references

      float weight = Float.parseFloat(weightText.getText().toString());
      float height = Float.parseFloat(heightText.getText().toString());
      // calculate the bmi value

      float bmiValue = calculateBMI(weight, height);
      // interpret the meaning of the bmi value
      String bmiInterpretation = interpretBMI(bmiValue);
      // now set the value in the result text

      resultText.setText(bmiValue + "-" + bmiInterpretation);
    // the formula to calculate the BMI index

    // check for
    private float calculateBMI (float weight, float height) {

     return (float) (weight * 4.88 / (height * height));

    // interpret what BMI means
    private String interpretBMI(float bmiValue) {

     if (bmiValue < 16) {
      return "Severely underweight";
     } else if (bmiValue < 18.5) {

      return "Underweight";
     } else if (bmiValue < 25) {

      return "Normal";
     } else if (bmiValue < 30) {

      return "Overweight";
     } else {
      return "Obese";


4. Running Your App in an Android Simulator

To create a virtual device to run you app, Goto Window -> AVD Manager from the eclipse. Click "New" to create a new android virtual device. Set the configurations similar to the below screenshot and click "CreateAVD".

Creating an Android virtual device (Simulator) to run your App

Then right click the project from the "Package Explorer" window and select "Run As" -> "Run Android Application". Wait for sometime till the devices is booted.

Android Virtual Device

Then then click the "Application Drawer" of the virtual device at the bottom and click the "BMI Calculator" app.

Running our App on Android Virtual Device

Put your weight and Height in the text boxes and check your BMI. I'm a bit overweight as all (good?) software developers should be:)

5. Running Your App in Your Android Phone

First you have to enable the "USB Debugging" mode in your phone. For that goto Settings -> Applications -> Development and check "USB debugging". And connect your phone to USB port of your computer.

Before launching the app, make sure the app is built with the SDK that compatible with your device. To check that, right click the project name from the "Package Explorer" window (in the eclipse IDE) and click "Properties". Select the Android tab, check the android version of your phone and click OK. And you have to make sure the min SDK version of the AndroidManifest.xml is also correct.

Now click, Run->Run Configuration. From the "Run Configuration" form, select the BMI project (named '') under the Android Application and click Target tab.

Running the App on a Manual Target (To select run it on the phone)

From there select "Manual" as the deployment target selection mode (as shown above), and press the "Run" button.

Selecting the phone as the running target

Then it show the connected android device or devices. Select the one you want to run your app and click the "OK" button. That will launch your app into your phone. Here is a screenshot of  BMI Calculor app in my phone.

Running the app on the phone

Hope you had fun developing this nice app and seeing it running on your phone. This is just a start. Hope you explore more and develop more awesome apps!!!

You can download the eclipse project and the android app that we created in this post from following links.

Download the eclipse project files (zipped)
Access the Source code from github github repo
Download the free BMI Calculator app (the latest version) from the Android Market. Available in Android Market

Next Steps

To arrange the widgets in your app using layouts, read Tutorial: Using Layouts in your Android App. To add an icon to your app, read Create Launcher Icon For Your Android App. To add themes to the app, read Tutorial: Theming an Android App.


  1. Great post - all about starting to develop applications on Android in one place. Thanks!

  2. Consider using github to host your tutorials :)

  3. Hi zproxy, Sure. I just added the link for github repo. Hopefully I will add more demo sources to github. Thanks.

  4. I am looking forward towards this kind of post.This is one of the useful post.Great work.
    Android app developers

  5. I get a force close when trying to calculate bmi any ideas?

  6. Hi,
    You can see where the error is coming from the log, if you are running in eclipse. My guess is you have misspelled the handler name of the button, calculateClickHandler.


  7. When I made the original application it added a starting point activity and was trying to call from there for the calculateClickHandler. I looked in the logcat and found that out! Thanks for the help. Great APP!

  8. Amazing Post!
    I love it. Will come back again - taking your feeds also.
    iCaption That

  9. Hello sir,

    I tried implementing the same app in eclipse. The problem im encountering is that when i provide values (i.e weight and height) in the emulator and click on calculate, im receiving a message as Unfortunately Body Mass has stopped. Can you please figure out what mistake I ve made.

    Looking forward for your help,
    Thank you.

  10. Could you check logCat window and see where the origin of the exception?

    As I replied to CuLo11, it is possible the error is due to the misspelling of the handler of the button, calculateClickHandler.

  11. I implemented a same project above and i added more futures like this BMI calculator for women & men tools

  12. That’s great article. By posting this article you help me a lot. Now a day’s android is very important concept.

  13. As you would imagine this module is made up of a good collection of reference material specificaly related to developing Android Apps Development .

  14. Thanks for his tutorial. I get error and crash when exditext is empty. Is there a way to tell if empty to enter 1?

    1. Hi Mingo,

      You can change the code that calculate weight for,

      float weight;
      if ("".equals(weightText.getText())) {
      weight = 1;
      } else {
      weight = Float.parseFloat(weightText.getText().toString());

  15. The matter that you provide is worth our time and energy.
    one click root

  16. Thumbs up guys your doing a really good job.

  17. Great post, I am an avid reader of this blog, keep up the good work, and I'll be a regular visitor for a very long time.
    Android application

  18. Your articles don’t beat around the bushes exact t to the point.
    rooting android tablet

  19. Thanku for sharing such an informative information. Here is some thing about Free BMI Calculator .

  20. Hi

    I have followed the steps and I am getting an error :
    resultText.setText(bmiValue + "-" + bmiInterpretation);

    resultText can not be resolved

    can you help please


    1. Hi, Your error says it can't find the definition of the variable resultText. Check whether there are any typo in its declaration,
      TextView resultText = (TextView)findViewById(;

  21. Nice post. Thanks for sharing this android bmi calculator with us.

  22. Awesome post. Mobile apps developer would get to learn a lot from the this blog.

  23. I beyond doubt appreciate your articles and blogsgo to this web-site

  24. Thanks for this article. Please put some more android development tutorials. :)

  25. this type of presentation is good for begginers.......... thanks for posting like this.......

  26. hi........
    I tried implementing the same app in eclipse. The problem im encountering is that when i provide values (i.e weight and height) in the emulator and click on calculate, im receiving a message as Unfortunately Body Mass has stopped. Can you please figure out what mistake I ve made.

  27. Hi thanks for such nice post but when i tried i got "emulator-5556 disconnected! Cancelling 'com.example.bmicalculator.MainActivity activity launch'!" this error i m not able to launch the app pls help

  28. Exceptional work! The data presented was extremely helpful. I really hope that you carry on the good job succesfully done.
    ray ban sunglasses

  29. Thanks for sharing this is such a very nice post i really like it your blog.
    Android application development company

  30. I think it might be cool to see a few posts on layout methods and theming. There's
    certainly a substantial hole between the essential learner standard UI components application and the high quality uniquely themed applications like Pulse. Maybe a post indicating how you might make a famous application's UI.
    Andriod Application Development // iPhone Application Development // iPhone Application Development

  31. Your article has demonstrated convenient to me. It's exceptionally useful and you are clearly extremely learned here. You have opened my eyes to changing perspectives on this subject with fascinating and strong substance.Android app maker // Android application development // mobile app developers

  32. I have enjoyed reading your articles. It is well written. It looks like you spend a large amount of time and effort in writing the blog. I am appreciating your effort. Please check out my site.
    body mass index

  33. hello sir in my system phone is not creating what to do ???
    then when i copy in my mobile it says force to close

  34. Interesting articles are published here. By reading it I got some knowledge about android apps. Thank you for sharing with us.

    Mobile app development company

  35. Wow, thanks for nice guild-lines and step by step tips about android apps, keep posting iphone apps also..

    iphone app development company

  36. Very nice post.This body mass index calculator is based on the standard BMI measurement that takes your weight and height and basically tells you if you have an unhealthy body weight.
    bmi calculator

  37. Really very good work to learners and android workers also,,very nyc...thanq,thanq very much

  38. Great post. You know we all think about this very topic.Mylifecare offers BMI calculator for men that takes your weight and height and basically tells you if you have an unhealthy body weight.

  39. I always prefer to read the quality content and this thing I found in you post. Thanks for sharing.
    facetime for android phones

  40. We want to create an app just like this one. We are very thankful that you've posted your own codes for us to have some reference. Thanks ^_^

  41. Android Development Tutorial: Creating a Simple Basic Calculator :

  42. I agree with your post. Android software development kit makes the application development process lot simpler and effective. You can create best performing android application with ease. Android Training Institutes in Chennai | Best Android Training in Chennai

  43. Great, Thanks for sharing this article.Really looking forward to read more.Awesome.Seo Training Courses In Coimbatore

  44. nice blogs
    Sports Packsms ACT SPO and send it to 50000. And to deactivate the service sms DEACT SPO and send it to 50000
    Rs. 7/Week.

  45. There are lots of information about latest technology and how to get trained in them, like Best Hadoop Training In Chennai have spread around the web, but this is a unique one according to me. The strategy you have updated here will make me to get trained in future technologies Hadoop Training in Chennai By the way you are running a great blog. Thanks for sharing this blogs..

  46. I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing..
    SalesForce Training in Chennai

  47. Pretty article! I found some useful information in your blog, it was awesome to read,thanks for sharing this great content to my vision, keep sharing..
    Unix Training In Chennai

  48. This information is impressive..I am inspired with your post writing style & how continuously you describe this topic. After reading your post,thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic..
    Android Training In Chennai In Chennai

  49. I have read your blog and i got a very useful and knowledgeable information from your blog.You have done a great job.
    SAP Training in Chennai

  50. Oracle Training in chennai
    Thanks for sharing such a great information..Its really nice and informative..

  51. Selenium Training in Chennai
    Wonderful blog.. Thanks for sharing informative blog.. its very useful to me..

  52. Data warehousing Training in Chennai
    I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly..

  53. Whatever we gathered information from the blogs, we should implement that in practically then only we can understand that exact thing clearly, but it’s no need to do it, because you have explained the concepts very well. It was crystal clear, keep sharing..
    Websphere Training in Chennai

  54. Oracle DBA Training in Chennai
    Thanks for sharing this informative blog. I did Oracle DBA Certification in Greens Technology at Adyar. This is really useful for me to make a bright career..

  55. This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic..
    Informatica Training in chennai | QTP Training in Chennai

  56. Calculate your BMI by using our Body mass index Calculator for adults & children. Calculated by dividing the weight in kilograms by the square of height in meters. Weight Calculator

  57. Hi…I think it is destiny that I accidentally stumbled and fell into your website.Your blog is good and impressive.Looking forward to learn more.
    Informatica courses in Chennai | Informatica Training in Chennai

  58. Enter your height and weight to find your body mass index (BMI) Extra weight can increase your risk for health problems. Bmi Calculator

  59. Programming is combination of intelligent and creative work. Programmers can do anything with code. The entire Programming tutorials that you mention here on this blog are awesome. Beginners Heap also provides latest tutorials of Programming from beginning to advance level.
    Be with us to learn programming in new and creative way.

  60. BMI Calculator
    Enter your height and weight to find your body mass index (BMI) Extra weight can increase your risk for health problems. Bmi Calculator

  61. Nice and interesting information and informative too. Can you pls let me know the good apps where we can visit: Mass Text App

  62. Calculate your BMI by using our Body mass index Calculator for adults & children. Calculated by dividing the weight in kilograms by the square of height in meters. BMI Calculator