Professional Documents
Culture Documents
Os Eclipse Androidwidget PDF
Os Eclipse Androidwidget PDF
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.
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.
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.
Trademarks
Page 3 of 31
developerWorks
ibm.com/developerWorks
2.
3.
4.
5.
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.
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.
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.
2.
Trademarks
Page 5 of 31
developerWorks
ibm.com/developerWorks
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.
src contains all the classes specified by the user, including the default
activity class.
2.
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.
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.
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.
c.
values folder Meant for all the name-value pairs (the strings
your application is going to define).
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:
Trademarks
Page 9 of 31
developerWorks
ibm.com/developerWorks
1.
2.
3.
Trademarks
Page 10 of 31
ibm.com/developerWorks
developerWorks
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);
}
}
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.
Trademarks
Page 13 of 31
developerWorks
ibm.com/developerWorks
Trademarks
Page 14 of 31
ibm.com/developerWorks
developerWorks
Trademarks
Page 15 of 31
developerWorks
ibm.com/developerWorks
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>
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.
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;
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
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
Trademarks
Page 21 of 31
developerWorks
ibm.com/developerWorks
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"?>
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
Trademarks
Page 23 of 31
developerWorks
ibm.com/developerWorks
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.
uri The URI using the content:// scheme for the content to
retrieve.
2.
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
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.
android.permission.GET_ACCOUNTS
2.
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
Trademarks
Page 26 of 31
ibm.com/developerWorks
developerWorks
Trademarks
Page 27 of 31
developerWorks
ibm.com/developerWorks
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.
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.
Trademarks
Page 30 of 31
ibm.com/developerWorks
developerWorks
Trademarks
Page 31 of 31