Top Banner
Introduction to Android development Using Eclipse and Android widgets Skill Level: Introductory Ayushman Jain ([email protected]) Eclipse JDT/Core Committer IBM 16 Nov 2010 This tutorial is intended for anyone interested in beginning Android development on Eclipse using the Android development tools plug-in. It offers insight into the salient features of an Android app, along with a brief explanation of its basic components. The Android process is introduced for developing rich UIs for the apps, as widgets. Finally, it showcases how easy it is to test the developed app by deploying it on an Android device simulator included in the SDK. Section 1. Introduction Android is a mobile operating system, similar to Symbian, iOS, Windows® Mobile, and others. It was initially developed by Android Inc., a company later purchased by Google. It is now owned by the Open Handset Alliance and is fully open sourced, accounting for its growing popularity. Google released most of the Android code under the Apache License. With this license, vendors can add proprietary extensions without submitting them back to the open source community. Many versions of Android have hit the market since its inception (the most recent as of Q3 2010), including the power-packed Froyo (V2.2). Android has moved beyond simply being a platform for mobile devices; the new Google TV also runs on Android. Android uses a modified Linux® kernel and allows applications to be developed in Java™ technology using Java libraries (some of which were developed by Google for Android). While Android applications are written in the Java language, there's no Java Virtual Machine in the platform, and Java byte code is not executed. Java classes are recompiled into Dalvik executables and run on a Dalvik virtual machine. Introduction to Android development Using Eclipse and Android widgets Trademarks © Copyright IBM Corporation 2010. All rights reserved. Page 1 of 31
31
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Os eclipse-androidwidget-pdf

Introduction to Android development Using Eclipseand Android widgetsSkill Level: Introductory

Ayushman Jain ([email protected])Eclipse JDT/Core CommitterIBM

16 Nov 2010

This tutorial is intended for anyone interested in beginning Android development onEclipse using the Android development tools plug-in. It offers insight into the salientfeatures of an Android app, along with a brief explanation of its basic components.The Android process is introduced for developing rich UIs for the apps, as widgets.Finally, it showcases how easy it is to test the developed app by deploying it on anAndroid device simulator included in the SDK.

Section 1. Introduction

Android is a mobile operating system, similar to Symbian, iOS, Windows® Mobile,and others. It was initially developed by Android Inc., a company later purchased byGoogle. It is now owned by the Open Handset Alliance and is fully open sourced,accounting for its growing popularity. Google released most of the Android codeunder the Apache License. With this license, vendors can add proprietary extensionswithout submitting them back to the open source community. Many versions ofAndroid have hit the market since its inception (the most recent as of Q3 2010),including the power-packed Froyo (V2.2). Android has moved beyond simply being aplatform for mobile devices; the new Google TV also runs on Android.

Android uses a modified Linux® kernel and allows applications to be developed inJava™ technology using Java libraries (some of which were developed by Googlefor Android). While Android applications are written in the Java language, there's noJava Virtual Machine in the platform, and Java byte code is not executed. Javaclasses are recompiled into Dalvik executables and run on a Dalvik virtual machine.

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 1 of 31

Page 2: Os eclipse-androidwidget-pdf

Dalvik is a modified VM for Android and optimized devices running on battery powerand with low CPU.

For developers, Android SDK provides a rich set of tools, including debugger,libraries, handset emulator, documentation, sample code, and tutorials. Androidapplications can be easily developed using Eclipse (Android's official developmentplatform) with the help of a plug-in called Android Development Tools (ADT). Thishelps leverage Eclipse's rich features, such as content assist, Java search, openresources, JUnit integration, and different views and perspectives for developing anAndroid app. A wide array of widgets, which are similar to Java swing widgets,facilitate in creating a rich UI for the apps. A detailed Javadoc makes thedevelopment process quite easy.

Here, we start with a guide for preparing the system for Android development. Wethen touch briefly upon the salient features of an Android application using a basicHello World Android app. We also talk about the files that make up an Android appand how the UI is separated from the implementation. After going through theprocess of creating, developing, and launching an Android app from Eclipse, wemove on to a discussion about a few Android widgets that help in building a rich UI(a very important part of mobile apps). We demonstrate a few basic widgets with thehelp of a sample application. We also talk about using the listView widget in anphonebook-like application and the ways it can be implemented. In between, we alsotalk about permissions that need to be set in order to be able to have an applicationaccess some data from the OS. Overall, a few hours on the article should enableyou to create an app implementing a basic functionality and with a nice UI.

System requirements

Before beginning Android development, please make sure you have the followinginstalled:

• Eclipse SDK — V3.5 is suggested for use with the latest Android SDK.This can be downloaded from the Galileo download page.

• Android SDK

• Android Development Tools (ADT) — This is an Eclipse plug-in. It is theequivalent of JDT (Java Development Tools) for Android Development.Please follow the detailed instructions for installing the ADT plug-in, andalso for setting the location of Android SDK in Eclipse.

Section 2. Android terminology

developerWorks® ibm.com/developerWorks

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 2 of 31

Page 3: Os eclipse-androidwidget-pdf

A typical Android application has the following components. Also given below aredefinitions provided by the Android Developer site:

• Activity — An activity presents a visual UI for one focused endeavor theuser can undertake. For example, an activity might present a list of menuitems users may choose from, or it might display photographs along withtheir captions. A text-messaging application might have one activity thatshows a list of contacts to send messages to, a second activity to writethe message to the chosen contact, and other activities to review oldmessages or change settings. Though they work together to form acohesive UI, each activity is independent of the others.

• Content providers — A content provider makes a specific set of theapplication's data available to other applications. The data can be storedin the file system, in a SQLite database, or in any other logical manner.

• Service — A service doesn't have a visual UI, but runs in the backgroundfor an indefinite period of time. For example, a service might playbackground music as the user attends to other matters, or it might fetchdata over the network or calculate something and provide the result toactivities that need it.

• Broadcast receivers — A broadcast receiver is a component that doesnothing but receive and react to broadcast announcements. Manybroadcasts originate in system code — timezone-changeannouncements, low-battery announcements, language-preferencechanges, etc.

Some other terms worth knowing:

• Intent — Activities, services, and broadcast receivers are activated byasynchronous messages called intents. An intent is an Intent objectthat holds the content of the message. For example, it might convey arequest for an activity to present an image to the user or let the user editsome text.

• Intent filter — An Intent object can explicitly name a target component. If itdoes, Android finds that component (based on the declarations in themanifest file) and activates it. If a target is not explicitly named, however,Android must locate the best component to respond to the intent. It doesso by comparing the Intent object to the intent filters of potential targets. Acomponent's intent filters inform Android of the kinds of intents thecomponent is able to handle.

For an understanding of these components, refer to "Develop Android Applicationswith Eclipse" and the Android Hello, World tutorial.

ibm.com/developerWorks developerWorks®

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 3 of 31

Page 4: Os eclipse-androidwidget-pdf

Section 3. Create an Android Virtual Device

This step is required in creating an Android phone emulator/Android Virtual Device(AVD) on which applications can be run and tested. Note that it takes some time foran AVD to start up. The good news is that separate AVDs are not needed for eachapplication to be deployed and tested. Once the AVD is launched, any numberapplications can be deployed while it is still running, and it can even be used todebug applications. To create an AVD:

1. In Eclipse, choose Window > Android SDK and AVD Manager.

2. Select Virtual Devices in the left panel.

3. Click New. The Create New AVD dialog appears.

4. Type the name of the AVD, such as "myPhone."

5. Choose a target. The target is the platform (that is, the version of theAndroid SDK, such as 2.1) to be run on the emulator. You will also get anoption to choose the Google APIs, but that is unnecessary unless wewant to have some Google API in the app specifically. The rest of thefields can be ignored for now.

6. Click Create AVD.

Once the AVD is launched, you can see how it gives the complete look and feel of areal Android-based mobile phone, complete with keyboard and multi-touch support.It can also be used in a variety of configurations to test your app, such aslandscape/portrait mode, network strength, and roaming network, etc. All of theseoptions can be configured using the AVD manager. The AVD is self-sufficient toemulate different devices available. You can create different AVDs for differentconfigurations and test your application on each of them to make sure it iscompatible across device types.

Section 4. Create a new Android project

Here's how to create a new Android project in Eclipse (see Figure 1):

developerWorks® ibm.com/developerWorks

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 4 of 31

Page 5: Os eclipse-androidwidget-pdf

1. From Eclipse, select File > New > Project. A folder called Androidshould be present in the dialog if the ADT plug-in for Eclipse has beensuccessfully installed. Expanding that folder should provide the option fora new Android project. Select it and click Next.

2. You will be prompted to fill in the following details in a form:

• Project name — This is the name of your project and can be somethinglike "HelloWorld."

• Application name — This is the name that will appear everywhere in yourAndroid device, along with the icons in the menu, in the shortcuts, and onthe title bar when you run your application. This can be something like"Hello Android."

• Package name — com.example.helloandroid or your own privatenamespace. The package name follows the same rules as those in theJava language.

• Create activity — We can call it SaySomething for our purposes here.This is the name for the class stub that will be generated by ADT. This willbe a subclass of Android's Activity class. An activity is simply a classthat can run and do some work. It can optionally have a UI. An applicationmay contain one or more activities. They are typically on a 1:1relationship with the screens found in an application. An applicationmoves from one activity to another by calling a method known asstartActivity() or startSubActivity().

• Min SDK version — This specifies the minimum API level required byyour application. The latest one is 7.

Figure 1. Create a new Android project

ibm.com/developerWorks developerWorks®

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 5 of 31

Page 6: Os eclipse-androidwidget-pdf

Section 5. Hello Android project details

The Hello Android is a basic Android project, which simply prints Hello World on thescreen. It has the following roles in this article:

• To demonstrate the process of creating a new Android project.

• To give an overview of the files in an Android project and their purpose.

• To demonstrate how to deploy an app on the AVD and test it.

To view the files and other resources part of the Android project and use the

developerWorks® ibm.com/developerWorks

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 6 of 31

Page 7: Os eclipse-androidwidget-pdf

Package Explorer view inside Eclipse (Window > Show View > PackageExplorer). The newly created Android project will consist of the following (see Figure2):

• There are two folders that contain the source code:

1. src contains all the classes specified by the user, including the defaultactivity class.

2. gen contains the files automatically generated by ADT. R.java inside thisfolder consists of static references to all the resources present in the resfolder so they can be easily and dynamically referenced from the Javacode. It is advised not to modify the contents of R.java manually.

Figure 2. Hello Android project contents

ibm.com/developerWorks developerWorks®

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 7 of 31

Page 8: Os eclipse-androidwidget-pdf

• A res folder contains all the resources for the project: icons, images,strings, and layouts. Having a separate resource folder keeps non-sourcecode resources external to the code and resources can be dynamicallyselected based on hardware, language, orientation, and location.

It consists of:

a. drawable folder(s) — Meant for all image files.

developerWorks® ibm.com/developerWorks

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 8 of 31

Page 9: Os eclipse-androidwidget-pdf

b. layout folder — Meant for the layouts specifying the UI screens forthe activities, in the form of XML code. Main.xml is automaticallygenerated. This folder pertains to the default portrait layout. Forrepresenting some UI in the landscape layout (when an Androiddevice is turned 90 degrees), create a layout-land folder and putyour layout XML file there. The main.xml file has a nice UIrepresentation, as shown in Figure 3. You can drag and dropdifferent layouts and views onto a blank screen to build the UIcomponents for the activity.

c. values folder — Meant for all the name-value pairs (the stringsyour application is going to define).

• AndroidManifest.xml is also an important part of the project. It's theequivalent of a plugin.xml file for plug-ins. It basically defines the activitiesin the applications and specifies the actions that have been specified foreach. It also lists out the permissions that the application requires toperform various actions. Once again, it has a nice UI.

Figure 3. UI for main.xml

Let's look at the actual contents of the project folder on the disc. Open the NavigatorView in Eclipse (Window > Show View > Navigator). You'll get the structure for theHelloWorld project as shown in Figure 4. Apart from the compiled class files, youobtain the following three files inside a bin folder:

ibm.com/developerWorks developerWorks®

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 9 of 31

Page 10: Os eclipse-androidwidget-pdf

1. classes.dex — Executable generated from compiled classes.

2. HelloWorld.apk — Zipped archive file that will be shipped to the Androiddevice. The app can be installed on any Android device via this archivefile.

3. resources.ap_ — Zipped application resources.

Android project's directory structure

developerWorks® ibm.com/developerWorks

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 10 of 31

Page 11: Os eclipse-androidwidget-pdf

The primary 'Activity' of the application

Let's examine MainActivity.java.

Listing 1. MainActivity.java

package com.example.helloandroid;

ibm.com/developerWorks developerWorks®

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 11 of 31

Page 12: Os eclipse-androidwidget-pdf

import android.app.Activity;import android.os.Bundle;

public class MainActivity extends Activity {/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);setContentView(R.layout.main);

}}

Things to note about this file are:

• MainActivity extends a base Android class named Activity, whichis located in the android.app package.

• The onCreate() method is the default entry point to this activity and hasto be implemented for each new activity. It receives an argument of typeBundle. Options and parameters required for the creation of the activityare passed in this parameter.

• The setContentView() is responsible for creating the primary UI usingthe R.layout.main argument. This is a constant defined in R.java andrepresents the main layout found in the resources of the application.

Main.xml

This XML file describes the UI of the application. An activity can reference to this UI.This UI, however, does not bind itself to any activity at all. A UI is built using layoutsand widgets. The main.xml that Eclipse builds by default consists of a singleLinearLayout, which means that all the elements are arranged in a single column. Itthen defines a textView, which is used to display a static non-editable text. In thiscase, the "hello" string defined in the strings.xml file (the '@' sign refers to a filedefined in the res folder). Each view element further has attributes, such aslayout_height and layout_width, etc.

Figure 5. Main.xml and the properties view

developerWorks® ibm.com/developerWorks

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 12 of 31

Page 13: Os eclipse-androidwidget-pdf

An easy to way to work with the main.xml file is through the properties view(Window > Show View > Other > General > Properties). When a particular view isselected in the outline view, the properties tab is populated with all possibleattributes of the view, as shown in Figure 5. Most of these attributes have only fixedvalues to chose from, which can be selected from a drop-down menu adjacent toeach attribute in the properties tab. For example, to set the layout_height, youcan see the drop-down box and find that it has only two allowed values:wrap_content and fill_parent. (wrap_content will only draw the view to itsoriginal size, while fill_parent will stretch it to cover the whole height, or width,or both.)Note: For the layout_height and layout_width, you can also specify size inthe following two units: (a) Density-independent pixels (dp) — This size enables thelayout to look the same when viewed on devices of different screen sizes. Forexample: layout_width = 10dp; (b) Scale-independent pixels (sp) — Similar todp, but this is the recommended standard for mobile phones. For example:layout_width = 10sp.) Another important thing to note is that if you want toreference some view/widget from Java code, it needs to have a unique ID. If you usethe layout tab of main.xml to drag and drop a widget, ADT will automatically createan ID for the widget, which will be of the form "@+id/someView." In the Java code,you can then reference it as R.id.someView.

ibm.com/developerWorks developerWorks®

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 13 of 31

Page 14: Os eclipse-androidwidget-pdf

Section 6. Running the app on the emulator

For deploying and running the app, you need to define a run configuration. SelectOpen > Run > Dialog or shortcut on the toolbar within Eclipse, and select Androidapplication. Click New and fill in the name of the run configuration. Specify thename of your project and default activity. Then in the target tab, choose somedesired emulator settings and specify an AVD you want to start. Click Run. You willget an AVD as shown in Figure 6. The screen of the device is shown on the left,alongside a QWERTY keypad on the bottom left, and common mobile buttons suchas dial, hang up, mute, volume, and home on the top left.

Figure 6. The Android Virtual Device

Section 7. Android widgets

Now that we know how to create and run a basic Android app, let's spruce things up

developerWorks® ibm.com/developerWorks

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 14 of 31

Page 15: Os eclipse-androidwidget-pdf

with widgets (see Figure 7):

• textView consists of widgets such as editText, Button, etc. Buttonscan be further categorized into:

• CheckBox

• RadioButton

• ToggleButton, etc.

• ImageView consists of widgets such as the ImageButton.

• ViewGroup consists of layouts such as:

• Relative Layout

• Table Layout

• Frame Layout

• Adapter View

• Linear Layout

For information about widgets, "A Visual Guide to Android GUI Widgets" is the bestguide. Be cautious, however, of inconsistencies introduced there because of rapidchanges in the Android platform. One glaring example is the use of id as anidentifier attribute for a widget in the main.xml in the above-mentioned guide. Inthe latest Android platform, the fully qualified android:id should be used.

Figure 7. Android widgets hierarchy

ibm.com/developerWorks developerWorks®

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 15 of 31

Page 16: Os eclipse-androidwidget-pdf

Section 8. A sample application using widgets

We will now modify our existing application to look like Figure 8. The purpose of thisexample is to make the reader familiar with the use of some basic widgets liketextView, editText, Button, and Toast in a real app.

Our application will consist of a title bar with the message "WELCOME!!!" It will havethree textView widgets starting from the top, arranged vertically: one saying "HelloWorld, how're you?" in default font; the next saying "Welcome to my first Androidapp" in italicized serif text, center-aligned, with white background; and a third saying"Type anything and press the button" in bold monospace text, with red background.These three are followed by an editText widget to take the user input, followed bya button widget (the button goes with the message "Click Me!"). Whatever is typed inthe editText widget appears in a Toast widget at the bottom center of the screenwhen the button is pressed.

There isn't much implementation code involved here. The reader should payattention to how the widgets are easily put into the app using ADT's GUI editor for

developerWorks® ibm.com/developerWorks

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 16 of 31

Page 17: Os eclipse-androidwidget-pdf

the XML files and how the widget properties are conveniently set using the"properties" view provided by Eclipse. This example will also showcase how the UIand implementation parts can be independently coded.

Figure 8. Android Virtual Device with widgets

string.xml

Let's add some new strings in the string.xml file, change the existing welcome string,and finally the title string. Let's also define the white and red colors here for thebackground for two textViews.

Listing 2. The string.xml file

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

<string name="hello">Hello World, how\'re you?</string><string name="app_name">Hello Android</string><string name="title">WELCOME!!!</string><string name="mainText">Welcome to my first android app</string><string name="subText">Type anything and press the button</string><color name="White">#FFFFFF</color><color name="Red">#FF0000</color>

</resources>

ibm.com/developerWorks developerWorks®

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 17 of 31

Page 18: Os eclipse-androidwidget-pdf

We changed the "hello" string to contain "Hello World, how're you?" Notice theescape character ('\') is required here for the apostrophe. We also defined twonew strings: mainText and subText, and colors white and red.

main.xml

Let's use the layout tab of main.xml to drag and drop two new textViews: aneditText widget and a button widget. Then we'll use the properties tab in main.xmlto edit attributes for each widget.

Listing 3. The main.xml file

<?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">

<TextViewandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:text="@string/hello"/>

<TextViewandroid:layout_height="wrap_content"android:layout_width="fill_parent"android:id="@+id/mainTextView"android:gravity="center"android:text="@string/mainText"android:textStyle="italic"android:typeface="serif"android:background="@color/White">

</TextView><TextView

android:layout_height="wrap_content"android:layout_width="fill_parent"android:layout_margin="20sp"android:gravity="left"android:id="@+id/subTextView"android:padding="10sp"android:text="@string/subText"android:textStyle="bold"android:typeface="monospace"android:background="@color/Red">

</TextView><EditText

android:text="Enter text here"android:id="@+id/EditText01"android:layout_width="wrap_content"android:layout_height="wrap_content">

</EditText><Button

android:text="Click me!"android:id="@+id/Button01"android:layout_width="wrap_content"android:layout_height="wrap_content">

</Button></LinearLayout>

With this, we have our UI defined. Now we have to link our activity code with it.

developerWorks® ibm.com/developerWorks

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 18 of 31

Page 19: Os eclipse-androidwidget-pdf

MainActivity.java

This is the file that actually links the UI to the implementation. Like the HelloWorldapplication, we use the Activity.onCreate(Bundle) method to decorate all theUI elements on the screen. The overridden onClick(View) method will contain thefunctionality of the button click, wherein the user input text will be read and displayedon the screen in a toast widget.

Listing 4. The MainActivity.java file

package com.example.helloandroid;

import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;

public class MainActivity extends Activity {/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);setContentView(R.layout.main);

String title = getString(R.string.title);setTitle(title); // done so that we can change the default title

//get handles to editText and button widgetsfinal EditText eText = (EditText) findViewById(R.id.EditText01);final Button button = (Button) findViewById(R.id.Button01);

button.setOnClickListener(new Button.OnClickListener(){

@Overridepublic void onClick(View v) {

//get the String entered into the editText widgetCharSequence editText = eText.getText();

//display the toastToast.makeText(MainActivity.this, editText, Toast.LENGTH_LONG).show();

}});

}}

Using this code, we obtain the application as shown in Figure 8.

Section 9. Using the listView widget: A sampleapplication

ibm.com/developerWorks developerWorks®

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 19 of 31

Page 20: Os eclipse-androidwidget-pdf

In this section, we'll create a sample application (see Figures 9a, 9b) to display allcontacts in the phonebook using the listView widget. The purpose of this exampleis to showcase not just the use of the listView widget but also to show how phonedata can be fetched using ContentProvider and ContentResolver classes. Payattention to the UI XML files because there are two UI layouts: one to specify howthe list shown by the listView widget fits into the main UI and another to specifyhow each element of the list looks. Another important point is the setting ofpermissions for the app to be able to read phone data. This example is the first stepto understanding how intents and intent filters can be incorporated in an app.Although intents are beyond the scope of this article, the reader may note that toconvert this example app into a real-world phonebook app, one simply needs toimplement click actions on the list items and create a call intent and intent filter toinitiate a call to the selected contact.

In this example, the contacts will be displayed in a vertical linear fashion, and theselected contact appears at the top of the list with a large italicized font and a bluebackground. We also have a checkbox at the bottom left of the screen, which, whenchecked, shows only starred (or favorited contacts). The title of the application in thiscase is "Contact Manager." Here we use three types of widgets: textView,listView, and checkBox. We use the textView widget to display the currentlyselected contact. You can assume the listView widget to be a list of textViewwidgets. A listView uses adapter design patterns to connect the data (thecontacts, in this case) and a data view (a textView, in this case) to the listView.Any clicks on the listView can be captured by implementingAdapterView.OnItemClickListener().

Before proceeding, we should have some stored contacts in the contacts section ofthe Android emulator (AVD). This can be done by clicking Contacts on the homescreen of the AVD, then Menu to get the Add Contacts option. The Favoritessection says how to mark a contact as favorite/starred.

Figure 9a. The contacts application showing all contacts in a listView widget

developerWorks® ibm.com/developerWorks

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 20 of 31

Page 21: Os eclipse-androidwidget-pdf

Figure 9b. The contacts application showing all starred contacts in a listViewwidget when the show-starred contacts checkbox is selected

ibm.com/developerWorks developerWorks®

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 21 of 31

Page 22: Os eclipse-androidwidget-pdf

Now we'll define a few strings.

Listing 5. Strings defined in the strings.xml file

<?xml version="1.0" encoding="utf-8"?><resources><string name="hello">Hello World, Manager!</string><string name="app_name">Contact Manager</string><string name="selectedEntry" /><color name="White">#FFFFFF</color><color name="Black">#000000</color><color name="Blue">#0000FF</color>

<string name="showStarred">Show starred contacts only</string></resources>

main.xml

Let's define the main layout for our app. The listView widget will accommodatethe list of all contacts in the phonebook. The listView displays each item inside atextView widget, which we'll define next.

Listing 6. main.xml

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

developerWorks® ibm.com/developerWorks

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 22 of 31

Page 23: Os eclipse-androidwidget-pdf

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent">

<TextViewandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:gravity="center"android:id="@+id/selectedContact"android:padding="10dp"android:textSize="20sp"android:textStyle="italic"android:typeface="serif"android:background="@color/Blue"android:textColor="@color/White"android:text="@string/selectedEntry"/>

<ListViewandroid:id="@+id/contactsListView"android:layout_width="fill_parent"android:layout_height="fill_parent"android:layout_weight="1"></ListView>

<CheckBox android:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/showStarred"android:text="@string/showStarred"/>

</LinearLayout>

Note that assigning a layout_weight of 1 to the listView makes sure that the listcovers as much screen area as it can until a new widget is defined.

contactItem.xml

Apart from the main layout, we need to define another layout here. This is torepresent each element in the listView. We use a simple textView here.

Listing 7. Code for textView widget, which constitutes each element of thelistView widget

<?xml version="1.0" encoding="utf-8"?><TextViewxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="wrap_content"android:padding="5dp"android:textStyle="bold"android:id="@+id/contactItem">

</TextView>

Note that Android by default provides a simple layout that can be used instead ofdefining your own. This can be referenced viaandroid.R.layout.simple_list_item_1.

ManageContacts.java

Listing 8. shows how the main activity is implemented. The method

ibm.com/developerWorks developerWorks®

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 23 of 31

Page 24: Os eclipse-androidwidget-pdf

populateContactList() is the one we use to query the contacts database anddisplay them in the listView.

Listing 8. Implementation of the main activity

public class ManageContacts extends Activity {private ListView mContactList;private CheckBox mCheckBox;private boolean mShowStarred;private TextView selectedText;/** Called when the activity is first created. */

@Overridepublic void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);setContentView(R.layout.main);

mContactList = (ListView) findViewById(R.id.contactsListView);mCheckBox = (CheckBox) findViewById(R.id.showStarred);selectedText = (TextView) findViewById(R.id.selectedContact);mShowStarred = false;

mCheckBox.setOnCheckedChangeListener(new CheckChangedListener());

mContactList.setOnItemClickListener(new ClickListener());

populateContactList();

}

public void populateContactList() {Uri uri = ContactsContract.Contacts.CONTENT_URI;String[] projection = new String[] {

ContactsContract.Contacts._ID,ContactsContract.Contacts.DISPLAY_NAME,

};String[] selectionArgs = null;String sortOrder = ContactsContract.Contacts.DISPLAY_NAME +

" COLLATE LOCALIZED ASC";String selection = mShowStarred? ContactsContract.Contacts.STARRED +

" ='1'" : null;Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs,

sortOrder);

String[] fields = new String[] {ContactsContract.Data.DISPLAY_NAME

};SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.contactitem,

c, fields, new int[] {R.id.contactItem});mContactList.setAdapter(adapter);

}

private class ClickListener implements OnItemClickListener {

@Overridepublic void onItemClick(AdapterView<?> arg0, View textView, int pos, long arg3) {

if(textView instanceof TextView)selectedText.setText(((TextView) textView).getText());

}}

private class CheckChangedListener implements OnCheckedChangeListener {

@Overridepublic void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

mShowStarred = isChecked;

developerWorks® ibm.com/developerWorks

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 24 of 31

Page 25: Os eclipse-androidwidget-pdf

selectedText.setText("");populateContactList();

}

}}

Things to note:

• We have two listeners — one each for handling clicks on a list item andone for handling clicks on the checkbox. The former simply sets the text inthe blue textView box to the display name of the currently selectedcontact. The latter is to set the mShowStarred field and repopulate thelist.

• To read the contacts from the phone database, we need to query it to geta cursor. The query has the following parameters:

1. uri — The URI using the content:// scheme for the content toretrieve.

2. projection — A list of which columns to return. Passing null willreturn all columns, which is discouraged to prevent reading datafrom storage that isn't going to be used.

3. selection — A filter declaring which rows to return, formatted as aSQL WHERE clause (excluding the WHERE itself). Passing null willreturn all rows for the given URI.

4. selectionArgs — You may include ?s, which will be replaced bythe values from selectionArgs, in the order that they appear inthe selection. The values will be bound as Strings.

5. sortOrder — How to order the rows, formatted as a SQL ORDERBY clause (excluding the ORDER BY itself). Passing null will use thedefault sort order, which may be unordered.

The result set cursor so obtained has to be linked to the UI via an adapter. We use aSimpleCursorAdapter here, though Android also provides a ListAdapter.Once the adapter is obtained, we need to attach it to the listView, and we'redone.

Permissions

A final step before our app would run successfully on an Android device is setting uppermissions. Without permissions to be able to read the contacts database, the

ibm.com/developerWorks developerWorks®

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 25 of 31

Page 26: Os eclipse-androidwidget-pdf

Linux kernel in the device will not allow the application to do so. So let's go to theAndroidManifest.xml>Permissions tab, and set the following permissions:

1. android.permission.GET_ACCOUNTS

2. android.permission.READ_CONTACTS

These can be set by clicking on the U icon and defining the permission. Figure 10shows how the permissions tab should look.

Figure 10. Android permissions manifest

developerWorks® ibm.com/developerWorks

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 26 of 31

Page 27: Os eclipse-androidwidget-pdf

listView widget using ListActivity

This example is meant to demonstrate another way of implementing a listView. Inthe above application, note that our main activity implements the activity class.When dealing with listView widgets, sometimes the ListActivity class comesin handier because it has public APIs to handle clicks on list items, setting listadapters, getting the click position, etc.

We can modify our activity to implement ListActivity as shown in Listing 9.

Listing 9. Implementation using ListActivity

public class ManageContacts extends ListActivity {@Overrideprotected void onListItemClick(ListView l, View v,

int position, long id) {// TODO Auto-generated method stubsuper.onListItemClick(l, v, position, id);if(v instanceof TextView)selectedText.setText(((TextView) v).getText());}private CheckBox mCheckBox;private boolean mShowStarred;private TextView selectedText;/** Called when the activity is first created. */@Overridepublic voidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);

mCheckBox = (CheckBox) findViewById(R.id.showStarred);selectedText = (TextView)findViewById(R.id.selectedContact);mShowStarred = false;

mCheckBox.setOnCheckedChangeListener(newCheckChangedListener());

populateContactList();

}

public void populateContactList() {Uri uri = ContactsContract.Contacts.CONTENT_URI;String[] projection = new String[] {ContactsContract.Contacts._ID,ContactsContract.Contacts.DISPLAY_NAME,};String[] selectionArgs = null;String sortOrder =ContactsContract.Contacts.DISPLAY_NAME +" COLLATE LOCALIZED ASC";String selection = mShowStarred?ContactsContract.Contacts.STARRED + " ='1'" : null;Cursor c =getContentResolver().query(uri, projection,selection, selectionArgs, sortOrder);

String[] fields = new String[] {ContactsContract.Data.DISPLAY_NAME};

ibm.com/developerWorks developerWorks®

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 27 of 31

Page 28: Os eclipse-androidwidget-pdf

ListAdapter adapter = newSimpleCursorAdapter(this,R.layout.contactitem, c, fields, newint[]{R.id.contactItem});setListAdapter(adapter);

}

private class CheckChangedListenerimplements OnCheckedChangeListener {

@Overridepublic void onCheckedChanged(CompoundButtonbuttonView, boolean isChecked) {mShowStarred = isChecked;selectedText.setText("");populateContactList();

}

}}

Note that here we simply implemented onListItemClick method ofListActivity, rather than declaring an anonymous class to handle clicks. Wealso didn't need to refer to the listView widget defined in main.xml here becauseListActivity assumes that the listView widget is defined with an ID of@android:id/list. This is important to note. Whenever we use ListActivity,we have to define the listView widget in main.xml to have an ID of@android:id/list; otherwise, the ListActivity will not know which listView torefer to.

Section 10. Conclusion

In this tutorial, we learned how to set up Eclipse for Android development and howthe rich features of Eclipse assist in every step in writing Android apps. We alsolearned how the apps can be easily deployed and tested on the Android emulator —AVD. We covered the salient features of an Android application using a Hello Worldexample and learned about the files that make up an Android app. We touched uponsome of the widgets provided by Android and saw their use in some real-worldexamples. You now should be well on the way to creating a cool application with aneat UI. As a first step, extend the contacts app to implement click action on a listitem to display the phone number and contact details, and a button to call theselected contact. A call intent should also be defined, along with an intent filter,which should implement the call-making functionality.

Android is a powerful platform for mobile applications, and coding in Javatechnology, along with Android Development Tools for Eclipse, make it easilyadoptable by beginners. Its wide array of widgets, along with its ability to dynamically

developerWorks® ibm.com/developerWorks

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 28 of 31

Page 29: Os eclipse-androidwidget-pdf

bind the UI elements to the implementation, provides a lot of flexibility and makesthe application lightweight, in spite of the rich UI. The concepts of activities, intents,content providers, etc., make it easy to manage the UI and data elements, andcontrol the binding between them. It also has a vast array of networking APIs toexplore. In addition, Google APIs provide functionality for maps, search, and mail,among other things, which can all be easily adopted in an Android application. Sodive into the wonderful world of Android and let your imagination run wild.

ibm.com/developerWorks developerWorks®

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 29 of 31

Page 30: Os eclipse-androidwidget-pdf

Resources

Learn

• The Developer's Guide is a practical introduction to developing applications forAndroid.

• Read "Develop Android applications with Eclipse" for an introduction to Androiddevelopment with a quick introduction to the platform.

• Be sure to see the Android Hello, World tutorial.

• "A Visual Guide to Android GUI Widgets" offers more information.

• Check out Eclipse Day at the Googleplex: Developing for Android with Eclipse.

• Don't miss Lars Vogella's Android development tutorial.

• Check out a set of video tutorials for Android from the Elon Computing SciencesDepartment.

• Check out the "Recommended Eclipse reading list."

• Browse all the Eclipse content on developerWorks.

• Follow developerWorks on Twitter.

• New to Eclipse? Read the developerWorks article "Get started with the EclipsePlatform" to learn its origin and architecture, and how to extend Eclipse withplug-ins.

• Expand your Eclipse skills by checking out IBM developerWorks' Eclipse projectresources.

• To listen to interesting interviews and discussions for software developers,check out check out developerWorks podcasts.

• The My developerWorks community is an example of a successful generalcommunity that covers a wide variety of topics.

• Stay current with developerWorks' Technical events and webcasts.

• Watch and learn about IBM and open source technologies and productfunctions with the no-cost developerWorks On demand demos.

• Check out upcoming conferences, trade shows, webcasts, and other Eventsaround the world that are of interest to IBM open source developers.

• Visit the developerWorks Open source zone for extensive how-to information,tools, and project updates to help you develop with open source technologiesand use them with IBM's products, as well as our most popular articles andtutorials.

developerWorks® ibm.com/developerWorks

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 30 of 31

Page 31: Os eclipse-androidwidget-pdf

Get products and technologies

• Be sure to download Eclipse for RCP/Plug-in.

• Download the Android SDK.

• Get the ADT Plug-in for Eclipse.

• As someone interested in development with Eclipse, you might want to checkout a trial of IBM's Rational Application Developer Standard Edition, acommercial development tool built on Eclipse technology.

• Check out the latest Eclipse technology downloads at IBM alphaWorks.

• Download Eclipse Platform and other projects from the Eclipse Foundation.

• Download IBM product evaluation versions or explore the online trials in theIBM SOA Sandbox and get your hands on application development tools andmiddleware products from DB2®, Lotus®, Rational®, Tivoli®, andWebSphere®.

• Innovate your next open source development project with IBM trial software,available for download or on DVD.

Discuss

• The Eclipse Platform newsgroups should be your first stop to discuss questionsregarding Eclipse. (Selecting this will launch your default Usenet news readerapplication and open eclipse.platform.)

• The Eclipse newsgroups has many resources for people interested in using andextending Eclipse.

• Participate in developerWorks blogs and get involved in the developerWorkscommunity.

About the author

Ayushman JainAyushman Jain works on the Eclipse team at IBM India Software Labs,Bangalore, as a JDT/Core committer. He leads the Eclipse@campusinitiative to evangelise Eclipse in Indian universities. He is enthusiasticabout Android as a platform and encourages its use due to ease ofdevelopment on Eclipse familiar environments. He is also the technicaleditor for a youth magazine called NOW, in circulation in Delhi, India.For NOW, he has reviewed HTC phones based on Android.

ibm.com/developerWorks developerWorks®

Introduction to Android development Using Eclipse and Android widgets Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 31 of 31