Home > Articles > Programming > Java

Learning Mobile App Development: Using Eclipse for Android Development

This chapter is an introduction to building a complete Android app. The chapter includes creating a new app project, exploring the components of an Android app, setting up the emulator to run and test apps, and building a variation of the traditional Hello World app
This chapter is from the book

This and the following chapters in this part assume that you have access to Eclipse and that it is set up for Android development. If this is not the case, refer to Appendix A, “Installing Eclipse and Setup for Android Development” before continuing.

Starting a New Project

Eclipse is a powerful, open source, integrated development environment (IDE) that facilitates the creation of desktop, mobile, and web applications. Eclipse is a highly versatile and adaptable tool. Many types of applications and programming languages can be used by adding different “plug-ins.” For example, plug-ins are available for a very large number of programming languages as diverse as COBOL, PHP, Java, Ruby, and C++, to name a few. Additionally, plug-ins provide the capability to develop for different platforms, such as Android, Blackberry, and Windows. Many of the tools in the Eclipse IDE will be explained through the act of developing an Android app.

Android is a mobile operating system designed for smartphones and tablets. The operating system is very powerful, enabling access to a diverse set of hardware resources on a smartphone or tablet. Android is provided by Google and is continually updated, improved, and extended. This makes the development of apps for Android smartphones and tablets both exciting and challenging. As with Eclipse, the many features of the Android environment are best explained through the act of developing an app.

Setting Up the Workspace

Eclipse uses the concept of a workspace for organizing projects. Because Eclipse can be used to develop many types of applications, this is very useful. A workspace, in reality, is just a folder on some drive on your computer. The folder contains the application’s code and resources, code libraries used by the application (or references to them), and metadata that is used to keep track of environment information for the workspace.

To begin, run Eclipse. The Workspace Launcher dialog window opens, asking which workspace you want to use. The default workspace (or last used) is displayed in the dialog window’s text box. Most IDEs are designed with the idea that developers are going to be working on the same machine each time they work on a project. This can cause problems in the education environment where students do not have the ability to work on the same machine and/or store their work on the machine they are currently working on. If you are using your own machine, you can skip to the next section; your workspace was created when you installed Eclipse and is ready to go. However, if you are working in an environment where you cannot use the same machine each time, you need to set up a workspace on either a flash drive or on a network drive. Determine which of these options is best for your situation and perform the following steps:

  1. Create a folder in your selected location named workspace.
  2. Go back to the Workspace Launcher and browse to your new folder. Click OK.

    Often in a situation where you change the workspace to a location not on the machine that Eclipse is installed on, Eclipse will not be able to find the Android SDK. If it cannot find the SDK, a dialog window opens. If this happens, you will have to tell Eclipse where the files are located by performing the next steps.

  3. Click Open Preferences on the dialog window and browse to the sdk folder. This is usually located in the .android folder. Click Apply.

    The available Android versions should be displayed in the window.

  4. Click OK to close the dialog window. Your workspace is now ready to begin Android development.

Creating the Project

The traditional beginning tutorial for many different languages and development platforms is “Hello World.” Your first Android app will be a slightly modified “Hello World” app. In Eclipse, all Android apps are created within a project. To create your first app, you will have to create your first project. Creating a new project requires stepping through a series of windows and making choices to configure your app. To get started, from Eclipse’s main menu choose File > New > Android Application Project. You should see the New Android Application dialog window, as shown in Figure 3.1.

Figure 3.1

Figure 3.1 Initial new Android application window configured for “Hello World.”

Fill out the screen as shown. The application name is displayed on the phone’s screen as the name of the app. You can use spaces if you want. As you type the name, the project name and package name will be completed. There are no spaces allowed in these items. The wizard will remove them as you type. Don’t put them back in either of these fields. The package name is important. For this initial project you don’t need to change the default. However, if you are building an app for sale, in place of “example” you should put your company name. This identifier will be used in the Play Store to link your apps to the services they use and connect all your apps.

Next, click the Minimum Required SDK drop-down. A list of potential Android SDKs are listed. SDK stands for Software Development Kit, and it is a set of tools and code libraries used to write software for a specific platform. Each release of the Android OS is associated with an SDK so that programmers can write code for that platform. An application programming interface (API) is a set of routines that allow a program (app) to access the resources of the operating system to provide functionality to the user. The minimum required SDK determines what phones and other Android devices will be able to install your app. (Phones and tablets using Android operating systems earlier than this selection will not even see your app in the Play Store.) This selection will also determine the features you can program into your app. The recommended minimum is the default: Froyo API 8. An app that has this minimum will be accessible to more than 90% of the devices “in the wild.”

The Target SDK should usually be set to the latest version of the Android operating system. At the writing of this book, that version is the Jelly Bean (API 17). After you release an app, you should periodically update these values and recompile your app as new versions of Android are released. At times, new versions of the operating system can affect the performance of your app, so it is best to keep the app up to date. The Compile With target should also be the latest SDK.

Themes are a useful way to ensure a consistent look for your app. However, because this is an introduction you will not be using them in this book. Click the drop-down and select None as your theme.

After you have verified that your selections match those in Figure 3.1, click the Next button and the Configure Project window will be displayed. You should accept the defaults on this screen. After you learn the app creation process, you may want to modify the default settings to better match your requirements. However, by using the defaults, some work is done for you that can easily be changed later as needed. Click the Next button to display the Configure Launcher Icon window.

The Configure Launcher Icon window allows you to associate an icon with your app that will be displayed on the phone’s screen along with the app name. Notice the different sizes of the icons. If you are providing an icon for your app, you will have to supply several sizes of the same picture. This is because Android apps can run on any Android device that meets the app’s SDK requirements. However, these devices can have different screen resolutions and different screen sizes. By supplying different icon sizes, the app will pick the one that best matches the device it is running on. This helps ensure that your app will show up as you design it, regardless of the characteristics of the device it is running on. Suggested sizes for app icons are 32×32, 48×48, 72×72, 96×96, and 144×144 pixels for low to extra high density screens. Accept the default icon for this app by clicking the Next button.

The Create Activity window is the next step in configuring your project. An Activity is a core component of any Android application. Activities are typically associated with a visible screen. Most of the core functionality of an app is provided by an activity and its associated screen (called a layout). Click among the different activity options. Notice that when you have selected some of them, the Next button is disabled. The choices are limited by your choice of minimum and target SDK. Eclipse won’t let you use features that will not work on the devices you targeted. In this case, because you selected API 8 as the minimum SDK that your app would be allowed to run on, some activity types are not available, even though they are available in the target SDK you selected.

From the list of possible activities, choose Blank Activity and click the Next button. The Blank Activity window is displayed (Figure 3.2). This allows us to configure the first Activity in our app. With this screen we can change the name of the activities we create. In the Activity Name text box, delete MainActivity and type HelloWorldActivity. Notice below Activity Name is Layout Name. As you typed in the activity name, the text in this box changed to reflect the text you entered. A layout is an XML file that provides the user interface for the activity. Layouts are discussed in detail later. For now, just remember that every activity has an associated layout file.

Figure 3.2

Figure 3.2 Blank Activity window with default selections.

The final item on this page is Navigation Type. Select it and click among the options. Notice that just like the Create Activity window, you are not allowed to use some navigation types. Again this is based on the SDK choices you made earlier. Select None as your Navigation Type and click Finish. Your app project is created! Depending on the capability of your computer, it may take some time to create the project. When Eclipse has finished creating your project, your Eclipse environment should look like Figure 3.3.

Figure 3.3

Figure 3.3 Eclipse with the newly created Hello World project.

Components of the IDE

Many of the items in the IDE will be explained as needed. For now you will examine just a few. The top center section is the Editor. Much of the development work is done here, including the UI design and writing code. It should currently be displaying the layout for the HelloWorldActivity in Graphical Layout mode. You can switch between graphical layout and the XML code that generates the layout with the tabs below the layout. One tab will always say Graphical Layout. The other will be the filename of the layout. In this case it is activity_helloworld.xml.

The left side of the IDE shows the Package Explorer. The Package Explorer displays the structure of the Android app and is used to move between different components of the app. Many of these items will be generated for you, and many others you will work with as you create your app. The src folder will contain all the Java code files for the app. Each file typically represents one class. Double-click the folder and its subfolders until you see HelloWorldActivity.java. This is where the code to create the activity’s functionality is written. Double-click the HelloWorld.java file. The file contents are displayed in the editor with some Java code listed. This code is explained later.

Next, look for the res folder in the Package Explorer. This folder contains a number of folders that all contain a different kind of resource file needed for your Android app. One very important note about resource files: There are no capital letters allowed in the file names! Double-click through the drawable-xxx folders. The drawable folders are for images. Android uses Portable Network Graphics (PNG) files for its images. Notice the ic_launcher.png file is in all the drawable folders except the drawable-lhdp folder. Each one of these files is the launcher icon in a different size to match the size recommendations for different screen resolutions. The lhdp folder does not contain an icon because no Android devices with low resolution are available with an API 8 or higher. When your app is installed on a device, Android automatically uses the one appropriate for the device it is installed in by selecting it from the correct folder.

Next is the layout folder. This folder holds all the layouts for the user interface of your app. The menu folder holds the menu items to be displayed in your app when a user clicks the device’s menu button. Menu functionality is not required for an app, and this book will not work with them.

The final set of folders is that of the values folders. Double-click the values folder. Three XML files will be displayed: dimens.xml, strings.xml, and styles.xml. The values files hold configuration data for an Android app. Android uses this information to limit the hard-coding of potentially changeable data. For example, the dimens.xml file could hold a value for screen title size that could be reused on each layout in the app. If you later decide that you want the screen title size to be different, you only have to change the value in the dimens.xml file and it automatically applies the new size to all titles that use that dimension. The values folders with a dash and number or other information are for values to be used for specific versions of the Android operating system. This enables the developer to take advantage of different OS capabilities within the same app. Some common values files are described below:

  • dimens.xml—Values for the display size of items in a layout.
  • color.xml—Values for the displayed color of item in a layout.
  • strings.xml—Values for text.
  • array.xml—Defines string arrays and the values in those arrays.
  • ids.xml—IDs that cannot be reused by items in layouts.

The Android Manifest

The final and very important item in the Package Explorer that we will examine is the AndroidManifest.xml file. The manifest file is not in a folder but is listed as one of the folder independent files following all the folders in the project. Double-click this file. The Manifest editor will be displayed in the editor. The manifest is used to configure the whole app and tell the device it is installed on what it can and should be able to do. There are multiple tabs (at the bottom of the editor) associated with the manifest. These are used to configure different aspects of your app. The Manifest tab (which is the initial tab open) includes several important elements. First, note the Version Code and Version Name elements. Version code is an integer value. It is used to indicate that there is a new version of the app available. Increasing the value enables the Play Store to notify users of the app that a new version is available. It also controls the install of the upgrade so that no user data is lost during an upgrade. The Version Name is the displayed version of your app. Beyond that it is nonfunctioning. However, it is good practice to have a consistent approach to changing this so that you know what version of the app is at issue when communicating with users about their problems with the app. Click Uses Sdk. The current selections for minimum and target SDK are displayed. These can be modified here. Next click the Application tab at the bottom of the editor. This tab provides the capability to configure specific operational and display elements of the app. Finally, click the AndroidManifest.xml tab. The selections made in the editors generate code that is displayed here.

Interpreting the XML

Although the tabs in the Manifest editor can be used to create a basic configuration of the manifest, the ability to read and manipulate XML is a critical skill for the Android app developer. Modifying a manifest to allow your app to do more advanced behaviors is common, and most online help on doing so, either from the Android Developer site or developer forums, is provided in XML. To get started, take a look at the manifest components in the AndroidManifest.xml file (Listing 3.1).

Listing 3.1 Manifest XML

<?xml version="1.0" encoding="utf-8"?>
                                                                              //1
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.helloworld"
    android:versionCode="1"
    android:versionName="1.0" >
                                                                              //2
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
                                                                              //3
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
                                                                              //4
        <activity
            android:name="com.example.helloworld.HelloWorldActivity"
            android:label="@string/app_name" >
                                                                              //5
            <intent-filter>
                                                                              //6
                <action android:name="android.intent.action.MAIN" />
                                                                              //7
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

The manifest contains a number of XML elements. Those elements and their attributes define basic operational aspects of your app. Refer to the numbers in Listing 3.1 to see the complete code associated with each element explanation below.

  1. The <manifest> component is the root element. The attributes associated with this element define the application package, version code, and version name (as well as others).
  2. The <uses-sdk> element and its attributes define the minimum and target SDKs for the app.
  3. The <application> element has both attributes and child elements that configure how the app works. Application attributes in this manifest define the app icon, theme, and name. Each activity in an app must have an entry in the <application> element. In our manifest there is one activity: the one created when we created the project. Its attributes identify the Java class file for the activity and the display name of the activity. Currently, that name is the same as the app’s name.
  4. The <activity> element tells the operating system that an activity has permission to run in your application. All activities used in an app must be defined in the manifest. If they are not, the app will crash when the user navigates to that activity. In this element the Java source file for the activity and the activity’s title are identified.
  5. A child element of the <activity> element, the <intent-filter> element, defines what the Android OS should do with this activity. Not all activities will have an intent-filter. Specifically, activities that you want users to launch when they are using the app do not need intent-filters. However, for this app you want this activity to be displayed when the user runs it.
  6. Therefore, the <action> tag identifies the activity as the main or first activity to run.
  7. The <category> tag tells the OS to use the app launcher to start this activity.

Configuring the Emulator

Now that you have some understanding of the development environment, you are almost ready to start creating the app. Don’t worry. Future projects will take less time to set up. You could start coding at this point, but until you tell Eclipse how to execute the app, you will not be able to see your results. Therefore, the next step will be to set up the test environment.

Android apps may be tested on either the emulator provided by the Eclipse IDE or on an Android device. The emulator is a program that simulates an Android device. If you choose to test on the emulator, you should also test on several varieties of real devices before you publish your app. Real devices often perform differently than the emulator. If you do not test on a real device, you will likely have many unhappy users.

To set up the emulator, we first must set up an Android Virtual Device (AVD). An AVD is a software replication of one or more types of Android devices. Multiple AVDs with different characteristics may be set up for testing. To set up an AVD we use the AVD Manager. From the main menu select Window > Android Device Manager to display the Android Virtual Device Manager (Figure 3.4).

Figure 3.4

Figure 3.4 Android Device Manager in initial state.

The manager opens with the Virtual Devices tab displayed. Click the Device Definitions tab. This displays all the device configurations your system knows about. Scroll through these to see how many devices your app could run on. Press the Device Definitions tab and then click the New button. The Create New Android Virtual Device (AVD) window is displayed. Complete the device definition as follows, changing only these options:

  • AVD Name: MyTestDevice
  • Device: 3.2 QVGA (ADP2) (320 x 480: mdpi)
  • Target: Android 4 2.2 – API Level 17
  • SD Card: Size 1024 MiB

When you click the Device drop-down, a large number of devices are available. Scroll down the list to find the device: 3.2 QVGA (ADP2) (320 x 480: mdpi) and select it. After you’ve selected the device, choose ARM from the CPU/ABI drop-down. Most devices have an SD card. However, if you want to test your app for those that do not, don’t change anything for the SD Card option. Click OK. The new AVD will be displayed in the Android Virtual Devices tab. Click the new AVD named MyTestDevice that now shows in the existing AVD list, and the buttons on the right of the AVD Manager will be enabled. Click the Start button and the Launch Options window will be displayed. Leave all the defaults. Checking the Scale Display to Real Size box will show the virtual device at the size of the real device. However, this can be hard to use during initial development. Checking the Wipe User Data box will wipe out any data created in a previous session. It is useful to leave the data intact so that you will not have to reenter data every time you want to test some aspect of the app.

Click Launch. The Start Android Emulator window will display and start loading the AVD. When it is done, the virtual device displays (Figure 3.5) and begins further loading. The speed at which the device loads depends greatly on your computer. At times it can be quite slow. If I am testing with the emulator, my first task when beginning any development session is to start the virtual device so that it is ready when I am. After the AVD is displayed, you can close the Start Android Emulator and AVD Manager windows. The AVD will remain running.

Figure 3.5

Figure 3.5 Android Emulator at initial launch.

Setting Up Run Configurations

The final step in setting up the test environment is to tell our app to use this newly created AVD. To do this you need to set up a Run Configurations.

  1. From the main menu select Run > Run Configurations. The Run Configurations window is displayed.
  2. Click Android Application in the left side of the screen. Then click the New button, which is the leftmost button above the text box that says Type Filter Text. The window changes, showing configuration options. Change the name to HelloWorldRunConfig.
  3. Use the Browse button to select your HelloWorld project. Click the Launch Default Activity option button.
  4. Click the Target tab. Click the box next to MyTestDevice. When you start testing on a real device, you will need to click the option button next to Always Prompt to Pick Device. This displays a device selection window where you can pick the device you want to test on.
  5. Click the Apply button and then the Close button. You are ready to begin coding your app!

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020