Lab 1: Hello World

Intro

The goal of this lab is to learn the fundamentals of developing Android applications, including programming tool installation, project creation and coding, and running an app on a physical or virtual Android device. More specifically, you should gain the knowledge of how to use basic development tools to support the application development process, as well as the key components of an Android application itself. These labs assume that you know the Java Programming Language. If you are not yet familiar with Java, consider taking Java Essentials for Android, a Udemy course by Dr. David Janzen. It will prepare you for completing these labs.

Remember to have fun and be excited to learn Android in a world full of mobile development opportunity! Now let's get started.

Objectives

  • Set up the Android Development Environment.
  • Create a basic "Hello World" Android Application containing a simple Graphical User Interface (GUI).
  • Understand the various parts and features of an Android Project, and how they relate to each other.
  • Become familiar with the Android Emulator.
  • Install and run the application on a physical Android device.

Contents

1. Setting Up the Development Environment

1.1 Install Eclipse

1.2 Install the Android SDK & Eclipse ADT Plugin

1.3 Install Android Platforms and Packages

2. Create "Hello World" Application

2.1 Create a new Android Project

3. Take a Tour of the Application

4. Run "Hello World"

4.1 On the Emulator

4.2 On a Physical Device

5. Application Components

6. Getting the User's Name

6.1 Create the User Interface

6.2 Create the Activity Class

6.3 Reconfigure the HelloWorld Application

6.4 Greeting the User

7. Exporting Your Application

8. Deliverables

Activities

1. Setting Up the Development Environment

NOTE: The following assumes you have Java already installed on your computer. You need the 32-bit Java Development Kit (JDK) since Android is exclusively 32-bit. More information about installing Java for Eclipse usage can be found here. Eclipse will not run unless a JDK is set up.

NOTE: You will also need to make sure that the Java Path variables are set properly, more information on this can be found here. There is possibly nothing to be done on your end to resolve this, as it may be done automatically for you.

Your first steps towards Android development involve several downloads and installations. Google suggests that you install the Android Bundle (contains all components in one package) found here, but in order to become more familiar with the development components and the environment, this lab will walk you through installing them separately. The first tool you need is Eclipse. Google announced Android Studio at Google I/O 2013. Android Studio is an alternative to Eclipse that looks very promising, but as of this writing, Android Studio is still in early access preview because it is missing some important features.

1.1 Install Eclipse

Eclipse is an Integrated Development Environment (IDE) that you will do all of your Android programming in. This is because Eclipse contains fantastic support for Android programming integration and designing--Google fully supports Eclipse integration so this is what we will use.

  • Follow the Eclipse installation walkthrough.
    • You must download Eclipse Juno (4.2) or higher.
        • Some Linux distributions may have special ways for installing Eclipse. For example, Fedora users may install Eclipse (and set up Android entirely) using these instructions.
    • If on Windows, make sure to place the unzipped Eclipse folder into the proper Program Files folder: Program Files if you got the 64-bit Eclipse download, Program Files (x86) otherwise.

You can launch Eclipse and make sure it loads properly, then continue on to the next step.

1.2 Install the Android SDK & Eclipse ADT Plugin

The Android Software Development Kit (SDK) provides everything to meet your Android needs.

  • Download the SDK here, and install it using the instructions under the Use an Existing IDE section.

The Android Development Tools (ADT) plugin acts as the glue for the Android SDK and Eclipse.

  • Open Eclipse if it's not open, then follow the walkthrough for installing the plugin.

Once done, open a command line or terminal and type adb then press Enter. If you receive a very long list of functions and properties, this means that the SDK is set up properly.

  • Depending on where you extracted the SDK, you may need to edit your system Path to include the platform-tools folder (the location of adb). If you don't want to edit your system Path to accommodate for this, you may have to run it with a different command such as ./adb on Linux.

1.3. Install Android Platforms and Packages

At the time of writing this lab there are 17 different versions of the Android platform in total but only 12 available for development, ranging from 1.5 (API 3) to 4.2 (API 17). To get a feel for what features and changes each primarily used version offers, check them out here.

It is best practice to develop for the oldest platform available that still provides the functionality you need. This way you can be assured that your application will be supported by as many devices as possible. However, you will still want to download newer versions of the platforms so that you can test your applications against these as well, especially the newest version. One way to check platform version usage is to check Google's Platform Versions page. Google collects data about which platform versions of the Android operating system have accessed Google's web and mobile store, Google Play.

We will target the highest platform that the majority of devices support at the time while still maintaining extensive feature support: Android 2.3.3 (API 10). Before we can begin developing we must download and install this platform.

Follow the walkthrough for launching the SDK Manager and installing platforms and packages.

  • For each Android version starting with API 10, you will want to install the SDK Platform and Google APIs packages. At the time of writing this lab, you will want to check those packages in the API 10 folder up to the API 17 folder, but if there are newer package versions then you will want to install those as well. It is suggested that you install all compatible packages in each of these folders, but this will take more time.
  • Also make sure that all packages in the Tools folder and all compatible packages in the Extras folder are checked.
  • Install all checked packages.

You're now ready to start developing!

2. Create "Hello World" Application

As is the custom for every new language or development environment, you will create a simple "Hello World" type of application. Get started by creating the project as detailed below.

2.1 Create a new Android Project

  • Open Eclipse.
  • Click the menu item File -> New -> Project...
  • In the New Project window that appears, expand the Android folder and select Android Application Project, then click Next.
  • In the New Android App window that appears, fill in the fields as follows then click Next:
    • Application Name: Hello World!
    • This is the name of the application as it will appear in the Google Play Store.
    • Project Name: lab1<userID>
    • The name of the Eclipse project. For instance, if your userID is jsmith, you would name your project lab1jsmith.
    • Minimum Required SDK: API 10: Android 2.3.3 (Gingerbread)
    • This specifies the minimum API Level on which your application can run. By default this is set to the API Level that allows you to target the majority of the platform versions currently being used in the market. As new APIs are added to newer Versions, their API levels increase as well. An app that uses an API Level of 10 won't be able to run on a platform that has a lower API Level.
    • Target SDK: Latest version of Android (at the time of writing this lab, API 17: Android 4.2 (Jelly Bean))
    • This identifies that the project is being built to be compatible with Android platform versions 2.3.3 and later. It's generally preferred that you choose the lowest build number possible, so as to be compatible with the largest number of existing systems in place. This build target can be changed any time later on through the Project Properties menu.
    • Compile With: API 17: Android 4.2 (Jelly Bean)
    • Set this to be the latest version of Android, since our target is the latest version as well.
    • Theme: None
    • We'll worry about themes in later labs.
  • Uncheck the Create custom launcher icon checkbox, and make sure Mark this project as a library is unchecked.
  • You can change the location of where you would like to save the project by unchecking the Create Project in Workspace check box and supplying your own location.
  • Click Next to bring up the Create Activity screen. Choose BlankActivity in the list and click Next.
  • In the New Blank Activity screen, fill in the following fields as such:
    • Activity Name: HelloWorldActivity
    • This is the name of the Java class that will be created to represent the app's main Activity. Activities will be described later in this lab.
    • Layout Name: layout_helloworld
    • In code, this is what the layout will be called. Layouts will also be described later in this lab.
    • Navigation Type: None
    • This is useful in later API versions that support tabs, swiping, etc. SDK level 14 or higher is required for these features, but we won't be using it for this lab anyway.
  • Click Finish. You will likely be taken to the layout_helloworld.xml file, but ignore it for now and continue on to the next section.

3. Take a Tour of the Application

The application you've just created is very similar to other java applications you may have created in Eclipse. Look in the Package Explorer side bar. Notice that the Android Development Toolkit (ADT) has generated a number of folders and files for you. Let's explore them a bit more in detail. Feel free to open any files to see what they look like by default.

NOTE: The files and folders with asterisks '*' next to their names are more important for you to look at more closely.

    • *src: If you expand this out you'll see the package hiearchy you previously entered. This is where your source code files will go.
      • *HelloWorldActivity.java - This is the auto-generated stub Activity Class with the name you entered into the project creation wizard. We'll add some code to this later.
  • *gen: This folder will contain Java files that get auto-generated by ADT. Notice that it already contains one file called "R.java". Do not modify these files under any circumstances!
    • *R.java - This is a special class that is used for referencing the data contained in your resource files (everything in the res folder). If you open this file you will see a number of static inner classes for each of the resource types, as well as static constant integers within them. Notice that the names of the member variables are the same as the names of the values in your resource files. Each value in a resource file is associated with an integer ID, and that ID is stored in a member variable of the same name, within a static class named after its data type.
      • For example, the app_name resource value has an integer ID (something like 0x7f050000)and its type is string. The ADT in Eclipse automatically adds an integer constant to the R.string class and names it 'app_name'.
      • A debugging hint: Occasionally, an Android project will report errors regarding R.java. Sometimes you can fix this by cleaning your project by selecting it in the Project Explorer and then choosing Project > Clean... to rebuild it completely.
      • You are encouraged to turn automatic project building on in Eclipse (Project > Build Automatically menu item) if it is not already enabled.
    • BuildConfig.java - Not surprisingly, this file contains a configuration for building the application. It is structured similarly to R.java but contains just one variable, DEBUG, set to true. This is maintained for the sake of debugging and is useful if you need to run debug-only code.
    • Android 4.2.2: This is the library of the Android version you had chosen in the project creation wizard. The application will be built using this version of 'android.jar' (location shown).
    • Android Dependencies: This is a listing of JAR files for other Android libraries (either they aren't available in older platform API versions and must be added manually here, or they aren't a part of the Google-provided API framework). The JAR file present for this project is android-support-v4.jar. Read more about the support libraries here. We will make good use of it in later labs.
    • assets: This folder is for asset files, which are quite similar to resources, the main difference being that anything stored in the 'assets' folder has to be accessed in the classic file manipulation style. For instance, you would have to use the AssetManager class to open the file, read in a stream of bytes, and process the data. You will not be using assets much at all.
    • bin: This folder contains files that are automatically generated by the compiler, which takes your code and resources and creates the application itself: a .apk file, which also resides in this folder.
    • libs: This is the location of all JAR files for additional features and functionality support in Android programming, such as support libraries. You'll likely see android-support-v4.jar in here. Read the Android Dependencies description above for more detail.
    • *res: This folder will contain all of the resources (a.k.a. external data files) that your application may need. There are three main types of resources that you will be using and Eclipse has created a subdirectory for each.
      • drawable-x: These folders will hold image and animation files that you can use in you application. There are several of these folders for various screen sizes/densities. For example, larger screens take up more physical space, and higher density screens have more pixels in a real physical screen area. We will not touch on multiple screen support in this lab, but feel free to read more about screens here for more information.
      • Each drawable-x folder already contains two files: one called ic_action_search.png which is used for search features in an application, and another called icon.png which represents the icon that Android will use for your application once it is installed.
      • NOTE: drawable-ldpi does not have any icons as API level 10 does not tailor to low density screens, since any devices running Android 2.3.3 (Gingerbread) or higher have at least medium density screens.
      • NOTE: Sometimes you will want a drawable folder to hold resources such as State Lists. More on this in later labs.
      • *layout: This folder will hold XML layout files that the application can use to construct user interfaces. You will learn more about this later, but using a layout resource file is the preferred way to layout your UI.
      • The folder already contains a file called layout_helloworld.xml which defines the user interface for your 'HelloWorldActivity.java' Activity class. Double clicking on this file will open up the Android UI Editor that you can use to help generate and modify XML layout files.
    • menu: This folder will hold XML menu files that the application can use to construct menus so users can change various app options. You will learn more about this later, but note that using a menu resource file is the preferred way to detail your app's menu structure.
      • The folder already contains a file called helloworld.xml which defines how the menu of 'HelloWorldActivity.java' will look like. Double clicking on this file will open up the Android UI Editor that you can use to help generate and modify XML menu files.
      • We will later rename the file so it is called menu_helloworld.xml instead; you can do this now or wait until later when the instructions mention it.
    • *values: This folder will hold files that contain value type resources, such as string and integer constants. Other similar folders, values-*, contains additional dimensions and styles for different and usually larger screen sizes (read more about configuration qualifiers here) but don't concern yourself much with those for now.
    • The values folder already contains three files. Double clicking on any of them will open up the Android Resource Editor and you will see their contents shown:
    • 1. dimens.xml - A location to store app dimensions, which can be used to space and pad various elements on the screen. The three dimension values listed use dp, or 'density-independent pixel', for measurements. Read more about screen measurements and units here, but it is not necessary for this lab.
    • 2. *strings.xml - A location to store string (text) variables. Notice that there are four strings in there already:
        • app_name - If you select this value, on the right hand side of the editor you should see the Application Name you entered in the project creation wizard. You can use this editor to add new resources to your application.
        • action_settings - Represents the text that appears on the first (and only) menu item. The menu of an application is reached when pressing the MENU button on a physical device or the emulator while the application is running. This string is currently used in hello_world.xml inside of the menu folder.
        • hello_world - A string placed into any new Android Application Project by default. It always shows up in the Graphical Layout of layout_helloworld.xml in the middle of the app screen.
    • 3. styles.xml - A location to store application themes/styles. For now we'll leave this file alone, but if you are curious and hunger for more information on styling your application, read here!
  • *AndroidManifest.xml: Every project has a file with this exact name in the root directory. It contains all the information about the application that Android will need to run it:
    • Package name used to identify the application.
    • Version code and name for app progress.
    • List of Activities, Services, Broadcast Recievers, and Content Provider classes and all of their necessary information, including permissions.
    • System Permissions the application must define in order to make use of various system resources like GPS, keeping the device 'on' or accessing an SD card.
    • Application-defined permissions that other applications must have in order to interact with this application.
    • Application profiling information.
    • Libraries and API levels that the application will use.
  • proguard-project.txt: Double-clicking this file will explain all there is to know about the ProGuard feature--it shrinks the application and makes it harder to reverse-engineer, among other benefits. You can read more about ProGuard here, but we won't use it.
  • project.properties: Ths file contains all of the project settings, such as the build target you chose in the project creation wizard. If you open the file, you should see 'target=10', which is your build target. You should never edit this file manually. If you wish to edit the project properties, do so by right-clicking the project in the 'Package Explorer' panel, and selecting 'Properties'.

Whew, that's a lot! Now let's explore the app itself a bit more in the context of Android development.

The project creation wizard has written the 'Hello World' application for you already, although it is not close to looking like our final product. A string resource containing the "Hello world!" display text has been placed into the res/values/strings.xml file. The value is named 'hello_world'.

The XML UI layout has been added to res/layout/layout_helloworld.xml. While you can use the Android Layout Editor to create and edit your XML layout, you can also code manually yourself. Lets take a look at this file:

  • In the res/layout folder, double click on layout_helloworld.xml, which then opens up the file in the primary coding area in Eclipse.
    • If you look at the bottom of the window that opens, you will notice two tabs: Graphical Layout and layout_helloworld.xml. The graphical layout is an interactive drag-and-drop style builder. The other tab shows the raw contents of the file. Both of them synchronize with each other as edits are made. We will primarily edit XML files like these in the raw format instead of the graphical format, for more control.
  • Click the layout_helloworld.xml tab to view the raw source of the file.

Notice the top level element, RelativeLayout, which defines the style of layout this file will be using. This 'RelativeLayout' is one of the most basic layouts (next to LinearLayout), and specifies that UI elements will be laid out in accordance with other elements inside of the layout. It has quite a few properties, but you want to mainly focus on the width and height as you'll be using those very often. These properties will be discussed in detail later in the lab.

What are the xmlns:android and xmlns:tools properties?
These are namespace declarations in XML. They help distinguish between different versions of identical elements in XML. Most of the time we will not have to worry about namespace clashes, just be aware of their existence. Some Android XML components will require an xmlns namespace declaration.

Now look at the second level element, TextView, which defines a UI element for displaying text. It has a few properties as well: width, height and the text to display. Not all properties are required when defining each Android element.

  • Notice that the TextView's text property is not set to the string "Hello world!" even though that is the text we wish to display. Instead it is set to reference the resource value (@string, which points to the strings.xml file we covered earlier) which contains the text we want to display. We will explain this reference syntax later in the lab.

4. Run "Hello World"

4.1 On the Emulator

Before we can run the application, we need to setup an Android Vitual Device (AVD), or emulator, to run it on. You can read more about AVDs here and about managing AVDs here. This is a good option if you do not own a physical Android device or own an Android device that does not run at least Android 2.3.3, Gingerbread.

You can create AVDs using one of the following steps:

  • Follow the walkthrough to create an AVD device that runs at least Android 2.3.3 (API 10). This will give you more control over the AVD fields.
  • Click the Device Definitions tab in the AVD Manager and create an AVD based on one of the devices listed. This will populate the AVD fields with preset values representing the device's properties. Remember that it must still run at least Android 2.3.3 (API 10).

We're now ready to run our application.

  • Right-click on your project in the Project Explorer and choose Run As -> Android Application.
  • Since this is the first time you are running an Android application, the Android Device Chooser window appears. Select Launch a new Android Virtual Device and click on the AVD you created.
    • Note: After you've decided which kind of device (physical or AVD) to use for development in the long run, you may wish to check the Use same device for future launches checkbox in the lower-left corner. For now, leave it unchecked.
    • Note: To adjust Android application project launch properties manually, right-click on your project in the Project Explorer and select the menu item Run As -> Run Configurations... then select the Android Application project you wish to configure and click the Target tab. From here, you have your choice for configuring how to launch the given project's application. For example, you can force your project to prompt for an Android device at each launch, which may come in handy for the next step...
  • Click OK.
    • Note: The emulator may take a long time to start up.
  • You can interact with the emulator using the mouse just like you would with a device, to simulate finger touches. See the image below to see what the emulator looks like (click image for full size).
Hello World on Nexus S

How the default application appears on an AVD. This is run on a Nexus S emulator on Fedora.

Congratulations, you've just created and launched an Android Application on an AVD! Now if you have a physical Android device such as an Android phone, we'll run it on the real thing.

4.2 On a Physical Device

Before we can run the application on a physical device, we need to make a configuration change on the phone and install some drivers for the phone on our development machine. Thankfully, the newer ADT plugins have automatically handled debugging, and thus turning on debug mode manually in the AndroidManifest.xml file is not needed! However, we still need to prepare the device (phone) for application installation.

  • Phone Modifications
    • Follow the walkthrough to prepare a physical device for development.
      • On 4.2 devices, developer options are hidden by default. Enabling them is just a few clicks away, or possibly more.
  • Back in Eclipse, ensure the device is properly connected by right-clicking on your project in the Project Explorer and selecting the menu item Run As -> Run Configurations..., then choose Always prompt to pick device under the Target tab and then click Apply and Run.
  • In the Choose a running Android device field, your device should appear and it should have a green check mark next to the target if it is compatible.
  • Select your device and click OK.

The "Hello World!" app should start on the phone or tablet (click image for full size):

Hello World on Nexus 7

How the default application appears on a physical device. This is run on a Nexus 7 tablet.

5. Application Components

There are four major types of component classes in any Android application. Consider them all "entry points" into your application, or ways to have the operating system invoke your Android application.

  • Activities: Much like a Form for a web page, activities display a user interface for the purpose of performing a single task. An example of an Activity class would be one which displays a Login Screen to the user. It's essentially a single interactive screen.
  • Services: These differ from Activities in that they have no user interface. Services run in the background to perform some sort of task. Other classes (such as Activities) can start and set up services. An example of a Service class would be one which fetches your email from a web server.
  • Content Providers: Components of this type function to provide data from their application to other applications. They work with shared application data that can be stored just about anywhere persistent (on the web, for example). Components of this type would allow an email application to use the phone's existing contact list application for looking up and retrieving an email address.
  • Broadcast Receivers: The sole purpose of components of this type is to receive and react to broadcast announcements which are either initiated by system code or other applications. If you've ever done any work with Java Swing, you can think of these like Event Listeners or Handlers. For example, a broadcast announcement may be made to signal that a WiFi connection has been established. A Broadcast Receiver for an email application listening for that broadcast may then trigger a Service to fetch your email.

You can read more about Application Components here.

In this lab, we will be focusing on what Activities are and how they are used. We will cover the other components in later labs.

In case you don't remember it from earlier, you have already created one of these component classes: the HelloWorldActivity class is an Activity Class (although it was probably obvious based on the name). It's a simple user interface designed to greet the user. You can't get much simpler than that!

In the section that follows, we'll make our application more personal by adding a new Activity class to ask for the user's name, and then update the existing HelloWorldActivity to display that name. It's coding time!

Note: If you ever have problems getting things to compile in Eclipse, you might try Project -> Clean.... You can also restart Eclipse and see if the errors go away.

6. Getting the User's Name

To get the user's name, you will be creating an Activity class which will allow the user to enter their name into a text field and press a button when finished to proceed to the HelloWorldActivity screen, which greets the user with the name they entered.

There are three separate steps to accomplish here:

-Lay out the user interface in XML.

-Create the new Activity class, hook the XML up to it, then parse the input from the user and initiate the HelloWorld Activity.

-Reconfigure the application to use your new retrieval Activity on startup instead of HelloWorldActivity.

6.1 Create the User Interface

Android allows you to lay out your user interfaces using a simple XML specification. We will go into more depth on this topic in the next lab, so for now you will be setting up a basic interface using four different GUI elements or components. Begin by creating a new Android XML file:

  • Select the menu File -> New -> Android XML Layout File, or right-click on the project in the Package Explorer and choose New -> Android XML Layout File.
  • If Android XML Layout File does not appear in the menu:
    • Select Other...
    • Expand the Android folder.
    • Select Android XML Layout File and click Next.
  • Ensure the Project matches the name of your project.
  • Enter "name_getter.xml" as the file name.
    • The name of your layout files must only contain lower case letters, the numbers 0-9, underscores '_', or periods '.'
  • Make sure LinearLayout is selected in the Root Element list, and click Finish.
Creating a new XML Layout file

Making a new XML layout file.

  • Notice that the file is created inside of the res/layout folder. By default, the file will be opened to the Graphical Layout tab. Select the tab at the bottom labeled name_getter.xml to switch to the XML Editor, or the raw text view.

Let's take a closer look at this file now. You should be able to see an XML opening and closing tag labeled LinearLayout in the editor. LinearLayout, like all screen components, derives from the View base class (read a description of the View class here). Each XML layout file must have a single root view component, inside which all other view components are nested. LinearLayout tells Android to arrange elements contained inside itself in a straight line in the order in which they appear. Let's make a few modifications to the LinearLayout by editing the attributes contained in the opening LinearLayout tag:

  • Set the attributes labeled android:layout_width and android:layout_height to "fill_parent" (Include the quotes).
    • This tells Android that the LinearLayout should take up all the available width and height on the screen.
  • Notice that the attribute labeled android:orientation is already set to "vertical", which is what we want.
    • This tells Android that elements nested inside the LinearLayout should be laid out in a column, as opposed to a single row as indicated by "horizontal". The first item inside the LinearLayout will be at the top, the second item below the first item, etc.

Lets add the other three UI elements to our XML layout file:

  • Switch back to the Graphical Layout tab.
    • Under the Palette on the left side of the window, select Textview under the Form Widgets folder. Click and drag the TextView beneath the "Hello World!" title.
    • The Layout Editor will pre-populate the label with its auto-generated id, which may look somewhat strange.
    • Repeat the previous step for the EditText (Plain Text) and Button (Small Button) components, which are located beneath the Text Fields and Form Widgets folders respectively.
    • Remember, order matters for the LinearLayout. Drag each component below the previous item!
    • In the below image, we see the basic look of the screen. However, we certainly want to make the interface more intuitive.
Layout - unfinished
      • The basic interface. It clearly needs some tuneup.
  • Switch back to the XML Editor (raw text) to change the attributes of the elements you just added.
    • Notice that all the UI elements you added are nested within the LinearLayout Element.
    • There may be warnings (yellow underlines) in parts of the text. Don't worry, we will address these next.
    • Important: there will always be only one root element. You may, however, nest other Layout elements within each other.
  • First up is the TextView element. A TextView is simply a component that displays text. This is the label that prompts the user to enter their name.
    • The TextView displays the value contained in the android:text attribute.
      • Set this attribute to ask the user what their name is.
      • 1. Open the strings.xml file in the res/values folder. In the Resources tab, click the Add... button.
      • 2. In the window that appears, select String and click OK.
      • 3. Make sure the new String is selected (it appears in the left column as 'String'). For Name, enter name_prompt. For Value, enter text that prompts the user to enter their name (e.g., What is your name?).
      • 4. Back in name_getter.xml, set the TextView's text attribute to @string/name_prompt. Yellow warning, begone!
What does the "@ /" syntax mean?
In Android development, this is the way to reference resources. For example, look at the android:id attribute in the TextView. This attribute specifies a variable name for referencing this element from within the code. Some important information about this kind of syntax:
1. References are specified with the syntax of @type/handle. For example, the String we just created, name_prompt, is specified like this: @string/name_prompt.
2. IDs are declared with the syntax of @+id/MyId01. They are created with the '+' character, not specified, since they do not exist elsewhere like other resources such as Strings. IDs serve as the identification of a component, and you will use them when we modify the Java files.
3. The text after the forward slash (such as MyId01) is the name, or handle, used to identify the element from within your application code via the Static R class. If you look at R.java now, under the final class String you will now see the handle name_prompt listed there. The text that name_prompt refers to is the String we created in strings.xml in the previous step (What is your name? or similar text you entered).
  • Next is the EditText element. This is the field where the user will input their name.
    • Add an attribute called android:hint and set it to indicate the text that should be entered into the EditText field (such as Enter your name). The hint attribute provides a hint to the user when the field is empty, and disappears when text is entered. Don't use a raw String, instead set the value to a String resource just like you did for the TextView.
    • Inside of the EditText component, you will see the line <requestFocus />. This means that focus will be given to the EditText component when the application is launched and this screen appears on screen, allowing users to immediately enter text into the field without having to navigate to or press the EditText component on the screen first.
  • Finally, the Button element. This is the button that will allow the user to continue to the next screen, which will greet them.
    • The Button will display the value contained in the android:text attribute.
      • Set this attribute to something like ok, next, or submit., setting the value to a String resource just like you did for the EditText.

Great, the XML layout is all set up! Let's see our layout in graphical form now:

Complete layout

Much more intuitive.

Now this is where things get more Java-oriented. It's time to integrate the XML layout into the Java Activity class that we want to use. First we need to create

6.2 Create the Activity Class

Using the HelloWorldActivity Class from section 2.1 as an example, use the Wizard to create a new Android Activity called EnterNameActivity that extends android.app.Activity and implements android.view.View.OnClickListener interface:

  • Activity Name: EnterNameActivity
  • Layout Name: layout_entername
  • Title: Hello World
  • Launcher Activity: (check this item)
  • Hierarchical Parent: (leave blank)
  • Navigation Type: None

Notice that the title of this Activity is also set to Hello World. Since we intend to have our new Activity show up upon launch, the Title property also represents the application's name.

If you click Next before Finish, you will see the list of changes that will be performed on all files in the project upon the creation of this new class. In particular, observe the change to AndroidManifest.xml. We will be touching this file later on to make some manual changes in relation to this change.

Notice that the menu XML files in the res/menu folder are named enter_name.xml and hello_world.xml. You will change their names so they are more easily identified.

  • Right-click on both files and choose Refactor -> Rename... (possibly just Refactor) and rename them to start with 'menu' instead.
    • Examine the call being made in the onCreateOptionsMenu() method in EnterNameActivity.java: R.menu.menu_entername. Similar to the XML style of using @ and / to refer to resources, this means that you are referring to the menu_entername resource under the menu type located in R.java. Now it's probably easy to see that XML and Java files share resources and interact through R.java.
    • Note: Menus will be covered in greater detail in later labs. In this lab, we will leave the menus for these Activities as they are since we don't need them.
  • In EnterNameActivity.java, notice that the layout being referenced is layout_entername.xml. You already created an XML layout file named name_getter.xml, so change the call to setContentView() in the onCreate method so it references R.layout.name_getter instead.
    • XML layout files are interchangeable! Remember that they are structured so they are independent of the Java Activity classes, but can be referenced very easily.
  • Now make EnterNameActivity implement the View.OnClickListener interface.
    • Hint: You can automate this with Eclipse.
      • We'll fill in the onClick() method once we have the pieces to make something happen in it.
  • Declare a class variable (above all methods in the class) of the type android.widget.EditText called nameField.
    • This will hold a reference to the text field in which the user will enter their name, the same one that you added to the name_getter.xml layout file.
  • Declare a class variable of type android.widget.Button called okButton.
    • This will hold a reference to the 'ok' button below the text entry field, the same one that you added to the name_getter.xml layout file.
  • Notice the first method in the class: public void onCreate(Bundle savedInstanceState).
    • This method will be called when the Activity starts and is where initialization of local and member data will be done. When you created the XML layout file earlier, the Eclipse ADT Plugin automatically added a static constant to the static R.layout class in the R.java file under the res/gen folder. This constant variable has the same name of the file and it's value is used to identify the layout file. This call tells Android to create a screen based off of the layout file specified.
    • Inside this method, you will see two calls:
      • A call to super.onCreate(savedInstanceState).
        • This should always be done first in this method to ensure that any necessary parent class initializations are performed.
      • A call to this.setContentView(R.layout.name_getter).
    • Now make a call to findViewById(R.id.editText1) and set your EditText member variable equal to the return value. This will link the EditText object in name_getter.xml to the EditText variable you recently created.
      • You will have to explicitly cast the return value to the type of EditText as this method only returns objects of type Object.
      • This static constant value was added in the same way as it was done for the R.layout.name_getter value and serves the same purpose.
    • Make a call to findViewById(R.id.button1) and set your Button reference equal to the return value.
      • You can make your coding faster by typing this before valid method calls or variables, then putting a period. This triggers Eclipse's autocomplete feature.
    • Make a call to okButton.setOnClickListener(this).
      • That will tell Android that this Button is going to rely on the class it's in, which implements OnClickListener, to listen for and handle its clicks.
  • Fill in the onClick() method stub:
    • Retrieve the user-entered text from the EditText field and keep it in a local String variable. Use Eclipse to help you locate which two method calls chained from nameField can get you the text in the EditText's text field as a string!
    • If the retrieved text is not empty:
      • Clear the EditText text field by setting it to an empty String. If Back is pressed, this will allow the user to enter new text into the EditText instead of leave the old text there.
      • Create a local android.content.Intent variable and set it equal to new Intent(this, HelloWorldActivity.class).
        • We'll use the Intent object to start the HelloWorld greeting activity and pass it information.
        • We'll discuss Intents in more depth in later labs, essentially we use them to interact with other application components in ways such as starting new activities.
      • Use the Intent class' putExtra(<key>, <value>) method to pass the user entered name to the HelloWorld greeting Activity. This method functions like a hashmap, where values can be stored by associating them with a string key and later retrieved with the same key. You can retrieve this hashmap later by calling getExtras().
        • Make a call to <intent>.putExtra(<key>, <value>).
        • <intent> should be replaced with the intent variable you just created.
        • <key> should be replaced with a string you will use to access the user's name later. The string should be something easily identifiable such as "name".
        • <value> should be replaced with the user's name obtained from the text field. You stored this value in the local String variable you created earlier. (Hint: the String variable should have been set to nameField.getText().toString() to obtain the correct value)
      • Make a call to this.startActivity(<intent>).
        • This command will initiate the switch to the HelloWorld greeting Activity.

6.3 Reconfigure the HelloWorld Application

The Android Manifest contains information on all of the Application's components, including which component should be used in different scenarios. We need to tell our application to use the new activity on startup instead of the HelloWorldActivity it was previously using. Begin by double-clicking the AndroidManifest.xml file to open it.

  • Like when you edited the Layout files, there is also a Manifest Editor tab for the Manifest file, as well as several other views for editing. However, we will edit this file manually. Switch to the raw XML Editor by clicking the AndroidManifest.xml tab along the bottom of the editor.
  • Find the first opening <activity ... > tag. You will see several attributes for HelloWorldActivity, such as android:name and android:label.
  • The Intent Filter tag you see nested inside the Activity tag is what tells the application that this Activity is the Main, or startup, Activity. Unfortunately, both activities have an Intent Filter tag (as you may have seen earlier), and we cannot have two main Activities! We want EnterNameActivity to be the first Activity launched.
    • Delete all traces of the intent filter from the HelloWorldActivity element in the Manifest file.

At this point, you should be able to try running the application. The application should start up and display the name retrieval activity you just created. You should be able to enter your name in the text field and hit the button, after which the old HelloWorldActivity greeting screen should appear (click image for full view):

Nearly finished app

Also make sure that pressing Back erases the entered name in the EditText field of EnterNameActivity.

  • If using an AVD: depending on your AVD setup and AVD of choice, the AVD's keyboard may not be working.
    • Close your AVD, then open the AVD Manager and select Edit... to modify your AVD.
    • Under the Hardware area, click the New... button and add the Keyboard Support property. Change its value to yes, then click Edit AVD to finalize the AVD changes.
    • Restart the AVD and relaunch your application from Eclipse.
  • The application as it appears on the Android device is called Hello World, since that is the name of the new main Activity.

6.4 Greeting the User

Now that we've got the name retrieval activity completed, let's update HelloWorldActivity to print out the name the user entered. In the onCreate() method of HelloWorldActivity.java:

  • Make a call to this.getIntent().getExtras() to retrieve the hashmap in which you placed the user entered name.
    • This will return an android.os.Bundle object which acts like a hashmap.
    • You should check to ensure that this value is not null.
  • Retrieve the user entered name from the Bundle object and store it in a local String object.
    • Make a call to the bundle's getString(<key>) method.
    • <key> should be replaced with the key String you used to put the user entered name into the hashmap in the name retrieval Activity's onClick method (e.g. "name").
    • You should check to ensure that this value is not null.
  • Get a reference to the TextView object in your layout_helloworld.xml layout file (you may need to add an id to it).
    • Change the RelativeLayout so it centers the TextView instead of padding it. This involves removing a great majority of the RelativeLayout's properties and setting the android:gravity property (think of gravity as a text-align property, only for horizontal and vertical alignment).
  • Set the text of the TextView object to say Hello <name>!
    • <name> should be replaced with the entered name that you retrieved from the bundle object.
  • Run your application. You should be able to type in a name into the text field, hit the button and then go to another screen that greets you! Below are three screenshots of what the application should look like (click image for larger view):
The finished app!

The final application in motion. Congratulations!

7. Exporting Your Application

In order for your application to be run on a physical device, it must be digitally signed with a certificate. The certificate does not need to be signed by a certificate authority like Verisign. It's acceptable to use a self-signed certificate.

As of now, you've only been executing your application on your physical device by launching it through Eclipse. By doing it this way, the Eclipse ADT Plugin has been signing your application with its own "debug" certificate. Signing with the "debug" certificate is not acceptable for release to the general public. In this short section you will learn how to generate a new keystore, compile your application as a ".apk" file, create a certificate, and sign it.

For more details on the Application signing you can view the documentation on the Android Developer Site, click here.

For those who haven't taken a Security class or are unfamiliar with the idea of Keys, Certificates and how they work, you can read more information about it on Wikipedia.

The Eclipse ADT plugin provides a simple Export Wizard that automates the entire process for you. Follow the instructions on the Android Developer Site on how to Compile and sign with Eclipse ADT. Make sure to read the short section following this one on Securing Your Private Key. Signing your application is not essential for the remainder of these labs, but it will be important if and when you release an application to the public in the Google Play Store in the future.

Make sure to keep track of your .apk file. You will be handing it in at the end of the lab as proof that you completed it.

8. Deliverables

To complete this lab you will be required to:

  1. Submit your signed .apk file to the Lab 1 assignment in PolyLearn. This effectively provides time-stamped evidence that you submitted the lab on time should there be any discrepancy later on in the course. The name of your application should be lab1<cal-poly-username>.apk. So if your username is jsmith, then your file would be named lab1jsmith.apk.
  2. Load your app on a mobile device and bring it to class on the due date to demo for full credit.
  3. Complete this survey: https://www.surveymonkey.com/s/436F13Lab1.

Primary Authors: James Reed, Kennedy Owen

Adviser: Dr. David Janzen