Taste of Android :: Part-2


Bhaskar S 05/04/2013


Android Application Development - I

Let us jump right into an example to jumpstart the understanding of Android application development. The following paragraphs will detail what it takes to build the Tip Calculator application.

When we go to a restaurant, we are served by a waiter or waitress. In the end, when we are about to pay for the food, we also want to tip the waiter or waitress. Based on the quality of service we received, we will tip them 20%, 15%, or 10% of the total amount.

Without much further ado, let us begin the development of the Tip Calculator Android application.

In Eclipse, select the File menu item, then click on the New sub-item, and then select the Android Application Project item as shown in the following figure 2.1 below:

New Android Project Image
Figure-2.1

Clicking on the Android Application Project item will launch the New Android Application window as shown in the following figure 2.2 below:

New Android Application Image
Figure-2.2

Our application is called DroidTipCalculator. Complete the project information details and click on the Next button as shown in the following figure 2.3 below:

New Android Application Image
Figure-2.3

This will bring us to the Configure Project screen as shown in the following figure 2.4 below:

Configure Android Project Image
Figure-2.4

In the Configure Project screen, uncheck the Create custom launcher icon option and click on the Next button as shown in the following figure 2.5 below:

Configure Android Project Image
Figure-2.5

This will bring us to the Create Activity screen. An Activity is the user interface screen of the Android application on an Android device through which an user interacts with the application. Associated with the Activity is the layout of all the visual components or widgets such as the text, buttons, etc. For the simple Tip Calculator application we will have only one Activity and hence one layout. Select the Blank Activity from the list and click on the Next button as shown in the following figure 2.6 below:

Create Activity Image
Figure-2.6

This will bring us to the Blank Activity screen as shown in the following figure 2.7 below:

Blank Activity Image
Figure-2.7

Change the Activity Name and Layout Name and click on the Finish button as shown in the following figure 2.8 below:

Black Activity Image
Figure-2.8

This will create the basic DroidTipCalculator project elements and we will be in the Eclipse IDE as shown in the following figure 2.9 below:

DroidTipCalculator Project Image
Figure-2.9

Now let us look at the Android project structure using the Eclipse Project Explorer for the newly created DroidTipCalculator project.

An Android project is made up of a number of files and directories. The following are some of the important ones:

The following figure 2.10 of the Eclipse Project Explorer highlights some of the important files in the DroidTipCalculator project:

DroidTipCalculator Project Image
Figure-2.10

We will now modify some of the files highlighted in the figure 2.10 above to implement the desired application functionality. When we created the project for DroidTipCalculator, Android created a basic template for the HelloWorld like application and Eclipse opened the Activity layout of the HelloWorld application in the graphical mode as shown in the figure 2.9 above. Click on the activity_tip_calculator.xml tab to open the layout in the XML editor mode as shown in the following figure 2.11 below:

DroidTipCalculator Project Image
Figure-2.11

The following figure 2.12 shows the Activity layout in the XML mode:

XML Activity Layout Image
Figure-2.12

Modify the contents of the dimens.xml file to look like the one shown in the listing 2.1 below:

Listing-2.1
<?xml version="1.0" encoding="utf-8"?>
<resources>

<dimen name="title_size">26sp</dimen>
<dimen name="margin_size">20dp</dimen>
<dimen name="result_size">20sp</dimen>

</resources>

Next, modify the contents of the strings.xml file to look like the one shown in the listing 2.2 below:

Listing-2.2
<?xml version="1.0" encoding="utf-8"?>
<resources>

<!-- id references -->

<string name="button1">button1</string>
<string name="edittext1">edittext1</string>
<string name="spinner1">spinner1</string>
<string name="textview1">textview1</string>
<string name="textview2">textview2</string>

<!-- Text references -->

<string name="action_settings">Settings</string>
<string name="app_name">DroidTipCalculator</string>
<string name="calculate">Calculate!</string>
<string name="calculate_tip">Calculate Tip</string>
<string name="choose_rating">Choose Rating</string>
<string name="enter_amount">Enter Amount</string>
<string name="tip_amount">Tip Amount</string>

<!-- Array references -->

<string-array name="ratings">
<item>Good</item>
<item>Average</item>
<item>Poor</item>
</string-array>
</resources>

Next, modify the contents of the activity_tip_calculator.xml layout file to look like the one shown in the listing 2.3 below:

Listing-2.3
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
android:id="@+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/calculate_tip"
android:textColor="#cc3300"
android:textSize="@dimen/title_size"
android:textStyle="bold"
android:typeface="sans" />

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="@dimen/margin_size"
android:paddingBottom="@dimen/margin_size"
android:paddingLeft="@dimen/margin_size"
android:paddingRight="@dimen/margin_size" >

<EditText
android:id="@+id/edittext1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/enter_amount"
android:inputType="numberDecimal" />

<Spinner
android:id="@+id/spinner1"
android:entries="@array/ratings"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:prompt="@string/choose_rating"
android:layout_below="@id/edittext1" />

<Button
android:id="@+id/button1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/calculate"
android:layout_alignParentRight="true"
android:layout_below="@id/spinner1" />

<TextView
android:id="@+id/textview2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/margin_size"
android:paddingBottom="@dimen/margin_size"
android:paddingLeft="@dimen/margin_size"
android:paddingRight="@dimen/margin_size"
android:text=""
android:gravity="center"
android:textColor="#0000ff"
android:textSize="@dimen/result_size"
android:textStyle="bold"
android:typeface="sans"
android:layout_below="@id/button1" />

</RelativeLayout>

</LinearLayout>

Let us now decipher the contents of the layout file activity_tip_calculator.xml from the listing 2.3 above:

To preview the Android application layout, click on the Graphical Layout as shown in in the following figure 2.13 below:

XML Layout Image
Figure-2.13

This will enable us to preview our application in the graphical layout mode as shown in the following figure 2.14 below:

XML Layout Image
Figure-2.14

Finally, modify the java source file TipCalculatorActivity.java to look like the one shown in the listing 2.4 below:

Listing-2.4
package com.polarsparc.android.tipcalculator;

import android.os.Bundle;
import android.app.Activity;
import android.view.KeyEvent;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Button;
import android.widget.TextView;
import android.view.View;

public class TipCalculatorActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_tip_calculator);

final TextView tipTxt = (TextView) findViewById(R.id.textview2);

final EditText amtFld = (EditText) findViewById(R.id.edittext1);

/* Set the OnKeyListener on the Amount EditText field so that the
* TextView that displays the tip calculation result display is
* blanked
*/

amtFld.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
tipTxt.setText("");
return false;
}
});

final Spinner ratSpn = (Spinner) findViewById(R.id.spinner1);

Button calBtn = (Button) findViewById(R.id.button1);

/* Set the OnClickListener on the Calculate Button such that
* when it is clicked, we can figure if we have a valid amount
* in the Amount TextView and then based on the selected value
* from the Spinner, we compute the Tip and display the result
* in the Tip result TextView
*/

calBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
double amount = 0.0;

String amtStr = amtFld.getText().toString();
try {
amount = Double.parseDouble(amtStr.trim());
}
catch (Throwable ex) {
}

if (amount > 0.0) {
double tip = 0.0;
String rating = ratSpn.getSelectedItem().toString();
String[] array = getResources().getStringArray(R.array.ratings);

if (array[0].equals(rating)) { // Good
tip = (amount * 20) / 100;
}
else if (array[1].equals(rating)) { // Average
tip = (amount * 15) / 100;
}
else { // Poor
tip = (amount * 10) / 100;
}

tipTxt.setText(String.format("%s :: %.2f",
getResources().getString(R.string.tip_amount), tip));
}
}
});
}

}

From the listing 2.4 above, we see the TipCalculatorActivity class extends the Android Activity class. As indicated earlier, an Activity displays a screen on the Android device for the user to interact with. When an Android application starts up, it automatically invokes the OnCreate() method on the application Activity. Hence we have implemented all the logic to handle all user interactions in this method.

There are references to the Android generated class R in the OnCreate() method. The class R is dynamically generated by Android and includes all definitions from strings.xml and dimens.xml available for use in the java classes.

Let us now decipher the logic inside the OnCreate() method from the listing 2.4 above:

We are now ready to test our Tip Calculator application on the virtual Android device we created in Part-1. In order to do so we need to create a Run Configuration for the application.

To create a new Run Configuration, click on the Eclipse Run menu item. Next, click on the Run Configurations... sub-item as shown in the following figure 2.15 below:

Create Run Configuration Image
Figure-2.15

We will be in the Run Configurations window. Select the first item Android Application from the list of choices on the left hand side as shown in the following figure 2.16 below:

Run Configurations Image
Figure-2.16

Click on the Create icon as shown in the following figure 2.17 below:

Run Configurations Image
Figure-2.17

We will now be in the New Configuration screen. Click on the Browse... button as shown in the following figure 2.18 below:

Run Configurations Image
Figure-2.18

Select the DroidTipCalculator from the Project Selection window and click on the Ok button as shown in the following figure 2.19 below:

Run Configurations Image
Figure-2.19

Change the Project Name to DroidTipCalculator and click on the Apply button as shown in the following figure 2.19 below:

Run Configurations Image
Figure-2.19

At this point the run configuration DroidTipCalculator is ready. Click on the Run button as shown in the following figure 2.20 below:

Run Application Image
Figure-2.20

After a few seconds, our virtual device becomes ready for use. Drag on the Lock icon to the right with the mouse as shown in the following figure 2.21 below:

My Phone Image
Figure-2.21

At this point our Tip Calculator application comes to life as shown in the following figure 2.22 below:

Tip Calculator Image
Figure-2.22

Enter the amount 44.75 and choose Average from the Spinner and click the Calculate! button. The application result will be as shown in the following figure 2.23 below:

Tip Calculator Test Image
Figure-2.23

We have successfully completed our Tip Calculator application.


References

Taste of Android :: Part-1