Section 2: Understanding the Android SDK

From CS160 Spring 2013
Jump to: navigation, search

Slides: File:Section2.pdf

Prerequisites

This tutorial assumes you have already installed Java, Eclipse, and the Android SDK. If you haven't, please do so according to the instructions from last week: Section 1: Installing the Android SDK.

Create Project

  1. In Eclipse, click File > New > Android Application Project.
    Note: If Android Application Project is not a top-level option in the menu, click Project... to open the New Project dialog and then select Android > Android Application Project.
  2. Follow the prompts in the wizard to set up your project:
    • Name the project "BMI Calculator".
    • The package name should be in the format edu.berkeley.cs160.yourname.bmicalculator
    • Change the min SDK version to 13 (3.2).
    • Click through the next two screens, leaving them at their defaults.
    • Leave the box checked to create a blank activity named MainActivity.
    • Click Finish.
  3. If it's not open, bring up the BMI Calculator project in the Eclipse Package Explorer.


Developing the BMI Calculator

Overview

BMI or Body Mass Index is a measurement of overall body composition. The formula for calculating BMI is BMI = ( Weight in Pounds * 703 / ( Height in inches x Height in inches ) This example calculator is meant to demonstrate features that you may want to use in your Tip Calculator, including:

  • Capturing user input
  • Responding to button clicks
  • Switching between screens/activities

Implementation

1. Create Layout for Main Activity

  1. Open the activity_main.xml file.
  2. In the GUI Editor you will see a RelativeLayout with one text field showing "Hello World". Delete this message.
  3. Switch to XML view
  4. Right below the RelativeLayout open tag, add a TextView which will label the weight input:
       
        <TextView
                android:id="@+id/weightLabel"
                android:layout_width="fill_parent"   
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:text="Weight"
                android:textAppearance="?android:attr/textAppearanceLarge" />
    
    
  5. Add an EditText for the weight value:
       
            <EditText
                android:id="@+id/weightTextbox"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_below="@+id/weightLabel"
                android:ems="10"
                android:digits="0123456789"     
                android:maxLength="3"           
                android:inputType="number" >     
            <requestFocus />
        </EditText>
    
  6. Add another TextView to label the weight units:
    <TextView
            android:id="@+id/poundsLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/weightTextbox"
            android:layout_alignParentRight="true"
            android:text="pounds"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    
  7. Repeat the previous steps to create a label, an EditText, and another label for height in inches.
        <TextView
            android:id="@+id/heightLabel"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/weightTextbox"
            android:text="Height"
            android:textAppearance="?android:attr/textAppearanceLarge" />
            
        <EditText
            android:id="@+id/heightTextbox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/heightLabel"
            android:ems="10"
            android:digits="0123456789"
            android:maxLength="2"
            android:inputType="number" />
    
        <TextView
            android:id="@+id/inchesLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/heightTextbox"
            android:layout_alignParentRight="true"
            android:text="inches"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    
  8. Add a button:
        <Button
            android:id="@+id/goButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/inchesLabel"
            android:layout_marginTop="14dp"
            android:onClick="getData"                
            android:text="Calculate BMI" />
            
  9. The text inputs don't take up much of the screen, leaving a big empty space. You may want to add an image to fill it. First copy the image you want to use and paste it into your project under res/drawable-mdpi, then replace '@drawable/chubbyandroid' in the XML below with '@drawable/yourfilename' (the filename without the extension).
    <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="false"
            android:layout_below="@+id/goButton"
            android:layout_centerInParent="true"
            android:src="@drawable/chubbydroid" />
    
  10. Save the layout. When you are finished, it should look something like this: Bmi screenshot.png
  11. 2. Add Event Handler

    Since your layout has a button, you will need to implement an event handler for the button to do anything. The easiest way to do this is to provide a function name to the android:onClick element as we did in step 8 above (the function will be named getData).

    getData doesn't exist yet, so let's add it to MainActivity.java:

    public void getData(View v) {
    		EditText heightBox = (EditText)findViewById(R.id.heightTextbox);
    		int height = Integer.valueOf(heightBox.getText().toString());
    		EditText weightBox = (EditText)findViewById(R.id.weightTextbox);
    		int weight = Integer.valueOf(weightBox.getText().toString());
    		Intent i = new Intent(this, ResultActivity.class);
    		i.putExtra("height", height);
    		i.putExtra("weight", weight);
    		startActivity(i);
    	}
     

    This code does a lot in a few lines:

    1. Gets the two textboxes for height and weight using findViewById(R.id.<id of the view>). findViewById returns a View object that you cast to the subclass of View you expect, in this case EditText.
    2. Gets the current values of the textboxes and converts them to integers.
    3. Creates a new explicit intent for a class called ResultActivity (which doesn't exist yet but you will create in the next step).
    4. Adds the height and weight values as Extras. Extras are akin to storage bins for transporting data between activities and services.
    5. The final line starts the activity.

    3. Create Result Activity

    1. Right-click the project name in the Package Explorer (so, BMI Calculator) and select New > Other > Android > Android Activity.
    2. Give this activity the name ResultActivity.
    3. Open up activity_result.xml.
    4. Like MainActivity, the result activity is prepopulated with a "Hello World" TextView, but we won't delete it this time -- since we only need one TextView for this activity we can repurpose it. To do so, change the ID of the TextView to "@+id/message".
    5. Open ResultActivity.java
    6. In the Result activity we need to do two things: get the output passed from Main, calculate the user's BMI, and display it.
    7. To accomplish this, first update the onCreate method of the ResultActivity to pull in data from Extras:
      	@Override
      	protected void onCreate(Bundle savedInstanceState) {
      		super.onCreate(savedInstanceState);
      		setContentView(R.layout.activity_result);
      		Bundle extras = this.getIntent().getExtras();
      		int height = extras.getInt("height");
      		int weight = extras.getInt("weight");
      		calculateBmi(height, weight);
      	}
      
    8. Finally, we implement the calculateBmi function and one helper function to get the user's BMI and post it on screen:
      	public void calculateBmi(int height, int weight) {
      		double bMI = weight * 703 / (height * height);
      		String category = getCategory(bMI);
      		TextView tv = (TextView)findViewById(R.id.message);
      		String message = String.format("Your BMI is: %.1f (%s)", bMI, category);
      		tv.setText(message);
      	}
      	
      	private String getCategory(Double score) {
      		if (score <= 15)
      			return "Very severely underweight";
      		if (score <= 16)
      			return "Severely underweight";
      		if (score <= 18.5)
      			return "Underweight";
      		if (score <= 25)
      			return "Normal (healthy weight)";
      		if (score <= 30)
      			return "Overweight";
      		if (score <= 35)
      			return "Moderately obese";
      		if (score > 35)
      			return "Severely obese";
      	return "";
      	}