Building "Helloworld" Android
Application Step by Step
Android is a software stack for mobile devices that includes an
operating
system, middleware and key applications. The
Android SDK
provides the tools and APIs necessary to begin developing applications
on the
Android platform using the Java programming language.
In this session, you are going to learn how install and configure
Android
programming development environment step by step. Then you are going to
learn how to build a simple Android application step by step. The goal
of this session is not to
give you the details of Android programming but to get you exposed to
the steps involved in building a typical Android application.
Expected duration: 160 minutes
(excluding homework)
Disclaimer
Portions of this page are modifications based on work created and shared by the Android Open
Source Project and used according to terms described in the Creative Commons
2.5 Attribution License.
This hands-on lab is part of the "Android Programming (with Passion!)"
online course offered by JavaPassion.com. If you want to see the
hands-on labs of other topics of the course, please go to JavaPassion.com and select
Android Programming. You have to be a paying subscriber in order
to see them all.
Software Needed
Before you begin, you need to install and configure the following
software as
described in Exercise 0 below.
- JDK
- Eclipse IDE
- Android SDK
Resources
- Web sites
- Android
basics website from developer.android.com - the Android
documentation from Google
- Forum
- Presentations
- Tutorials
- Misc
Change Log
- July 15th, 2010: Created (Sang Shin)
- July 21st, 2010: Work-around to Eclipse's Helios release's XML
editor bug (Sang Shin)
- July 24th, 2010: Exercise 6 (logging) and Exercise 7 (Button
click event handler) are added (Sang Shin)
- July 26th, 2010: Some cosmetic changes are made (Sang Shin)
- July 29th, 2010: Added warnings, troubleshooting, changed order
of steps in configuration, added configuration of JRE, added
explanation for emulator boot, added creation of new AVD in exercise 4;
hence playing with two emulators in exercise 5, modified slightly the
homework (Michèle Garoche)
- Aug. 5th, 2010: Some cosmetic changes are made (Sang Shin)
- Aug. 15th, 2010: Added reference for creating a run configuration
in Exercise 5.2 if the device chooser does not get displayed (Michèle
Garoche)
- Aug. 28th, 2010: Added trouble-shooting tip when copying a
project
(Sang Shin)
- Dec. 23rd, 2010: Updated with Eclipse Helios + ADT 8.0.1. (Sang
Shin)
- May 9th, 2011: Made minor cosmetic change (Sang Shin)
- May 17th, 2011: ApiDemos app instruction is updated with Android
3.1 (Sang Shin)
Lab Exercises
Exercise 0: Installation and configuration
(0.1)
Download and install JDK (Java Development Kit) if you have not done so
yet.
If your system does not have JDK yet,
please download and install
JDK.
(If you've been building Java applications, it is highly likely that
you already have JDK installed on your system.)
The steps of downloading and installing JDK is
described in
step
0.1 of "Getting to know your Java programming environment" lab
(1001_javase_progenv.zip)
from
Java Programming (with Passion!)
online course.
return to top of
the exercise
(0.2)
Download and unzip Eclipse IDE
1. Download Eclipse IDE.
- Using your browser, go to http://www.eclipse.org/downloads/.
- Select your OS from the drop-down menu.
- Download either Eclipse IDE for
Java EE Developers or Eclipse
IDE for Java Developers.
- Download it either from main download site or mirror site.
2. Unzip it and run Eclipse IDE.
- Save it in a local directory of your choice.
- Unzip it. You can use "jar xvf <zip-file-name>" or
whatever unzip utility program of your choice.
- Observe that the eclipse directory
is created.
- Observe that there is an executable file, eclipse.exe (for Windows platform,
for example)
under the eclipse directory.
- Run the executable by double clicking it.
return to top of
the exercise
(0.3)
Download and unzip Android SDK
1. Download Android SDK.
2. Unzip it in a directory of your choice.
- Unzip it in a directory of choice using a zip utility of your
choice.
- Observe that it creates android-sdk-<OS>
directory.
- Make a note of the name and
location of the unpacked SDK directory on your system,
C:\download\android\android-sdk=windows, in this example above, because
you will need
to
refer to the SDK directory later, when setting up the ADT plugin in the
Eclipse IDE or
when using
the SDK tools.
return to top of
the exercise
(0.4)
Install Android Development Tools (ADT) plug-in into Eclipse IDE
Android Development Tools (ADT) is a plugin for the Eclipse IDE that
is designed to give you a powerful, integrated environment in which
to build Android applications.
ADT extends the capabilities of Eclipse to let you quickly set up
new Android
projects, create an application UI, add components based on the Android
Framework API, debug your applications using the Android SDK tools, and
even
export signed (or unsigned) APKs in order to distribute your
application.
Developing in Eclipse with ADT is highly recommended and is the
fastest way
to get started. With the guided project setup it provides, as well as
tools
integration, custom XML editors, and debug output pane, ADT gives you
an
incredible boost in developing Android applications.
1. Start Eclipse IDE.
- Double click eclipse executable.
- You might see Workspace
Launcher/Select a workspace dialog box as shown below.
- For the Workspace field,
either take the given directory or choose a different directory.
The Workspace is the directory where Eclipse maintains its projects.
- Check Use this as the default
and do not ask again checkbox.
- Click OK.
(0.5)
Configure ADT plug-in with the location of Android SDK
Once you've successfully installed
ADT plug-in to the Eclipse as described above, the next step
is to modify your ADT preferences in Eclipse to point to the Android
SDK directory:
1. Open Eclipse Preferences window.
- On Unix/Windows machines, select Windows->Preferences
- On Mac OS X machines, select Eclipse->Preferences
2. Configure ADT plug-in with the location of Android SDK, which you
have downloaded and unzipped in the previous step.
- If the location of the Android SDK is not already set, browse to
that location and click OK.
return to top of
the exercise
Trouble-shooting: If you
experience
the following problem, make sure you are using
SDK Tools r08
and
ADT
plugin 8.0.x.
If you are developing in Eclipse with ADT, note that SDK Tools r08 is
designed for use with ADT 8.0.0 and later. After installing SDK Tools
r08, we highly recommend updating your ADT Plugin to 8.0.0.
Also note that SDK Tools r08 requires a new SDK component called
Platform-tools. The new Platform-tools component lets all SDK platforms
(Android 2.1, Android 2.2, and so on) use the same (latest) version of
build tools such as adb, aapt, aidl, and dx. To download the
Platform-tools component, use the Android SDK Manager, as described in
Adding SDK Components
Upgrading from SDK Tools r7:
If you are upgrading to SDK Tools r08 from an earlier version, note
that
the the default installed location for the adb tool has changed from
<SDK>/tools/adb to <SDK>/platform-tools/adb. This means
that you should add the new location to your PATH and modify any custom
build scripts to reference the new location. Copying the adb executable
from the new location to the old is not recommended, since subsequent
updates to the SDK Tools will delete the file.
<end of trouble-shooting>
(0.6)
Install additional Android SDK components - platforms, add-ons, docs
and samples
The latest version of Android SDK comes
with no platforms and Google add-ons. This step will add those required
components plus the optional docs and
samples components we will study and work with.
1. (This is an optional step) Check the
android-sdk-<OS-Platform> directory and observe that
it has empty
add-ons, empty
platforms directories, and
tools directories but
it currently does not have
docs and
samples directories. Via
Android SDK and AVD Manager, you
can
update your Android SDK.
2. Run
Android SDK and AVD Manager.
3. Download and install available packages. The available
packages include Documentation's, Platforms, Samples, etc. You
can selectively choose them.
Notice that the packages list may vary from system to system.
Install them all or at the minimum SDK Platform Android 2.2, API8,
revision 2, Samples for SDK API8, revision x. You can install the
rest later on if needed.
4. Restart ADB.
Note that the installation may be very long (20 minutes or much
more). You may improve the speed by:
- Using http instead of https in the location of the Android plugin
site in Eclipse (in Windows|Eclipse->Preferences->Install
Updates->Available Software Updates).
- Deactivating anti-virus software
- Install only the latest version of platform, Google add-ons,
samples, USB driver (only for Windows machines), and docs
5. Verify the
samples, docs, and other
directories are now added.
return to top of
the exercise
(0.7)
Create an Android Virtual Device (AVD)
In this step, you are going to create a
virtual device which will give options to the emulator to model an
actual device.
1. Select
Windows->Android SDK and
AVD Manager (if it has not been
opened already)
2. Click New in the Virtual Devices frame of the Android SDK and AVD
Manager
The options below are the minimal options to give so that the emulator
works correctly. You may further refine them.
- Enter my_avd_2.2 (or
whatever name you want) as Name for the new
device
- Choose Android 2.2-API
Level 8 for the target. It is the
system which will run on the emulator.
- Optionally enter a minimal size for the SD card -
Important for Mac OS X users: it should
be at least 12 MiB if
you define it.
- Click on Create AVD
- Notice that the new virtual device has been created.
3. Close Android SDK and AVD Manager.
return to top of
the exercise
(0.8)
Configure the JRE to use in Eclipse
This step is only targeted at machines
which have several JRE installed, specifically Mac OS X machines.
By default, Eclipse uses JDK 1.5 and its associated JRE on Mac OS X
machines, that is it does not respect the Java settings if you have set
Java 1.6 as your default JDK/JRE. So you have to tell it to use JDK 1.6
as some exercises require it to build without errors.
- Select Eclipse->Preferences
- Click Java->Installed JRES
- Check JVM 1.6.0
- Click OK
return to top of
the exercise
return to top of
the document
Exercise 1: Build and run "Helloworld"
Android application (using Eclipse IDE)
In this exercise, you are
going to build a simplest possible "Helloworld"-like Android
application. Despite its simplicity, it uses all the necessary
pieces that make up a typical Android application.
(1.1)
Create, build, and run "Helloworld" Android application
1. Create a new Android Project.
- Select File->New->Other (or File->New->Android Project if
you see Android Project from the pop-up menu)
- Select Android->Android
Project, click Next
2. Fill in the project details.
- For the Project name
field, enter HelloAndroid
(or whatever project name of your choice)
- For Build Target, check Android 2.2
(if you already created Android 2.2 AVD).
- For Application name
field, enter Hello,
Android (or whatever Application name of your choice)
- For Package name field,
enter com.example.HelloAndroid
(or com.javapassion or
whatever package name of your choice).
- For the Create Activity
field, enter HelloAndroid.
- Click Finish.

Study point: The following
is the description of each field in the New Android Project dialog box
above.
Project Name
- This is the Eclipse Project name - a directory with this name
will be created under the workspace. This directory will contain
the project files.
Build target
- Notice that the "Build Target" you've selected uses the Android
2.2
platform. This means that your application will be compiled against the
Android 2.2 platform library. The version of build target and the one
over which the AVD runs don't have to match; Android applications are
backward-compatible, so an
application built against the 2.2 platform
library will run normally on the 1.5 platform. The reverse is not true.
- Application Name
- This is the human-readable title for your application - the
name
that will appear on the Android device.
- Package Name
- This is the package namespace (following the same rules as for
packages in the Java programming language) that you want all your
source code to reside under. This also sets the package name under
which the stub Activity will be generated.
-
Your package name must be unique across all packages installed
on the Android system; for this reason, it is important to use a
standard domain-style package for your applications. The example above
uses the "com.example" namespace, which is a namespace reserved for
example documentation - when you develop your own applications, you
should use a namespace that's appropriate to your organization or
entity, for example, com.javapassion.
- Create Activity
- This is the name for the class stub that will be generated by the
plugin. This will be a subclass of Android's
Activity
class. An Activity is simply a class that can run and do work. It can
create a UI if it chooses, but it doesn't need to. As the checkbox
suggests, this is optional, but an Activity is almost always used as
the basis for an application.
- Min SDK Version
- This value specifies the minimum API Level on which the
application is able to run. API Level is an integer value that
uniquely identifies the framework API
revision offered by a version of the Android platform. For
more information, see Android
API Levels.
3. Build and run the application.
- Right click HelloAndroid project
node and select Run As->Android
Application. (Or select Run
from the top-level menu and then select Run.)
4. Observe that the Android device emulator gets displayed.

The Eclipse plugin automatically
creates a new run configuration for your project
and then launches the Android Emulator. Depending on your environment,
the Android
emulator might take several minutes to boot fully, so please be
patient.
5. Slide down the arrow to the right.
6. Observe that the result.
7. Display Console.
The warning message is related to the fact that we did not
specify a minimal SDK version for the project. If you want to get rid
of them, specify a minimal SDK version when creating the project.
Troubleshooting
#1 - If you
experience a "No compatible target found" as
shown below,
it is likely that you have not created an AVD before creating the
project. You may create it now, or better - to avoid problem when
restarting the emulator - delete the project and create the AVD as
explained in Step 0.7 before creating
the project.
Troubleshooting #2 - If you
experience a "Project whatever is missing required source
folder:'gen'" as shown below, it is likely that you installed the
Helios release of Eclipse on Mac machine. The best solution is to
uninstall all what you have installed already and do the installation
again with the Galileo release of Eclipse, because this error is just
the first one of many other ones which will impede you to work
correctly with Android on your machine.
Trouble-shooting #3 - If the
application does not show on the emulator as shown below:
Wait till the the Activity manager has launched the intent and click on
Menu in the emulator.
Trouble-shooting #4 - If you
can no more find a way to get at the application in the
emulator, click on Home, then click on the kind of trackpad centered at
the bottom of the screen (or scroll down the screen if you don't see
the trackpad), click on your application.
return to top of
the exercise
(1.2)
Study
"Helloworld" Android application

A typical Android application is
made of the following components. In this exercise, you are going
to explore each of these components in a cursory fashion.
(You are going to learn the details of these in the rest of the course.)
- Activity classes - there
could be one or more Activity classes for an Android application
- Layout resource files - each screen typically has its
own XML layout resource file
- AndroidManifest.xml -
there is only one for each application
- strings.xml resource file
- there is only one for each application, defines strings
- R.java file -
automatically generated by the Android system
1. Study
HelloAndroid Activity
class defined in the
HelloAndroid.java.

Notice that the HelloAndroid class
extends
the
Activity
class. An Activity is a single application entity that is used to
perform actions. An application may have multiple activities, but
the user interacts with them one at a time. The
onCreate()
method will be called by the Android system when your Activity starts -
it is where you should perform all initialization and UI setup. An
activity is not required to
have a user interface, but usually will.
- Double click HelloAndroid.java
under HelloAndroid->com.example.helloandroid.
- Observe that the HelloAndroid.java
is displayed in the editor window.
- Move the cursor to "Activity" and wait a second or so and observe
that documentation of
Activity class gets displayed. (Please use this feature of
Eclipse IDE to study any Android API you need to have more information.)
2. Study layout resource file in graphical mode.

Every screen has a corresponding
layout resource file (unless it is created programmatically).
Since this simple Helloworld application
has only one screen, there is only one layout resource file. It
is named as
main.xml file in
this application. The activity specifies which layout resource
file to use for each screen it represents.
- Expand HelloAndroid->res->layout.
- Double click main.xml
(or right click it and select Open).
The main.xml
layout file may be displayed in graphical mode as a default depending
on the system as shown below. If it is not, click on Layout tab
at the bottom of the editor to view
it in graphical mode.
3. Display and study layout resource file in XML mode.
- Click main.xml
tab.
- Observe the main.xml
layout resource file is now displayed in XML
mode.
3. Study
AndroidManifest.xml.

Before Android system can start an
application component, for example an Activity, it must learn that the
component exists.
Therefore, applications declare their components in a manifest file
that's bundled into the Android package, the
.apk file
that also holds the application's code, files, and resources.
The manifest is a structured XML file and is always named
AndroidManifest.xml for all
Android applications. It does a number of things in
addition to declaring the application's components, such as naming any
libraries the application needs to be linked against (besides the
default Android library) and identifying any permissions the
application expects to be granted.
But the principal task of the manifest is to inform Android about the
application's components.
In this example, we have only one Application component,
HelloAndroid Activity.
- Double click AndroidManifest.xml.
- Observe that AndroidManifest.xml
file is displayed in wizard mode.
- Click AndroidManifest.xml
tab and observe that the file is
displayed in raw XML format.
- Observe that this application contains a single Activity called .HelloAndroid.

The
name attribute
of the
<activity>
element names the
Activity
subclass that implements the activity. In the example above, it is set
to
.HelloAndroid. The package,
com.example.helloandroid, and
the Activity name,
.HelloAndroid,
constructs the full path to the Activity class,
com.example.helloandroid.HelloAndroid in this example.
The
icon and
label
attributes point to resource files containing an icon and label that
can be displayed to users to represent the activity.

An activity that contains the
<intent-filter> sub-element,
with is own sub-elements
<action
android:name="android.intent.action.MAIN" /> and
<category
android:name="android.intent.category.LAUNCHER" /> specifies
that this Activity is the starting Activity. Using an
analogy of a Java application, this indicates
that the
onCreate() method of
this Activity works like the "main" method of a Java application. (We
are going to spend more time on Activity in the rest of the course.)
<?xml version="1.0"
encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloandroid"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon"
android:label="@string/app_name">
<activity
android:name=".HelloAndroid"
android:label="@string/app_name2">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="7" />
</manifest>
|
4. Study
strings.xml resource file.
The
strings.xml resource file
is where you define all text strings for your user
interface. So instead of using hard-coding a string in your
layout resource file or in your Java classes, you would want to define
the string in the
strings.xml
file and then refers to it using the name of the string.
- Expand HelloAndroid->res->values.
- Double strings.xml.
- Observe that the entries in the strings.xml
file are displayed in a wizard mode.
- Click strings.xml tab at
the bottom.
- Observe that the strings.xml
is displayed in XML mode.
- Observe that there are two string elements - "hello" and "app_name" - are defined in the strings.xml file of this application.
5. Study
R.java file.
A project's R.java
file is an index into all the
resources defined in the resources files of the application.
Examples of resource files include layout resource file - main.xml in this example - or the strings.xml resource file. You use
this class in your source code as a sort of short-hand
way to refer to resources you've included in your project. This is
particularly powerful with the code-completion features of IDEs like
Eclipse because it lets you quickly and interactively locate the
specific reference
you're looking for.
It is possible yours looks slightly different from the one shown
below (perhaps the
hexadecimal values are different). For now, notice the inner class
named "layout", and its
member field "main". The
Eclipse plugin noticed the XML
layout file named main.xml and
generated a class for it here. As you
add other
resources to your project (such as strings in the res/values/strings.xml
file or drawables inside
the res/drawable/ directory) you'll see R.java
change to keep up.
You should never edit this file by hand.
return to top of
the exercise
return to
top of
the document
Exercise 2: Modify "Helloworld" Android
application
In this exercise, you are
going to make simple modifications in various places and see the
resulting change.
(2.1)
Modify "strings.xml" resource file - change values of existing strings
1. Modify
strings.xml resource file as shown
below.
<?xml version="1.0"
encoding="utf-8"?>
<resources>
<string name="hello">Life is worth living
with Passion!</string>
<string name="app_name">My First Android
Application</string>
</resources> |
Trouble-shooting: If you
experience
java.lang.NullPointerException, please take the steps
mentioned
in
2.0 above.
2. Run the application.
- Observe that Eclipse IDE will ask if you want to save any changes
that have not been saved before running the application.
- Click Yes.
- Observe that the new strings are used to display application name
and text.
return to top of
the exercise
(2.2)
Modify "strings.xml" resource file - add new strings
1. Add new strings.
- Add two new strings to the strings.xml
as shown below and Save.
<?xml version="1.0"
encoding="utf-8"?>
<resources>
<string name="hello">Life is worth living with
Passion!</string>
<string name="app_name">My First Android
Application</string>
<string
name="hello2">Life is worth living with Passion! 2</string>
<string name="app_name2">My First Android Application
2</string>
</resources>
|
2. Use the newly added string in the TextView.
- Modify the main.xml as
shown below and Save.
3. Use the newly added string as the label.
- Modify the AndroidManifest.xml
file as shown below and Save.
4. Run the application.
- Observe that the newly added strings are now used for application
name and text.
return to top of
the exercise
(2.3)
Add another TextView
(2.4)
Add another Layout
1. Create a new layout,
main2.xml,
by copying the existing
main.xml.
2. Add a button to the "main2.xml" layout.
- Double-click main2.xml to open it in the Editor.
- Click Layout tab to
display the main2.xml layout
resource file in graphical mode.
- Drag the Button under Views to the location where you
want place the button.
- Observe that the button is now placed with @+id/Button01 notation. What this
means is that Android will create an id for the button and give the
button the text "false".
3. Save the change.
- Click main2.xml tab to
display in the main2.xml in
XML mode.
<?xml version="1.0"
encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello2"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:text="@+id/Button01"
android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
</LinearLayout>
|
4. Change the layout used by the application.
- Double-click HelloAndroid.java
to open it in the editor
- Change the layout to call main2
instead of main
- Click Save button
5. Run the application.
6. Use the "
hello2" string as
value of the button.
- Change the text value for the button in main2.xml to
"@string/hello2"
- Click Save button
<?xml version="1.0"
encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello2"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:text="@string/hello2"
android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
</LinearLayout> |
7. Run the application.
- Observe that the button is now displayed with the value of the hello2 string defined in strings.xml.
return to top of
the exercise
return to
top of
the document
Exercise 3: Rebuild the "Helloworld"
Android application using "Programmatic" UI layout
In this exercise, you are
going to build the "Helloworld" application you've built above using
"programmatic"
UI layout. This means that you construct and build your application's
UI
directly in Java code (instead of using XML layout resource file). If
you've done much UI programming, you're
probably familiar with how brittle that approach can sometimes be:
small
changes in layout can result in big source-code headaches. It is also
easy to forget to properly connect Views together, which can result in
errors in
your layout and wasted time debugging your code. For these
reasons, building your UI using programmatic UI layout is in general
discouraged while usage of XML based layout resource file is a
preferred approach.
- Create a new project (by copying existing
project)
- Modify Activity code to use Programmatic UI
layout
- Add a button
(3.1)
Create a new project (by copying existing project)
1. Copy the existing project.
- Right click the HelloAndroid project
and select Copy.
2. Paste the project.
- Select Edit and then Paste.
- Observe that the Copy Project
dialog box appears.
- For the Project Name
field, enter new project name, HelloAndroid_CreateViewViaJavaCode,
for example.
- Click OK.
Trouble-shooting: Sometimes you will see an error condition in
the newly copied project - somehow the Android library is not correctly
set up. The easiest way to fix this error condition is changing
the Project Build Target to another version and changing it back to its
original version taking the steps below.
- Right click the newly copied project and select Properties.
- Select Android on the left (if it has not been selected already).
- Change the Project Build Target to Android 2.1 (or whatever
version you have other than the one that has been already selected).
- Change it back the Target to its original version.
return to top of
the exercise
(3.2)
Modify Activity to use Programmatic UI layout
1. Modify
HelloAndroid_CreateViewViaJavaCode.java
as
shown below.
The modification is to create
TextView
object programmatically (instead of leveraging the automatic
creation of it by the
Android system through the layout resource file.) The code fragment
that needs to be added is highlighted in bold font.
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new
TextView(this);
tv.setText("Hello, Android");
setContentView(tv);
//setContentView(R.layout.main2);
}
}
|
(3.3)
Add a Button (programmatically)
1. Modify
HelloAndroid_CreateViewViaJavaCode.java
as
shown below. The modification is to use another View object,
Button object in this example. The code fragment that needs to be
added is highlighted in bold font.
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new
TextView(this);
tv.setText("Hello, Android");
Button bt = new Button(this);
bt.setText("Life is good!");
setContentView(bt);
//setContentView(R.layout.main2);
}
}
|
2. Fix imports (Ctrl|Cmd-Shift-O) and Save
<Eclipse tip>: If you type
bt.setT
and wait a bit (or press Ctrl+Space), code completion feature of
Eclipse kicks in.
3. Run the application.
- Observe that the button with "Life is good!" covers the whole
screen.
return to top of
the exercise
return to
top of
the document
Exercise 4: Build and run Sample
applications from Android SDK
Android SDK comes with a set of
excellent sample applications. (The detailed documentation's on these
sample applications can be found
here.)
One of those is called "ApiDemos", which includes a variety of small
applications that illustrate the use of various Android APIs such as
following. Many sample apps we are going to use in this course
are borrowed from this application.
- Notifications
- Alarms
- Progress Dialogs
- Intents
- Menus
- Search
- Persistent application state
- Preferences
- Background Services
- App Widgets
- Voice Recognition
- And many many more...
In this exercise, you will learn
how to build and run "ApiDemos" and other sample applications.
The goal of this exercise is not to understand all the features and
APIs demonstrated but get you exposed to these sample applications as
future references.
- Make sure you have installed "Android
Compatibility package" (if you are using Android SDK 3.0 or after)
- Create "ApiDemos" sample application
- Run "ApiDemos" sample application
- Explore the internals of "ApiDemos" sample
application
(4.0)
Make sure you have installed "Android Compatibility package"
The following steps are required only
when you are building ApiDemo application from SDK version 12(?).
1. Make sure you've installed Android Compatibility package. (If
you have not, click Available packages and install it.)
2. Make sure the
android-support-v4.jar
is present under libs.
3. Make sure the Java Build Path contains
android-support-v4.jar
return to top of
the exercise
(4.1)
Create "ApiDemos" sample application
1. Create Android project.
- Right click on an empty place inside Package Explorer and select
New->Android Project
2. Create a new Android project from existing source.
Important notice: The
project will be created inside the demos directory not inside your
default current workspace. You will see it as it will build the
workspace.
- For Project Name field, enter ApiDemos.
- For Contents, select Create
project from existing source.
- For Location browse down to <Android_SDK_Directory>/samples/android-x.
Select ApiDemos.
Click OK (Open on a Mac).
- For Build Target, select
Android version, for example, Android
3.1 as shown below
- Click Finish.
return to top of
the exercise
(4.2)
Run "ApiDemos" sample application
(4.3)
Explore the internals of "ApiDemos" sample application
1. Explore Java source codes.
2. Explore layout XML resource files.
3. Explore strings.xml resource files.
4. Explore AndroidManifest.xml file.
Exercise 5: Import Android applications
(5.1)
Import an existing sample application
- Observe that the Import dialog
box appears.
- Expand General.
- Select Existing Projects into
Workspace.
- Click Next.
- Click Browse button of the Select
root directory.
- Observe that the Browser For Folder dialog box appears.
- Browse down to <LAB_UNZIPPED_DIRECTORY>/android_stepbystep
directory.
- Expand samples.
- Select helloworld_CreateViewUsingLayout.
(This is the same "HelloAndroid" application you built in Exercise 1
but with a different name.)
- Click OK.
- Observe that the helloworld_CreateViewUsingLayout
project is now displayed under Package.
return to top of
the exercise
(5.2)
Build and run the imported sample application
1. Run the application.

You may have to choose the
emulator which the application will be run
on, if you have not closed the first emulator. Since both emulators are
compatible with the 2.1-update 1 built target,
you may choose which one you want. Click on an emulator to select
it and click OK. You may want to close the first emulator in order to
avoid to be asked
each time for an emulator.

If you don't see the device
chooser, see
Creating a Run Configuration in Android Developer's Guide.
2. Observe that the application opens in the chosen emulator.
return to top of
the exercise
return to
top of
the document
Exercise 6: Logging
(6.1)
Add logging statements to your Java code
1. Modify
HelloAndroid.java as
shown below., then click on Save. The code fragments that need to
be added are
highlighted in bold font.
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class HelloAndroid extends Activity {
private static
final String TAG = "HelloAndroid---->";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
Log.v(TAG,
"onCreate() is called");
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
}
}
|
2. Build and run the application
return to top of
the exercise
(6.2)
Display log messages
1.
Choose
Debug perspective and
observe that Log is displayed. (If
you don't see the Debug perspective as shown below, select
Window->Open Perspective->Debug.)
2. Observe that log message is displayed.
return to top of
the exercise
(6.3)
Create and use log filter
(6.4)
Change perspective back to Java perspective
Exercise 7: Add button click event handler
(7.1)
Add button click event handler
1. Modify HelloAndroid.java as shown below.
package com.example.helloandroid;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class HelloAndroid extends Activity {
private static final String TAG =
"HelloAndroid---->";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
Log.v(TAG, "onCreate() is
called");
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
// Create Button object from layout definition file.
Button button1 = (Button)
findViewById(R.id.Button01);
// Event listener for the button
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View v) {
Button b =
(Button)v;
b.setText("JavaPassion.com is awesome!");
b.setBackgroundColor(Color.YELLOW);
}
};
// Register event listener to the button
button1.setOnClickListener(listener);
}
}
|
(7.2)
Run the application
1. Run the application.
2. Click the button.
3. Observe that the text of the button and background color has been
changed.
The solution to
this exercise is provided as a ready-to-import-and-run
Eclipse project as
<LAB_UNZIPPED_DIRECTORY>/android_stepbystep/solutions/helloworld_CreateViewUsingLayout_solution
return to top of
the exercise
return to
top of
the document
Homework
Exercise
1. The homework is to create your own
"Helloworld" Android project called
MyHelloAndroid
as following.
- The title of the application should be "My Own Android Application"
- Name your layout resource file as myownlayout.xml.
- The display should look something like following.
- When each button is clicked, change the text of the clicked
button and color as following
- "Android programming" to "Android chosen", color of text
Color.GREEN
- "Ruby On Rails Programming" to "Ruby On Rails chosen", color
of button Color.YELLOW
- "Advanced Enterprise Java Programming" to "Advanced
Enterprise
Java chosen", color of text COLOR.BLUE, color of button COLOR.CYAN
2. Create
MyHelloAndroid.zip
file following the steps described below (in order to submit your
homework).
- Right click MyHelloAndroid project
and select Export.
- Expand General.
- Select Archive File.
(Please make sure you select Archive
File under General not
Android.)
- Click Next.
- Select MyHelloAndroid on
the left.
- For the To archive file
field, enter the name of the zip file in a directory of your choice.
- Click Finish.
Now you created
MyHelloAndroid.zip
file under your local file system,
which you can send as a homework submission.
Note: Someone else should be able to import your
MyHelloAndroid.zip file you created
in order to recreate
MyHelloAndroid project
in his/her workspace as shown below.
3. Send the following files to
androidhomeworks@javapassion.com
with
Subject as
android_stepbystep.
- MyHelloAndroid.zip file.
- Captured output screen -
name it as android_stepbystep.gif
or android_stepbystep.jpg (or android_stepbystep.<whatever
graphics format>)
- Any screen capture that shows that your program is working is
good enough.
return to
top of
the document