Вы находитесь на странице: 1из 31

Introduction to Android development Using Eclipse and Android widgets

Skill Level: Introductory Ayushman Jain (ayushman_jain@in.ibm.com) 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 Copyright IBM Corporation 2010. All rights reserved.

Trademarks Page 1 of 31

developerWorks

ibm.com/developerWorks

Dalvik is a modified VM for Android and optimized devices running on battery power and with low CPU. For developers, Android SDK provides a rich set of tools, including debugger, libraries, handset emulator, documentation, sample code, and tutorials. Android applications can be easily developed using Eclipse (Android's official development platform) with the help of a plug-in called Android Development Tools (ADT). This helps leverage Eclipse's rich features, such as content assist, Java search, open resources, JUnit integration, and different views and perspectives for developing an Android 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 the development process quite easy. Here, we start with a guide for preparing the system for Android development. We then touch briefly upon the salient features of an Android application using a basic Hello World Android app. We also talk about the files that make up an Android app and how the UI is separated from the implementation. After going through the process of creating, developing, and launching an Android app from Eclipse, we move 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 the help of a sample application. We also talk about using the listView widget in an phonebook-like application and the ways it can be implemented. In between, we also talk about permissions that need to be set in order to be able to have an application access some data from the OS. Overall, a few hours on the article should enable you 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 following installed: 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 the equivalent of JDT (Java Development Tools) for Android Development. Please follow the detailed instructions for installing the ADT plug-in, and also for setting the location of Android SDK in Eclipse.

Section 2. Android terminology


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

ibm.com/developerWorks

developerWorks

A typical Android application has the following components. Also given below are definitions provided by the Android Developer site: Activity An activity presents a visual UI for one focused endeavor the user can undertake. For example, an activity might present a list of menu items users may choose from, or it might display photographs along with their captions. A text-messaging application might have one activity that shows a list of contacts to send messages to, a second activity to write the message to the chosen contact, and other activities to review old messages or change settings. Though they work together to form a cohesive UI, each activity is independent of the others. Content providers A content provider makes a specific set of the application's data available to other applications. The data can be stored in 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 background for an indefinite period of time. For example, a service might play background music as the user attends to other matters, or it might fetch data over the network or calculate something and provide the result to activities that need it. Broadcast receivers A broadcast receiver is a component that does nothing but receive and react to broadcast announcements. Many broadcasts originate in system code timezone-change announcements, low-battery announcements, language-preference changes, etc. Some other terms worth knowing: Intent Activities, services, and broadcast receivers are activated by asynchronous messages called intents. An intent is an Intent object that holds the content of the message. For example, it might convey a request for an activity to present an image to the user or let the user edit some text. Intent filter An Intent object can explicitly name a target component. If it does, Android finds that component (based on the declarations in the manifest file) and activates it. If a target is not explicitly named, however, Android must locate the best component to respond to the intent. It does so by comparing the Intent object to the intent filters of potential targets. A component's intent filters inform Android of the kinds of intents the component is able to handle. For an understanding of these components, refer to "Develop Android Applications with Eclipse" and the Android Hello, World tutorial.

Introduction to Android development Using Eclipse and Android widgets Copyright IBM Corporation 2010. All rights reserved.

Trademarks Page 3 of 31

developerWorks

ibm.com/developerWorks

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 for an AVD to start up. The good news is that separate AVDs are not needed for each application to be deployed and tested. Once the AVD is launched, any number applications can be deployed while it is still running, and it can even be used to debug applications. To create an AVD: 1. 2. 3. 4. 5. In Eclipse, choose Window > Android SDK and AVD Manager. Select Virtual Devices in the left panel. Click New. The Create New AVD dialog appears. Type the name of the AVD, such as "myPhone." Choose a target. The target is the platform (that is, the version of the Android SDK, such as 2.1) to be run on the emulator. You will also get an option to choose the Google APIs, but that is unnecessary unless we want to have some Google API in the app specifically. The rest of the fields can be ignored for now. Click Create AVD.

6.

Once the AVD is launched, you can see how it gives the complete look and feel of a real 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 as landscape/portrait mode, network strength, and roaming network, etc. All of these options can be configured using the AVD manager. The AVD is self-sufficient to emulate different devices available. You can create different AVDs for different configurations and test your application on each of them to make sure it is compatible across device types.

Section 4. Create a new Android project


Here's how to create a new Android project in Eclipse (see Figure 1):
Introduction to Android development Using Eclipse and Android widgets Copyright IBM Corporation 2010. All rights reserved. Trademarks Page 4 of 31

ibm.com/developerWorks

developerWorks

1.

From Eclipse, select File > New > Project. A folder called Android should be present in the dialog if the ADT plug-in for Eclipse has been successfully installed. Expanding that folder should provide the option for a new Android project. Select it and click Next. 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 something like "HelloWorld." Application name This is the name that will appear everywhere in your Android device, along with the icons in the menu, in the shortcuts, and on the title bar when you run your application. This can be something like "Hello Android." Package name com.example.helloandroid or your own private namespace. The package name follows the same rules as those in the Java 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 will be a subclass of Android's Activity class. An activity is simply a class that can run and do some work. It can optionally have a UI. An application may contain one or more activities. They are typically on a 1:1 relationship with the screens found in an application. An application moves from one activity to another by calling a method known as startActivity() or startSubActivity(). Min SDK version This specifies the minimum API level required by your application. The latest one is 7.

2.

Figure 1. Create a new Android project

Introduction to Android development Using Eclipse and Android widgets Copyright IBM Corporation 2010. All rights reserved.

Trademarks Page 5 of 31

developerWorks

ibm.com/developerWorks

Section 5. Hello Android project details


The Hello Android is a basic Android project, which simply prints Hello World on the screen. 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

Introduction to Android development Using Eclipse and Android widgets Copyright IBM Corporation 2010. All rights reserved.

Trademarks Page 6 of 31

ibm.com/developerWorks

developerWorks

Package Explorer view inside Eclipse (Window > Show View > Package Explorer). The newly created Android project will consist of the following (see Figure 2): There are two folders that contain the source code: 1. 2. src contains all the classes specified by the user, including the default activity class. gen contains the files automatically generated by ADT. R.java inside this folder consists of static references to all the resources present in the res folder so they can be easily and dynamically referenced from the Java code. It is advised not to modify the contents of R.java manually.

Figure 2. Hello Android project contents

Introduction to Android development Using Eclipse and Android widgets Copyright IBM Corporation 2010. All rights reserved.

Trademarks Page 7 of 31

developerWorks

ibm.com/developerWorks

A res folder contains all the resources for the project: icons, images, strings, and layouts. Having a separate resource folder keeps non-source code resources external to the code and resources can be dynamically selected based on hardware, language, orientation, and location. It consists of: a. drawable folder(s) Meant for all image files.

Introduction to Android development Using Eclipse and Android widgets Copyright IBM Corporation 2010. All rights reserved.

Trademarks Page 8 of 31

ibm.com/developerWorks

developerWorks

b.

layout folder Meant for the layouts specifying the UI screens for the activities, in the form of XML code. Main.xml is automatically generated. This folder pertains to the default portrait layout. For representing some UI in the landscape layout (when an Android device is turned 90 degrees), create a layout-land folder and put your layout XML file there. The main.xml file has a nice UI representation, as shown in Figure 3. You can drag and drop different layouts and views onto a blank screen to build the UI components for the activity. values folder Meant for all the name-value pairs (the strings your application is going to define).

c.

AndroidManifest.xml is also an important part of the project. It's the equivalent of a plugin.xml file for plug-ins. It basically defines the activities in the applications and specifies the actions that have been specified for each. It also lists out the permissions that the application requires to perform 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 Navigator View in Eclipse (Window > Show View > Navigator). You'll get the structure for the HelloWorld project as shown in Figure 4. Apart from the compiled class files, you obtain the following three files inside a bin folder:

Introduction to Android development Using Eclipse and Android widgets Copyright IBM Corporation 2010. All rights reserved.

Trademarks Page 9 of 31

developerWorks

ibm.com/developerWorks

1. 2.

classes.dex Executable generated from compiled classes. HelloWorld.apk Zipped archive file that will be shipped to the Android device. The app can be installed on any Android device via this archive file. resources.ap_ Zipped application resources.

3.

Android project's directory structure

Introduction to Android development Using Eclipse and Android widgets Copyright IBM Corporation 2010. All rights reserved.

Trademarks Page 10 of 31

ibm.com/developerWorks

developerWorks

The primary 'Activity' of the application


Let's examine MainActivity.java. Listing 1. MainActivity.java
package com.example.helloandroid;

Introduction to Android development Using Eclipse and Android widgets Copyright IBM Corporation 2010. All rights reserved.

Trademarks Page 11 of 31

developerWorks

ibm.com/developerWorks

import android.app.Activity; import android.os.Bundle; public class MainActivity extends Activity { /** Called when the activity is first created. */ @Override public 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, which is located in the android.app package. The onCreate() method is the default entry point to this activity and has to be implemented for each new activity. It receives an argument of type Bundle. Options and parameters required for the creation of the activity are passed in this parameter. The setContentView() is responsible for creating the primary UI using the R.layout.main argument. This is a constant defined in R.java and represents 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 layouts and widgets. The main.xml that Eclipse builds by default consists of a single LinearLayout, which means that all the elements are arranged in a single column. It then defines a textView, which is used to display a static non-editable text. In this case, the "hello" string defined in the strings.xml file (the '@' sign refers to a file defined in the res folder). Each view element further has attributes, such as layout_height and layout_width, etc. Figure 5. Main.xml and the properties view

Introduction to Android development Using Eclipse and Android widgets Copyright IBM Corporation 2010. All rights reserved.

Trademarks Page 12 of 31

ibm.com/developerWorks

developerWorks

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 is selected in the outline view, the properties tab is populated with all possible attributes of the view, as shown in Figure 5. Most of these attributes have only fixed values to chose from, which can be selected from a drop-down menu adjacent to each attribute in the properties tab. For example, to set the layout_height, you can 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 its original 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 in the following two units: (a) Density-independent pixels (dp) This size enables the layout to look the same when viewed on devices of different screen sizes. For example: layout_width = 10dp; (b) Scale-independent pixels (sp) Similar to dp, but this is the recommended standard for mobile phones. For example: layout_width = 10sp.) Another important thing to note is that if you want to reference some view/widget from Java code, it needs to have a unique ID. If you use the layout tab of main.xml to drag and drop a widget, ADT will automatically create an 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.

Introduction to Android development Using Eclipse and Android widgets Copyright IBM Corporation 2010. All rights reserved.

Trademarks Page 13 of 31

developerWorks

ibm.com/developerWorks

Section 6. Running the app on the emulator


For deploying and running the app, you need to define a run configuration. Select Open > Run > Dialog or shortcut on the toolbar within Eclipse, and select Android application. Click New and fill in the name of the run configuration. Specify the name of your project and default activity. Then in the target tab, choose some desired emulator settings and specify an AVD you want to start. Click Run. You will get 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 such as 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
Introduction to Android development Using Eclipse and Android widgets Copyright IBM Corporation 2010. All rights reserved. Trademarks Page 14 of 31

ibm.com/developerWorks

developerWorks

with widgets (see Figure 7): textView consists of widgets such as editText, Button, etc. Buttons can 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 best guide. Be cautious, however, of inconsistencies introduced there because of rapid changes in the Android platform. One glaring example is the use of id as an identifier attribute for a widget in the main.xml in the above-mentioned guide. In the latest Android platform, the fully qualified android:id should be used. Figure 7. Android widgets hierarchy

Introduction to Android development Using Eclipse and Android widgets Copyright IBM Corporation 2010. All rights reserved.

Trademarks Page 15 of 31

developerWorks

ibm.com/developerWorks

Section 8. A sample application using widgets


We will now modify our existing application to look like Figure 8. The purpose of this example is to make the reader familiar with the use of some basic widgets like textView, editText, Button, and Toast in a real app. Our application will consist of a title bar with the message "WELCOME!!!" It will have three textView widgets starting from the top, arranged vertically: one saying "Hello World, how're you?" in default font; the next saying "Welcome to my first Android app" 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 by a button widget (the button goes with the message "Click Me!"). Whatever is typed in the editText widget appears in a Toast widget at the bottom center of the screen when the button is pressed. There isn't much implementation code involved here. The reader should pay attention to how the widgets are easily put into the app using ADT's GUI editor for

Introduction to Android development Using Eclipse and Android widgets Copyright IBM Corporation 2010. All rights reserved.

Trademarks Page 16 of 31

ibm.com/developerWorks

developerWorks

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 UI and 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 the background 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>

Introduction to Android development Using Eclipse and Android widgets Copyright IBM Corporation 2010. All rights reserved.

Trademarks Page 17 of 31

developerWorks

ibm.com/developerWorks

We changed the "hello" string to contain "Hello World, how're you?" Notice the escape character ('\') is required here for the apostrophe. We also defined two new 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: an editText widget and a button widget. Then we'll use the properties tab in main.xml to 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" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <TextView android: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.

Introduction to Android development Using Eclipse and Android widgets Copyright IBM Corporation 2010. All rights reserved.

Trademarks Page 18 of 31

ibm.com/developerWorks

developerWorks

MainActivity.java This is the file that actually links the UI to the implementation. Like the HelloWorld application, we use the Activity.onCreate(Bundle) method to decorate all the UI elements on the screen. The overridden onClick(View) method will contain the functionality of the button click, wherein the user input text will be read and displayed on the screen in a toast widget. Listing 4. The MainActivity.java file
package com.example.helloandroid; import import import import import import android.app.Activity; android.os.Bundle; android.view.View; android.widget.Button; android.widget.EditText; android.widget.Toast;

public class MainActivity extends Activity { /** Called when the activity is first created. */ @Override public 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 widgets final EditText eText = (EditText) findViewById(R.id.EditText01); final Button button = (Button) findViewById(R.id.Button01); button.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View v) { //get the String entered into the editText widget CharSequence editText = eText.getText(); //display the toast Toast.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 sample application

Introduction to Android development Using Eclipse and Android widgets Copyright IBM Corporation 2010. All rights reserved.

Trademarks Page 19 of 31

developerWorks

ibm.com/developerWorks

In this section, we'll create a sample application (see Figures 9a, 9b) to display all contacts in the phonebook using the listView widget. The purpose of this example is to showcase not just the use of the listView widget but also to show how phone data can be fetched using ContentProvider and ContentResolver classes. Pay attention to the UI XML files because there are two UI layouts: one to specify how the list shown by the listView widget fits into the main UI and another to specify how each element of the list looks. Another important point is the setting of permissions for the app to be able to read phone data. This example is the first step to 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 to convert this example app into a real-world phonebook app, one simply needs to implement click actions on the list items and create a call intent and intent filter to initiate a call to the selected contact. In this example, the contacts will be displayed in a vertical linear fashion, and the selected contact appears at the top of the list with a large italicized font and a blue background. We also have a checkbox at the bottom left of the screen, which, when checked, shows only starred (or favorited contacts). The title of the application in this case is "Contact Manager." Here we use three types of widgets: textView, listView, and checkBox. We use the textView widget to display the currently selected contact. You can assume the listView widget to be a list of textView widgets. A listView uses adapter design patterns to connect the data (the contacts, in this case) and a data view (a textView, in this case) to the listView. Any clicks on the listView can be captured by implementing AdapterView.OnItemClickListener(). Before proceeding, we should have some stored contacts in the contacts section of the Android emulator (AVD). This can be done by clicking Contacts on the home screen of the AVD, then Menu to get the Add Contacts option. The Favorites section says how to mark a contact as favorite/starred. Figure 9a. The contacts application showing all contacts in a listView widget

Introduction to Android development Using Eclipse and Android widgets Copyright IBM Corporation 2010. All rights reserved.

Trademarks Page 20 of 31

ibm.com/developerWorks

developerWorks

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

Introduction to Android development Using Eclipse and Android widgets Copyright IBM Corporation 2010. All rights reserved.

Trademarks Page 21 of 31

developerWorks

ibm.com/developerWorks

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 accommodate the list of all contacts in the phonebook. The listView displays each item inside a textView widget, which we'll define next. Listing 6. main.xml
<?xml version="1.0" encoding="utf-8"?>

Introduction to Android development Using Eclipse and Android widgets Copyright IBM Corporation 2010. All rights reserved.

Trademarks Page 22 of 31

ibm.com/developerWorks

developerWorks

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android: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"/> <ListView android: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 list covers 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 to represent each element in the listView. We use a simple textView here. Listing 7. Code for textView widget, which constitutes each element of the listView widget
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns: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 of defining your own. This can be referenced via android.R.layout.simple_list_item_1. ManageContacts.java Listing 8. shows how the main activity is implemented. The method

Introduction to Android development Using Eclipse and Android widgets Copyright IBM Corporation 2010. All rights reserved.

Trademarks Page 23 of 31

developerWorks

ibm.com/developerWorks

populateContactList() is the one we use to query the contacts database and display 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. */ @Override public 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 { @Override public void onItemClick(AdapterView<?> arg0, View textView, int pos, long arg3) { if(textView instanceof TextView) selectedText.setText(((TextView) textView).getText()); } } private class CheckChangedListener implements OnCheckedChangeListener { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mShowStarred = isChecked;

Introduction to Android development Using Eclipse and Android widgets Copyright IBM Corporation 2010. All rights reserved.

Trademarks Page 24 of 31

ibm.com/developerWorks

developerWorks

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

Things to note: We have two listeners one each for handling clicks on a list item and one for handling clicks on the checkbox. The former simply sets the text in the blue textView box to the display name of the currently selected contact. The latter is to set the mShowStarred field and repopulate the list. To read the contacts from the phone database, we need to query it to get a cursor. The query has the following parameters: 1. 2. uri The URI using the content:// scheme for the content to retrieve. projection A list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used. selection A filter declaring which rows to return, formatted as a SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given URI. selectionArgs You may include ?s, which will be replaced by the values from selectionArgs, in the order that they appear in the selection. The values will be bound as Strings. sortOrder How to order the rows, formatted as a SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.

3.

4.

5.

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

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

Introduction to Android development Using Eclipse and Android widgets Copyright IBM Corporation 2010. All rights reserved.

Trademarks Page 25 of 31

developerWorks

ibm.com/developerWorks

Linux kernel in the device will not allow the application to do so. So let's go to the AndroidManifest.xml>Permissions tab, and set the following permissions: 1. 2. android.permission.GET_ACCOUNTS android.permission.READ_CONTACTS

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

Introduction to Android development Using Eclipse and Android widgets Copyright IBM Corporation 2010. All rights reserved.

Trademarks Page 26 of 31

ibm.com/developerWorks

developerWorks

listView widget using ListActivity This example is meant to demonstrate another way of implementing a listView. In the above application, note that our main activity implements the activity class. When dealing with listView widgets, sometimes the ListActivity class comes in handier because it has public APIs to handle clicks on list items, setting list adapters, 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 { @Override protected void onListItemClick(ListView l, View v, int position, long id) { // TODO Auto-generated method stub super.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. */ @Override public void onCreate(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(new CheckChangedListener()); 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 };

Introduction to Android development Using Eclipse and Android widgets Copyright IBM Corporation 2010. All rights reserved.

Trademarks Page 27 of 31

developerWorks

ibm.com/developerWorks

ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.contactitem, c, fields, new int[]{R.id.contactItem}); setListAdapter(adapter); } private class CheckChangedListener implements OnCheckedChangeListener { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mShowStarred = isChecked; selectedText.setText(""); populateContactList(); } } }

Note that here we simply implemented onListItemClick method of ListActivity, rather than declaring an anonymous class to handle clicks. We also didn't need to refer to the listView widget defined in main.xml here because ListActivity 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 to refer to.

Section 10. Conclusion


In this tutorial, we learned how to set up Eclipse for Android development and how the rich features of Eclipse assist in every step in writing Android apps. We also learned 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 World example and learned about the files that make up an Android app. We touched upon some of the widgets provided by Android and saw their use in some real-world examples. You now should be well on the way to creating a cool application with a neat UI. As a first step, extend the contacts app to implement click action on a list item to display the phone number and contact details, and a button to call the selected 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 Java technology, along with Android Development Tools for Eclipse, make it easily adoptable by beginners. Its wide array of widgets, along with its ability to dynamically

Introduction to Android development Using Eclipse and Android widgets Copyright IBM Corporation 2010. All rights reserved.

Trademarks Page 28 of 31

ibm.com/developerWorks

developerWorks

bind the UI elements to the implementation, provides a lot of flexibility and makes the 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, and control the binding between them. It also has a vast array of networking APIs to explore. In addition, Google APIs provide functionality for maps, search, and mail, among other things, which can all be easily adopted in an Android application. So dive into the wonderful world of Android and let your imagination run wild.

Introduction to Android development Using Eclipse and Android widgets Copyright IBM Corporation 2010. All rights reserved.

Trademarks Page 29 of 31

developerWorks

ibm.com/developerWorks

Resources
Learn The Developer's Guide is a practical introduction to developing applications for Android. Read "Develop Android applications with Eclipse" for an introduction to Android development 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 Sciences Department. 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 Eclipse Platform" to learn its origin and architecture, and how to extend Eclipse with plug-ins. Expand your Eclipse skills by checking out IBM developerWorks' Eclipse project resources. 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 general community 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 product functions with the no-cost developerWorks On demand demos. Check out upcoming conferences, trade shows, webcasts, and other Events around 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 technologies and use them with IBM's products, as well as our most popular articles and tutorials.

Introduction to Android development Using Eclipse and Android widgets Copyright IBM Corporation 2010. All rights reserved.

Trademarks Page 30 of 31

ibm.com/developerWorks

developerWorks

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 check out a trial of IBM's Rational Application Developer Standard Edition, a commercial 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 the IBM SOA Sandbox and get your hands on application development tools and middleware products from DB2, Lotus, Rational, Tivoli, and WebSphere. 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 questions regarding Eclipse. (Selecting this will launch your default Usenet news reader application and open eclipse.platform.) The Eclipse newsgroups has many resources for people interested in using and extending Eclipse. Participate in developerWorks blogs and get involved in the developerWorks community.

About the author


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

Introduction to Android development Using Eclipse and Android widgets Copyright IBM Corporation 2010. All rights reserved.

Trademarks Page 31 of 31

Вам также может понравиться