You are on page 1of 102

Copyright NIIT. All rights reserved.

This product or document is protected by copyright and


distributed under licenses restricting its use, copying,
distribution and decompilation. Please view Mark of
Authenticity label to establish proper licensed usage. No
part of this document may be copied, reproduced, printed,
distributed, modified, removed, amended in any form by
any means whether electronic, mechanical, digital, optical,
photographic or otherwise without prior written
authorization of NIIT and its authorized licensors, if any.
Information in this document is subject to change by NIIT
without notice. The names of companies, products, people,
characters, and/or data mentioned herein are fictitious and
are in no way intended to represent any real individual,
company, entity, services, product or event, unless
otherwise noted.
All products are registered trademarks of their respective
organizations.
All software is used for educational purposes only.
Disclaimer: The documents and graphics on this
courseware could include technical inaccuracies or
typographical errors/translation errors. Changes are
periodically added to the information herein. NIIT may
make improvements and/or changes herein at any time.
NIIT makes no representations about the accuracy of the
information contained in the courseware and graphics in
this courseware for any purpose. All documents and
graphics are provided "as is". NIIT hereby disclaims all
warranties and conditions with regard to this information,
including all implied warranties and conditions of
merchantability, fitness for any particular purpose, title
and non-infringement. In any event, NIIT and/or its
licensor(s)/supplier(s) shall not be liable to any party for
any direct, indirect, special or other consequential
damages for any use of the courseware/translated
courseware, the information, or on any other hyper linked
web site, including, without limitation, any lost profits,
business interruption, loss of programs or other data on
your information handling system or otherwise, even if
NIIT is expressly advised of the possibility of such
damages.
Due to the dynamic nature of the internet, the URLs and
web references mentioned in this document may be (are)
subject to changes, for which NIIT shall not hold any
responsibility.

DMAJ - I/SG/10-M06-V02

COURSE DESIGN

Objectives

About This Course


Prologue
Description
This course focuses on developing mobile application by
using Java Micro Edition (Java ME). Although the Java
platform is extensively used for developing Desktop
applications and Web-based applications, Java ME is a
popular platform for developing applications for mobile
devices, such as mobile phones and Personal Digital
Assistants (PDA).
This course covers the implementations of software
solutions for mobile devices. It begins by introducing the
Java ME architecture and wireless technology. The course
explains how to create high-level and low-level user
interfaces. In addition, it explains managing storage of
information and implementing security. Also, the course
explains how to create multimedia applications, wireless
messaging applications, and gaming applications by using
Java ME. Finally, this course will enable the students to
develop, debug, test, and securely deploy mobile
applications.

Rationale
The availability of wireless Internet services on mobile
devices such as mobile phones is making communication
possible anywhere and at anytime. When connected to the
Internet, the functionality provided by these mobile
devices becomes seamlessly endless.
Java is a very popular technology. It has been accepted as
the de facto standard by the mobile industry for
developing mobile applications. However, the standard
edition of Java cannot be used for creating applications for
mobile devices since it uses a lot of memory. Therefore,
Sun Microsystems released Java ME for developing
applications for resource-restricted devices. Java ME
offers a flexible and robust platform for mobile application
development with enterprise-class performance, reliability,
and value.
Java ME aims at developing applications for micro
devices like mobile phones and Personal Digital Assistants
which have limited application capacity. It allows
developers to use the Sun Java wireless toolkit to create
applications and programs for wireless and mobile
devices.

After completing this course, students will be able to:


Explain the profiles and configurations in Java
ME technology
Execute a MIDlet, and package and run MIDlet
suites using NetBeans 6.0.1
Describe MIDP User Interface components and
their hierarchy
Create User Interfaces using High Level UI APIs
Create user interfaces using low-level APIs
Store and manipulate data in MIDlet by using
RMS
Establish network connection using the GCF
Implement MIDlet Security
Play sounds and videos using MMAPI package
Create, send, and receive SMS messages using
WMA
Develop gaming application
Identify the use of push registry
Deploy MIDlets through local Machine and Web
Server

Entry Profile
The students wanting to undergo this course are
recommended to have the following skills:
Knowledge of core Java
Basic knowledge of XML

Exit Profile
After completing this course, the student should be able to:
Develop Mobile Applications by using the Java
ME Technology

Conventions
Convention

Indicates...
Note

Just a minute

Chapter 1
Introduction to Java ME
In recent times, there are several small devices, such as
mobile phones and embedded devices, available in the
market. These devices have less resource as compared to
desktop computers. However, they provide certain features
that can be compared with the feature provided by desktop
computers. We need a new platform to create application
for these resource-limited devices.
This chapter introduces Java Micro Edition (Java ME) as a
platform for developing applications for resource limited
devices. Further, this chapter describes the configuration
and profiles in Java ME technology. In addition, this
chapter introduces the Java Technology for the Wireless
Industry (JTWI) as a standard and discusses the goals and
characteristics of the JTWI specification.

Objectives
In this chapter, you will learn to:
Identify the basics of mobile application development
Describe the CLDC configuration and the MIDP
profile
Identify the characteristics of JTWI specification

Introduction to Mobile Application


Development
Mobile applications are developed for handheld devices
such as mobile phones and Personal Digital Assistants
(PDAs). At present, several platforms such as Java ME,
Symbian, Binary Runtime environment for Wireless
(BREW), Microsoft .NET Compact Framework, Objective
C, and Python are available for developing mobile
applications.
Java ME, formerly known as Java 2 Micro Edition
(J2ME), is a Java-based platform developed by Sun
Microsystems. Java ME provides an environment for
developing applications for wireless mobile devices, such
as mobile phones and PDAs, and embedded devices, such
as set-top boxes and printers.
The Java ME platform includes flexible User Interfaces
(UIs), a strong security model, and built-in network
protocols that can be used to create rich and powerful
wireless applications for mobile devices.

Introducing Java ME

The cross-platform capability of the Java programming


language helps in reducing the development cost. This has
led to the expansion of the Java platform to create
applications for rich user interfaces.
Sun Microsystems have released several versions of Java,
and they have maintained a consistent architecture across
these versions. Each newer version has several new
features in it. After the release of Java 1.2, there has been a
change in the way Java is packaged and licensed. This has
split the Java platform into the following three editions:
Java Standard Edition (Java SE): Java SE is a
core collection of tools and Java Application
Program Interfaces(APIs). It is used for creating
applets and Java applications that are stand-alone
and Web-based.
Java Enterprise Edition (Java EE): Java EE is
used for enterprise computing wherein a single
application is spread across a distributed network.
Java EE is used for building server applications.
It contains all the functionality of Java SE and
focuses on server-side programming by using
Enterprise Java Beans (EJB), Servlets and Java
Server Pages (JSP), and Extensible Markup
Language (XML).
Java Micro Edition (Java ME): Java ME is a
collection of technologies and specifications to
create a platform that fits the requirements for
mobile and embedded consumer devices.
Majority of the Java ME applications are
developed for wireless handheld devices. Java
ME handles the computing requirements of
resource-limited devices with as little as 128 KB
of Random Access Memory (RAM) and with
processors that are less powerful as compared to
desktop computers.

Note
RAM is a form of data storage where the
information is lost after the power is switched
off.
The following figure shows the library sets of the three
Java editions in terms of a set diagram.

Library Sets of Java Editions


Java ME shares some classes with Java SE and Java EE
APIs. In addition, Java ME contains its own classes, called
Profile APIs that are not a part of Java SE and Java EE
APIs.
Java ME is designed for small devices that have common
hardware and software characteristics. Some of these
characteristics are:
Limitedmemory: These devices have limited
RAM ranging from 128 KB to 2 MB.
Limitedprocessing: These devices have low
CPU speed, ranging from 100 MHz to 200 MHz
as compared to personal computers whose speeds
are in the GHz range.
Limited display: These devices have lowresolution and small-sized screens. The screen
size can be as small as 96x54 pixels. In addition,
java ME supports devices that do not have any
display unit.
Limited input methods: These devices use
keypads that have limited number of input keys
as compared to desktop computers.
Limited networking capabilities: These devices
support wireless and two-way networks with
limited bandwidth.

Understanding the Java ME


Architecture
The micro world includes a wide range of devices with
different capabilities. It is not possible to create a single
software product to suit all of them. Java ME is designed
as a collection of specifications that define a set of
platforms. Each of these platforms is suitable for a subset
of the collection of devices that fall within its scope. This
subset for a particular collection of devices is defined by a
configuration and one or more profiles. The configuration
and profile, together, provide APIs to develop applications
for this collection of devices.

Describing Java ME Configurations

A configuration is a specification that defines a software


environment for a range of devices defined by a set of
characteristics that the specification relies upon. The
characteristics that are defined for the range of devices
may be the type and amount of memory available, the type
of processor and its speed, and the type of network
connections available to the devices.
A configuration represents the minimum platform for the
devices. For example, a configuration can define a Java
platform for all handheld devices, such as mobile phones
and PDAs. It provides the basic set of classes and libraries
required to support devices with similar memory and
processing requirements.
The two types of configurations in Java ME are Connected
Device Configuration (CDC) and Connected Limited
Device Configuration (CLDC). CDC defines a basic set of
classes and libraries for devices such as set-top boxes.
CLDC defines a basic set of classes and libraries for
resource-restricted devices such as mobile phones and
PDAs.

Describing Java ME Profiles


A profile provides additional classes for a certain range of
devices within the framework of a chosen configuration.
The classes provided by the profile are suitable to a
particular family of devices within a given configuration.
The Java ME configurations, CLDC and CDC, have one
or more profiles associated with them. The Mobile
Information Device Profile (MIDP) is a CLDC-based
profile that defines class libraries to develop applications
for network-connectable mobile devices. The MIDP is a
commonly used Java ME profile for CLDC. The profile
for PDA is Personal Digital Assistance Profile (PDAP)
that implements CLDC. The Foundation profile is a Java
ME profile for CDC.
Profiles help in managing device-specific features, such as
creating GUI, and managing data storage and network
connections. Each profile provides various device-specific
APIs.

Note
Information Module Profile (IMP) is also a
CLDC-based profile, which is used with
devices having similar memory and resource
requirements as MIDP. However, IMP based
devices do not have rich graphical capabilities
as compared to MIDP based devices. Parking
meters and wireless modules in home alarm
systems are examples of devices that
implement IMP.

Describing the Java ME Architecture

Java ME uses a layered architecture, which defines the


following major categories of components:
Configuration layer: This layer includes a
Kilobytes Virtual Machine (KVM) or C Virtual
Machine (CVM), which is similar to the Java
Virtual Machine (JVM). KVM is a part of the
CLDC configuration whereas CVM is part of the
CDC configuration. Configuration layer also
defines class libraries for a range of devices that
have similar requirements for memory,
processing power, and network connectivity. For
example, mobile phones, pagers, and PDAs form
a range of devices with similar requirements.
Profile layer: This layer adds classes to the
chosen configuration to support device specific
functionality, which are not provided by the
classes in the configuration layer. It defines class
libraries that provide access to device capabilities
such as I/O and GUI.
Together, the configuration layer and profile layer form
the Java ME runtime environment. The Java ME layered
architecture also includes an additional layer of optional
packages. An optional package is always used in
combination with a configuration or a profile. These
packages add standard APIs to develop applications that
provide functionality, such as ability to send messages and
play audio content.
For example, Wireless Messaging API (WMA) is an
optional package that can be used to develop applications
for sending and receiving messages through mobile
devices having Short Messaging Service (SMS)
capabilities. This package can be used with CLDC and
MIDP, or with some other configuration and profile.
The following figure shows the layered architecture of
Java ME for the CLDC configuration.

The Java ME Layered Architecture

Just a minute:
Steve is a mobile application developer with
Info Super Corp. He is assigned the task to
develop a game application for mobile
devices. Steve needs to add GUI to the game
application. Which layer of Java ME
architecture can provide him the class
libraries to perform the required task?

Answer:
Profile layer

Features of Java ME
The features of the Java ME platform are:
Security: Performs class file verification on the
Java ME applications before downloading them
on a mobile device. This process is called
preverification. This preverification process
ensures that the applications are secure and do
not damage the mobile device or the wireless

network. Java ME provides the facility for


downloading authenticated wireless applications
to perform secure financial transactions. For
example, it allows you to download applications
that can securely access the transaction server of
a bank.

Note
Class file verification is the process of
identifying and rejecting invalid class
files in a Java ME application. For
Java ME applications, this process
takes place in two phases. The first
phase takes place before an
application is downloaded on to a
mobile device and is called
preverification. The second phase
takes place after downloading the
application on to a mobile device.
Portability: Provides standard language features
and libraries. Therefore, applications developed
by using Java ME are portable across various
devices that support Java ME.
Dynamic content delivery: Allows devices to
download and run dynamic and interactive
content.
Enhanced UI and Interactive content: Provides
packages such as
javax.microedition.lcdui to enhance
the UI and graphic capabilities in mobile devices.
Offline access: Enables you to use mobile
applications without maintaining a constant
connection with the wireless network. After an
application is downloaded, it can run offline. As a
result, network failures and transport costs are
reduced.
Compatibility with Java SE and Java EE
platforms: Enables you to access the information
provided by applications and web services
developed by using Java SE and Java EE.

Introducing Wireless Technologies


Java ME is a widely used platform for wireless mobile
devices, such as mobile phones. The purpose of such
devices is lost if it is required to connect these devices to
cables for its working.
Wireless technology provides solution for such
environments where wires may not be the best solution. It
is a term used to describe a network where there is no

physical connection between a sender and a receiver, and


they are connected through radio signals. For example,
you may want to connect to the Internet to access your emails while travelling. Connecting to the Internet through
Digital Subscriber Line (DSL) or dial-up connection,
which uses wires, is not possible in such a situation.
However, wireless technology provides you the solution
by enabling you to connect to the Internet through a
mobile phone.
Wireless technologies are used in many devices, such as
mobile phones, PDA devices, pocket PCs, and digital
diaries. These devices can communicate with other
wireless devices or/and get information from a remote
server.
Wireless devices allow you to run wireless applications.
Wireless applications provide user interfaces to connect
and exchange data with a network. However, the
communication between the wireless devices is
established with the help of various wireless technologies,
such as Global System for Mobile communications (GSM)
and General Packet Radio Service (GPRS).
Mobile wireless technologies have experienced the
following generations of technology evolution:
First Generation (1G): This generation uses
analog voice signaling to transfer voice-based
data in mobile devices. Also, this generation uses
the Frequency Division Multiple Access (FDMA)
technology to transfer data.
Second Generation (2G): This generation uses
digital voice encoding to transfer voice-based
data. It uses the Time Division Multiple Access
(TDMA) technology to transfer data. TDMA
transmits multiple calls on the same frequency by
dividing each call into separate time slots.

Note
The FDMA technology assigns
different frequencies for different
calls. However, the TDMA technology
enables multiple calls on the same
radio frequency.
Third Generation (3G): This generation
provides advanced features to send and receive
data through wireless devices. Some of these
features are enhanced multimedia, and highspeed data access.
Fourth Generation (4G): This generation is still
under the planning stage. However, there are
some expectations from 4G technologies such as
delivering high quality audio and video and high
data transfer rates.

Note
To ensure that the shift from one generation to
another generation of technologies is a steady
move, there is another set of technologies
introduced between 2G and 3G technologies.
These set of technologies are known as the
2.5G technologies. 2.5G technologies are
slightly advanced as compared to the 2G
technologies. However, they are not as
advanced as the 3G technologies.
Some important terms used in the wireless telephony
related to the preceding generations of wireless
technologies are:
GSM
Code Division Multiple Access (CDMA)
3GSM
GPRS
Enhanced Data rates for GSM Evolution (EDGE)
Wireless Application Protocol (WAP)

GSM
Most of the wireless technologies are based on the GSM
platform. GSM is a 2G wireless network for digital mobile
communication. It allows its customers to talk while they
are on the move. In addition, it provides a low-cost
alternative to voice calls, known as SMS. Most GSM
networks operate in the 900 MHz or 1800 MHz bands.
GSM uses the TDMA technology that allows a single
frequency to support multiple data channels.

CDMA
CDMA is another 2G technology that is used to transfer
data. CDMA is a spread-spectrum implementation that
uses full frequency spectrum for each channel rather than
assigning specific frequencies to particular users. It
separates the calls by using digital encoding.
CDMA uses a single spectrum of bandwidth instead of
time slices like TDMA. Therefore, it transmits all user
signals onto the channel at the same time and assigns a
unique code for each conversation. To avoid interference
with multiple users on the same channel at the same time,
Orthogonal Frequency Division Multiplexing (OFDM) is
designed to make them as different from each other as
possible. The data is sent in small chunks and spread
across the entire bandwidth by using a unique spreading
code. This code is used at the receivers end to collate and
recover the data chunks.
The CDMA-based networks can carry large number of
calls. In addition, these networks enable fast and secure
data transfer.
CDMAOne and CDMA2000 are standards based on

CDMA that are used for mobile devices. CDMA2000 is a


hybrid 2.5G and 3G protocol based on CDMA.
CDMA2000 is an efficient and robust technology. It
delivers highest voice capacity and data throughput by
using the least amount of spectrum. Moreover, it can be
used to provide cost effective services in remote areas.

3GSM
3GSM is an enhanced version of the GSM platform that
provides 3G mobile multimedia services. 3GSM provides
high bandwidth and quality for transmitting voice, text,
and visual data across a wireless network.
3GSM uses an additional radio signal that was not
available in the GSM platform. This additional radio
signal provides added bandwidth that enables mobile
device subscribers to access high data transmission speed
and multimedia data services.

GPRS
GPRS is a data service. It is used to send and receive data
across a wireless network. GPRS data service is available
for 2G as well as 3G technology users. GPRS enables
various mobile devices to connect to a server in order to
access the required data. It allows you to download
wireless applications on mobile devices. It also enables
you to send and receive multimedia messages that may
contain text, sounds, still, and animated images through
mobile phones. In addition, it provides the facility to
access textual and visual information, such as sports
scores, news headlines, and weather information. Wireless
application technologies, such as Java ME can be used to
develop interfaces for showing such information on the
mobile device screen.

EDGE
EDGE is a 3G wireless technology that provides broader
bandwidth and faster data transfer in mobile devices. It is
an enhanced version of GPRS technology. The EDGE
technology enables mobile users to download video and
music clips and access high speed Internet. EDGE
wireless technology connects to the Internet and
exchanges data faster than the 2G wireless technology.

WAP
Wireless Application Protocol (WAP) is a specification
that uses several data handling techniques used by Web
Protocols such as Transmission Control Protocol/Internet
Protocol (TCP/IP). The development of WAP applications
is simple because it reuses existing Web technologies. To
generate dynamic WAP content, you can use either
Servlets and Java Server Pages (JSP) or Wireless Markup
Language (WML). When using the WAP technology, the
mobile device runs a browser that accesses the intranet or
Internet applications. However, Java ME applications run
directly on the mobile devices without the help of a Web
browser. WAP is a complimentary technology to Java ME.

that a Virtual Machine (VM) must have. It also defines a


set of packages and classes for mobile devices that have
limited resources.

Components of CLDC

Just a minute:
State whether the following statement is true
or false.
GPRS provides the facility to deliver textual
and visual information, such as sports scores,
news headlines, and weather information.

Answer:
True

Just a minute:
State whether the following statement is true
or false.
GPRS provides advanced multimedia services
and the highest available bandwidth.

Answer:
False

Exploring CLDC and MIDP


To develop a mobile application by using Java ME, you
need to select a configuration and profile for your
application. Selecting a configuration and a profile
depends on the device for which the application is to be
developed.
For developing applications for mobile devices, the CLDC
configuration and the MIDP profile are used.

Describing CLDC
The CLDC is the basic building block on which the Java
ME profile, MIDP, is built. CLDC specifies the features

CLDC contains the following components of the Java


platform that are implemented on a mobile device:
CLDC library
KVM

CLDC Library
The CLDC library contains a minimum useful set of APIs
that support mobile application development. CLDC also
contains some extra libraries to support networking
capabilities in a mobile device.
CLDC libraries provide upward compatibility of
applications to other Java platform editions, such as Java
SE and Java EE. To support upward compatibility of its
applications, CLDC separates its libraries into the
following categories:
The first category is of the classes that are on the
subset of standard Java SE libraries, such as
java.lang.*, java.util.*, and
java.io.*. These libraries are upward
compatible with Java SE and Java EE. The
classes in these libraries have the same class
name and package name as Java SE and Java EE.
These classes do not add any public or protected
methods or fields that are not available in the
corresponding Java SE classes.
The second category is of the classes that are
specific to CLDC, such as the classes of
javax.microedition.* package. These
classes are not upward compatible with Java SE
libraries. These classes provide a network
communication framework, which is called the
Generic Connection Framework (GCF). Most of
the classes in the GCF are interfaces that
represent different types of communications, such
as socket, serial, datagram, and Hypertext
Transfer Protocol (HTTP).

Kilobyte Virtual Machine


KVM represents a virtual machine for small devices that
implement CLDC. It is an optimized implementation of a
JVM, which is used in Java SE. It has limited features as
compared to a JVM.
The following table lists the differences between a KVM
and a JVM.

Differences Between a KVM and a JVM


The following figure shows the components of CLDC.

Comparison Between CLDC1.0 and CLDC1.1

Requirements of CLDC 1.1


Specification
Components of CLDC

The CLDC specification defines a minimum set of


hardware requirements that all CLDC compliant mobile
devices need to fulfill.
The minimum hardware requirements for a CLDCcompliant mobile device are:
160 KB of non-volatile memory for the virtual
machine and CLDC libraries
32 KB of volatile memory for the virtual machine

Just a minute:
State whether the following statement is true
or false.
KVM represents a virtual machine for small
devices that implement CLDC.

Answer:

Just a minute:
State whether the following statement is true
or false.

True

Versions of CLDC
There are two versions of CLDC, namely CLDC 1.0 and
CLDC 1.1. CLDC 1.0 was upgraded to CLDC 1.1 by
adding more features and specifications to it.
The following table compares the features of CLDC 1.0
and CLDC 1.1.

Names of thread objects in CLDC 1.1 are


similar to the names of thread objects in Java
SE.

Answer:
True

Describing MIDP
The MIDP profile is based on the CLDC configuration.
MIDP is a set of Java APIs. The MIDP profile adds certain
features such as networking capabilities, UI components,
and local storage to the CLDC configuration. The MIDP
profile, being aimed at limited display and storage
facilities of mobile devices, provides a simple UI and
basic networking capabilities.
MIDP and CLDC work together to provide a core
application functionality, which is nothing but a complete
Java ME application runtime environment, for mobile
phones. MIDP 1.0 provides the core application
functionality along with basic UI and network security in
mobile devices.
MIDP 2.0 is a revised version of MIDP 1.0. MIDP 2.0
includes several new features such as enhanced
multimedia, game functionality, and application-level
security to mobile devices. MIDP 2.0 is also backward
compatible with MIDP 1.0.
The following table compares some of the features of
MIDP 1.0 and MIDP 2.0.

Comparison Between MIDP 1.0 and MIDP 2.0

Requirements for MIDP


The MIDP specification defines a minimum set of
hardware and software requirements that all MIDPcompliant devices need to fulfill.
The minimum hardware requirements for an MIDPcompliant device are:
Screen size of 96x54 pixels
Display depth of 1-bit
Minimum non-volatile memory of 128 KB
Minimum volatile memory of 32 KB for Java
runtime
User input mechanism supporting HalfQWERTY (one-handed) keyboard, QWERTY
(two-handed) keyboards, or touch screens
Support for two-way wireless connectivity of
limited bandwidth

Describing the JTWI Specification


The JTWI was created by a group of experts from
organizations such as Motorola, Nokia, and Siemens. This
group is called the Java Community Process (JCP) expert
group, Java Specification Requirements (JSR) -185. JSRs
are descriptions of the proposed final specifications for
Java platform. JSR-185 gives descriptions for a wireless
Java application environment.
CLDC 1.1 was developed under JCP as JSR 139. In
addition, MIDP was developed under JCP as JSR 37 for
MIDP version 1.0 and JSR 118 for MIDP version 2.0.
JTWI specifies the technologies that must be included in
JTWI-compliant devices. It specifies that JTWI-compliant
devices should include APIs such as CLDC 1.0 and MIDP
2.x. In addition, JTWI also specifies the platform that
should be used for the Java ME enabled mobile devices.

Identifying Goals of JTWI


Specification
The JTWI specification is based on certain goals that the
JCP expert group JSR-185 plans to achieve in the Javaenabled wireless industry.
The goals set for JTWI specification are:
To set standards for the APIs used in mobile
devices by providing:
Minimum hardware specifications for
mobile device manufacturers
Minimum API specifications for
application developers
To improve the interoperability (ability to work
together) and compatibility (capable of being
used with other devices) of Java enabled mobile
phones

Characteristics of JTWI
Specifications
The JTWI specification defines three categories of Java
ME specifications:
Mandatory specifications
Conditionally required specifications
Minimum configuration specifications

Mandatory Specifications
Mandatory (Important / Compulsory) specifications
include a set of specifications that must be implemented in
a mobile device to make it JTWI compliant.
The two mandatory specifications provided by JTWI are:
MIDP 2.x: Includes a set of additional APIs in
addition to the APIs that exist in MIDP 1.0. These

APIs provide advanced features, such as


improved gaming and media support, in a mobile
device. MIDP 2.x also supports enhanced UI and
security features in a mobile device.

Note
MIDP 1.0 is a set of APIs initially
provided by Java ME. These APIs
support core application features,
such as UI, network connectivity, and
local data storage, which are required
by mobile device applications.
Wireless Messaging API (WMA) 1.1: Includes
a set of APIs that provide platform independent
resources for wireless communication services,
such as Short Message Service (SMS).

Conditionally Required
Specifications
Conditionally required specifications specify that if a
JTWI compliant device implementing JSR 185 includes
specific features such as camera and music player that are
exposed through Java APIs, then it must support JSR-135
MMAPI. MMAPIs enable you to play and record audio,
take pictures, and play videos in mobile devices. MMAPI
1.1 defines the media that helps develop advanced games
and support multimedia content.

Minimum Configuration
Specifications
Minimum configuration specification includes
specifications for the virtual machine and a set of APIs
that are required for the Java ME runtime environment.
The CLDC 1.0 specification represents the minimum
configuration specification of JTWI.
By using these specifications, Java ME can be used to
develop standard applications for mobile devices.

Summary
In this chapter, you learned that:
Java ME provides an environment for developing
applications for wireless mobile devices, such as
mobile phones and PDAs, and embedded
devices, such as set-top boxes and printers.
The Java ME platform includes flexible UIs, a
strong security model, and built-in network
protocols that can be used to create rich and
powerful wireless applications for mobile
devices.
The Java ME architecture is designed for small

devices that have common hardware and


software characteristics. Some of these
characteristics are:
Limited memory
Limited processing
Limited display
Limited input methods
Limited networking capabilities
A configuration and a profile, together, provide
APIs to develop mobile applications.
A configuration is a specification that defines the
software environment for mobile devices.
The two types of configurations in Java ME are
CDC and CLDC.
The MIDP is a commonly used Java ME profile
for CLDC.
Java ME uses a layered architecture, which
defines the following major categories of
components:
Configuration layer
Profile layer
The Java ME layered architecture also includes
an additional layer of optional packages, which is
always used in combination with a configuration
or a profile.
The features of the Java ME platform are:
Security
Portability
Dynamic content delivery
Enhanced UI and Interactive content
Offline access
Compatibility with Java SE and Java EE
platforms
The communication between the wireless devices
is established with the help of various wireless
technologies, such as GSM and GPRS.
Mobile wireless technologies have experienced
the following generations of technology
evolution:
1G
2G
3G
4G
Java ME is used to create mobile applications for
mobile devices that have limited processor,
memory, and display capabilities.
Some important terms used in the wireless
telephony are:
GSM: Is a 2G wireless network for digital
mobile communication.
CDMA: Is another 2G technology that is
used to transfer data.
3GSM: Is an enhanced version of the GSM
platform that provides 3G mobile
multimedia services.

GPRS: Is a data service that is used to send


and receive data across a wireless network.
EDGE: Is a 3G wireless technology that
provides broader bandwidth and faster data
transfer in mobile devices.
WAP: Is a specification that uses several
data handling techniques used by Web
Protocols such as TCP/IP.
CLDC contains the following components of the
Java platform that are implemented on a mobile
device:
CLDC library
KVM
The CLDC library contains a minimum useful set
of APIs that support application development.
KVM represents a virtual machine for small
devices that implement CLDC.
CLDC 1.0 was upgraded to CLDC 1.1 by adding
more features and specifications to it.
MIDP is a set of Java APIs that is based on the
CLDC configuration.
MIDP 1.0 provides the core application
functionality along with basic UI and network
security in mobile devices.
MIDP 2.0 is a revised version of MIDP 1.0.
MIDP 2.0 includes several new features such as
enhanced multimedia, game functionality, and
application-level security to mobile devices.
JTWI specifies the technologies that must be
included in JTWI-compliant devices.
The JTWI specification defines three categories
of Java ME specifications:
Mandatory specifications
Conditionally required specifications
Minimum configuration specifications

Reference Reading
Introduction to Mobile Application
Development
Reference Reading: Books
J2ME in a Nutshell: By Kim
TopleyPublisher: OReilly
Enterprise J2ME:
Developing Mobile Java
Applications By Michael
Juntao Yuan
Publisher: Prentice Hall
PTR.
Enterprise J2ME:
Developing Mobile Java
Applications

Reference Reading: URLs


http://developers.sun.com/
techtopics/mobility/getstart/
http://www.developer.com/
ws/article.php/1475521

By John W. Muchow
Publisher: Prentice Hall
PTR.

Exploring CLDC and MIDP


Reference Reading: Books Reference Reading: URLs
Enterprise J2ME:
Developing Mobile Java
Applications By Michael
Juntao Yuan
Publisher: Prentice Hall
PTR.
J2ME in a Nutshell: By Kim
Topley
Publisher: OReilly
Enterprise J2ME:
Developing Mobile Java
Applications
By John W. Muchow
Publisher: Prentice Hall
PTR.

Describing the JTWI Specification


Reference Reading: Books
J2ME in a Nutshell: By Kim
TopleyPublisher: OReilly
Java 2 Micro Edition
Application Development
By Michael Kroll, Stefan
Haustein
Publisher: Sams
Publishing.
Enterprise J2ME:
Developing Mobile Java
Applications By Michael
Juntao Yuan
Publisher: Prentice Hall
PTR.

Reference Reading: URLs


http://developers.sun.com/
techtopics/mobility/getstart/
http://java.sun.com/
products/jtwi/

starting, running, stopping, and removing


MIDlets from a mobile device.

Chapter 2
Developing MIDlets
A MIDlet is a Java application framework for MIDP.
MIDlets are Java classes that form the interface between
an application and the operating system in an MIDP
device. A group of collected MIDlets forms a MIDlet
suite. The MIDlets in a MIDlet suite are packaged and
installed on a mobile device as a single entity, known as
the JAR file. The JAR file represents a MIDlet suite.
This chapter explains the lifecycle of MIDlets. Further, it
discusses executing and testing MIDlet applications. In
addition, it discusses the process of managing and building
a MIDlet suite.

Objectives
In this chapter, you will learn to:
Explain the lifecycle and execution of MIDlets
Manage a MIDlet suite
Run a sample program
Develop and obfuscate a MIDlet Suite

Understanding MIDlets
Applications that are developed by using Java ME APIs
are called MIDlets. MIDlets run on Java-enabled mobile
devices. Although MIDlets are similar to Java applets, the
following list states some differences between a MIDlet
and an applet:
An applet is a Java class file embedded into an
HTML page. On the other hand, a MIDlet is a
Java class file packaged into a Java Archive
(JAR) file.
An applet runs in a Web browser. On the other
hand, a MIDlet runs in an Application
Management Software (AMS) that is already
installed on MIDP devices. AMS provides an
environment for KVM and MIDlets.
An applet is viewed in a browser or applet viewer
tool on desktop computers. On the other hand, a
MIDlet is viewed on handheld devices that
support CLDC and MIDP.

Note
An AMS is a device dependent program that is
implemented by the manufacturers of mobile
device. The AMS is responsible for installing,

A MIDlet cannot use classes or interfaces other than those


provided by CLDC and MIDP APIs. Unlike other Java
applications, MIDlets do not have the main() method
and are not executed by using the Java interpreter.

Explaining the MIDlet Lifecycle


Similar to an applet, a MIDlet undergoes various changes
in its state. The life cycle of a MIDlet describes the
sequence of the MIDlets states. The life cycle begins
when a MIDlet is launched in a mobile device, paused
when a call comes onto the mobile device, and ends when
the MIDlet is destroyed.
A MIDlet inherits the properties and methods of the
MIDlet class, which is located in the
javax.microedition.midlet package of MIDP
APIs. The MIDlet class contains all the methods that
define the life cycle of a MIDlet. The MIDlet class
provides three basic methods, startApp(), pauseApp
(), and destroyApp() to control the execution of a
MIDlet.
The states of the MIDlet life cycle are:
Paused state: Indicates the state when a MIDlet
initially starts after the AMS launches it, or when
a MIDlet stops temporarily. This state is defined
by the pauseApp() method of the MIDlet
class.
Active state: Indicates the state when a MIDlet
gets the resources it needs and begins to perform
its service. This state is defined by the
startApp() method of the MIDlet class. To
place a MIDlet in the active state, the AMS calls
the startApp() method of the MIDlet class.
Destroyed state: Indicates the state when a
MIDlet is terminated. This state is defined by the
destroyApp() method of the MIDlet class.
The MIDlet may enter the destroyed state from
either the paused state or the active state.
The following figure shows the life cycle of a MIDlet.

Lifecycle of a MIDlet
The AMS controls the change from one MIDlet state to
another by using the startApp(), pauseApp(), and
destroyApp() methods of the MIDlet class.
When you run a MIDlet, the AMS creates an instance of
the MIDlet by using the MIDlet constructor, and the
MIDlet enters the paused state.
In the paused state, the AMS invokes the startApp()
method to start the MIDlet. After the startApp()
method is called, the MIDlet enters the active state. In this
state, the MIDlet obtains the resources to begin its
services.
If the AMS identifies that the active MIDlet is not
currently required, the AMS invokes the pauseApp()
method to pause the running MIDlet. When the MIDlet
reaches the paused state, it releases all the resources that it
has obtained in the active state.
The MIDlet can re-enter the active state if the AMS calls
the startApp() method again.
When the AMS identifies that the active MIDlet is no
longer required and a high priority MIDlet is waiting to be
run, then the AMS destroys the active MIDlet by calling
the destroyApp() method. The MIDlet releases all the
resources before entering the destroyed state.
An active MIDlet can send a request to the AMS to
prevent its entry in the destroyed state by throwing the
MIDletStateChangeException exception. This
occurs when the MIDlet is in the middle of an important
process. However, the AMS may or may not grant this
request. If the unconditional argument of the
destroyApp() method is set to true, the AMS ignores
the request from the MIDlet. However, the request is
granted if the unconditional argument is set to false
and the destroyApp() method is called after some
time.
A MIDlet can also request the AMS for a state change. In
this condition, the AMS will not call the pauseApp() or
destroyApp() method. If the MIDlet wants to enter
the paused state or the destroyed state, it can call the
notifyPause() method or the notifyDestroy()
method. The MIDlet needs to perform all resource
cleaning activities before notifying the AMS for a state
change.

Note
A MIDlet can re-enter the active state only
from the paused state. However, it can enter
the destroyed state from both the paused state
and the active state. A MIDlet can enter the
paused state either from the active state or
when the AMS initially launches the MIDlet.

The following code snippet shows the structure of a


MIDlet class:
public class MyMIDlet extends MIDlet {
// Defining the default constructor
of MIDlet class.
MyMIDlet( ) {
}
protected void startApp( ) throws
MIDletStateChangedException {
}
protected void pauseApp( ) {
}
protected void destroyApp(boolean
unconditional)
throws
MIDletStateChangedException {
}
}

Just a minute:
Ed Young is working as a mobile application
developer with Super Graphics. Ed is
developing a MIDlet to display news
headlines. Ed wants to stop the MIDlet
temporarily whenever a call comes during its
execution. How will Ed achieve this?

Answer:
Ed needs to use the pauseApp() method to
temporarily stop the news headlines
application.

Running and Testing the MIDlets


Once a MIDlet is created, it has to be tested to ensure that
the application runs successfully. If the MIDlet is
developed to run on different mobile devices, it needs to
be tested in each of these devices. Java Wireless Toolkit
along with an emulator provides a mechanism to simulate
(create a representation or model) these environments and
test the application. A successful emulator test increases
the probability of a MIDlet performing its operations on
the actual device.

Identifying the Functions of Java


Wireless Toolkit

The functions of Java Wireless Toolkit are:


Building and packaging: Compiles the source
code, verifies the class files, and packages the
MIDlets.
Running and monitoring: Enables you to run
and debug the MIDlets on a desktop computer by
using the Java ME emulator before actually
deploying the MIDlet on a mobile device.

Note
The Java ME emulator is a simulated
(computer-generated) environment
that you use to test a MIDlet
application before deploying it on a
mobile device.
MIDlet suite signing: The toolkit contains tools
for signing the MIDlets by using cryptography
(using secret codes instead of plain text). Signing
the MIDlets makes it a trusted application.

Note
Trusted application means that the application
is from an identified valid source. In addition,
trusted applications do not harm the mobile
device or its data in any way.

Describing Sun Java Wireless Toolkit


Sun Java Wireless Toolkit is a set of tools that you can use
to develop wireless applications based on the Java MEs
CLDC and MIDP. This toolkit also supports optional
packages such as WMA 2.0. The applications developed
by using the Sun Java Wireless Toolkit can run on mobile
devices such as mobile phones and PDAs.
The Sun Java Wireless Toolkit contains the following tools
to build and test Java ME applications in a simulated
environment:
WirelessToolkit: It is a development
environment for developing MIDlets. It provides
a visual environment to test and run the MIDlets.
You can use the Wireless toolkit to build, run, and
debug a MIDlet. You can also modify the
attributes of a MIDlet by using the Wireless
toolkit. It also makes it possible for the users to
select the appropriate mobile device emulator.
This ensures that the developed Java ME
application is compatible with the actual mobile
device for which the application is developed.
Wireless toolkit manages source code files

effectively and automates (make automatic) the


building process of MIDlets. In addition, it
provides all the utilities required to perform
preverification of code.
Emulator: It is an environment that allows code
to be tested on a computer. A MIDlet has to be
tested in real-life conditions before it is ready to
be deployed. This involves testing the MIDlet in
each device for which it is created. The Java ME
emulator provides an efficient environment to
perform this test. When the simulation is carried
out, the image of the device appears on the screen
and the application executes exactly as it would
execute on that particular device. The user can
interact with the device by using the mouse to
click the various buttons available on the device.
The Sun Java Wireless Toolkit does not provide an
Integrated Development Environment (IDE) to create,
view, and modify the source code. The Sun Java Wireless
Toolkit version 2.5.2 for CLDC is integrated with
NetBeans 6.0.1. Therefore, NetBeans 6.0.1 can be used to
write, test, and debug applications for the Java enabled
handheld devices.
There are different models of devices that you can
simulate by using the Java ME Emulator. Sun Java
Wireless Toolkit 2.5.2 for CLDC provides the following
models of emulator:
DefaultColorPhone
DefaultGrayPhone
MediaControlSkin
QwertyDevice
The DefaultColorPhone is a model of mobile phones that
supports color screens and DefaultGrayPhone supports
monochromatic screens.
The following figure shows the Emulator window for the
DefaultColorPhone emulator.

emulate various types of mobile devices. The following


figure shows the Emulator window for the
DefaultCldcPhone1 emulator included in Sun Java ME
SDK 3.0.

The DefaultColorPhone Emulator Window


The latest enhancement of the Sun Java Wireless Toolkit
2.5.2 for CLDC is Sun Java ME Software Development
Kit (SDK) 3.0. It provides several features, such as an IDE
and a device emulator, for developing mobile applications.
You can also use Sun Java ME SDK 3.0 for developing
applications for the CDC configuration.
Sun Java ME SDK 3.0 provides several emulators to

The DefaultCldcPhone1 Emulator Window

Managing MIDlet Suites


A MIDlet suite consists of one or more MIDlets packaged
in a JAR file. A MIDlet suite contains all the resources to
run a Java ME application on a mobile device.
The packaging and deployment of a Java ME MIDlet
application is different from that of a Java SE application.
For example, to package a MIDlet application, you need a
Java Application Descriptor (JAD) file. The JAD file is
not required for packaging an application in Java SE.

Note
The JAR file format is used for combining
many files into a single file. Creating a JAR
file helps in easier handling and distribution
of Java applications.

Describing MIDlet Suites


All the class files of a MIDlet application need to be
packaged into a JAR file. Each JAR file may contain more
than one MIDlet application. This group of MIDlet
applications is known as a MIDlet suite.
You can download a JAR file and install it in a mobile
device by using either a serial cable connected to a
computer or a wireless network. When the JAR file is
installed, a menu entry appears for each MIDlet in the
MIDlet suite. You can select and execute the required
MIDlet application from the menu entries.
The following figure shows various menu entries for each
MIDlet in a MIDlet suite.

Menu Entries for Each MIDlet in a MIDlet Suite


A MIDlet suite contains many other components apart
from the Java class files for a MIDlet.
A MIDlet suite has the following components:
A JAR file
A JAD file

Identifying the Components of a JAR


file

All the MIDlets are packaged in a JAR file for


distribution. A JAR file contains the following
components:
Java class files
Resources
A manifest file
The following figure shows the contents of a sample JAR
file.

MIDlet-Info-URL

MIDlet-<n>

MIDlet-Jar-URL

MIDlet-Jar-Size

Contents of a Sample JAR file

Java Class Files

MIDlet-Data-Size

The Java class files in a MIDlet suite are compiled files of


the Java source files. In a MIDlet suite, all Java class files
are packaged into a JAR file.

Resources
A MIDlet package also contains files other than the Java
class files, called resources. Resources include images or
data files needed to run the MIDlet.

Manifest File
In addition to class files and resource files, a JAR file also
contains a META-INF folder that has a manifest file called
manifest.mf. A manifest file provides information about
the contents of a JAR file. For example, the manifest.mf
file provides the name, version, and vendor of the MIDlet
suite.
A manifest file contains a list of MIDlet attributes, made
up of name-value pairs, separated by colons. These
attributes describe the MIDlets that you need to package in
a MIDlet suite.
The following table describes the MIDlet attributes of the
manifest file.
Attribute Name
MIDlet-Name

Description
It represents the name of the
MIDlet suite.
MIDlet-Version
It specifies the version
number of the MIDlet suite.
MIDlet-Vendor
It specifies the vendor that
provides the MIDlet suite.
MIDlet-Icon
It specifies the name of the
Portable Network Graphics
(PNG) file within the JAR
file used as an icon for the
MIDlet suite.
MIDlet-Description It provides the description of
the MIDlet suite.

MicroEditionProfile
MicroEditionConfiguration

It provides a Uniform
Resource Locator (URL),
which further describes the
MIDlet.
It specifies the name, icon,
and class of a MIDlet in a
series of MIDlets stored in
the JAR file. The n
parameter specifies the
position of the MIDlet in a
series of MIDlets.
It specifies the URL from
which the JAR file can be
downloaded.
It specifies the size of the
JAR file, in bytes.
It specifies the minimum
number
of
bytes
of
persistent data required by
MIDlets. The default value
of the MIDlet-Data-Size
attribute is zero.
It represents the required
Java ME profile.
It represents the required
Java ME configuration.

Table Describing the MIDlet Attributes of the


Manifest File

Just a minute:
Jerry Smith is working as an application
manager with Technology Systems. He wants
to know about the contents of the JAR file.
Which file should he open to access these
details?

Answer:
The manifest file
There are six mandatory attributes that you need to specify
in the manifest file. The application manager does not load
the JAR file, if any of these attributes are missing in the
manifest file.
The mandatory attributes of the manifest file are:
MIDlet-Name

MIDlet-Version
MIDlet-Vendor
MIDlet-<n> for each MIDlet in the
JAR file
MicroEdition-Profile
MicroEdition-Configuration
The following code snippet shows the contents of the
manifest.mf file for a sample application:
MIDlet-Name: HelloWorld
MIDlet-Vendor: AB Corp
MIDlet-Version: 1.0
MIDlet-1: HelloWorld, HelloWorld.png,
HelloWorld
MicroEdition-Configuration: CLDC-1.1
MicroEdition-Profile: MIDP-2.1
In the preceding code snippet, HelloWorld represents
the name of the MIDlet suite. The vendor name is AB
Corp, and the version of the MIDlet package is 1.0. The
MIDlet-1 parameter represents the attribute of the first
MIDlet in this MIDlet suite. If the MIDlet suite includes
more than one MIDlet, a separate entry MIDlet-<n> is
required, where n represents the nth MIDlet in the MIDlet
suite.
In the MIDlet-1 field, the first value, HelloWorld, is
the name of the MIDlet. HelloWorld.png is the icon
file of the MIDlet, and the second HelloWorld text
represents the class name of the MIDlet.

Identifying the Attributes of a JAD


File
You also need to include a JAD file in a MIDlet suite,
along with the JAR file of the application. The JAD file
contains information about a MIDlet suite.
The JAD file is included in a MIDlet suite to:
Provide information to the application manager
about the content of a JAR file. For example, the
application manager can determine if a MIDlet
requires more memory than the mobile device
can provide, by looking at the MIDlet-DataSize attribute of the JAD file.
Provide a MIDlet access to its attributes. For
example, a MIDlet can access the attributes of a
JAD file through the getAppProperty()
method of the MIDlet class.
There are certain mandatory attributes that you need to
define in a JAD file. If these attributes are not defined, the
application manager will not load the MIDlet. These
mandatory attributes are:
MIDlet-Name
MIDlet-Version
MIDlet-Vendor
MIDlet-<n> for each MIDlet
MIDlet-Jar-URL
MIDlet-Jar-Size

The values of the MIDlet-Name, MIDlet-Version,


and MIDlet-Vendor attributes need to be the same as
the values of the respective attributes in the manifest file
of JAR. If there is any difference in the files, the
application manager does not load the JAR file. However,
if only the MIDlet-Jar-size attribute value is
different in the two files, the application manager will
consider the value of the JAD file. In addition, if any
attribute that is not mandatory is missing from the JAD
file, the corresponding attribute of the manifest file is
taken as default.
The following code snippet shows the contents of a JAD
file for a sample application:
MIDlet-Name: HelloWorld
MIDlet-Vendor: Unknown
MIDlet-Version: 1.0
MIDlet-1: HelloWorld, HelloWorld.png,
HelloWorld
MIDlet-Jar-URL: http://
www.webinfo.com/MIDlets/HelloWorld.jar
MIDlet-Jar-Size: 23653

Invoking and Closing MIDlets in


Suites
When a MIDlet suite is downloaded in a mobile device,
the application manager can invoke any MIDlet present in
a MIDlet suite. Because the application manager is device
dependent, the invoking mechanism of MIDlets is
different for different mobile devices.
When an application manager invokes a MIDlet, it
invokes the startApp() method to start the MIDlet.
It also makes the following components accessible to the
MIDlet:
CLDC and KVM: Specifies that MIDlets can
use all classes defined within the CLDC.
MIDP defined classes: Specifies that MIDlets
can use all classes defined within the MIDP.
These classes define various functions, such as
UIs and network support, for a mobile device.
JAR file: Specifies that MIDlets can access
classes and other resources, such as images,
present within the JAR file.
JAD file: Specifies that MIDlets can access a
JAD file.
To close a MIDlet from a MIDlet suite, the application
manager calls the destroyApp() method.

Just a minute:
John Barrett is working as a mobile
application developer with XYZ Inc. John
wants to create a manifest file to describe the
MIDlets that he needs to package in a MIDlet
suite. Identify the MIDlet attributes that John
should use to specify the URL from where the
JAR file can be downloaded.

Answer:
MIDlet-Jar-URL

Describing the MIDlet Building


Process
The building process of a MIDlet specifies various tasks
that need to be performed to implement a MIDlet.
To build a MIDlet, you need to perform the following
tasks:
1. Compile the MIDlet.
2. Verify the MIDlet.
3. JAR the MIDlet.
In addition to the preceding tasks, a MIDlet is obfuscated
in order to reduce the size of the application.

Compiling the MIDlet


Compilation is the process of compiling the Java source
files into executable byte code. The compiler of the virtual
machine compiles the Java source code.

Verifying the MIDlet


Class file verification is the process of verifying all classes
within a MIDlet suite to ensure that mobile applications do
not perform incorrect operations. The class file
verification for MIDlet suites is performed by the KVM in
the following two phases:
Preverification
In-device verification
The following figure shows how the KVM verifies the
class files in a MIDlet.

The Verification Process of a MIDlet

Preverification
The preverification process is performed before a class file
is loaded on a mobile device. The preverification process
reduces the amount of work done by the mobile device.
This is important because a mobile device has limited
memory and cannot support complete verification of class
files.
In the preverification process, additional attributes are
inserted in the class file by a software program called
preverifier. These additional attributes help in describing
the class as preverified. They also provide information that
reduces the amount of time and memory necessary for the
KVM to perform the verification. After the preverification
process, the size of the class files becomes approximately
5% larger than its previous size.

In-Device Verification
The in-device verification is a verification process that is
performed by the in-device verifier present in the KVM of
the mobile device. When a mobile device loads a
preverified class file, the in-device verifier verifies the
syntax of the Java class files. When the in-device verifier
finds an error in a class file, it reports the error and rejects
the class file.

Jaring the MIDlet


In the jaring process, the MIDlets are packaged into a
single JAR file. This JAR file includes all the class files,
resource files, and manifest file of a MIDlet application.
NetBeans performs the jaring process automatically when
a project is built.

Note
You can find the JAR file in the dist folder of
the projects root directory.

Obfuscating the MIDlet


The compiled class files of Java can be reverse engineered
to produce the Java source files by using a tool called
decompiler. This process is a threat to the Java source
files. Obfuscation prevents this threat by preventing
reverse engineering.
In other words, obfuscation refers to the process of
obscuring Java classes, making them difficult to
decompile back into source code.
Further, obfuscation also helps in reducing the size of the
Java byte code of a MIDlet application. Obfuscation helps
in reducing the time required to download the MIDlet
application in a mobile device. It also helps in securing the
Java source code of a MIDlet application.
The obfuscation process removes information such as
comments, line numbers, and local variable names present
in the Java source files. After this information is removed,
any attempt at reverse engineering is not successful. This
is because the information that is derived after
decompiling the Java source files becomes very difficult to
understand.

MIDlet. In order to execute the Hello MIDlet, Steve needs


to perform the following tasks:
1. Open the Hello MIDlet.
2. Run the Hello MIDlet.

Task 1: Opening the Hello MIDlet


To open the Hello MIDlet, Steve needs to perform the
following steps:
1. Select startAll ProgramsNetBeans
6.0.1NetBeans IDE to open the NetBeans
IDE 6.0.1 window, as shown in the following
figure.

Note
Decompiling is the reverse process of
compilation, where you can retrieve the source
files from the compiled Java files. This process
is performed with the help of a tool called
decompiler.

The NetBeans IDE 6.0.1 Window


2. Select FileNew Project. The New Project
dialogbox appears, as shown in the following
figure.

Obfuscation also reduces the size of Java classes by


removing additional information and replacing large
identifiers. For example, obfuscation replaces the variable
names and source file names with machine-generated
names.

Running a Sample Program


Problem Statement
Steve has recently joined the SkyBlue service provider as
a Wireless developer. He is assigned the task to create a
new mobile application by using Java ME. For this, Steve
is allocated a system that has NetBeans 6.0.1 already
installed on it. However, Steve needs to check whether the
installation is performed correctly by executing a sample
application.

Solution
To check whether the installation is performed correctly,
Steve needs to execute the sample application, Hello

The New Project Dialog Box


3. Select the Mobility option from the Categories
section.
4. Ensure that the MIDP Application option is
selected in the Projects section.
5. Click the Next button. The Name and Location
page is displayed, as shown in the following
figure.

The Name and Location Page


6. Type HelloWorld in the Project Name text box.
7. Type <Drive Letter>:\JavaMEProjects in the
Project Location text box.

The More Configurations Selection Page


10. Click the Finish button. The HelloWorld NetBeans IDE 6.0.1 window with the current
status of the HelloWorld project appears, as
shown in the following figure.

Note
<Drive Letter> indicates the letter
assigned by the Operating System to
the drive.
8. Click the Next button. The Default Platform
Selection page is displayed, as shown in the
following figure.

The HelloWorld - NetBeans 6.0.1 Window

Task 2: Running the Hello MIDlet


To run the Hello MIDlet, Steve needs to perform the
following steps:
1. Select BuildBuild Main Project to build the
HelloWorld project.
2. Select RunRun Main Project to run the
HelloWorld project. The DefaultColorPhone
emulator window is displayed, as shown in the
following figure.

The Default Platform Selection Page


9. Click the Next button. The More Configurations
Selection page is displayed, as shown in the
following figure.

The DefaultColorPhone Emulator Window


3. Click the soft key below Launch on the
DefaultColorPhone emulator window to display
the text Hello Hello, World! on the emulator
screen, as shown in the following figure.

The DefaultColorPhone Emulator Displaying


the Output
4. Select MIDletExit to close the
DefaultColorPhone emulator window.
5. Select FileExit to close the NetBeansIDE.

Developing and Obfuscating a


MIDlet Suite
Problem Statement
Steve is working as a Wireless developer with SkyBlue
service provider. He is given applications that provide
real-time updates on various types of information, such as

News, Cricket, and Stock. Each application is in the form


of a MIDlet. Steve is asked to create a MIDlet suite for
these MIDlets and reduce its size to improve the
applications performance on a mobile device.
Prerequisite: The following input files are required for
performing this activity:
Cricket.java
CricketMidlet.java
News.java
NewsMidlet.java
StockUpdate.java
StockUpdateMidlet.java
\icons\CricketProgram.png
\icons\NewsProgram.png
\icons\StockUpdateProgram.png
Ask your faculty to provide the preceding input files.

Solution
To create the required MIDlet suite, Steve needs to
perform the following tasks:
1. Create a MIDlet suite project.
2. Obfuscate and build the MIDlet suite project.

Task 1: Creating a MIDlet Suite Project


To create a MIDlet suite project, Steve needs to perform
the following steps:
1. Select startAll
ProgramsNetBeansNetBeans IDE 6.0.1 to
open the NetBeans IDE 6.0.1 window.
2. Select FileNew Project to open the New
Project dialog box.
3. Ensure that the Mobility option is selected in the
Categories section.
4. Ensure that the MIDP Application option is
selected in the Projects section.
5. Click the Next button. The Name and Location
page is displayed.
6. Type MIDletSuiteDemo in the Project Name
text box to assign a name to the new project.
7. Type <Drive Letter>:\JavaMEProjects as the
location of the project in the Project Location
text box.
8. Clear the Create Hello MIDlet check box.
9. Ensure that the Set as Main Project check box is
selected.
10. Click the Next button. The Default Platform
Selection page is displayed.
11. Click the Next button. The More Configurations
Selection page is displayed.
12. Click the Finish button to create the
MIDletSuiteDemo project.
13. Right-click the MIDletSuiteDemo node under
the Projects tab, and then select NewJava
Package from the pop-up menu. The New Java
Package dialog box appears, as shown the

following figure.

The New Java Package Dialog Box


14. Type example.MidletSuit in the Package Name
text box.
15. Click the Finish button.
16. Copy the input files, Cricket. java,
CicketMidlet.java, News.java,
NewsMidlet.java, StockUpdate.java, and
StockUpdateMidlet.java, to the <Drive
Letter>:\JavaMEProjects\MIDletSuiteDemo
\src\example\MidletSuit folder.
17. Copy the icons folder to the <Drive Letter>:
\JavaMEProjects\MIDletSuiteDemo\src folder.
18. Switch to the MIDletSuiteDemo - NetBeans
IDE 6.0.1 Window.
19. Right-click the MIDletSuiteDemo node under
the Projects tab and select the Properties option
from the pop-up menu. The MIDletSuiteDemo
dialog box appears, as shown in the following
figure.

The MIDletSuiteDemo Dialog Box


20. Select the ApplicationDescriptor node from the
category section.
21. Select the MIDlets tab on the MIDletSuiteDemo
dialog box.
22. Click the Add button. The Add MIDlet dialog
box appears, as shown in the following figure.

36. Click the OK button. The control returns to the


MIDletSuiteDemo dialog box, as shown in the
following figure.

The Add MIDlet Dialog Box


23. Type StockUpdate in the MIDlet Name text
box.
24. Ensure that
example.MidletSuit.StockUpdateMidlet is
selected in the MIDletClass drop-down list.
25. Select /icons/StockUpdateProgram.png from
the MIDlet Icon drop-down list.
26. Click the OK button to add the StockUpdate
MIDlet. The details of the StockUpdate MIDlet
are displayed in the MIDletsintheSuite section,
as shown in the following figure.

TheMIDletSuiteDemo Dialog Box


27. Click the Add button to open the Add MIDlet
dialog box.
28. Type News in the MIDlet Name text box.
29. Select example.MidletSuit.NewsMidlet from
the MIDlet Class drop-down list.
30. Select /icons/NewsProgram.png from the
MIDlet Icon drop-down list.
31. Click the OK button.
32. Click the Add button to open the Add MIDlet
dialog box.
33. Type Cricket in the MIDlet Name text box.
34. Select example.MidletSuit.CricketMidlet from
the MIDlet Class drop-down list.
35. Select /icons/CricketProgram.png from the
MIDlet Icon drop-down list.

TheMIDletSuiteDemo Dialog Box


37. Select the Obfuscating option under the Build
node of the Categories section. The Obfuscation
Level details are displayed, as shown in the
following figure.

The MIDletSuiteDemo Dialog Box displaying


Obfuscation Level Details

Task 2: Obfuscating and Building the


MIDlet Suite Project
To obfuscate and build the MIDletSuiteDemo project,
Steve needs to perform the following steps:
1. Use Obfuscation Lever to set the Obfuscation
Level as High.
2. Click the OK button to close the
MIDletSuiteDemo dialog box.
3. Select BuildBuild Main Project to build the
project.

Note
Steve can note that size of the JAR file
has reduced after obfuscation by
checking the sizes of the beforeobfuscation.jar and obfuscated.jar
files in the \MIDLetSuiteDemo\build
folder.
4. Select MIDletExit to close the
DefaultColorPhone emulator window.
5. Select FileExit to close the NetBeansIDE.

Summary
In this chapter, you learned that:
Applications that are developed by using Java
ME APIs are called MIDlets.
The states of the MIDlet life cycle are:
Paused state
Active state
Destroyed state
The AMS controls the change from one MIDlet
state to another by using the startApp(),
pauseApp(), and destroyApp() methods
of the MIDlet class.
An active MIDlet can send a request to the AMS
to prevent its entry in the destroyed state by
throwing the
MIDletStateChangeException
exception.
Sun Java Wireless Toolkit is a set of tools that
you can use to develop wireless applications
based on the Java MEs CLDC and MIDP.
The functions of Java Wireless Toolkit are:
Building and packaging
Running and monitoring
MIDlet suite signing
The Sun Java Wireless Toolkit contains the
following tools to build and test Java ME
applications in a simulated environment:
Wireless Toolkit
Emulator
The Sun Java Wireless Toolkit does not provide
an integrated editor to create, view, and modify
the source code.
The Sun Java Wireless Toolkit version 2.5.2 for
CLDC is integrated with NetBeans 6.0.1 that can
be used to write, test, and debug applications for
the Java enabled handheld devices.
Sun Java Platform ME SDK 3.0 is a toolkit that
can be used for developing mobile applications.
Java ME SDK 3.0 is a successor of Sun Java
Wireless Toolkit 2.5.2 for CLDC that provides
several features for developing mobile

applications.
A MIDlet suite consists of one or more MIDlets
packaged in a JAR file.
A MIDlet suite contains the following
components:
A JAR file
A JAD file
All the MIDlets are packaged in a JAR file to
distribute the application. The JAR file contains
the following components:
Java class files
Resources
A manifest file
The building process of a MIDlet specifies the
various tasks that need to be performed to
implement a MIDlet.
To build a MIDlet, you need to perform the
following tasks:
a. Compile the MIDlet.
b. Verify the MIDlet.
c. JAR the MIDlet.
Obfuscation refers to the process of obscuring
Java classes, making them difficult to decompile
back into source code.

Exercises
Exercise 1
You are working as a wireless application developer with
SkyBlue service provider. The organization has opened its
new subsidiary and you are posted to the new office. You
are assigned a new project to develop a mobile gaming
application for the customers of SkyBlue service provider.
The computer that has been assigned to you does not have
NetBeans 6.0.1 installed.
You need to install NetBeans 6.0.1. After the installation,
you need to test the installation by running a Hello
MIDlet.

Note
Ensure that NetBeans 6.0.1 is not installed on
your machine before performing this exercise.

Exercise 2
You are working as a wireless application developer with
SkyBlue service provider. The organization needs to
provide a new service for its existing customers. With this

service, the customers can view information about latest


movie updates, jokes, and news on their mobile devices.
You have already created three MIDlet classes for movies,
jokes, and news. All the three MIDlet classes have to be
packaged into a MIDlet suite.
You need to create a new project, build it, and test the
project by using NetBeans 6.0.1. In addition, you need to
reduce its size to ensure that the application performs
efficiently in a mobile device.
Prerequisites: The following files are required to run the
application:
/icons/Jokes.png
/icons/Movies.png
/icons/News.png
/source Files/Jokes.java
/source Files/JokesMidlet.java
/source Files/MoviesUpdate.java
/source Files/MoviesUpdateMidlet.java
/source Files/NewsUpdate.java
/source Files/NewsUpdateMidlet.java

Reference Reading
Understanding Midlets
Reference Reading: Books
J2ME in a Nutshell: By Kim
Topley
Publisher: OReilly
Enterprise J2ME:
Developing Mobile Java
Applications
By John W. Muchow
Publisher: Prentice Hall
PTR.

Reference Reading: URLs


http://developers.sun.com/
techtopics/mobility/learn/
midp/lifecycle/

Managing MIDlet Suites


Reference Reading: Books
J2ME in a Nutshell: By Kim
Topley
Publisher: OReilly
Wireless J2ME Platform
Programming
By Vartan Piroumian
Publisher: Prentice Hall
PTR.

Reference Reading: URLs


http://www.onjava.com/pub/
a/onjava/2001/04/26/
midlet.html
http://www.onjava.com/
pub/a/onjava/2001/04/26/
midlet.html

Chapter 3
Describing the MIDlet User
Interface
Java ME is used to develop applications for mobile
devices. These applications are user interactive that
require various UI components. Users can interact with the
application by using these components.
As mobile devices have limited resources, various UI
design considerations have to be kept in mind while
developing UIs for them. The two types of UIs that are
created for mobile devices are high-level and low-level
UIs. MIDP UI APIs provide various classes and interfaces
to develop both types of UIs.
This chapter describes MIDP UI APIs. Further, it discusses
the UI design considerations in mobile devices. In
addition, it describes the type and environment of MIDP
UIs. It also discusses various classes and interfaces
provided in the javax.microedition.lcdui
package that are used for implementing MIDP UI
components.

Objectives
In this chapter, you will learn to:
Identify MIDP UIs
Work with MIDP UIs

Identifying the MIDP UI


Java ME is used to create applications for a variety of
mobile devices, such as mobile phones and PDAs. These
devices differ in terms of display screens and resources.
As a result, there is no common standard UI API or
package for creating UIs of Java ME applications. The
JTWI specification defines a number of UI APIs based on
resources and display capabilities of various devices. For
example, the MIDP UI APIs define the classes and
interfaces for mobile devices with limited memory and
display capabilities.
The UI of a mobile application is made up of various
components, such as forms, lists, and text boxes. These
components enable users to interact with the application.
The following figure shows some UI components of a
mobile device.

Some UI Components of a Mobile Device


You can create custom UI components for a mobile
application by using MIDP UI APIs.

Introducing MIDP UI APIs


MIDP provides the javax.microedition.lcdui
package. This package contains various classes, such as
Form, Screen, and Alert, to implement MIDP UI
components. You can extend or use these classes to create
the UI of mobile applications. The UI components of
mobile applications can receive input by using eventhandling classes defined in MIDP UI APIs.
MIDP UI APIs are not based on Abstract Windows Toolkit
(AWT), which is used to create the UIs in J2SE. The AWT
uses a large amount of display and memory resources.
Therefore, it cannot be used to create UIs for mobile
devices that are limited in display and memory resources.
The MIDP UI API contains a new set of classes and
interfaces for creating UIs of such devices. However,
many UI design considerations need to be kept in mind
while creating UIs of such resource-limited devices.

UI Design Considerations in a Mobile


Device
The features of UIs in mobile devices are different from
the UIs of the computers on which desktop applications
run. For example, a desktop computer always has a
pointing device, such as a mouse, attached to it. Whereas,
most mobile phones do not have any pointing devices
attached to them. As a result, a mobile application has
different UI design restrictions as compared to a desktop
application.
The UI design restrictions in mobile devices are:
Screen size: The size of a mobile device screen is
smaller than that of a desktop computer screen.
As a result, you will be able to display less
number of UI components on the screen of a

mobile device.
Number of colors and resolution: The screen
resolution and number of displayable colors on a
mobile device screen are less than those of a
desktop computer screen. As a result, you need to
minimize the number of colors and resolution of
UI components in a mobile application.
Memory requirements: The memory capacity of
mobile devices is very small as compared to
desktop computers. As a result, the UI of mobile
devices should use minimum memory resources.
Number of UI components: The number and
types of UI components for a mobile application
is less as compared to the number and types of UI
components in a desktop application. This is
because the display area and input hardware of
mobile devices are limited. For example,
consider an e-mail registration form in a desktop
application. This form has many UI components,
such as drop-down list and calendar control. On
the other hand, a similar form in a mobile
application will have very few UI components,
such as text fields or string items.
Number of input keys: The number of input
keys in a mobile device keypad is less as
compared to the keyboard of desktop computers.
Therefore, you need to develop application inputs
and shortcuts to overcome the input restriction of
mobile devices. For example, you do not have
Page Up and Page Down buttons in a mobile
device keypad. Therefore, to access the previous
page and next page, you can add a hyperlink in
your application.

However, you cannot display the online help and play a


game at the same time.

Environment for MIDP UI


The MIDP UI APIs provide a screen-based environment
for creating UIs for mobile applications. The screen-based
environment is similar to the window-based environment
of desktop computers. There are two types of screens that
can be developed by using MIDP UI APIs. However, the
types of screens depend upon the types of interfaces
developed by the MIDP UI APIs. The types of screens are:
Structured Screens: These screens are created
by using high-level UI APIs. The high-level UI
APIs help you to create structured screens by
providing UI components, such as buttons. You
can use structured screens with different mobile
devices but you cannot control the structured
screens.
Unstructured Screens: These screens are created
by using low-level UI APIs. The low-level UI
APIs helps you to createunstructured screens by
providing various classes and methods to create
UIs of mobile devices.

Just a minute:
State whether the following statement is true
or false.

Types of MIDP UI
Depending upon the preceding restrictions of the mobile
devices, MIDP can be used to develop the following types
of interfaces:
High-level: The high-level UI APIs enable you to
create portable UI components, which can be
used in a variety of mobile devices. For example,
you can use high level APIs to create a menu
item, such as an inbox, for mobile devices.
Low-level: The low-level UI APIs enable you to
create highly customized interfaces for mobile
applications. For example, low-level APIs allow
you to develop interface for game applications.
The UI components created by using low-level
APIs are device-dependent and therefore, are not
portable across various device types.
A single MIDlet can provide both high-level and low-level
UI APIs, but you cannot use them at the same time. For
example, you can use high-level UI APIs to create online
help for a mobile game and low-level UI APIs to create
the interface and control the graphical objects of the game.

MIDP UI API defines classes and interfaces


to create UI in mobile applications.

Answer:
True

Just a minute:
State whether the following statement is true
or false.
MIDP UI API is based on AWT, which is used
for creating UI in J2SE.

Answer:

or false.

False

Comparing High-Level and LowLevel UI APIs


Besides the types of screens, the high-level and low-level
UI APIs differ from each other in many other features. The
following table lists the differences between high-level
and low-level UI APIs.
High-level UI APIs
Low-level UI APIs
They support widget-based They support pixel-based
model. A widget is a model.
reusable UI component,
such as buttons and text
boxes.
They
contain
several They contain four classes:
classes, such as Screen and Canvas, Graphics, Font,
Item. These classes provide and Image. These classes
UI components, such as help
you
to
create
buttons, which you can use customized UIs for mobile
to create UI for mobile devices.
devices.
They provide the portability They provide device-specific
feature, which enables you support for creating UIs. As
to use the same UI a result, you cannot display
components for several the same low-level UI
mobile devices.
component on different
mobile devices.
They restrict you from They provide methods to
controlling
the
display control the display screen of
screen of a mobile device. a mobile device.
They do not control the user They enable you to control
inputs to a mobile device. the user inputs to a mobile
device.
They provide support for They provide support for
structured screens.
unstructured screens.

Differences Between High-level and Low-level UI


APIs

Just a minute:
State whether the following statement is true

Low level UI APIs support pixel-based model


and provide device-specific support for
creating UIs.

Answer:
True

Working with MIDP UI


The classes and interfaces provided in the
javax.microedition.lcdui package of the MIDP
UI can be used to create the UI for mobile applications.
The MIDP UI contains several classes. The following
classes are some of the important classes at the top of the
hierarchy of the javax.microedition.lcdui
package:
Display: Every MIDlet has its own Display
class that manages the screen and input keys of a
mobile device. The Display class handles the
graphical information that a mobile device
displays.
Displayable: The Displayable object
represents the graphical information that is to be
displayed on the display device. You can have a
number of Displayable objects in an
application. However, at a time, the application
can display only one Displayable object on
the display device, which is referred to as current
Displayable object.
The object of the Display class is responsible for
managing and changing the Displayable objects in a
UI. You can change the current Displayable object by
using the setCurrent() method of the Display
class. In addition, you can use the getCurrent()
method of the Display class to retrieve the current
Displayable object.
The difference between the Display class and
Displayable class is that the Display class
represents the display device, whereas the
Displayable class represents the object that can be
shown on the display device. In addition, there is exactly
one instance of Display class per MIDlet.
The following figure shows a relationship between the
MIDlet, Display, and Displayable classes.

Relationship Between MIDlet, Display, and


Displayable classes
When a MIDlet application runs, the initial
Displayable object is displayed. The current
Displayable object changes when:
A user interacts. The Displayable object may
change in response to a user action. The events
generated by user inputs are traced and the
methods of the Display class are used to
change the current Displayable object.
A thread interferes. A thread may also change the
current Displayable object in response to
some event.
The timer of an alarm elapses.

class

Describing the MIDP Component


Hierarchy
The javax.microedition.lcdui package contains
various classes, such as Display and Displayable,
that help you to create effective UIs for mobile
applications. These classes are arranged in a hierarchy
according to their usage.
The Displayable class is an abstract class. It is at the
top of the hierarchy. The two classes, Screen and
Canvas, are derived from the Displayable class. The
Screen class and its subclasses are used to implement
high-level UI APIs, and the Canvas class is used to
implement low-level UI APIs.
The following figure shows the hierarchy of the
Displayable class.

Just a minute:
Don Allen is working as a mobile application
developer with Super Graphics. He is using
MIDP UI API to create the UI of a mobile
device. He wants to manage the display and
input hardware of the mobile device. Which
class of the
javax.microedition.lcdui package
should Don use to perform this task?

Answer:
The Display class

The Displayable Class Hierarchy

Describing the Displayable Class


and its Methods

Just a minute:
Jim Lewis is working as a software developer
with LMN Inc. Jim is developing a graphical
application for mobile devices. Jim wants to
change the current Displayable object. Which
method should Jim use to perform the
preceding task?

Answer:
The setCurrent() method of the Display

The Displayable class controls the device-specific


display of the graphics. For example, the Displayable
class is responsible for controlling how a MIDlet would be
displayed on display devices having different screen sizes.
The Displayable class provides methods to control
and modify Displayable objects. The following table
describes the methods defined in the Displayable
class.
Method
Description
addCommand(Command Adds a Command type
cmd)
object to the current
Displayable object.
getHeight()
Returns the height of the

screen area available for


displaying
the
UI
components.
getTicker()
Returns the Ticker object
used
by
the
current
Displayable object.
getTitle()
Returns the title of the
current Displayable object.
getWidth()
Returns the width of the
screen area available for
displaying
the
UI
components.
isShown()
Checks if the current
Displayable object is visible
on the display.
removeCommand
Removes a command from
(Command cmd)
the current Displayable
object.
setCommandListener Replaces
the
current
(CommandListener L) CommandListener
object
with
the
specified
CommandListener.
On
successful execution of this
method, the new object, L is
used to listen for the
commands on the current
displayable.
setTicker(Ticker
Sets the specified Ticker
tick)
object, tick, to be used as a
ticker with the current
displayable, replacing the
previous tickers.
setTitle(String s) Sets the specified title, s, as
the title of the current
Displayable object.
sizeChanged(int
Is
invoked
by
the
width, int height) Displayable
class
implementation when the
size of available area to the
Displayable
object
is
changed.

Methods of the Displayable Class

Note
Ticker is used to display the text that runs
continuously across the screen of a mobile
device. The Ticker class is defined in the
javax.microedition.lcdui package.

Describing the Display Class and its


Methods
You can manage the content that is to be displayed on a
mobile device by using the methods of the Display
class.
Each MIDlet application contains a single instance of the
Display class. You can retrieve a reference to the
Display class object by invoking the getDisplay()
method.
The following table describes the commonly used methods
of the Display class.
Method
Description
flashBacklight(int Enables the flashing effect
time)
of the mobile device
backlight for the specified
duration, which is passed as
an int value to the method.
getColor(int
Returns a color from the
colspecifier)
high level UI color scheme
based on a color specifier
passed as an int value to the
method.
getCurrent()
Returns the object, which is
being currently displayed.
isColor()
Returns the information
about the color support of
the device. This method
returns a true value if the
device supports colors.
NumColors()
Returns the total number of
displayable colors of the
mobile device.
SetCurrent(Alert
Specifies that the alert1
alert1, Displayable object
is
currently
d1)
displayable and the d1
object is displayed after the
alert1 object.
setCurrent
Specifies the d1 object as
(Displayable d1)
the current displayable.
vibrate(int
Requests
the
device
duration)
hardware to invoke the
device vibrator for a
specified duration.
setLabel(String
Sets the items label, which
label)
is passed as a String
parameter to this method.
setLayout(int
Sets the items layout
Layout)
directive, which is passed as
an int parameter to this
method.

setPreferredSize
Sets the preferred size of the
(int
width,
int item, which is specified in
height)
terms of width and height.

Commonly Used Methods of the Display Class

Summary
In this chapter, you learned that:
You can create custom UI components for your
mobile application by using MIDP UI API.
MIDP provides the
javax.microedition.lcdui package,
which contains classes, such as Form, Screen,
and Alert, to implement the UI components.
The UI design restrictions in mobile devices are:
Screen size
Number of colors and resolution
Memory requirements
Number of UI components
Number of input keys
MIDP can be used to develop the following two
types of interfaces:
High-level
Low-level
The high-level UI API enables you to create
portable UI components, which can be used in a
variety of mobile devices.
The low-level UI API enables you to create
highly customized interfaces for your mobile
applications.
Both high-level and low-level UI APIs provide
two different types of screens. These are:
Structured
Unstructured
Some of the classes of the
javax.microedition.lcdui package are:
Display
Displayable
Each MIDlet has its own Display class that
manages the screen and input keys of a mobile
device.
The Displayable object represents the
graphical information that is to be displayed.
The Displayable class is an abstract class at
the top of the hierarchy, and the two classes,
Screen and Canvas are derived from it.
The Screen class and its subclasses are used to
implement high level UI APIs, and the Canvas
class is used to implement low level UI APIs.
You can show a Displayable object by
setting it to current displayable by using the
setCurrent() method of the Display class.

Reference Reading
Identifying the MIDP UI
Reference Reading: Books
J2ME in a Nutshell: By Kim
Topley
Publisher: OReilly
Wireless J2ME Platform
Programming
By Vartan Piroumian
Publisher: Prentice Hall
PTR.

Reference Reading: URLs


http://www.onjava.com/pub/
a/onjava/excerpt/
wirelessjava_ch5/
index2.html
http://www.onjava.com/pub/
a/onjava/excerpt/
wirelessjava_ch5/
index1.html

Working with MIDP UI


Reference Reading: Books
J2ME in a Nutshell: By Kim
Topley
Publisher: OReilly
Enterprise J2ME:
Developing Mobile Java
Applications
By John W. Muchow
Publisher: Prentice Hall
PTR.

Reference Reading: URLs


http://developers.sun.com/
techtopics/mobility/midp/
articles/event/

Chapter 4
Introducing High-Level UI APIs-I
The high-level UI of mobile applications is made up of
various types of screens, such as lists, text boxes, and
forms. These screens are created by using the methods
provided by the Screen class and its subclasses. A form
is a special type of screen that further contains elements in
it. The elements of the form are UI components that are
created by using the methods of the Item class and its
subclasses.
This chapter discusses various classes of high-level UI
APIs. It introduces various types of screens that can be
developed by using the Screen class and its subclasses.
Further, it discusses the use of the Item class and its
subclasses that are used to create UI components to be
displayed on a form.

Objectives
In this chapter, you will learn to:
Work with different types of screens and their
elements
Work with the Item class and its subclasses

Working with Screen and its


Elements
The high-level UI APIs defined in MIDP UI contains
ready-to-use UI components for creating UIs of mobile
applications. All the high-level UI components have the
Screen class as their superclass. The following figure
shows the relationship between various classes in highlevel UI.

Relationship Between Various Classes in High-level


UI
The Screen class is used to display the objects on the
screen of a mobile device. It is a subclass of the
Displayable class. Various classes are derived from
the Screen class to implement various types of screens.
The four classes that are derived from the Screen class
are:
List: Creates a screen containing a list of
elements. A user can scroll through the list of
elements and select them. The phonebook of a
mobile phone is implemented using the List
class.
TextBox: Displays a text box on the screen of a
mobile device. You can enter and edit the text in
the text box. The SMS compose window of a
mobile phone is created by using the TextBox
class. This text box covers the entire screen of the
mobile device.
Alert: Displays an alert screen to the user for a
specified time and then displays the next screen
(The Displayable object). An Alert object
contains a text string and an image. You can use
the Alert objects to notify the users about some
event. For example, you can create an Alert
object to notify the users about the deletion of an
SMS message from the Inbox of a mobile phone.
In this case, the alert covers the entire screen of
the mobile device. You can also implement an
alert to notify users about errors and exceptions
occurring in a MIDlet.
Form: Displays a form containing items, such as

text fields, images, and choice groups. For


example, you can create a registration form that
consists of text boxes and radio buttons to enable
the users to fill in their details. Items used in the
form are instances of classes that are derived
from the Item class. One form can have several
items on it.

Implementing List
The List class, derived from the Screen class,
implements a list of elements from which a user can select
one or more elements.
The List class contains two constructors that help to
create List objects with the specified parameters. The
constructors defined in the List class are:
List(String title, int ListType):
Generates a new List object with a specified
title and type.
List(String title, int ListType,
String[] elements, Image[]
ImageElements): Generates aList object
with a specified title, type, array of elements, and
their images.
The List class implements the Choice interface to
define various types of lists. Various list choices that you
can specify for list types are:
List.EXCLUSIVE: Allows you to select
exactly one element at a time. When
implemented in code, this field shows a radio
button with each element of the list on the screen
of the mobile device.
List.MULTIPLE: Allows you to select multiple
elements at a time. It shows a check box with
each element of the list on the screen of the
mobile device.
List.IMPLICIT: Allows you to select an
element and give confirmation for the selected
element. When a user selects an element, the list
immediately fires off an event. It shows only the
elements of the list, without any radio button or
check box on the screen of the mobile device.
The preceding list choices are inherited from the Choice
interface. The following figure shows various types of lists
that can be created by using the List class.

Various Types of Lists


After creating a list, you can use the methods of the List
class to perform various operations on the list.
The following table describes some methods defined in the
List class.
Method
Description
append(String
Appends
the
specified
stringpart,
Image element after the last
imagepart)
element of the List object.
The text and image of the
element are passed as
parameters to this method.
delete(int Indexno) Removes the element with
the specified index number.
deleteAll()
Deletes all elements from a
List object.
getImage(int
Retrieves the image of an
Indexno)
element with the specified
index number.
getSelectedIndex() Returns the index number of
the
currently
selected
element.
getString(int
Returns the text of the
Indexno)
element with the specified
index number.
insert(int Indexno, Inserts an element in the
String text, Image List object before the
img)
element with the specified
index number. The text and
image of the element to be
inserted are also specified
as parameters to the
method.
isSelected(int
Returns a Boolean value
Indexno)
indicating whether or not
the element with the
specified index number is
currently selected.
removeCommand
Removes
the
specified
(Command cmd)
Command object from the
current list.
set(int elementNum, Replaces
the
specified

String stringpart, element with the new text


Image imgpart)
and image, which are
passed as parameters to this
method.
size()
Gets the number of elements
available in the List object.

Some Methods of the List Class


You can use the following code to create a list by using the
List class:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class Midlet extends MIDlet
{
public void startApp() {
// code snippet to create a list
List lst=null;
lst = new List("List Demo",
List.IMPLICIT);
lst.append("Element 1", null);
lst.append("Element 2", null);
lst.append("Element 3", null);
// specify the list as the current
displayable object
Display.getDisplay(this).setCurrent
(lst);
}
public void pauseApp() {
}
public void destroyApp(boolean
unconditional) {
}
}
When the preceding code is executed, an emulator
window containing a list of elements is displayed, as
shown in the following figure.

The Emulator Displaying the List of Elements

Just a minute:
Ken Burton is working as a mobile application
developer with Technology Systems. Ken is
developing an application to list various
elements on a mobile device screen. After
adding elements to the List object, Ken needs
to retrieve the number of elements available in
the list. Which method should Ken use to
perform this task?

Answer:
size()

Implementing TextBox
The TextBox class is used to display a text box on the
screen of a mobile device. The text box enables users to
enter and edit text by using the keypad of a mobile device.
Each TextBox object has a maximum size, which
specifies the maximum number of characters that can be
stored in the TextBox object.
You can manage the size of a text box based on the screen
size of a mobile device. For example, consider a text box
containing 10 lines of text. In this case, the text will be
displayed as a simple text box on a mobile device with a
screen size of 10 lines. However, if the screen of a mobile
device can display only six lines of text at a time, the
TextBox class implementation makes the text area
scrollable.
The TextBox class defines a constructor, as shown in the
following code snippet:
TextBox (String title, String Text, int
maxSize, int constraints);
The constructor can be used to create a new TextBox
object. The title, initial text, maximum size, and input
constraints are passed as parameters to the constructor.
The preceding constructor of the TextBox class defines
the constraints parameter in addition to other
parameters. This parameter is used to set the input
constraints for each TextBox. This allows the application
to request that the user's input be restricted in a variety of
ways.
The different input constraints are:
ANY: Allows you to enter alphanumeric values.
NUMERIC: Allows you to enter only integer
values.
DECIMAL: Allows you to enter numeric values
containing fractions.
PHONENUMBER: allows you to enter phone
numbers.
URL: Allows you to enter a Uniform Resource

Locator (URL).
EMAILADDR: Allows you to enter an e-mail
address.

Note
The input constraints of a text box controls the
type of characters allowed in a particular
TextBox object. For example, you can set
the input constraints of a text box to
TextBox.NUMERIC to accept only numbers
as input in the text box.
The following table describes some of the methods
available in the TextBox class.
Method
Description
delete(int offset, Removes
the
specified
int length)
number of characters from
the TextBox object starting
from the specified position,
offset. The number of
characters to be deleted is
passed as the int parameter,
length.
getCaretPosition() Returns the position of the
cursor in the text box.
getChars(char[]
Copies the content of the
data)
text box into a character
array.
getMaxSize()
Returns
the
maximum
number of characters that
can be stored in the text box.
getString()
Returns the content of the
text box as a String object.
insert(String src, Inserts a specified string in
int position)
the text box starting from the
specified position.
setMaxSize(int
Specifies the maximum
maxSize)
number of characters that
can be stored in the text box.
setString(String
Replaces the current content
str)
of the text box with the
specified string.
setTitle(String
Sets the title of the text box
title)
to the specified title.
size()
Returns the number of
characters in the text box.

Methods of the TextBox Class


You can implement a text box by creating a TextBox

class object and specifying the text to be displayed in it.


You can use the following code to create a text box by
using the TextBox class:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class Midlet extends MIDlet {
public void startApp() {
// code snippet for creating a text
box
TextBox writeMail = new TextBox
("Text Box Demo","Write anything
here...",200,TextField.ANY);
//specifies the text box as current
displayable
Display.getDisplay(this).setCurrent
(writeMail);
}
public void pauseApp() {
}
public void destroyApp(boolean
unconditional) {
}
}
The preceding code creates a text box with the title, Text
Box Demo. The initial text displayed in the text box is
Write anything here..., and the text box can contain 200
characters of any type of text, such as numeric and string.
The following figure shows the output of the preceding
code.

The Emulator Displaying a Text Box

Implementing Alerts
Alerts are simple dialogs that notify a user about the
change in the state of the application. The Alert class
implements a type of screen that is displayed to a user
either for a specific time duration or until the user closes

it. For example you see the message, your message is


sent after you send an SMS from your mobile phone.
However, sometimes the user has to close the alert as it is
not closed automatically. For example, when you display
the message Are you sure you want to delete this item?,
and provide the users with the Yes or No options, the
user must close this alert.
After the alert time duration is over, the
nextDisplayable object is displayed on the screen.
You can create an Alert object by using the following
two constructors of the Alert class:
Alert(String Title): Constructs a new
Alert object with the specified title.
Alert(String title, String
alttext, Image alertimage,
AlertType alert): Constructs a new
Alert object with the specified title, alternate
text, image, and type, passed as arguments to the
methods.

Note
An alternate text is displayed in case the
Alert object cannot be displayed on a
mobile device display.
The Alert class also defines several methods that you
can use to perform operations such as getting and setting
the text and image of an Alert object.
The following table describes some of the methods
defined in the Alert class.
Method
Description
addCommand(Command Adds a command object to
comm1)
the current Alert object.
getDefaultTimeout() Returns the default time out
period for the Alert object.
The time out period is the
duration for which the Alert
object is displayed.
getImage()
Retrieves the image of the
Alert object.
getIndicator()
Returns
the
progress
indicator for the current
Alert object.
getString()
Returns the text used in the
Alert object.
getTimeout()
Returns the time duration
for which the Alert object is
displayed.
setImage(Image img) Sets specified image for the
Alert object.

setIndicator(Gauge Sets the Gauge object,


Indicator)
which is displayed as a
progress indicator.
setString(String
Sets the text for the Alert
str)
object.
setTimeout(int
Sets the time for which the
time)
Alert object is displayed

Some Methods of the Alert Class

Tip
You can also play a sound with an Alert
object by using the playSound() method of
the AlertType object.
An Alert object consists of the following data fields:
DISMISS_COMMAND: The
DISMISS_COMMAND field is a command that is
available by default on an Alert object. This
command informs the CommandListener that
the Alert object is dismissed.
FOREVER: The FOREVER field specifies that the
Alert object will be displayed until the user
dismisses it.
The following code shows the implementation of the
Alert class:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class Midlet extends MIDlet {
public void startApp() {
Alert alt = new Alert("Alert Demo");
alt.setString("Alert: MIDlet launched!
\n The screen will disappear in some
time..");
Display.getDisplay(this).setCurrent
(alt);
}
public void pauseApp() {
}
public void destroyApp(boolean
unconditional) {
}}
The preceding code displays an alert when the MIDlet is
launched. The alert automatically disappears after some
time. The following figure shows the alert screen that is
displayed when the MIDlet is launched.

Form class to create and manage forms. A form can


contain several items on it. These items are instances of
the classes derived from the Item class.
Each element of a form is assigned a unique index
number. This index number is used to refer to the element.
The implementation of a Form class arranges various
items of a Form object in horizontal rows. The number
and size of rows are dependent on the screen size of the
mobile device on which the form is displayed. If a mobile
device screen is unable to show all the items of the form
then the implementation of the Form class makes the
Form object scrollable.
The Form class also defines a layout policy that is used to
define the number of rows, size of each row, size of the
scroll bar, and the margins between the rows. The Form
class uses a layout algorithm to generate rows in a form
and show various items on it.
A user can interact with a Form class object by using the
items displayed on it. For example, the user can select the
items from a list or type the text in the text field item of a
form.
The Form class has the following two constructors:
Form(String title): Creates a blank
Form object with no component.
Form(String title,Item[] items):
Creates a new Form object with the specified
items. The items to be displayed are passed to
this method as an array of Item objects.
The Form class also contains methods to add, remove,
and traverse the elements in a form.
The following table describes some of the methods
defined in the Form class.
Method
append(Image
imageobject)

append(Item
itemname)

append(String
stringobject)

The Alert Screen when the MIDlet is Launched

Implementing Form
A form is a screen object that consists of a number of UI
components, such as text fields, choice groups, and
images. A form can also be defined as a container that
holds these UI components. MIDP UI API defines the

insert(int
itemNumber,
item)

Description
Adds an image to the
current Form object. This
method returns the index
number of newly added
Image object.
Adds an item to the current
Form object. This method
returns the index number of
the newly added Item object.
Adds a textual string to the
current Form object. The
string is passed as an
argument of String object.
This method returns the
index number of the newly
added string.
Adds an item to the current
Item form before the item with the
specified index number.

delete(int
itemNumber)

Deletes the item referenced


by the specified index
number.
DeleteAll()
Deletes all the items from
the current form.
get(int itemNumber) Returns the item with the
specified index number.
getHeight()
Returns the height of the
display area, which is
available for displaying
items.
getWidth()
Returns the width of the
display area, which is
available for displaying
items.
set(
int Replaces the Item object
itemNumber,
Item with the specified index
itemname)
number with the item,
itemname.
size()
Returns the number of items
in the current form.

Some Methods of the Form Class

Just a minute:
Christine Turner is working as a mobile
application developer with Super Graphics.
In his current project, Christine needs to
develop a graphic application for mobile
devices. The application needs to display a
form containing several Item objects.
Christine wants to add an Item object to the
current Form object. Which method should
Christine use to perform the preceding
operation?

Answer:
append(Item itemname)
You can use the following code to create a form by using
the Form class:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class Midlet extends MIDlet {
public void startApp() {

Form writemail = new Form("Form


heading");
writemail.append("This is just a Form
\n A String is painted on it");
Display.getDisplay(this).setCurrent
(writemail);
}
public void pauseApp() {
}
public void destroyApp(boolean
unconditional) {
}
}
The preceding code creates a form as shown in the
following figure.

IllegalStateException exception is
thrown.

Working with Item Class and its


Subclasses
Items are also high-level UI API elements. They are
displayed as components of a form generated by using the
Form class, which is a subclass of the Screen class. A
form can contain several items, such as text fields and
buttons.

Describing the Item Class and its


Methods
The Item class is an abstract class that cannot be
instantiated. It is extended to create items, such as a text
box. These items can be used as UI components on a form.
Various classes, such as TextField and ImageItem,
are derived from the Item class. The instances of these
classes are added to the Form object. For example, the
TextBox class is derived from the Item class and its
objects are used as text boxes within a form.
The following figure shows the hierarchy of classes in the
Item class.

The Item class and its Subclasses

Subclasses of the Item Class

The Emulator Displaying a Form

Note
You cannot share an item object among
several form objects. If you try to add an
existing item of a form to another form, the

The Item class acts as a superclass for various classes


that are used to create form components, such as text
fields, radio buttons, and images.
The following classes are derived from the Item class:
ChoiceGroup: Is used to represent a group of
elements that can be provided in a Form object
for allowing the user to select one or more
elements from it. For example, you can create a
ChoiceGroup object to display a list of radio
buttons from which the user can select an item.
CustomItem: Is used to derive new classes that
can be used to add customized items to a form.
The CustomItem class is an abstract class that
you can use to derive new classes to define
custom items on a form. You can extend the

CustomItem class to create a new type of item,


which can be added to the Form object. The
paint() method is used to draw and display
the new item on the screen of a mobile device.
DateField: Is used to display the date and
time in a Form object. This class also allows you
to change the time and date information stored in
a mobile device. For example, you can use the
DateField object to display the date on the
screen of the mobile device.
Gauge: Is used to represent the status
information, such as volume level or network
availability in mobile devices, in the form of a
bar graph. The status information is represented
internally in the form of integer values. For
example, a mobile device displays a bar graph
when you increase or decrease the volume of a
ring tone. This bar graph is implemented by using
the Gauge object.
ImageItem: Enables you to insert images on a
form. For example, you can set the wallpaper of a
mobile device by using this UI object on a plain
form.
Spacer: Represents a blank area on a form. You
can use this item to insert spaces between two
components in a row. For example, you can use
this item to add spaces between two text fields on
a form that are placed one after the other.
StringItem: Is used to display textual strings
on a form. For example, you can use this item to
display the welcome screen of a mobile phone.
TextField: Represents an editable text area,
which can be used on a form. The TextField
class enables you to enter text in a text field. For
example, you can use the TextField class to
enable the users to enter new phone numbers in
the memory of a mobile device.

Features of the Item Class


The Item class provides several important features for
items that are created by using the instances of the
subclasses derived from it. These features can be used to
modify and control the display of the items on mobile
devices.
Additional features of the Item class are:
Label: Provides information about an item. The
label of an item is displayed alongside or above
it. However, when you do not want to have a
label for an item, you can set the value of the
label as null.
Layout: Specifies the positioning of an item on
the screen of a mobile device. For example, you
can use the LAYOUT_CENTER layout directive
to specify that the item should be center aligned

on the display screen.


Appearance mode: Specifies the interactivity of
a string or an image created by using the
StringItem and ImageItem objects,
respectively. The Item class defines the
following types of appearance modes:
Plain: Specifies the non-interactive display
of text and images.
Hyperlink: Specifies the text or image to
be displayed as a hyperlink.
Button: Specifies the text or image to be
displayed as a button. The item specified as
a button can be pressed to execute the
command or action associated with it.

Methods of the Item Class


The Item class contains several methods that can be used
to control the display of items on mobile devices.
The following table describes some methods of the Item
class.
Method
addCommand(Command
cmd)
getLabel()

Description
Adds a Command type
object to the current item.
Returns the label of the item
in the form of a String
object.
getLayout()
Returns
the
layout
directives, which are used to
place the item on the form.
getMinimumHeight() Returns the minimum height
of the item.
getMinimumWidth() Returns the minimum width
of the item.
getPreferredHeight Returns the preferred height
()
of the item.
getPreferredWidth() Returns the preferred width
of the item.
notifyStateChanged Instructs the form that
()
contains the current item, to
notify the ItemStateListener
object.
setLabel(String
Sets the items label, which
label)
is passed as a String
parameter to this method.
setLayout(int
Sets the items layout
Layout)
directive, which is passed as
an int parameter to this
method.
setPreferredSize
Sets the preferred size of the
(int
width,
int item, which is specified in
height)
terms of width and height.

Some Methods of the Item Class

Implementing the Item Class


You need to create a form to implement various items on
it. These items are implemented by creating objects of the
subclasses of the Item class.
In order to implement the following subclasses of the
Item class, you need to create a Form object, and append
the objects of this subclass to it:
ChoiceGroup
DateField
ImageItem
StringItem
TextField
Gauge

Implementing ChoiceGroup
By using the ChoiceGroup class, you can display a list
of elements from which the users can select an element.
The ChoiceGroup class has the following two
constructors:
ChoiceGroup(String label,int
choiceType): Creates a new and empty
ChoiceGroup object that specifies its title and
its type.
ChoiceGroup(String label,int
choiceType,String[]
stringElements, Image[]
imageElements): Creates a new
ChoiceGroup object that specifies the title, the
type of the ChoiceGroup object, and an array
of strings and images to be used as its initial
contents.
The following table describes some of the methods
defined in the ChoiceGroup class.
Method
Description
append(String
Appends an element to
stringPart,
Image ChoiceGroup.
imagePart)
delete(int
Deletes
the
element
elementNum)
referenced by elementNum.
getImage(int
Gets the image part of the
elementNum)
element
referenced
by
elementNum.
getString(int
Gets the string part of the
elementNum)
element
referenced
by
elementNum.
size()
Gets the number of elements
present in the list.

Some Methods of the ChoiceGroup Class


The following code implements the ChoiceGroup class

to display a list of selectable elements:


import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class Midlet extends MIDlet {
public void startApp() {
//Create a Form object
Form writemail = new Form("Choice
Group Demo");
// Create a ChoiceGroup object
ChoiceGroup login_save = new
ChoiceGroup("",ChoiceGroup.MULTIPLE);
login_save.append("Save Login",null);
writemail.append(login_save);
// Specify the form as current
displayable
Display.getDisplay(this).setCurrent
(writemail);
}
public void pauseApp() {
}
public void destroyApp(boolean
unconditional) {
}
}
When the preceding code is executed, an element in the
ChoiceGroup object is displayed in the mobile phone
emulator window. The following figure shows the mobile
phone emulator window.

selector, and other devices enable users to change the date


and time by entering the values by using the keypad.
The DateField class contains three static data fields,
which specify the input modes to accept the date and time
information from the user. The static data fields provided
by the DateField class are:
DATE: Specifies the input mode in which you can
enter the date information only.
TIME: Specifies the input mode in which you can
enter the time information only.
DATE_TIME: Specifies the input mode in which
you can enter both the date and time information.
The DateField class defines the following constructors:
DateField(Sting label, int mode):
Creates a DateField object with the specified
label and mode.
DateField(Sting label, int mode,
TimeZone timezone): Creates a
DateField object with the specified label,
mode, and timezone. The timezone is passed as a
TimeZone object.
The following table describes some of the methods
defined in the DateField class that allows you to
specify and retrieve the date and time information.
Method
getDate()

Description
Returns
the
date
information. If the date
value is not set in the device,
then this function returns
null.
getInputMode()
Returns the input mode of
the DateField object.
setDate(Date date) Specifies
new
date
information for the current
DateField object.
setInputMode(int
Sets input mode for the
mode)
current DateField object.

Some Methods of the DateField Class

The Emulator Displaying a ChoiceGroup Object

Implementing DateField
The DateField class enables you to display and modify
the date and time information on a form. The UI for
modifying the date and time information is devicespecific.
For example, some mobile devices allow the users to edit
the date and time by using a graphical date and time

Just a minute:
State whether the following statement is true
or false.
The getInputMode() method of the

DateField class returns the input mode of


the DateField object.

copying data from files, resource bundles, or


networks. These images cannot be modified.

Answer:
True

Implementing ImageItem
The ImageItem class is derived from the Item class.
This class is used to insert image components on a form.
The object of the ImageItem class contains a reference
to an object of the Image class. The Image class is used
to create, store, and display images in MIDP UI.
The following figure shows the screen of a mobile device
that displays a form with an ImageItem object.

Screen Displaying a Form with an ImageItem


Object
Images on a MIDP-compliant mobile device conform to
the Portable Network Graphics (PNG) format.
The ImageItem class stores the following types of
images:
Mutable Images: These are blank images
containing only white pixels. These images can
be modified by the MIDlets by using the
Graphics class objects and its functions.
Immutable Images: These images are created by

Note
In case the Image object referenced by an
ImageItem object is mutable, the
ImageItem object stores the snapshot of the
Image object at the time of creation of the
Image object. Any further modifications to
the mutable Image object are not reflected in
the ImageItem object.
The ImageItem class defines various layout directives
that are used to control the display of an image on the
screen of a mobile device. For example, you can use the
LAYOUT_RIGHT layout directive to right-align an
ImageItem object on the mobile device display. You can
also set the appearance mode of an image.
The constructors that you can use to create an
ImageItem object are:
ImageItem(String label, Image
image, int Layout, String
alttext): Creates an ImageItem object with
the specified label, image, layout directive, and
alternate text. An alternate text is displayed in
case the ImageItem object cannot be displayed
on a mobile device display.
ImageItem(String label, Image
image, int Layout, String
alttext, int appearance Mode):
Creates an ImageItem object with the specified
label, image, layout directive, alternate text, and
appearance mode.
The ImageItem class also contains various methods to
display and manage images on a screen.
The following table describes some methods of the
ImageItem class.
Method
getAltText()

Description
Returns the alternate text,
which is displayed in case
the size of the image exceeds
the display capacity of the
mobile device.
getAppearanceMode() Returns the appearance
mode of the ImageItem
object.
getImage()
Returns the Image object
referred to by the ImageItem
object.
getLayout()
Returns the layout directive,

which is used to control the


positioning of the ImageItem
object.
setLayout(int
Specifies the layout directive
Layout)
for the current ImageItem
object.
setImage(Image img) Specifies the image for the
current ImageItem object.
setAltText(String Specifies the alternate text
alt)
for the current ImageItem
object.

Some Methods of the ImageItem Class


The following code snippet shows the implementation of
the ImageItem object:
//Creates a form
Form ImageForm = new Form("Form
heading");
//A new Image item is created using
the constructor ImageItem imgItem = new
ImageItem("Image Item Demo ", imgObj,
Item.LAYOUT_CENTER, null,Item.BUTTON);
//Append this image item to the form
ImageForm.append (imgItem);
//Display the image item
Display.getDisplay(this).setCurrent
(ImageForm);
The preceding code snippet creates an ImageItem object
named imgItem, which will be displayed in the
ImageItem form.

Implementing StringItem
The StringItem class that is derived from the Item
class is used to display text on a form. A StringItem
object consists of two components, text and a label. The
text appears as read only on the screen of a mobile device
to the users. However, this text can be modified by the
application with respect to some event.
The StringItem class defines the following two
constructors:
StringItem(String label, String
text): Creates a StringItem object with the
specified label and text, which are passed as
parameters to the constructor.
StringItem(String label, String
text, int Appmode): Creates a new
StringItem object with the specified label,
text, and appearance mode.
The following code snippet creates a StringItem
object:
StringItem strItem = new StringItem
("HyperlinkExample ", "This is a
hyperlink", Item.HYPERLINK);
The preceding code snippet creates a StringItem

object. The text of the StringItem object is displayed


as a hyperlink.
The StringItem class contains various methods to
manage the string item on the screen.
The following table describes some methods defined in the
StringItem class.
Method
Description
getAppearanceMode() Returns the appearance
mode of the StringItem
object.
getFont()
Returns the preferred font
for displaying the text of the
StringItem object.
getText()
Returns the text stored in the
StringItem object.
setFont(Font font) Sets the preferred font for
displaying
the
StringItem object.
setText(String txt) Sets the text to be displayed
by
the
StringItem
object.

Some Methods of the StringItem Class


The following code creates and displays a StringItem
object on a form:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class Midlet extends MIDlet {
public void startApp() {
Form form1 = new Form("Welcome to
J2ME");
// Add Commands and CommandListener
StringItem si = new StringItem
("Label 1","String Item One\n");
StringItem si1 = new StringItem
("Label 2","String Item Two\n");
StringItem si2 = new StringItem
("Label 3","String Item Three");
form1.append(si);
form1.append(si1);
form1.append(si2);
Display.getDisplay(this).setCurrent
(form1);
}
public void pauseApp() {
}
public void destroyApp(boolean
unconditional) {
}
}
The preceding code snippet creates three StringItem
objects. These objects are displayed on a form named

form1.
The following figure shows the output of the preceding
code when the MIDlet is launched.

number of characters that can be stored in the


TextField object. The maximum size of a text field can
be more than the screen size of a mobile device. In such
cases, the text field is displayed as a scrollable UI
component.

Tip
By using the TextField class, you can also
create the text fields, which already have some
text inside them. Users can either use the text
inside the text field or enter the text they want
to enter.
A TextField class also defines various input
constraints, which can be used to control and restrict the
type of characters that a user can enter by using mobile
device keypad. For example, you can specify the
NUMERIC constraint to restrict the users to input
numerical digits only.
The TextField class defines a single constructor that
enables you to create a TextField object with the
specified initialization parameters. The syntax of the
TextField constructor is:
TextField(String label, String text,
int Size, int constraints);
The preceding syntax creates a new TextField object
whose label is specified as a String object, label. The
initial text of the TextField object is passed to this
constructor as a String object, text. The constructor
also accepts the maximum size and input constraints as
int values, Size and constraints.
The TextField class also defines several methods,
which can be used to manage the text fields.
The following table describes some methods defined by
the TextField class.

The Emulator Displaying the StringItem Object

Implementing TextField
The TextField class enables you to create editable text
component that can be used on a form. The maximum size
of a text field component depends on the maximum

Method
Description
delete(int offset, Deletes the characters from
int length)
the TextField object.
The position from where the
characters need to be
deleted is specified as a
parameter to this method.
The number of characters to
be deleted is also passed as
an argument.
getCaretPosition() Returns the current input
position in the TextField
object.
getChars(char[]
Copies the content of the

data)

TextField object to the


specified character array.
getConstriants()
Returns
the
input
constraints of the current
TextField object.
getMaxSize()
Returns the maximum size of
the TextField object.
The size is returned as an
integer
value,
which
specifies the number of
characters.
getString()
Returns the content of the
TextField as a String
object.
insert(char[] data, Inserts
a
range
of
int
offset,
int characters
in
the
length,
int TextField object. The
position)
range of characters is
specified by using an offset
value, length of characters,
and the position where the
characters are inserted.
setChars(char[]
Replaces the previous text
data, int offset, by inserting characters in
int length)
the TextField object.
The characters are passed
as a char array.
setMaxSize(int
Specifies the maximum size
size)
of the TextField object.
The size is specified as an
int value, which specifies the
number of characters.
setConstraints(int Specifies
the
input
constraints)
constraints
of
the
TextField object.
setString(String
Inserts the text specified by
Strtext)
the string, Strtext, in the
TextField
object
replacing previous content.
size()
Returns the number of
characters currently stored
in the TextField object.

Some Methods of the TextField Class


The following code snippet implements the TextField
class:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class Midlet extends MIDlet {
public void startApp() {
Form form1 = new Form("Welcome to
J2ME");

// Create an instance of the


TextField class
TextField tf = new TextField
("TextField","Initial
Value",25,TextField.ANY);
form1.append(tf);
Display.getDisplay(this).setCurrent
(form1);
}

public void pauseApp() {


}
public void destroyApp(boolean
unconditional) {
}
}
When you launch the MIDlet created in the preceding
code, the emulator window displays a form with a
TextField object, as shown in the following figure.

Just a minute:
State whether the following statement is true
or false.
The getString() method of the
TextField class returns the content of the
TextField as a String object.

Answer:
True

Implementing Gauge
The Gauge class implements a bar graph display of a
value that is used in a form. By using the Gauge class,
you can represent a single value from a contiguous range
of integers starting from zero to a value that will be the
maximum value supplied by the application. The Gauge
can be either interactive or noninteractive. A Gauge that
is set as interactive allows the user to increase or decrease
its values, whereas, a Gauge that is set as nonintercative
represents a progress bar. A progress bar is used to provide
feedback about the progress of running application. A
noninteractive Gauge can also be placed in an Alert as
an activity indicator.
The Gauge class provides the following constructor:
Guage(String label, Boolean b, int
maxval, int initval);
In the preceding code snippet, maxval specifies the
largest value of the range covered by the gauge and
initval specifies the initial value that will be displayed
by the gauge. The argument b determines if the user can
adjust the value in the gauge. In order to use the slider in
the gauge, this argument has to be set to true.
The following table describes some methods defined by
the Gauge class.

The Emulator Displaying a Form with a TextField


Object

Method
getValue()
getmaxValue()
isInteractive()

Description
Gets the current value of the
Gauge object.
Gets the maximum value of
the Gauge object.
Informs whether the user is
allowed to change the value
of the Gauge object.

setMaxValue()
setValue()

Sets the maximum value of


the Gauge object.
Sets the current value of the
Gauge object.

Some Methods of the Gauge Class


The following code implements the Gauge class:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class Midlet extends MIDlet {
public void startApp() {
Form form1 = new Form("Welcome to
J2ME");
Gauge g =new Gauge
("Signal",true,5,2);
form1.append(g);
Display.getDisplay(this).setCurrent
(form1);
}
public void pauseApp() {
}
public void destroyApp(boolean
unconditional) {
}
}
When you launch the MIDlet created by the preceding
code, the emulator window displays a Signal gauge on the
screen, as shown in the following figure.

The Emulator Displaying the Signal Gauge

Creating a Movie Reservation


Application
Problem Statement

Sam is working as a mobile application developer at


Global Systems Inc. His organization uses the Java ME
platform for developing mobile applications. Sam is
assigned the task of developing a movie reservation form
that mobile users can use to book movie tickets online
through their mobile phones.
As per the requirements given to Sam by his Project
Manager, the application should display a welcome screen
before displaying the form.

text box to assign a name to the new MIDlet.


6. Click the Finish button to create the
ReservationMIDlet.java MIDlet.
7. Replace the existing code for the
ReservationMIDlet.java MIDlet in the Editor
with the following code:
import
javax.microedition.midlet.*;
import
javax.microedition.lcdui.*;

Solution

public class ReservationMIDlet


extends MIDlet {
//create an instance of the
ReservaltionMIDlet MIDlet
public static ReservationMIDlet
instance;
//create an instance of
MovieReservation class
MovieReservation displayable;

To create the movie reservation application, Sam needs to


perform the following tasks:
1. Create a NetBeans project.
2. Add class files to the project.
3. Build and execute the project.

Task 1: Creating the NetBeans Project


To create a NetBeans project, Sam needs to perform the
following steps:
1. Select startAll
ProgramsNetBeansNetBeans IDE 6.0.1 to
open the NetBeans IDE 6.0.1 window.
2. Select FileNew Project to open the New
Project dialog box.
3. Ensure that the Mobility option is selected in the
Categories section.
4. Ensure that the MIDP Application option is
selected in the Projects section.
5. Click the Next button. The Name & Location
page is displayed.
6. Type MovieReservationApplication in the
Project Name text box to assign a name to the
new project.
7. Ensure that <Drive Letter>:\JavaMEProjects is
displayed in the Project Location text box.
8. Clear the Create Hello MIDlet check box.
9. Click the Next button. The Default Platform
Selection page is displayed.
10. Click the Next button. The More Configurations
Selection page is displayed.
11. Click the Finish button to create the
MovieReservationApplication project.

10.

Task 2: Adding Class Files to the Project

11.

For adding files to the MovieReservationApplication


project, Sam needs to perform the following steps:
1. Select FileNew File to open the New File
dialog box.
2. Ensure that the MIDP option is selected from the
Categories section.
3. Ensure that the MIDlet option is selected in the
File Types section.
4. Click the Next button. The Name and Location
page is displayed.
5. Type ReservationMIDlet in theMIDlet Name

public ReservationMIDlet()
{
instance=this;
}
public void startApp() {
displayable= new
MovieReservation();
}
public void pauseApp() {
}

8.
9.

12.
13.
14.

public void destroyApp(boolean


unconditional) {
}
}
Select FileNew File to open the New File
dialog box.
Select the Java option from the Categories
section.
Ensure that the Java Class option is selected in
the File Types section.
Click the Next button. The Name and Location
page is displayed.
Type MovieReservation in the Class Name text
box to assign a name to the new Java class file.
Click the Finish button to create the
MovieReservation.java Java class file.
Replace the existing code for the
MovieReservation.java Java class file in the
Editor with the following code:
import
javax.microedition.lcdui.*;

public class MovieReservation {


//constructor of the
MovieReservation class
public MovieReservation(){
//create an alert screen
Alert alt = new Alert("Star
Cast Movies");
alt.setString("Welcome to
online movie registration...");
alt.setTimeout(4000);
//create a new form
Form bookTickets= new Form
("Movie Reservation Form");
TextField Name= new TextField
("Name:","",20,TextField.ANY);
ChoiceGroup Movie= new
ChoiceGroup
("Movie:",ChoiceGroup.EXCLUSIVE);
Movie.append("The Mask", null);
Movie.append("Spiderman",
null);
Movie.append("Cast Away",
null);
DateField BookingDate= new
DateField("Date and
Time:",DateField.DATE);
ChoiceGroup ShowTime= new
ChoiceGroup
("Time:",ChoiceGroup.EXCLUSIVE);
ShowTime.append("12:00 PM",
null);
ShowTime.append("3:30 PM",
null);
ShowTime.append("7:00 PM",
null);
TextField Tickets= new
TextField("Number of
Tickets:","",10,TextField.NUMERIC
);
//add items on the form
bookTickets.append(Name);
bookTickets.append(Movie);
bookTickets.append
(BookingDate);
bookTickets.append(ShowTime);
bookTickets.append(Tickets);
//Set alert as current
displayable and form as next
displayable

Display.getDisplay
(ReservationMIDlet.instance).setC
urrent(alt,bookTickets);
}
}

Task 3: Building and Executing the


Project
To build and execute the MovieReservationApplication
project, Sam needs to perform the following steps:
1. Select BuildBuild Main Project to build the
MovieReservationApplication project.
2. Select RunRun Main Project to execute the
MovieReservationApplication project. The
DefaultColorPhone emulator window is
displayed, as shown in the following figure.

The DefaultColorPhone Emulator Window


3. Click the soft key below Launch to launch the
ReservationMIDlet MIDlet. An alert will be
shown on the emulator window with the text,
Welcome to online movie registration..., for
four seconds and then the Movie Reservation
Form form will be displayed, as shown in the
following figure.

The DefaultColorPhone Emulator Window


Displaying the Movie Reservation Form
4. Select MIDletExit to close the
DefaultColorPhone emulator window.
5. Select FileExit to close the NetBeansIDE.

Summary
In this chapter, you learned that:
The Screen class is a superclass for all highlevel UI components.
The four classes that are derived from the
Screen class are:
List
TextBox

Alert
Form
The List class, derived from the Screen class,
implements a list of elements from which a user
can select one or more elements.
The TextBox class is used to display a text box
on the screen of a mobile device.
The Alert class implements a type of screen
that is displayed to a user for specific time
duration.
A form is a screen object that consists of various
UI components, such as text fields, choice
groups, and images.
The Item class is an abstract class that is
extended to create items, such as text box.
Items are displayed as components of a form
generated by using the Form class, which is a
subclass of the Screen class.
Additional features of the Item class are:
It provides information about an item.
It specifies the positioning of an item on
the screen of a mobile device.
It specifies the interactivity of a sting or an
image created by using the StringItem
and ImageItem objects, respectively.
The classes derived from the Item class are:
ChoiceGroup
CustomItem
DateField
Gauge
ImageItem
Spacer
StringItem
TextField
The ChoiceGroup class is used to create a
group of elements that can be provided in a Form
object for allowing the user to select one or more
elements from it.
The CustomItem class is used to derive new
classes that can be used to add customized items
to a form.
The DateField class is used to display the date
and time in a Form object.
The Gauge class is used to create gauge
components that represent status information,
such as volume level or network availability in
mobile phones, in the form of a bar graph.
The ImageItem class enables you to insert
images on a form.
The Spacer class id used to create a spacer that
represents a blank area on a form.
The StringItem class is used to display
textual strings on a form.
The TextField class represents an editable

text area, which can be used on a form.


The Gauge class implements a bar graph display
of a value that is used in a form.

Exercises
Exercise 1
Sam is working as a mobile application developer at
Moser Inc. The Grand Palace, a hotel chain, has asked his
organization to develop a mobile application through
which their customers can book hotel rooms online by
using their mobile phones. Sam is assigned the task of
developing a hotel booking form for the mobile
application.
As per the requirements given by the Manager of the
Grand Palace, Sam needs to display a welcome screen
before displaying the form.

Reference Reading
Working with Screen and its
Elements
Reference Reading: Books
J2ME in a Nutshell: By Kim
Topley
Publisher: OReilly
Wireless J2ME Platform
Programming
By Vartan Piroumian
Publisher: Prentice Hall
PTR.

Reference Reading: URLs


http://developers.sun.com/
mobility/midp/articles/
guiapis/

Working with Item Class and its


Subclasses
Reference Reading: Books
J2ME in a Nutshell: By Kim
Topley
Publisher: OReilly
Wireless J2ME Platform
Programming
By Vartan Piroumian
Publisher: Prentice Hall
PTR.

Reference Reading: URLs


http://developers.sun.com/
mobility/midp/articles/
guiapis/

applications by handling events generated by


the application.

Chapter 5
Introducing High-Level UI APIs-II
To create interactive interfaces and navigate screens of a
MIDlet application, you need to handle events. These
events are generated when users interact with high-level
UI components of mobile applications. For example, when
a user clicks the Ok button of a mobile device after filling
the details of a login form, an event is generated. You can
track this event to authenticate the user and display the
next screen.
MIDP UI API provides various types of event listener
interfaces for handling events. It also provides animation
based UI components such as gauge and ticker that can be
used to display dynamic information in mobile
applications.
This chapter discusses handling of high-level UIs. It
explains the process of handling high-level events and
navigating screens in mobile applications. In addition, it
discusses the use of animation-based UI components to
display dynamic information in mobile applications.

Handling High-Level Events


Event handling is an important part of the UI design
process. In event handling, the events generated in
response to the user actions are handled by using the event
handlers or listeners.
MIDP UI uses the event delegation model for handling
events. In the event delegation model, one or more event
sources generate events. Event sources are the objects of
theDisplayable class and its subclasses. Events
generated by the event sources are delegated to the event
listeners. Event listeners are the interfaces that contain
methods to handle events.
The following figure shows the event delegation model.

Objectives
In this chapter, you will learn to:
Handle high-level UIs
Implement animation-based UI components in a
MIDlet application

Handling High-Level UIs


Events are generated when a user interacts with high-level
UI components of MIDP applications. For example, when
a user changes the text of a text box, an event is generated.
To handle such events in MIDP, you need to add
Command objects to high-level UI components. A
Command object contains information about the events
that are generated in response to a user interaction with UI
components.
For example, the Command object of a form includes all
the information regarding the event that is generated when
a user submits the form.
Events in MIDP are classified into the following types:
High-level
Low-level

Note
You can also navigate screens in MIDP

The Event Delegation Model


To implement the event delegation model, you need to
perform the following steps:
1. Implement the event listener interface in a class.
2. Register the listener object with the UI
component.
3. Listen for the events generated in the UI
component by using the listener objects.
4. Process the events by using the listener object
and its methods.
MIDP UI APIs define the following event listener
interfaces:
CommandListener: This interface is used to
respond to the command events generated by the
user.
ItemStateListener: This interface is used
by the MIDlet applications that need to receive
events indicating changes in the state of the
interactive items within a Form object.
ItemCommandListener: This interface is
used to receive notification of commands that
have been invoked on Item objects.

Note
Although a Command object is triggered by
key presses on the mobile devices, the
Command object for mobile devices is
triggered by pressing the soft keys on the
mobile handset.

Note
The ItemCommandListener interface is
used for defining context-sensitive command
actions for Item objects. The addCommand
() and removeCommand() methods of the
Item class control the commands that are
associated with items. The
ItemCommandListener interface is
notified automatically when a user activates a
Command of an Item object.

Using Command and


CommandListener
The Command class is used to store information about an
event. The information about handling of an event,
represented by a Command object, is stored in the
command listener associated with the Command object.
For example, you can associate a Command object with
the Exit button of a mobile device. On clicking this button,
the code of the commandAction() method defined in
the CommandListener interface is executed.

Note
The commandAction() method contains
the code to be executed on receiving the event.
The Command class defines the following two
constructors to create a Command object:
Command( String label, int
CommandType, int priority): Creates a
Command object with the specified label,
command type, and priority value.
Command( String label, String
longlabel, int type, int
priority): Creates a Command object with
the specified label, long label, command type,
and priority value.
The Command object created by the preceding
constructors will have the following attributes:

Label
Command type
Priority

Label
Label is a string shown to the user to represent the
command. Depending upon the number of characters used
to represent a label, it can be classified as a short label or a
long label. Every Command object must have a short
label. However, the long label is optional. The
implementation chooses one of the labels to be displayed
to the user depending upon the space available for
displaying the label.

Command Type
Command type is an integer value that represents various
types of commands. The following fields of the Command
class can be used to specify the command type of the
Command object:
BACK
CANCEL
HELP
EXIT
ITEM
OK
SCREEN
STOP

Priority
Priority is an integer value that represents the importance
of the Command object with respect to other Command
objects. Lesser the value of this attribute, higher will be
the priority of the Command object. For example, consider
two commands with priority values 1 and 2. The command
with the priority value 1 has higher priority than the
command with priority value 2.
When a MIDlet is executed, the mobile device chooses the
placement of a command based on the command type.
Consider the following example with three commands:
exitCommand = new Command("Exit",
Command.SCREEN, 1);
infoCommand = new Command
("Info",Command.SCREEN, 2);
buyCommand = new Command("Buy",
Command.SCREEN, 2);
The following figure shows the placement of the
preceding commands in a mobile device.

Answer:
getCommandType()

Exit, Info, and Buy Commands


In the preceding example, the application manager maps
the Exit command to the screen. As shown in the
preceding figure, the application manager creates a Menu
command to hold the Info and Buy commands. Clicking
the soft key below Menu displays a menu with two
options: Info and Buy.
The Command class also defines methods to retrieve
information about the Command object.
The following table describes some of the methods
defined by the Command class.
Method
getCommandType()

getLabel()
getLongLabel()
getPriority()

Description
Returns an int value to
indicate the type of the
current Command object.
Returns the label of the
Command object.
Returns the long label of the
Command object.
Returns an int value to
specify the priority of the
Command object.

Table Describing Some Methods of the Command


Class

Just a minute:
Which method of the Command class returns
an integer value to indicate the type of the
current Command object?

After creating a Command object, you can add it to a


Displayable object by using the addCommand()
method. The following example adds a Command object,
event1 to a Displayable object, screen1:
screen1.addCommand(event1);
After adding the Command object to the Displayable
object, you need to set the event listener for the Command
object. You can set the event listener by implementing the
CommandListener interface in the MIDlet class. The
MIDlet class must define the commandAction()
method. This method accepts the following two
parameters:
A Command object that has all the information
regarding the event
A Displayable object that represents the
component on which the event has occurred
You can use the following code snippet to implement
event handling by using the Command object and
theCommandListener interface:
import javax.microedition.lcdui.Form;
import
javax.microedition.lcdui.Command;
import
javax.microedition.lcdui.CommandListene
r;
import
javax.microedition.lcdui.Displayable;
public class NewClass extends Form
implements CommandListener{
Command ok = null;
Command back = null;
public NewClass(){
Command cmdOK = new Command
("Okey",1,Command.OK);
Command cmdBACK = new
Command
("Exit_App",1,Command.BACK);
this.addCommand(cmdOK);
this.addCommand(cmdBACK);
/*Class Which has extended screen
Object*/
this.setCommandListener(this); /
*Class that has
implemented
CommandListener*/
}
public void commandAction(Command
cmd, Displayable disp){
if(cmd.getCommandType() ==
Command.OK){
}

if(cmd.getCommandType() ==
Command.BACK){
}
// Or Commands Can be recognized by
other
//types.
if(cmd == ok){
}
if(cmd == back) {
}
}
}
The NewClass class in the preceding code snippet
implements the CommandListener interface. Two
command objects, cmdOK and cmdBACK, are added to the
current displayable object. Further, the commandAction
method is implemented to check whether the command
type is OK or BACK. Based on the command type, this
method will perform the appropriate action.

Using ItemStateListener
Whenever the user changes the state of an item on a form,
an event is generated. For example, an event is generated
when an element in the list of a form is selected.
Java ME applications implement the
ItemStateListener interface to track these events.
In other words, the ItemStateListener interface is
attached to Item objects. The state of the items on a form
is changed when the user:
Changes the set of selected values in a
ChoiceGroup object.
Adjusts the value of a Gauge object.
Enters or modifies the value in a TextField
object.
Enters a new date or time in a DateField
object.
Whenever any of the preceding user action takes place, the
code of the itemStateChanged() method is
executed. Besides user actions, the
itemStateChanged() method can also be executed
when the notifyStateChanged() method of the
Item class is called on an Item object.
An Item object that is of the Gauge, ChoiceGroup,
DateField, or TextField type, whose state is
changed, is passed as a parameter to the
itemStateChanged()method. However, the objects
of type stringItem, spacer, and ImageItem do not
have the ability to recognize events.
You can use the following code snippet to implement
event handling by using the ItemStateListener
interface:
import
javax.microedition.lcdui.ItemStateListe

ner;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Item;
import
javax.microedition.lcdui.TextField;
public class ItemStateListenerDemo
extends Form implements
ItemStateListener {
public ItemStateListenerDemo(){
TextField tf= new TextField("Do you
want to save the
message?","",3,TextField.ANY);
this.append(tf);
this.setItemStateListener(this);
}
public void itemStateChanged(Item itm)
{
TextField tf1 = (TextField)itm ;
String str = tf1.getString();
if(str.equals("yes"))
showAlert();
else if(str.equals("no"))
quitApp();
}
}
In the preceding code snippet, the itemStateChanged
() method checks whether the user has entered yes or
no in the text field named tf, which is passed as a
parameter to the itemStateChanged()method. If the
user enters yes, an alert is shown on the screen and if the
user enters no, the application exists.

Navigating Screens
The desktop UI applications created by using AWT in Java
consist of a number of layered screens and UI objects,
which you can display at a time. However, MIDP imposes
a restriction on the UI of the mobile applications so that
only a single screen is visible at a time. The restriction is
imposed because the hardware resources and processing
power of mobile devices is less as compared to desktop
computers. In addition, only one Displayable object
can be shown to the user at a time, which is managed
through the Display object. As a result, you need to use
the navigation technique to create mobile applications.
When you start a mobile application, an initial screen
containing certain UI components and associated
commands is displayed on the mobile device. When you
press a button on the mobile device, an event is generated.
On receiving the event, the event listener in the MIDlet
class displays the next screen of the mobile application UI
based on the key pressed by the user. Each MIDlet

contains a single Display object that represents the


screen of the mobile device. It displays or hides various
Displayable objects on the screen of the mobile
device. The following code snippet is used to display a
Displayable object, Screen2 on the screen of the
mobile device:
Display.getDisplay
(MIDlet.instance).setCurrent(Screen2);
You can use the preceding code snippet in the
commandAction() or itemStateChanged()
method to display the next screen of the mobile
application.
The following code implements screen navigation by
using the CommandListener interface:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class ScreenNavigationMidlet
extends MIDlet implements
CommandListener{
public static ScreenNavigationMidlet
instance;
//Command Objects
public Command sendMsg = null;
public Command back = null;
//Screen objects
private TextBox tb = null;
private Alert alt;
/* Constructor */
public ScreenNavigationMidlet() {
instance = this;
}
public void startApp() {
tb = new TextBox("New Message","Type
your message here!",180,0);
sendMsg = new Command("Send
Message",1,Command.OK);
back = new Command
("Cancel",1,Command.OK);
tb.addCommand(sendMsg);
tb.addCommand(back);
tb.setCommandListener
(this); Display.getDisplay
(ScreenNavigationMidlet.instance).setCu
rrent(tb);
}
public void pauseApp() { }
public void destroyApp(boolean
unconditional) { }
public static void quitApp() {
instance.destroyApp(true);
instance.notifyDestroyed();
instance = null;
}

public void showAlert(Displayable


disp){
alt = new Alert("Alert Screen");
alt.setString("Sending Message...");
Display.getDisplay
(ScreenNavigationMidlet.instance).setCu
rrent(alt,disp);
}
public void commandAction(Command cmd,
Displayable disp){
if(cmd == sendMsg)
{
showAlert(tb);
}
if(cmd == back){
ScreenNavigationMidlet.quitApp();
} Display.getDisplay
(ScreenNavigationMidlet.instance).setCu
rrent(tb);
}
}
When the MIDlet in the preceding code is launched, the
New Message text box screen is displayed in the emulator
window, as shown in the following figure.

The Emulator Window Displaying the New Message


Text Box Screen
On selecting the send message option from the menu of
the preceding text box screen, an alert screen is displayed,
as shown in the following figure.

The Emulator Window Displaying an Alert Screen

Implementing Animation-Based UI
Components
The high-level UI API also defines animation-based UI
components. These components include:

Gauge: Displays a progress indicator to show the


status of a task dynamically. You can implement
a gauge item by using the Gauge class, which is
a subclass of the Item class.
Ticker: Displays a string that continuously
scrolls along the screen of a mobile device. The
ticker component is used to highlight information
on the screen. For example, you can create a
news MIDlet to retrieve news information from
the server and display it as a ticker. You can
implement a ticker by using the Ticker class.

a new Ticker object. The following syntax shows the


constructor of a Ticker object:
Ticker(String str)
In the preceding syntax, the text displayed in the Ticker
object is passed as a String object to the constructor.
The following table describes the methods defined in the
Ticker class.
Method
getString()
setString(String
str)

Note
The Ticker class is not a part of the
Displayable class hierarchy. It is
available as a separate class in the
javax.microedition.lcdui package.

Description
Returns the text displayed by
the Ticker object.
Replaces the current text of
the Ticker object with the
text specified as a String
object, which is passed to
this method.

Methods of the Ticker Class

Implementing Ticker
Describing the Ticker Class and its
Methods
The Ticker class is used to implement a ticker. You can
share a Ticker object among several Displayable
objects. You can use the setTicker() method of
aDisplayable object to add a Ticker object to it. By
sharing a Ticker object, you can display the same
scrolling text on the screens of a mobile application. For
example, you can display a scoreboard ticker on different
screens of a game MIDlet.
A Ticker can be added to any instance of a
Displayable object with the addTicker()method,
and it can be removed with the setTicker(null)
method.

The following code shows the implementation of a ticker


in a MIDlet:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class TickerExample extends
MIDlet implements CommandListener{
private Display display;
private Ticker ticker;
private Command exit;
private Form form;
public TickerExample(){
form = new Form("Demo Ticker");
display = Display.getDisplay(this);
ticker = new Ticker("This is a
ticker Demo...");

Note
The Ticker class does not provide methods
to stop and start the ticker. However, the
Ticker class implementation is allowed to
pause the scrolling of text to minimize power
consumption. For example, if the user does not
interact with the mobile device for a certain
specified duration, the ticker is paused by the
implementation. The scrolling of the text
restarts when the user interacts with the
mobile device again.
The Ticker class provides a single constructor to create

exit = new Command("Exit",


Command.SCREEN, 1);
form.addCommand(exit);
form.setCommandListener(this);
form.setTicker(ticker);
}
public void startApp(){
display.setCurrent(form);
}
public void pauseApp(){ }
public void destroyApp(boolean

unconditional){
notifyDestroyed();
}

public void commandAction(Command c,


Displayable display){
String label = c.getLabel();
if (label.equals("Exit")){
destroyApp(false);
}
}
}
When you run the preceding code snippet, the emulator
window appears displaying the name of the MIDlet,
TickerExample. On launching the MIDlet, a ticker is
displayed on the emulator window.

Note
The best practice is to make only one Ticker
object in the application and attach this
Ticker object with all the required
Displayable objects.
The following figure shows the emulator window with the
ticker created by the preceding code.

The Emulator Window Displaying the Ticker


Object

Creating a Stock Information


Application

Problem Statement
Jim Luis is working as a mobile application developer at
Nortel Ltd. His organization uses the Java ME platform
for developing mobile applications. He has been assigned
the task of developing a mobile application using which
mobile users can authenticate themselves to access the
stock information.
As per the requirements given to Jim by his Project
Manager, the stock information should be displayed as a
running text on the screen of the mobile device.

5. Type StockInfoMidlet in theMIDlet Name text


box to assign a name to the new MIDlet.
6. Click the Finish button to create the
StockInfoMidlet.java MIDlet.
7. Replace the existing code for the
StockInfoMidlet.java MIDlet in the Editor with
the following code:
import
javax.microedition.midlet.*;
import
javax.microedition.lcdui.*;

Solution

public class StockInfoMidlet


extends MIDlet {

To create the stock information application, Jim needs to


perform the following tasks:
1. Create a NetBeans project.
2. Add class files to the project.
3. Build and execute the project.

//create an instance of the


StockInfoMidlet MIDlet
public static StockInfoMidlet
instance;

Task 1: Creating a NetBeans Project


To create a NetBeans project, Jim needs to perform the
following steps:
1. Select startAll
ProgramsNetBeansNetBeans IDE 6.0.1 to
open the NetBeans IDE 6.0.1 window.
2. Select FileNew Project to open the New
Project dialog box.
3. Ensure that the Mobility option is selected in the
Categories section.
4. Ensure that the MIDP Application option is
selected in the Projects section.
5. Click the Next button. The Name & Location
page is displayed.
6. Type StockInfoApplication in the Project Name
text box to assign a name to the new project.
7. Ensure that <Drive Letter>:\JavaMEProjects is
displayed in the Project Location text box.
8. Clear the Create Hello MIDlet check box.
9. Click the Next button. The Default Platform
Selection page is displayed.
10. Click the Next button. The More Configurations
Selection page is displayed.
11. Click the Finish button to create the
StockInfoApplication project.

Task 2: Adding Class Files to the Project


For adding files to the StockInfoApplication project, Jim
needs to perform the following steps:
1. Select FileNew File to open the New File
dialog box.
2. Ensure that the MIDP option is selected in the
Categories section.
3. Ensure that the MIDlet option is selected in the
File Types section.
4. Click the Next button. The Name and Location
page is displayed.

//create an instance of the


GetInfo class
GetInfo displayable;
public StockInfoMidlet()
{
instance=this;
}
public void startApp() {
displayable= new GetInfo();
}
public void pauseApp() {
}
public void destroyApp(boolean
unconditional) {

8.
9.
10.
11.
12.
13.
14.

}
}
Select FileNew File to open the New File
dialog box.
Select the Java option from the Categories
section.
Ensure that the Java Class option is selected in
the File Types section.
Click the Next button. The Name and Location
page is displayed.
Type GetInfo in theClass Name text box to
assign a name to the new Java class file.
Click the Finish button to create the
GetInfo.java Java class file.
Replace the existing code for the GetInfo.java
Java class file in the Editor with the following
code:

import
javax.microedition.lcdui.*;
public class GetInfo implements
CommandListener{
//Command Objects
public Command cmdOK = null;
public Command cmdCancel =
null;
public Command cmdBack= null;
//Screen objects
private TextField login = null;
private TextField pswd = null;
private Form FrmLogin = null;
private Ticker ticker;
private Form frmStockInfo
=null;
private Alert AlrtInvalidLogin=
null;
// Constructor
public GetInfo()
{
ShowLoginForm();
}
public void ShowLoginForm()
{
FrmLogin= new Form("Login
Form");
login = new TextField("Login
Name:","",10,TextField.ANY);
pswd= new TextField
("Password:","",10,TextField.PASS
WORD);
cmdOK = new Command
("OK",1,Command.OK);
cmdCancel = new Command
("Cancel",2,Command.CANCEL);
FrmLogin.append(login);
FrmLogin.append(pswd);
//Adding command objects to
the form
FrmLogin.addCommand(cmdOK);
FrmLogin.addCommand
(cmdCancel);
FrmLogin.setCommandListener
(this);
//Set FrmLogin as current
displayable
Display.getDisplay
(StockInfoMidlet.instance).setCur
rent(FrmLogin);
}
public void ShowStockInfo()

{
frmStockInfo = new Form("LMN
Stock News");
//Creating a new ticker
object
ticker= new Ticker("BNB - 728.30
| Pasni- 309.53 | Dolbe Inc. 1234.90 | FCT - 879.30");
//adding ticker to the form
frmStockInfo.setTicker
(ticker);
cmdBack= new Command
("Back",1,Command.BACK);
frmStockInfo.addCommand
(cmdBack);
frmStockInfo.setCommandListen
er(this);
//Set frmStockInfo as current
displayable
Display.getDisplay
(StockInfoMidlet.instance).setCur
rent(frmStockInfo);
}
public void quitApp()
{
StockInfoMidlet.instance.destr
oyApp(true);
StockInfoMidlet.instance.notif
yDestroyed();
StockInfoMidlet.instance =
null;
}
public void commandAction
(Command cmd, Displayable disp){
if(cmd == cmdOK)
{
String LoginName=
login.getString();
String Password=
pswd.getString();
if
(LoginName.equalsIgnoreCase
("JOHN") &&
Password.equalsIgnoreCase
("JOHNJOHN"))
{
ShowStockInfo();
}
else
{
//Displaying an alert for
incorrect login details
AlrtInvalidLogin = new Alert
("Login Failed");

AlrtInvalidLogin.setString
("Please enter correct login
details!");
Display.getDisplay
(StockInfoMidlet.instance).setCur
rent(AlrtInvalidLogin,FrmLogin);
}
}
if(cmd == cmdCancel){
quitApp();
}
if(cmd==cmdBack)
{
ShowLoginForm();
}
}
}

Task 3: Building and Executing the


Project
To build and execute the StockInfoApplication project,
Jim needs to perform the following steps:
1. Select BuildBuild Main Project to build the
StockInfoApplication project.
2. Select RunRun Main Project to execute the
StockInfoApplication project. The
DefaultColorPhone emulator window is
displayed, as shown in the following figure.

The DefaultColorPhone Emulator Window


3. Click the soft key below Launch to launch the
StockInfoMidlet MIDlet. The Login Form form
will be displayed, as shown in the following
figure.

The DefaultColorPhone Emulator Window


Displaying the Login Form
4. Type JOHN in the Login Name text box by
clicking the keys given in the emulator keypad.
5. Click the down-arrow key in the emulator
keypad.
6. Type JOHNJOHN in the Password text box by
clicking the keys given in the emulator keypad.
7. Click the soft key below OK in the
DefaultColorPhone emulator window to view the
stock information. The stock information will be
shown in a ticker, as shown in the following
figure.

The DefaultColorPhone Emulator Window


Displaying the Stock Information
8. Select MIDletExit to close the
DefaultColorPhone emulator window.
9. Select FileExit to close the NetBeans IDE.

Summary
In this chapter, you learned that:
Events are generated when a user interacts with
high-level UI components of MIDP applications.
Events in MIDP are classified into the following
types:
High-level
Low-level

MIDP UI uses the event delegation model for


handling events.
In the event delegation model, one or more event
sources generate events.
MIDP UI APIs define the following event listener
interfaces:
CommandListener
ItemStateListener
ItemCommandListener
The Command class is used to store information
about an event.
After creating a Command object, you can add it
to a Displayable object by using the
addCommand() method.
Java ME applications implement the
ItemStateListener interface to track the
events that are generated whenever the user
changes the state of an item on a form.
The high-level UI API defines the following
animation-based UI components:
Gauge
Ticker
A ticker displays a string that continuously scrolls
along the screen of a mobile device.
You can share a Ticker object among several
Displayable objects.

Exercises
Exercise 1
Peter Peterson is working as a mobile application
developer at G Rome Ltd. His organization uses the Java
ME platform for developing mobile applications. He has
been assigned the task of developing a mobile application
that allows users to view the headlines of the day given by
the BCB news channel after providing their credentials,
such as user name and password.
As per the requirements given to Peter by his Project
Manager, the headlines of the day should be displayed as a
running text on the screen of the mobile device.

Reference Reading
Handling High-Level UIs
Reference Reading: Books
J2ME in a Nutshell: By Kim
Topley
Publisher: OReilly
Enterprise J2ME:
Developing Mobile Java

Reference Reading: URLs


http://developers.sun.com/
techtopics/mobility/getstart/
http://developers.sun.com/
techtopics/mobility/midp/

Applications
By John W. Muchow
Publisher: Prentice Hall
PTR.

ttips/llapi/

Implementing Animation-Based UI
Components
Reference Reading: Books
J2ME in a Nutshell: By Kim
Topley
Publisher: OReilly
Enterprise J2ME:
Developing Mobile Java
Applications
By John W. Muchow
Publisher: Prentice Hall
PTR.

Reference Reading: URLs


http://developers.sun.com/
techtopics/mobility/midp/
ttips/repaint/
http://developers.sun.com/
techtopics/mobility/midp/
ttips/llapi/

Chapter 6
Introducing MIDP Low-Level UI
APIs
MIDP high-level UI APIs provide you several predefined
components to build a UI for mobile applications.
However, if you have to build any custom component
according to your requirement, you have to use MIDP low
level UI APIs. MIDP low-level UI APIs provide several
classes and methods for developing and managing custom
UI components.
This chapter explains the process of developing UIs by
using MIDP low-level UI APIs. It also discusses various
classes and their methods that are provided by MIDP low
level UI APIs. Further, it explains various hardware
dependencies of low-level UI APIs. In addition, it
discusses the characteristics of low-level UI APIs.

graphical objects being displayed. However, low-level UI


APIs create porting issues because they provide devicespecific mechanisms to control input events, coloring
schemes, and graphical objects.
Low-level UI APIs provide several classes for controlling
the input events and graphical objects. The classes
provided by low-level UI APIs are:
Canvas: This class provides a blank screen to
the MIDlets on which graphical objects can be
drawn.
Graphics: This class provides methods for
drawing graphical objects.
Image: This class is used to hold graphical
image data.
Font: This class is used to represent fonts.

Working with the Canvas Class


The Canvas class is an abstract class that provides a base
for drawing graphical objects on the display of mobile
devices. It handles low-level events. In addition, the
Canvas class defines the abstract method, paint(),
which enables you to draw graphical objects.

Objectives
In this chapter, you will learn to:
Create UIs by using low-level UI APIs
Handle low-level events
Develop a moving image application

Creating User Interfaces by Using


Low-Level UI APIs
Consider a scenario where you have to develop a car
racing game for mobile devices by using the Java ME
platform. The car racing game will have several objects,
such as cars, buildings, and roads. There are no predefined
UI components that can be used to represent these objects.
Therefore, you have to create the objects for the car racing
game by using the classes and methods provided by lowlevel UI APIs of MIDP. These APIs will also allow you to
control the objects on the screen of the mobile device.
A low-level UI API enables you to control the display of a
mobile device. It also provides access to input events, such
as key press and key released. However, a low-level UI
API does not provide predefined UI controls, such as
buttons. As a result, while using a low-level UI API for
developing a UI, you need to create the required UI
controls.

Creating Low-Level UIs


A low-level UI is created for applications in which you
need to gain access to input events and control the

Note
Since the system calls the paint()method,
you need not explicitly call the paint()
method while writing the code for an
application. However, you need to use the
repaint() method to let the system know
that the paint() method needs to be called.
In order to create a UI by using the Canvas class, you
need to create a subclass of the Canvas class and
implement the paint() method.
When an object of the Canvas class is displayed on the
screen, the paint() method is automatically invoked
and an object of the Graphics class is passed to the
paint() method by the Java Runtime Environment
(JRE). The object of the Graphics class specifies the
pixels on the display screen that need to be painted.

Note
Pixel is a short form for Picture Element,
which is the smallest piece of information on
an image. The screen of a mobile device is
divided into small rectangular spaces called
pixels. The location of pixels on the display
screen is specified by using the co-ordinate
system.

The following code snippet shows how to create a


subclass of the Canvas class:
Class CanvasDemo extends Canvas {

not affect the physical location of the clip region, which


means that the clip region will contain the same set of
pixels before and after the translation.

void paint(Graphics g)
{

Note
}
}
In the preceding code snippet, the CanvasDemo class is a
subclass that is created by extending the Canvas class.
The object, g is an object of the Graphics class.
The canvas class also provides various methods to
determine the canvas size. Canvas size refers to the size of
the drawing area on the display screen of a mobile device.
This area varies from one mobile device to another. Lowlevel applications need to know the size of the display
screen of the mobile device to determine whether they can
be displayed correctly or not.
The Canvas class provides the following methods for
enabling an application to identify the canvas size of a
mobile device:
getHeight(): Retrieves the height of the
drawing area of a mobile device.
getWidth(): Retrieves the width of the
drawing area of a mobile device.

An object of the Graphics class is called a


Graphics object.

Anchor Points
The methods of the Graphics class also enable you to
modify the pixels by specifying the font and color values.
In addition, the Graphics class contains methods to
draw text on the screen of a mobile device. The text is
drawn on the screen of a mobile device with the help of
anchor points, which specifies the vertical and horizontal
positioning of the text. The anchor points are specified by
combining a horizontal constant with a vertical constant
by using the bit-wise OR operator. The horizontal
constants can be LEFT, HCENTER, or RIGHT, and the
vertical constants can be TOP, VCENTER, BASELINE, or
BOTTOM. Using zero for the anchor point value gives
results identical to TOP | LEFT.

Working with the Graphics Class


The Graphics class is used to draw primitive shapes,
such as lines and arcs. The Graphics class contains
several methods for drawing two-dimensional geometric
figures, such as rectangles and circles on the display of a
mobile device. You can also use the methods of the
Graphics class to fill the geometric figures with colors.
The Graphics class is similar to the
java.awt.Graphics class that is used in Java SE.

The Coordinate System


The methods of the Graphics class use co-ordinate
points, (x, y) to specify the pixels that need to be used for
drawing a graphical object. The co-ordinate points, (0, 0)
represent the upper left corner of the screen of a mobile
device. The numeric value of the x co-ordinate increases
from left to right. The numeric value of the y co-ordinate
increases from top to bottom.
The coordinate system can be translated for each
Graphics object. The translate() method allows
you to move the location of the origin by a specified
horizontal and vertical offsets in the coordinate system.
All subsequent operations for that Graphics object will
be performed relative to the translated origin. For
example, you can use the translate() method and the
appropriate arithmetic operations if you want to relocate
the origin to the center of the screen of a mobile device
with a positive value for y axis. However, translation does

Note
A bit-wise OR operator takes two bit patterns
and produces another one by matching up
corresponding bits. The bitwise OR operator is
represented by a "|" (pipe).

Line Stroke Styles


The methods of the Graphics class enable you to draw
shapes such as lines, arcs, rectangles, and rounded
rectangles. These shapes can be drawn by using either a
SOLID or a DOTTED stroke style, although the default
stroke style is SOLID. The setStrokeStyle()
method can be used to change the stroke style.
The lines, arcs, rectangles, and rounded rectangles are
drawn with a stroke that is one pixel wide. If you need
additional width, you must draw two or more lines in
parallel.

Clipping
A clip is a rectangular region that consists of a set of
pixels. These pixels are painted by a Graphics object
and can be modified by using graphics operations. A
Graphics object consists of a single clip. A clip can be
set by using the setClip() method. The methods
getClipWidth(), getClipHeight(), getClipX
(), and getClipY() are used for obtaining the current

clip region.

Color Support
The MIDP UIs support both the 24-bit color and the grayscale models. You can use the setColor() method to
set the current drawing color. The current color can be
used for drawing lines and text and to fill rectangles and
arcs.

Note
The low-level UI APIs do not support separate
background and foreground colors.
The 24-bit color model has eight bits for each of the red
color, the green color, and the blue color. However, few
mobile devices support the 24-bit color model. The mobile
devices that do not support 24-bit color model map the
color requested by the application to the nearest color that
is available on the device.
The gray-scale color model is supported with values in the
range of 0 to 255. You can set the current gray-scale value
by using the setGrayScale() method.
The following table describes the methods defined by the
Graphics class.
Method
Description
clipRect
(int
x, Draws a rectangle by
int y, int width, intersecting the clip of a
int height)
Graphics object with the
specified rectangle.
drawArc (int x, int Draws a circular or
y, int width, int elliptical arc by using the
height,
int current color and stroke
startAngle,
int style. A stroke style defines
arcAngle)
the way a line is drawn. A
stroke style can be solid or
dotted.
drawChar
(char Draws
the
specified
character, int x, character by using the
int y, int anchor) current font and color.
drawChars
(char[] Draws
the
specified
data, int offset, characters by using the
int length, int x, current font and color. You
int y, int anchor) can use this method to draw
more than one character
simultaneously.
drawImage
(Image Draws the specified image
img, int x, int y, by using the anchor point.
int anchor)
An anchor point specifies
the boundaries within which
an image or a text is to be
drawn.

drawLine (int x1, Draws a line between the


int y1, int x2, int coordinates (x1, y1) and
y2)
(x2,y2) by using the current
color and stroke style.
drawRect
(int
x, Draws the outline of the
int y, int width, specified rectangle by using
int height)
the current color and stroke
style.
drawRoundRect (int Draws the outline of the
x,
int
y,
int specified rounded corner
width, int height, rectangle by using the
int arcWidth, int current color and stroke
arcHeight)
style.
drawstring (String Draws the specified string
str, int x, int y, by using the current font and
int anchor)
color.
drawSubstring
Draws
the
specified
(String
str,
int substring of a string by
offset,
int
len, using the current font and
int x, int y, int color.
anchor)
fillArc (int x, int Fills a circular or elliptical
y, int width, int arc covering the specified
height,
int rectangle.
startAngle,
int
arcAngle)
fillRect
(int
x, Fills the specified rectangle
int y, int width, with the current color.
int height)
fillRoundRect (int Fills the specified rounded
x,
int
y,
int corner rectangle with the
width, int height, current color.
int arcWidth, int
arcHeight)
getDisplayColor() Is used to determine the
device color that is mapped
to a given Red-Blue-Green
(RGB) color.
isColor()
Returns true if the display is
capable
of
supporting
multiple colors, and false if
the display supports grayscale or black and white
only.
numColors()
Is used to identify the
number of distinct color or
gray levels that is available.
getColor()
Is used to identify the
corresponding color.

Table Listing the Methods of the Graphics Class

Just a minute:
Larry Williams is working as a software
developer with Blue Moon Computers. Larry
has been assigned the task to develop a bike
racing game for mobile devices. Larry needs
to draw graphical objects, such as bikes and
roads, on the display screen. Which class of
low-level UI APIs should Larry use to perform
the task?

Answer:
Graphics

Just a minute:
Tom Wilkins is working as a mobile
application developer with Red Sky IT
Systems. The management asks Tom to develop
a gaming application for mobile devices. Tom
needs to draw a rectangle by using the current
color and stroke style. Which method should
Tom use to perform the task?

Answer:
DrawRect (int x, int y, int
width, int height)

Working with the Image Class


The Image class provides methods for creating mutable
(editable) images that exist only in the off-screen memory,
called the off-screen buffer, of a mobile device. Images
created by using the Image class will not be displayed on
the screen unless an explicit command to paint the image
is issued by the application. For example, when you create
an image by using the Image class, it is not displayed on
the screen but exists in the off-screen buffer. However, the

paint() method of the Canvas class can be called to


paint the image on the screen.
The createImage() method of the Image class is a
static method that can be used to create an off-screen
mutable image. The following code snippet shows the use
of the createImage() method:
Image img = Image.createImage(100,
100);
The preceding code snippet creates a mutable image with
the width and height as 100 pixels each.
In addition, the Image class provides the following static
methods to create an immutable image:
public static Image createImage
(String name): Used to load images that are
included as a part of MIDlet installed on the
mobile device.
public static Image createImage
(byte [] data, int offset, int
length): Used to create an image from the data
read into a byte array from the network or the
data retrieved from the devices permanent
storage.
There are several other methods provided by the Image
class that can be used to create and modify off-screen
images. The following table describes some of the
methods defined by the Image class.
Method
createImage(Image
source)
getGraphics()

getHeight()
getWidth()
isMutable()

Description
Creates an immutable image
from a source image.
Creates and returns a new
Graphics object that renders
the source image.
Gets the height of an image
in pixels.
Gets the width of an image
in pixels.
Checks whether an image is
mutable or not.

Some Methods of the Image Class

Working with the Font Class


The Font class provides support for using fonts in MIDP
UIs. The getFont() method of this class can be used to
obtain an object that represents a font. The attributes of a
font are passed as parameters to the method. If the
requested font is not available, the operating system
returns an in-built font that matches the requested font as
closely as possible.
The following attributes are passed to the getFont()
method:
Face: Specifies the font face for the requested
font. The following fields can be used to specify

the font face:


FACE_SYSTEM
FACE_MONOSPACE
FACE_PROPORTIONAL
Style: Specifies the font style for the requested
font. The following fields can be used to specify
the style of the requested font:
STYLE_PLAIN
STYLE_BOLD
STYLE_ITALIC
STYLE_UNDERLINED
The fields, STYLE_BOLD, STYLE_ITALIC,
and STYLE_UNDERLINED, can be combined by
using the | (OR) operator to specify the font. For
example, the constant, STYLE_BOLD |
STYLE_UNDERLINED is used to specify the
font as bold and underlined. However, the
STYLE_PLAIN field cannot be combined with
any other style.
Size: Specifies the size for the requested font.
One of the following fields can be used to specify
the size of the font:
SIZE_SMALL
SIZE_MEDIUM
SIZE_LARGE
The following code snippet shows the use of the
getFont() method:
Font font = Font.getFont(FACE_SYSTEM,
STYLE_PLAIN, SIZE_MEDIUM);
In the preceding code snippet, font is an object of the
Font class. FACE_SYSTEM, STYLE_PLAIN, and
SIZE_MEDIUM are the values for the attributes of the
required font.
Several other methods are provided by the Font class to
manage fonts in an MIDP application.
The following table describes some of the methods
provided by the Font class.
Method
getFace()
getDefaultFont()
getHeight()
getSize()
getStyle()
isBold()
isItalic()
isPlain()
isUnderlined()

Description
Returns the face of the font.
Returns the default font of
the system.
Returns the standard height
of a line of text in this font.
Returns the size of the font.
Returns the style of the font.
Returns true if the font is
bold.
Returns true if the font is
italic.
Returns true if the font is
plain.
Returns true if the font is

underlined.

Some Methods of the Font class

Drawing Graphical Objects


The Graphics class provides various low-level drawing
primitives. To draw various shapes, you need to call the
respective methods of the Graphics class that will allow
you to set the color, translation, and clipping.

Drawing Shapes
The following figure shows the result of the code
g.drawLine(4, 1, 19, 7);.

Example of the drawLine() Method


In the preceding figure, x1 = 4, y1 = 1, x2 = 19, and y2 =
7.
The following figure shows the result of the code
g.drawRect(5, 2, 15, 8);.

Example of the drawRect() Method


In the preceding figure, x = 5, y = 2, height = 8, and width
= 15.
The following figure shows the result of the code
g.fillRoundRect(4, 2, 16, 8, 6, 6).

Example of the fillRoundRect() Method


In the preceding figure, x = 4, y = 2, width = 16, height =
8, arc width = 6, and arc height = 6.

Drawing Text
The Graphics class provides methods using which you
can draw text in the form of a single character, an array of
characters, a string, or a part of a string. The characters are
rendered by using the current drawing color of the
Graphics object. The pixels within and around the
characters are left unchanged. The following table lists
some of the methods that are used to draw text and their
corresponding descriptions.
Method
Description
Public
void Renders the character c. the
drawChar(char
c, position of c is determined
int x, int y, int by x, y, and the anchor
anchor)
arguments.
drawChars(char[]
Draws characters ch[offset]
ch, int offset, int through ch[offset+length-1]
length, int x, int by using the arguments x, y,
y,int anchor)
and anchor that provides the
positioning information.
drawString(String Renders the string str at the
s, int x, int y, given location.
int anchor)
drawSubstring
Draws the part of the string
(String
s,
int given by the argument s that
offset, int length, occupies the character
int x, int y, int positions offset to (offset +
anchor)
length - 1).

Table Describing Some of the Methods for Drawing


Text
You can use the following line of code to draw the string,
Hello World in the top left corner of the Canvas:
g.drawString(Hello World, 0, 0,
Graphics.TOP | Graphics.LEFT);
To right-justify the string, Hello World at the top of the
canvas, you need to write the following code:
g.drawString(Hello, World,
canvas.getWidth(), 0, Graphics.TOP |
Graphics.RIGHT);

Drawing Images
If you have a mutable or an immutable image, you can
draw it onto a Canvas by using the drawImage()
method, as shown in the following code snippet:
public void drawImage (Image im, int x,
int y, int anchor)
The drawImage() method renders an entire Image at a
location specified by x, y, and anchor.

Identifying Characteristics of LowLevel UI APIs

The characteristics of MIDP low-level UI APIs that enable


you to efficiently create the UIs of mobile applications
include:
Font support
Repaint technique
Double buffering

Font Support
MIDP low-level UI APIs provide support for various fonts
by using the Font class. An application cannot create
fonts, but it can request for a font based on the face, style,
and size attributes.
The face, style, and size attributes are passed as
parameters to the getFont() method of the Font class
for obtaining an object that represents a font.
After obtaining a font, you can use the getFace(),
getSize(), and getStyle() methods to retrieve
information about the font attributes.

Repainting Technique
Repainting is a technique that is used to refresh the screen
of a mobile device. When an object of the Screen class
is displayed, the changes made to that object are
automatically reflected on the mobile device. However,
when an application displays an object of the Canvas
class, you need to use the repainting technique for
reflecting the changes made to the Canvas object.
The following methods of the Canvas class can be used
for repainting a component:
public final void repaint(int x,
int y, int width, int height):
Requests the paint() method to draw the
graphical objects on the specified drawing region.
public final void repaint():
Requests the paint() method to draw the
entire canvas.
The repaint (0, 0, getWidth(), getHeight
()) method is also used to repaint the entire canvas.
In low-level UI APIs, the canvas is painted with several
components. All the components cannot be repainted with
a single repaint() method. Therefore, an MIDP
application calls several repaint() methods at the
same time to repaint various components simultaneously
(at the same time). The repaint() methods can return
without waiting for the paint() method to finish
executing. In order to synchronize the repaint()
method with the paint() method, you can use either the
Display.callSerially() method or the
serviceRepaints() method.
When more than one paint requests are in queue, the
serviceRepaints() method forces the paint()
method to complete its task immediately. This is
performed by a single thread. The serviceRepaints
() method blocks the thread until the painting is finished.

Meanwhile, if any other thread tries to call the paint()


method on the same canvas, a deadlock occurs. This is
because the paint() method is trying to access an
object that is already locked.

Graphics context is a collection of information


about the graphical output displayed on the
screen of a mobile device.

Creating a Mutable Image


Note
Deadlock is a situation when two methods try
to access the same operating system resource
simultaneously. As a result, none of the
methods gain access to that resource and the
methods are not executed. In order to avoid
deadlock, you must not call the paint() and
the serviceRepaints() method from the
same thread.

Double Buffering
Double buffering is a technique in which you draw
graphical objects on a copy of the mobile device screen,
instead of the original display screen. The copy of the
screen, called off-screen buffer, is maintained in the
memory of a mobile device. After you have finished
drawing the graphical objects on the off-screen buffer, the
contents of the off-screen buffer are copied to the display
screen.
The advantage of double buffering is that it makes the
screen updates look smooth because the user never sees
partially updated frames on the screen. The partially
updated frames can result in display flashing or temporary
inconsistencies while the display is being redrawn on the
screen. This results in flickering of the display. Double
buffering solves this problem by enabling you to create
flicker-free screens.
Most of the mobile devices support double buffering by
default. However, some mobile devices do not support
double buffering. As a result, you need to implement
double buffering for these mobile devices in the
application code itself. You can implement the code for
double buffering in MIDP applications by using the lowlevel UI APIs.
In order to implement double buffering, you need to
perform the following tasks:
1. Create a mutable image with the size of the
screen.
2. Obtain a graphics context for the off-screen
buffer.
3. Draw graphical objects on the off-screen buffer.
4. Copy the off-screen buffer on the display screen.

Note

A mutable image is a copy of an original image that can be


modified. The following code snippet shows how to create
a mutable image with the size of the screen:
int w = getWidth ();
int h = getHeight ();
Image offscreenImg = Image.createImage
(w, h);

Obtaining a Graphics Context


To obtain a graphics context for the off-screen buffer, you
need to create an instance of the Graphics class and
instantiate it with the getGraphics() method of the
Image class. The following code snippet shows how to
obtain a graphics context for the off-screen buffer:
Graphics g = offscreenImg.getGraphics
();

Drawing Graphical Objects


After obtaining the graphics context for the off-screen
buffer, you need to draw graphical objects on it. The
following code snippet shows how to draw a rectangle on
the off-screen buffer:
g.drawRect (20, 20, 25, 30);

Copying the Off-screen Buffer


After creating an image on the off-screen buffer, you need
to copy the off-screen buffer on the screen of the mobile
device. To copy the off-screen buffer on the screen of a
mobile device, you need to override the paint()
method. The following code snippet shows how to
override the paint() method:
public void paint(Graphics g) {
g.drawImage(mImage, 0, 0,
Graphics.TOP | Graphics.LEFT);
}
The paint() method is either called automatically or by
the repaint() method. In both the cases, the
Graphics object is automatically passed to the paint
() method.
The following code shows how to implement double
buffering:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class Canvas1 extends MIDlet {
protected Display display;
protected Displayable displayable;
public Canvas1() {
display = Display.getDisplay

(this);
displayable = new MyCanvas1();
}
public void startApp() {
display.setCurrent(displayable);
}

Answer:
int width = getWidth (); int
height = getHeight (); Image
buffer = Image.createImage
(width, height);

public void pauseApp() {


}
public void destroyApp(boolean
unconditional) {
display = null;
displayable = null;
}
}
class MyCanvas1 extends Canvas {
private Image mImage;
public void paint(Graphics g) {
if (mImage == null)
initialize();
g.drawImage(mImage, 0, 0,
Graphics.TOP | Graphics.LEFT);
}
private void initialize() {
int w = getWidth();
int h = getHeight();
mImage = Image.createImage(w, h);
Graphics g = mImage.getGraphics();
g.drawRect(70, 100, 100, 100);
g.drawRect(95, 125, 50, 50);
}
}

Just a minute:
Steve works as a software programmer with
Super Graphics Inc. The management asks
Steve to develop a gaming application for a
mobile device. To make the game flicker-free,
Steve decides to implement the double
buffering technique in the application. For
this, Steve wants to create an image with the
size of the screen. Write a code snippet that
will help Steve to achieve the task?

Just a minute:
Ron works as a software programmer with
Blue Moon Computers. Ron needs to develop a
game for mobile devices. To improve the
quality of the display, Ron decides to
implement the double buffering technique. For
this, Ron draws a mutable image on the offscreen buffer. Now, he needs to copy the image
from the off-screen buffer to the screen of a
mobile device. What should Ron do to perform
the task?

Answer:
public void paint (Graphics g)
{ g.drawImage ( buffer, 0, 0,
0);}

Handling Low-level Events


Consider a scenario where you have developed a low-level
UI for a bike race mobile game. You have developed
various components, such as a bike, a road, and a building
by using MIDP low-level UI APIs. However, you want to
turn the bike left or right on the screen, depending on the
left or right key pressed by a user.
Whenever a user presses a key on the mobile device, an
event is generated. MIDP low-level UI APIs provide a
mechanism to handle these events and move the objects
according to the requirements of an application.

Using the Canvas Class for Handling


Low-Level Events
There are two kinds of low-level event handling:
Key events
Pointer events

Key Events

You can add commands to an object of the Canvas class


for mapping the keys on the keypad of mobile devices.
However, the Canvas class allows you to capture keypress events for most of the keys available on a mobile
device. The following methods of the Canvas class needs
to be used for monitoring key-press activities:
keyPressed(): This method can be used to
monitor the event that is generated when a user
presses any key on the keypad of the mobile
device.
keyReleased(): This method is used to
monitor the event that is generated when a
pressed key is released.
keyRepeated(): This method is used to
monitor the event that is generated when a key is
held down. All platforms may not support this
event. You can verify whether a platform
supports this event or not with the help of the
hasRepeatEvents() method.
To monitor key events, you need to ensure that a subclass
of the Canvas class overrides one of the preceding
methods. All the preceding methods take an int
parameter that represents a key code of a mobile device.
Every key for which events are generated is assigned a key
code. Key codes can vary for different mobile devices. For
example, on mobile device A, pressing "2" on the keypad
may give the key code 25 but on mobile device B, the
same key might give the key code 12. However, to make
the application portable across various mobile devices, key
codes are standardized for all mobile devices.
The Canvas class provides a numeric key mapping for
standardizing key codes. There are 10 constant values,
ranging from 0 to 9, each corresponding to a 10-digit
numeric keypad. In addition, two more constant values are
provided by the Canvas class for the "*" and "#" keys.
The following constants for the key codes are provided by
the Canvas class:
KEY_NUM0
KEY_NUM1
KEY_NUM2
KEY_NUM3
KEY_NUM4
KEY_NUM5
KEY_NUM6
KEY_NUM7
KEY_NUM8
KEY_NUM9
KEY_STAR
KEY_POUND

Pointer Events
The Canvas class has methods that the application can
override to handle pointer events. Pointer events are
events that are generated from a pointing device such as a
stylus. If the application needs to handle pointer events, it

must override and implement the methods,


pointerPressed(), pointerReleased(), and
pointerDragged().
Not all MIDP target devices support pointer events, and
therefore the pointer methods might never be called. The
application can check whether the pointer and pointer
motion events are available by calling the methods,
hasPointerEvents() and
hasPointerMotionEvents().

Implementing Low-Level Event


Handling
The following code snippet shows how to handle lowlevel events by using the keyPressed() method:
class MyCanvas1 extends Canvas {
public void paint(Graphics g) { }
public void keyPressed(int kpress)
{
if (kpress == KEY_NUM4)
{
System.out.println("Key 4 is
Pressed!");
}
}
}
In the preceding code snippet, kpress is an int value
passed as a parameter to the keyPressed() method.
The method implementation checks weather the value of
the variable, kpress is equal to the key code,
KEY_NUM4 or not.
MIDP does not provide constants to map all the keys of a
mobile device that support more than a 10-digit keypad,
such as an alphanumeric keypad. If an application needs to
monitor an extended key code range, device-specific key
handling needs to be implemented.

Developing a Moving Image


Application
Problem Statement
You are working as a mobile application developer with
Global Systems Inc. The organization specializes in
developing mobile applications by using the Java ME
platform. You are a part of a team that is currently working
on developing a game. You are assigned the task of
moving an object in different directions on the screen. You
need to ensure that the image of the object does not flicker.
Prerequisites: The car.png file is needed to run this
application. Ask your faculty to provide the preceding
input file.

Solution

public class ImageMIDlet extends


MIDlet {

To create a phonebook application, you need to perform


the following tasks:
1. Create a NetBeans project.
2. Add class files to the project.
3. Build and execute the project.

protected Display display;


protected Displayable
displayable;

Task 1: Creating a NetBeans Project


To create a NetBeans project, you need to perform the
following steps:
1. Select startAll
ProgramsNetBeansNetBeans IDE 6.0.1 to
open the NetBeans IDE 6.0.1 window.
2. Select FileNew Project to open the New
Project dialog box.
3. Ensure that the Mobility option is selected in the
Categories section.
4. Ensure that the MIDP Application option is
selected in the Projects section.
5. Click the Next button. The Name and Location
page is displayed.
6. Type DisplayImageApp in the Project Name
text box to assign a name to the new project.
7. Ensure that <Drive Letter>:\JavaMEProjects is
displayed in the Project Location text box.
8. Clear the Create Hello MIDlet check box.
9. Click the Next button. The Default Platform
Selection page is displayed.
10. Click the Next button. The More Configurations
Selection page is displayed.
11. Click the Finish button to create the
DisplayImageApp project.

Task 2: Adding Class Files to the Project


For adding files to the DisplayImageApp project, you
need to perform the following steps:
1. Select FileNew File to open the New File
dialog box.
2. Ensure that the MIDP option is selected from the
Categories section.
3. Ensure that the MIDlet option is selected in the
File Types section.
4. Click the Next button. The Name & Location
page is displayed.
5. Type ImageMIDlet in theMIDlet Name text box
to assign a name to the new MIDlet.
6. Click the Finish button to create the
ImageMIDlet.java MIDlet.
7. Replace the existing code for the
ImageMIDlet.java MIDlet in the Editor with the
following code:
import
javax.microedition.midlet.*;
import
javax.microedition.lcdui.*;

public ImageMIDlet() {
display = Display.getDisplay
(this);
displayable = new
ImageCanvas();
}
public void startApp() {
display.setCurrent
(displayable);
}
public void pauseApp() {
}
public void destroyApp(boolean
unconditional) {
display = null;
displayable = null;
}

8.
9.
10.
11.
12.
13.
14.

}
Select FileNew File to open the New File
dialog box.
Select the Java option from the Categories
section.
Ensure that the Java Class option is selected in
the File Types section.
Click the Next button. The Name and Location
page is displayed.
Type ImageCanvas in theClass Name text box
to assign a name to the new Java class file.
Click the Finish button to create the
ImageCanvas.java Java class file.
Replace the existing code for the
ImageCanvas.java Java class file in the Editor
with the following code:
import java.io.IOException;
import
javax.microedition.lcdui.*;
import javax.microedition.io.*;
class ImageCanvas extends Canvas
{
private Image mImage;

//initializing variables with


the size of the screen
int imageX=getWidth()/2;
int imageY=getHeight()/2;
int anchor= Graphics.VCENTER|
Graphics.HCENTER;
public void paint(Graphics g) {
try {
g.setColor(255,255,255);
// sets the drawing color to
white
g.fillRect(0, 0, getWidth(),
getHeight());
mImage = Image.createImage("/
car.png");
//drawing the image on the
middle of the screen
g.drawImage
(mImage,imageX ,imageY ,anchor);
} catch (IOException ex) {
ex.printStackTrace();
}
}
//method of displaying the image
on the left of the screen
public void left()
{
imageX=0;
imageY=getHeight()/2;
anchor= Graphics.VCENTER|
Graphics.LEFT;
repaint();
}
//method of displaying the image
on the right of the screen
public void right()
{
imageX=190;
imageY=getHeight()/2;
anchor= Graphics.VCENTER|
Graphics.LEFT;
repaint();
}
//method of displaying the image
on the top of the screen
public void top()
{
imageX=getWidth()/2-20;
imageY=50;
anchor= Graphics.VCENTER|
Graphics.LEFT;
repaint();
}
//method of displaying the image

on the bottom of the screen


public void bottom()
{
imageX=getWidth()/2-20;
imageY=getHeight()-50;
anchor= Graphics.VCENTER|
Graphics.LEFT;
repaint();
}
//method for tracking keypressed events
protected void keyPressed(int
keyCode)
{
if ((keyCode == KEY_NUM4)) {
System.out.println("You have
pressed Left Key");
left();
}
if ((keyCode == KEY_NUM6)) {
System.out.println("You have
pressed Right Key");
right();
}
if ((keyCode == KEY_NUM2)){
System.out.println("You have
pressed Up Key");
top();
}
if ((keyCode == KEY_NUM8)) {
System.out.println("You have
pressed Down Key");
bottom();
}
}
}
15. Copy the car.png file to the <Drive Letter>:
\JavaMEProjects\DisplayImageApp\src folder.
16. Switch to the NetBeans window.

Task 3: Building and Executing the


DisplayImageApp Project
To build and execute the DisplayImageApp project, you
need to perform the following steps:
1. Select BuildBuild Main Projectto build the
DisplayImageApp project.
2. Select RunRun Main Project to execute the
DisplayImageApp project. The
DefaultColorPhone emulator window is
displayed, as shown in the following figure.

The DefaultColorPhone Emulator Window


3. Click the soft key below Launch to launch the
ImageMidlet MIDlet. An image of a car will be
displayed, as shown in the following figure.

The DefaultColorPhone Emulator Window


Displaying an Image
4. Press the 4 key on the keypad of the
DefaultColorPhone emulator to move the image
to the left of the emulator screen. The image of
the car will be displayed on the left of the
emulator screen, as shown in the following
figure.

Summary

The DefaultColorPhone Emulator Window


Displaying an Image

Note
You can press the keys, 2, 6, and 8 to
move the image to the top, right, or
bottom, respectively on the emulator
screen.
5. Select MIDletExit to close the
DefaultColorPhone emulator window.
6. Select FileExit to close the NetBeansIDE.

In this chapter, you learned that:


Low-level UI APIs provide access to input
events, such as a key press.
A low-level UI is created for developing
applications in which you need to gain access to
input events and control the graphical objects
being displayed.
Low-level UI APIs create porting issues because
they provide device-specific mechanisms to
control input events, coloring schemes, and
graphical objects.
Low-level UI APIs provide the following classes
for controlling the input events and graphical
objects:
Canvas
Graphics
Image
Font
The Canvas class is an abstract class that
provides a base for drawing graphical objects on
the display of mobile devices.
To create a UI by using the Canvas class, you
need to create a subclass of the Canvas class
and implement the paint() method.
The Graphics class is used to draw primitive
shapes, such as lines and arcs.
The methods of the Graphics object use the
co-ordinate points, (x, y) to specify the pixels that
need to be modified for drawing a graphical
object.
The methods of the Graphics class also enable
you to modify the pixels by specifying the font
and color values.
The methods of the Graphics class enable you
to draw shapes such as lines, arcs, rectangles, and
rounded rectangles.
A clip is a rectangular region that consists of a set
of pixels.
The MIDP UIs support both the 24-bit color and
the gray-scale models.
The Image class provides methods for creating
mutable images that exist only in the off-screen
memory, called off-screen buffer, of a mobile
device.
The createImage() method of the Image
class can be used to create an off-screen mutable
image.
The Font class provides support for using fonts
in MIDP UIs.
The getFont() method of this class can be
used to obtain an object that represents a font.
The following attributes are passed to the

getFont() method:
Face
Style
Size
The Graphics class provides various low-level
drawing primitives.
To draw various shapes, you need to call the
respective methods of the Graphics class that will
allow you to set the color, translation, and
clipping.
The Graphics class provides methods using
which you can draw text in the form of a single
character, an array of characters, a string, or a
part of a string.
If you have a mutable or an immutable image,
you can draw it onto a Canvas by using the
drawImage()method.
The characteristics of MIDP low-level UI APIs
that enable you to efficiently create the UIs of
mobile applications include:
Font support
Repaint technique
Double buffering
Repainting is a technique that is used to refresh
the screen of a mobile device.
In order to synchronize the repaint() method
with the paint() method, you can either use
the Display.callSerially() method or
the serviceRepaints() method.
Double buffering is a technique in which you
draw graphical objects on a copy of the screen of
a mobile device, instead of the original screen.
Double buffering involves the following tasks:
a. Creating a mutable image with the size
of the screen.
b. Obtaining a graphics context for the offscreen buffer.
c. Drawing graphical objects on the offscreen buffer.
d. Copying the off-screen buffer on the
display screen.
There are two kinds of low-level event handling:
Key events
Pointer events

Exercises
Exercise 1
You are working as a mobile application developer with
Global Systems Inc. The organization specializes in
developing mobile applications by using the Java ME
platform. You are a part of a team that is currently working
on developing a game. You are assigned to develop a

module of the game where you need to display an image


of a smiley in different corners of the screen depending on
the corresponding keys pressed by a user. You need to
ensure that the image of the smiley does not flicker.
Prerequisites: The smiley.png file is needed to run the
application.

Reference Reading
Creating User Interfaces by Using
Low-Level UI APIs
Reference Reading: Books
J2ME in a Nutshell: By Kim
Topley
Publisher: OReilly
Enterprise J2ME:
Developing Mobile Java
Applications
By John W. Muchow
Publisher: Prentice Hall
PTR.

Reference Reading: URLs


http://developers.sun.com/
techtopics/mobility/midp/
ttips/repaint/
http://developers.sun.com/
techtopics/mobility/midp/
ttips/llapi/

Handling Low-level Events


Reference Reading: Books
J2ME in a Nutshell: By Kim
Topley
Publisher: OReilly
Enterprise J2ME:
Developing Mobile Java
Applications
By John W. Muchow
Publisher: Prentice Hall
PTR.

Reference Reading: URLs


http://developers.sun.com/
techtopics/mobility/midp/
ttips/repaint/
http://developers.sun.com/
techtopics/mobility/midp/
ttips/llapi/

Chapter 7
Implementing Persistent Storage
Support in MIDP
Many times, application data needs to be preserved for
future use after the application has been closed. For
example, you have created a playlist for your media player
application. You need to preserve the playlist for the next
time the application is run. For this, the media player
application needs to implement persistent storage.
The javax.microedition.rms package provides
classes and interfaces for implementing persistence
storage in MIDlets. It helps you to create and manage
record stores for persisting the application data.
This chapter discusses the implementation of persistent
storage in MIDlets. It also explains the process of
managing record stores and records. In addition, it
discusses the use of various interfaces provided by the
javax.microedition.rms package.

device.
A MIDlet application can store data into a binary file
before it terminates. When the application is executed
again, it can retrieve the data from the binary file. RMS
enables various MIDlets in a MIDlet suite to share
common data.

Managing a Record Store Within


MIDlet Suites
A MIDlet suite can have several record stores, which are
identified with the help of their names and the MIDletvendor attribute. Each record store within a MIDlet suite
is represented by a unique name. Therefore, MIDlets
within a MIDlet suite are not allowed to create more than
one record store with the same name. Record stores cannot
be shared among different MIDlet suites in MIDP 1.0.
However, in MIDP 2.0, you can share the record stores
with other MIDlet suites.
A record store is implemented in MIDlet suites by using
an instance of the
javax.microedition.rms.RecordStore class.

Objectives
In this chapter, you will learn to:
Implement persistent storage in MIDlets

Implementing Persistent Storage in


MIDlets
Persistent storage is a permanent storage space that is used
to store objects and their states.
When an application is closed, objects used in the
application along with their states are destroyed. Persistent
storage enables you to store these objects and their states
even after the application has been closed. As a result, you
can read the state of these objects and work with them the
next time the application is executed. For example, when
you make a new high score while playing a game in your
mobile device, the new high score is added to the list of
high scores. Every time when you run the application after
closing it, you can view the previous high scores that
persisted on the mobile device.
The MIDP Record Management System (RMS) is a
mechanism that provides persistent storage for MIDlets.
The MIDP RMS helps you to store persistent data by
using a record store in a mobile device. A record store is a
database that stores records on a mobile device. RMS
consists of a set of classes and interfaces that help to
implement and manipulate record stores. It stores records
in a binary file that resides in the memory of a mobile

Note
The implementation of the RecordStore
class ensures that all individual operations on
a record store are atomic (indivisible),
synchronous (exist at the same time), and
serialized (arranged serially). As a result, the
chance of inconsistency in case of multiple
access is reduced.
The following table describes the methods defined by the
javax.microedition.rms.RecordStore class.
Method
Description
int addRecord(byte Adds a record to a record
[]
data,
int store. This method returns
offset,
int the recordID of the new
numBytes)
record that is added to the
record store.
addRecordListener Adds a specified listener to
(RecordListener
a record store. When a
listener)
record store is closed, all the
listeners registered to it are
removed.
closeRecordStore() Closes the current record
store. If you try to access the
record store that has been
closed,
the

RecordStoreNotOpenE
xception is thrown.
Deletes a particular record
from a record store.
Deletes a record store with
the specified record store
name.
Returns an enumeration for
traversing a set of records in
a record store.

deleteRecord(int
recordId)
deleteRecordStore
(String
recordStoreName)
RecordEnumeration
enumerateRecords
(RecordFilter
filter,
RecordComparator
comparator, Boolean
keepUpdated)
getNextRecordID() Returns the recordID of
the next record to be entered
in a record store. This
recordID is valid only
before the recordset is
closed and the call to
addRecord() method is
made.
getRecord(int
Returns the data stored in a
recordId)
specified record. Returns the
value, NULL, if the specified
record does not exist.
listRecordStores() Displays an array of the
names of record stores
present in a MIDlet suite.
openRecordStore
Opens a record store present
(String
in a MIDlet suite. If the
recordStoreName,
record store is not present in
Boolean
the MIDlet suite, this
createIfNecessary) method creates the specified
record store.
openRecordStore
Opens a record store that
(String
can be shared among other
recordStoreName,
MIDlet suites. This method
boolean
creates a record store if the
createIfNecessary, specified record store is not
int
authmode, present in a MIDlet suite.
boolean writable) writable is a boolean
variable that is used to
specify
whether
other
MIDlet suites are allowed to
write in the record store or
not.
openRecordStore
Opens a record store
(String
associated with the specified
recordStoreName,
MIDlet suite. The access to
String vendorName, the record store is governed
String suiteName) by the authorization mode of
the current MIDlet suite.
removeRecordListene Removes
the
specified

r(RecordListener
listener from a record store.
listener)
setMode(int
Modifies the access mode
authmode,
Boolean for the current record store.
writable)

Table Describing the Methods of the RecordStore


Class
The methods of the RecordStore class can be used to
manage record stores in MIDlet suites. The following
activities are involved in managing record stores:
Creating and opening record stores
Sharing record stores
Closing record stores
Removing record stores
Several exceptions are thrown while managing record
stores. These are:
InvalidRecordIDException: Is thrown
when an operation could not be completed
because of an invalid record identification (ID).
RecordStoreException: Is thrown when an
exception occurs in a record store operation.
RecordStoreFullException: Is thrown
when an operation could not be completed
because the record store is full.
RecordStoreNotFoundException: Is
thrown when an operation could not be
completed because the record store could not be
found.
RecordStoreNotOpenException: Is
thrown when an operation is attempted on a
closed record store.

Just a minute:
Which method of the RecordStore class
deletes the record store with the specified
record store name?

Answer:
deleteRecordStore(String
recordStoreName)

Sharing a Record Store

Just a minute:
State whether the following statement is true
or false.

It is not possible to share record stores across


MIDlet suites in MIDP 2.0.

Answer:
False

Creating and Opening a Record Store


You can use the RecordStore.OpenRecordStore
() method to create and open a record store. This method
returns an object of the RecordStore class.
You can use the following method to open a record store:
RecordStore openRecordStore(String
recordStoreName,
boolean createIfNecessary)
In the preceding syntax, the openRecordStore()
method opens an existing record store within a MIDlet
suite. If the record store does not exist, the boolean
variable, createIfNecessary, is set to true and a new
record store is created.
The following code snippet shows how to open a record
store:
import javax.microedition.rms.*;

You can create and share a new record store across MIDlet
suites by providing additional attributes to the
openRecordStore() method.
The following code snippet shows how to share a record
store across other MIDlet suites:
RecordStore openRecordStore(String
recordStoreName,
boolean createIfNecessary,
int authmode,
boolean writable)
To share a record store, you need to pass the following
additional parameters to the openRecordStore()
method:
authmode: Represents the authorization mode
that determines whether other MIDlet suites can
access a record store in the specified MIDlet
suite.
writable: Determines whether other MIDlet
suites can change a record store in the specified
MIDlet suite. If the writable parameter is set
to false, the customer MIDlet suites can only read
the record store.
The following code snippet shows how a record store is
shared with other MIDlet suites:
RecordStore rs = null;
int authMode =
RecordStore.AUTHMODE_ANY;
boolean writable = true;
rs = RecordStore.openRecordStore
( "myrs", true, authMode, writable );
In the preceding code snippet, rs is an instance of the
RecordStore class. The authorization mode of the rs
record store is set to AUTHMODE_ANY for sharing the
record store with other MIDlet suites.

class NewClass {
public void analyze( String rsName ){
RecordStore rs = null;
try {
rs = RecordStore.openRecordStore
( rsName, false );
} catch( RecordStoreException e ){}
finally {
try {
rs.closeRecordStore();
} catch( RecordStoreException e ){
// Ignore this exception
}
}
}
}

Note
The value of the authmode and writable
parameters can be altered at any time by the
MIDlet suite that contains the record store.
This is performed by using the
RecordStore.setMode() function.

Closing a RecordStore
You need to close a record store when it is no longer
required or when the application using the record store is
terminated. A record store can be closed by calling the
closeRecordStore() method of the RecordStore
class.
The syntax of the closeRecordStore() method is:
rs.closeRecordStore();

In the preceding syntax, the closeRecordStore()


method closes the RcrdStore record store.

Removing a Record Store


A record store can be removed from a MIDlet suite by
using the deleteRecordStore() method. A record
store can only be removed by the MIDlet suite that has
created it.
The syntax of the deleteRecordStore() method is:
static RecordStore.deleteRecordStore
(String storeName)
A record store can be removed only after it is closed. If a
MIDlet suite is removed from a mobile device, all the
associated record stores in that MIDlet suite are
automatically removed.
The following code snippet shows how to remove a record
store from a MIDlet suite:
String RecordName= rs.getName();
try {
RecordStore.deleteRecordStore
(RecordName);
} catch (RecordStoreNotFoundException
e){
// No such record store
} catch (RecordStoreException e){
// record store is already open
}

Managing Records in a Record Store


A record store consists of individual units of storage called
records. Records can contain a number, a string, an array,
or an image. However, the records are represented as a
byte array.
The RMS creates a record store and adds individual
records to it. When a record is created, the record store
assigns a unique identifier called recordID to the
created record. For example, the first record of a record
store is assigned the recordID, one, and the second
record is assigned the recordID, two.

The following tasks are performed for managing records


in a record store:
Add records
Modify records
Delete records

Adding a Record
A new record can be added to a record store by using the
addRecord() method of the RecordStore class.
When you add a new record to a record store, the new
record is added at the end of the record store.
The syntax of the addRecord() method is:
int addRecord(byte[] data, int offset,
int numBytes)
The following parameters are passed to the addRecord
() method:
byte[] data: Specifies a byte array that
contains the data to be added to a record store. If
this parameter is left blank, an empty record is
added to the record store.
int offset: Specifies the offset of the array.
int numBytes: Specifies the number of bytes
to be written to the record.
If a record is added successfully, the addRecord()
method returns a new recordID for it.

Converting Data to a Byte Array


Because the addRecord() method takes a byte array as
a parameter, you need to convert the data that needs to be
stored in a record store into a byte array. To convert data
into a byte array, you can use the methods provided by the
ByteArrayOutputStream and
DataOutputStream classes. These classes are
provided in the java.io package.
The following code snippet shows how to convert data
into a byte array for storing the data in a record store:
public class NewClass {
public NewClass() throws IOException,
RecordStoreNotOpenException,
RecordStoreException{
int val = 1;
String str = "Hello";
//Create a new record store
RecordStore rs = null;

Note
RecordIDs are not reusable. This is because
when a record is deleted, the remaining
records are not renumbered to maintain a
continuous sequence.
Record IDs persist until the record is removed from the
record store. RMS uses this record ID to efficiently
manage individual records in a record store. RMS treats
each record as a byte array with a unique ID, and is not
concerned with the actual content of each record.

//Create an object of the


ByteArrayOutputStream
ByteArrayOutputStream byteOut = new
ByteArrayOutputStream();
//Create a data output stream by
using the byteOut object
DataOutputStream out = new
DataOutputStream(byteOut);

//Write the data to the output stream


out.writeInt(val);
out.writeUTF(str);
//Create a byte array and initialize
it with the data in the //output stream
byte[] data = byteOut.toByteArray();
//Add the byte array data to the
record store
rs.addRecord(data, 0, data.length);
}
}
In the preceding code snippet, the data converted into a
byte array is added to the record store by using the
addRecord() method. The process of converting a byte
array into record store data is initiated by creating a
ByteArrayOutputStream object and using it in the
DataOutputStream object. The writeInt()and
writeUTF() methods of the DataOutputStream
class are used to write primitive data types to an output
stream.
Various other methods provided by the
DataOutputStream class for writing primitive data
types to an output stream are:
writeBoolean()
writeByte()
writeChar()
writeShort()
writeLong()

Exceptions Encountered while Adding


Records
The following exceptions are raised when a record is
added to a record store by using the addRecord()
method:
RecordStoreNotOpenException: Is
raised if a record store is not opened.
RecordStoreFullException: Is raised if
the required space for a new record store is not
available.
RecordStoreException: Is raised if a
general exception occurs in a record store
operation.
SecurityException: Is raised if a record
cannot be added to a record store due to security
limitations.

Retrieving a Record
You can retrieve a record from a record store by using the
getRecord() method of the RecordStore class.
The syntaxes of the getRecord() method are:
getRecord (int recordID): This method
creates a byte array of the desired size, and
copies data to it.

getRecord (int recordID, byte []


data, int offset): This method copies
data into a preallocated array, starting from an
offset, and returns the number of bytes copied to
the array.

Converting Byte array to Get Record


Store Data
To retrieve a record, you use the getRecord() method
that returns a byte array containing data. You can convert
this byte array to primitive data types for retrieving the
data of a record store. To convert a byte array to primitive
data types, you can use the methods provided by the
ByteArrayInputStream and DataInputStream
classes. These classes are provided in the java.io
package.
The following code snippet shows the conversion of a byte
array, which is returned by the getRecord() method, to
a primitive data type:
public void readStream()throws
RecordStoreNotOpenException,
InvalidRecordIDException,
RecordStoreException
{
try {
byte[] data = rs.getRecord
(recordID);
ByteArrayInputStream byteIn = new
ByteArrayInputStream(data);
DataInputStream in = new
DataInputStream(byteIn);
String str = in.readUTF();
} catch (IOException ex) {
ex.printStackTrace();
}
}
In the preceding code snippet, rs is the instance of the
Recordstore class from which the records are fetched.
The readUTF() method of the DataInputStream
class is used to read data from the input stream.
Various other methods provided by the
DataInputStream class for reading data from the
input stream are:
readBoolean()
readByte()
readChar()
readShort()
readInt()
readLong ()

Exceptions Encountered while Retrieving


Records
The following exceptions are associated with the
getRecord() method:
InvalidRecordIDException: Is raised if

an invalid recordID is passed to the


getRecord() method.
ArrayIndexOutOfBoundsException: Is
raised when the byte array is smaller than the size
of the record.
RecordStoreNotOpenException: Is
raised if the record store is not already open.

thrown.

Modifying a Record
You can modify an existing record by using the
setRecord() method. The setRecord() method
does not update records, but overwrites them.
The syntax for the setRecord() method is:
RecordStore.setRecord(int recordID,
byte[] newData, int offset, int
numBytes)
The following code snippet shows how to modify an
existing record:
int recordID = 2;
byte[] data = new byte[]{0, 10, 20,
30};
rs.setRecord(recordID, data, 1, 2);
In the preceding code snippet, rs is an instance of the
RecordStore class. The record with the record ID, 2 is
modified by the data in the data byte array. The
SecurityException exception is raised if an
application is not allowed to update records in a record
store.

Note
To update records in a record store, you need
to build the entire record in the memory as a
byte array and then update it by using a single
call to the setRecord() method.

Deleting a Record
You can delete records in a record store by using the
deleteRecord() method. The syntax of the
deleteRecord() method is:
RecordStore.deleteRecord(int recordID)
The preceding method deletes the record with the
specified recordID from the current record store. Any
other record cannot use the deleted recordID again.
The following code snippet shows how to delete a record
from a record store:
int recordID = 2;
rs.deleteRecord(recordID);
The preceding code snippet deletes the record of the rs
record store whose record ID is 2.
If you try to delete a record store that has read only
permissions on it, a SecurityException exception is

Just a minute:
Pat Greene is working with XYZ Inc. as a
mobile application developer. He is developing
a program for adding a new record to a record
store. However, while adding this record to the
record store, Pat finds that an exception is
raised due to the lack of space in the record
store. Identify the type of exception.

Answer:
RecordStoreFullException

Using Interfaces of RMS


After creating records in a record store, you might want to
search, sort, or compare the records. Writing complete
codes to search, sort, compare, and handle records can be
a difficult task.
Therefore, to ease the task of managing and handling
records in record stores, the following interfaces are
provided by the javax.microedition.rms package:
RecordFilter: Provides a filter to check if a
record matches a specific criterion.
RecordComparator: Provides comparison
between two records in a record store.
RecordListener: Provides an event listener
that is notified when records are added, deleted,
or modified in a record store.
RecordEnumeration: Provides navigation in
both the directions on a record store.

Implementing RecordFilter
The RecordFilter interface defines a filter that
examines a record to see if it matches a filtering criterion.
The filtering criterion is defined by the application that
implements the RecordFilter interface.
The RecordFilter interface uses the matches
(byte [ ] rec1) method, which is an abstract
method, to match the record with a particular criterion.
This method returns true if a particular criterion is met.
For example, you can define the matches() method to
return true if the value of a record is greater than a
specified value.
The following code snippet shows the implementation of

the RecordFilter interface:


class BuildFilter implements
RecordFilter //implementing
RecordFilter
{
private String searchCriteria = null;
public BuildFilter (String
searchCriteria)
//Creating RecordFilter
{
this.searchCriteria =
searchCriteria.toUpperCase(); //
Filtering Criteria
}
public boolean matches (byte []
candidate)
//Filtering using the matches()
method
{
String str = new String
(candidate).toUpperCase();
if (searchCriteria != null &&
str.indexOf(searchCriteria) != -1)
return true;
else
return false;
}
}
In the preceding code snippet, the BuildFilter class
implements the RecordFilter interface and overrides
the matches() method. The constructor of the
BuildFilter class creates a search criterion on which
the search is made. The matches() method returns true
if a record matches the search criterion.

Implementing RecordComparator
The RecordComparator interface is used to compare
and match two records that are implemented by using byte
arrays. This interface uses the compare(byte []
rec1, byte [ ] rec2) method to compare two
records that are passed as a parameter to this method. The
compare() method returns the appropriate results of
comparison. It returns one of the following three integer
constants:
EQUIVALENT: Is returned if the records match.
FOLLOWS: Is returned if the first record follows
the second record.
PRECEDES: Is returned if the first record
precedes the second record.
The compare() method is also used by the
RecordEnumeration interface to sort the records of a
record store in an order specified by the application
implementing the RecordComparator interface.
The following code snippet implements the

RecordComparator interface for comparing two


records:
public class comparator implements
RecordComparator
{
public int compare (byte [] rec1,
byte [] rec2)
{
String str1 = new String(rec1), str2
= new String(rec2);
int result = str1.compareTo(str2);
if (result == 0)
return RecordComparator.EQUIVALENT;
else if (result < 0)
return RecordComparator.PRECEDES;
else
return RecordComparator.FOLLOWS;
}
}
In the preceding code snippet, the compare() method
must return one of the three return values: EQUIVALENT,
PRECEDES, FOLLOWS.

Implementing RecordListener
The RecordListener interface notifies a user about
the changes made to the records. The RecordListener
interface generates a notification whenever any record is
added, deleted, or modified.
The RecordListener interface contains the following
methods:
void recordAdded(RecordStore
store, int recordID): This method is
implemented to handle the event that is generated
when a new record is added to a record store.
void recordChanged(RecordStore
store, int recordID): This method is
implemented to handle the event that is generated
when a record in the record store is modified.
void recordDeleted(RecordStore
store, int recordID): This method is
implemented to handle the event that is generated
when a record is deleted from a record store.
The parameters that are passed to the preceding methods
are:
Recordstore store: Identifies the record
store on which the listener is to be registered.
Int recordID: Identifies a particular record
on which the listener is to be implemented.
You can use the addRecordListener() method to
register a RecordListener object.
The syntax of the addRecordListener() method is:
RecordStore.addRecordListener
(RecordListener listener)
The preceding method registers a listener to a record store.
The listener will notify the changes made to the records.

The following code snippet shows the implementation of


the RecordListener interface:
class practiseRecordListener implements
RecordListener
{
public void recordAdded (RecordStore
recordStore, int recordID)
{
System.out.println("New Record has
been added");
}
public void recordDeleted(RecordStore
recordStore, int recordId)
{
System.out.println(" A Record has been
deleted");
}
public void recordChanged(RecordStore
recordStore, int recordID)
{
System.out.println("A Record has been
changed");
}
}
In the preceding code snippet, the RecordListener
interface is implemented in the
practiseRecordListener class.

Implementing RecordEnumeration
Whenever a record of a record store is deleted, the
recordID of the deleted record is not assigned to any
other record. As a result, the recordID remains
discontinuous. Therefore, records are not in a continuous
and sequential order. Enumerating such records is a
difficult task.
The javax.microedition.rms package provides
the RecordEnumeration interface to enumerate
records in a record store.
The RecordEnumeration interface provides methods,
such as nextRecordID() and nextRecord(), that
enable you to maintain an internal list of recordIDs. The
internal list of recordIDs is a copy of the recordIDs stored
in a record store. When a record is deleted from a record
store, the continuous sequence of recordIDs is changed.
This change in the recordIDs is not reflected in the index
of the enumeration.
To allow an enumeration to keep track of the changes in
the records within a record store, you can register a
listener to the RecordEnumeration interface. When
the listener is registered, the index in the enumeration
reflects the changes that occur in a record store.
The RecordEnumeration interface allows you to
traverse through a set of records in both directions. The
hasNextElement() method or the
hasPreviousElement() method is called to

determine if there are any more records to traverse in a


specific direction.
The following table describes the methods defined by the
RecordEnumeration interface.
Method
int numRecords()

Description
Returns the number of
records in a record store.
byte[] nextRecord() Returns the next record from
a record store.
int nextRecordID() Returns the recordID of
the next record from a
record store.
byte[]
Returns the previous record
previousRecord()
from a record store.
int
Returns the recordID of
previousRecordID() the previous record from a
record store.
boolean
Returns true if there are
hasNextElement()
more records in the forward
direction of a record store.
boolean
Returns true if there are
hasPreviousElement more records in the reverse
()
direction of a record store.
void
keepUpdated Specifies
whether
the
(boolean
enumeration updates its
keepUpdated)
index with the changes in
the records, as specified by
the
keepUpdated
parameter.
boolean
Returns true if the records
isKeptUpdated()
are updated.
void rebuild()
Rebuilds the enumeration
for the specified record
store.
void reset()
Restores all the indexes to
the initial values that were
present when enumeration
was first instantiated.
void destroy()
Deletes the enumeration and
releases any resources held.

Table Describing the RecordEnumeration


Interface Methods

Enumerating Records in a Record Store


You can identify the set of records to be traversed by using
the enumerateRecords() method of the
RecordStore class. The following code snippet shows
the syntax of the enumerateRecords() method:
public RecordEnumeration
enumerateRecords(RecordFilter filter,
RecordComparator comparator, boolean

keepUpdated)
The enumerateRecords() method takes the
following parameters:
RecordFilter filter: Is used to filter the
records in a record store.
RecordComparator comparator: Is used
to sort the records in a record store.
boolean keepUpdated: Is used to indicate
whether enumeration is set for tracking changes
in the record store or not. If the value of this
parameter is set to true, any changes to the record
store are reflected during enumeration.
If the first two parameters are null, the records are
returned in an undefined order. A filter is used as a first
argument in the enumerateRecords() method if you
need to search a subset of records based on a specified
criterion. This method uses the Comparator class to
return the records in a specific order. The user has to pass
an instance of the Comparator class, which implements
the RecordFilter() or RecordComparator()
method, or both, to search the records.
The enumerateRecords() method throws the
RecordStoreNotOpenException exception if the
record store is not open. The enumerateRecords()
method throws the IllegalStateException
exception if the RecordEnumeration() method is
accessed after calling the
RecordEnumeration.destroy() method.
The following code snippet shows how the
enumerateRecords() method filters and sorts
records in a record store:
public class MyFilter implements
RecordFilter {
public boolean matches( byte[]
recordData ){
return( recordData.length > 0 &&
recordData[0] != 0 );
}
}
public class MyComparator implements
RecordComparator {
RecordStore rs = .....; // an open
record store
public int compare( byte[] rec1,
byte[] rec2 ){
if( rec1.length == rec2.length ){
return
RecordComparator.EQUIVALENT;
} else if( rec1.length <
rec2.length ){
return
RecordComparator.PRECEDES;

} else {
return RecordComparator.FOLLOWS;
}
}
public void enumerate()
{
RecordEnumeration rEnum =
rs.enumerateRecords( new MyFilter(),
new MyComparator(), false );
}}
The preceding code snippet returns an enumeration with
records in the specified order. The myFilter()and
myComparator() methods define the filtering and
sorting criterion.

Just a minute:
Ed Young, a software developer with
Supersoft2000, is developing a program to
create and maintain record stores in a MIDlet
suite. In this program, Ed needs to traverse
through a set of records, in both directions.
For this, he is using the
RecordEnumeration interface. In his
application, Ed needs to return the record ID
of the next record from the record store. Which
method should Ed use to perform the required
task?

Answer:
int nextRecordID()

Developing a Phonebook
Application
Problem Statement
You are working as a mobile application developer with
TNT Inc. The organization specializes in developing
mobile applications by using the Java ME platform. You
are assigned the task of developing a phonebook
application for mobile users. The mobile users should be
able to add and view contacts by using the application.

public class PhonebookMidlet


extends MIDlet {
public static PhonebookMidlet
instance;
RecordStorePH displayable;
public PhonebookMidlet()
{
instance=this;
}
public void startApp() {
displayable= new RecordStorePH
();
}

Solution
To create a phonebook application, you need to perform
the following tasks:
1. Create a NetBeans project.
2. Add class files to the project.
3. Build and execute the project.

Task 1: Creating a NetBeans Project


To create a NetBeans project, you need to perform the
following steps:
1. Select startAll
ProgramsNetBeansNetBeans IDE 6.0.1 to
open the NetBeans IDE 6.0.1 window.
2. Select FileNew Project to open the New
Project dialog box.
3. Ensure that the Mobility option is selected in the
Categories section.
4. Ensure that the MIDP Application option is
selected in the Projects section.
5. Click the Next button. The Name and Location
page is displayed.
6. Type PhoneBookApp in the Project Name text
box to assign a name to the new project.
7. Ensure that <Drive Letter>:\JavaMEProjects is
displayed in the Project Location text box.
8. Clear the Create Hello MIDlet check box.
9. Click the Next button. The Default Platform
Selection page is displayed.
10. Click the Next button. The More Configurations
Selection page is displayed.
11. Click the Finish button to create the
PhoneBookApp project.

Task 2: Adding Class Files to the Project


For adding files to the PhoneBookApp project, you need
to perform the following steps:
1. Select FileNew File to open the New File
dialog box.
2. Ensure that the MIDP option is selected in the
Categories section.
3. Ensure that the MIDlet option is selected in the
File Types section.
4. Click the Next button. The Name & Location
page is displayed.
5. Type PhonebookMidlet in theMIDlet Name text
box to assign a name to the new MIDlet.
6. Click the Finish button to create the
PhonebookMidlet.java MIDlet.
7. Replace the existing code for the
PhonebookMidlet.java MIDlet in the Editor
with the following code:
import
javax.microedition.midlet.*;
import
javax.microedition.lcdui.*;

public void pauseApp() {


}

8.
9.
10.
11.
12.
13.
14.

public void destroyApp(boolean


unconditional) {
}
}
Select FileNew File to open the New File
dialog box.
Select the Java option from the Categories
section.
Ensure that the Java Class option is selected in
the File Types section.
Click the Next button. The Name and Location
page is displayed.
Type RecordStorePH in theClass Name text box
to assign a name to the new Java class file.
Click the Finish button to create the
RecordStorePH.java Java class file.
Replace the existing code for the
RecordStorePH.java Java class file in the Editor
with the following code:
import java.io.*;
import
javax.microedition.lcdui.*;
import javax.microedition.rms.*;
public class RecordStorePH
implements CommandListener{
//creating objects
public List menu;
public List names;
public Form frmadd;
public Command cmdOK;
public Command cmdSave;
public Command cmdBack;
public TextField name;
public TextField number;
String Name;
String Number;
public RecordStore rs;

public static final String


RS_NAME = "PhoneBook";
RecordEnumeration re;
//constructor
public RecordStorePH()
{
menu = new List("Phonebook",
List.IMPLICIT);
menu.append("View Contacts",
null);
menu.append("Add Contact",
null);
menu.append("Delete All
Contacts", null);
cmdOK = new Command("OK",
Command.OK, 1);
menu.addCommand(cmdOK);
menu.setCommandListener(this);
//displaying the menu list as
current
displayable Display.getDisplay
(PhonebookMidlet.instance).setCur
rent(menu);
}
public void DisplayFrmAdd()
{
frmadd= new Form("Add
Contact");
name= new TextField
("Name","",20,TextField.ANY);
number= new TextField
("Number","",10,TextField.NUMERIC
);
frmadd.append(name);
frmadd.append(number);
cmdSave = new Command("Save",
Command.OK,1);
frmadd.addCommand(cmdSave);
cmdBack=new Command("Back",
Command.BACK,1);
frmadd.addCommand(cmdBack);
frmadd.setCommandListener
(this);
Display.getDisplay
(PhonebookMidlet.instance).setCur
rent(frmadd);
}
public void commandAction
(Command cmd, Displayable disp) {
int
index=menu.getSelectedIndex();
if(disp==menu){
if(cmd==List.SELECT_COMMAND||
(cmd==cmdOK))
{

//Checks if the first item of


the menu list is selected
if(index==0)
{
try {
viewPhoneBook();
} catch (IOException ex) {
ex.printStackTrace();
}
}
//Checks if the second item of
the menu list is selected
if(index==1){
DisplayFrmAdd();
}
//Checks if the third item of
the menu list is selected
if(index==2)
{
DeletePhoneBook();
}
}
}
if(cmd==cmdSave)
{
Name=name.getString();
Number=number.getString();
SaveRecord(Name, Number);
}
if(cmd==cmdBack)
{
Display.getDisplay
(PhonebookMidlet.instance).setCur
rent(menu);
}
}
private void SaveRecord(String
Name, String Number) {
//Converting data to a byte
array
String Contact=Name+" "+Number;
ByteArrayOutputStream baos =
new ByteArrayOutputStream();
DataOutputStream outputStream =
new DataOutputStream(baos);
try {
outputStream.writeUTF(Contact);
}
catch (IOException ioe) {
System.out.println(ioe);
ioe.printStackTrace();
}

byte[] b = baos.toByteArray();
try {
//opening a record store
rs= RecordStore.openRecordStore
(RS_NAME, true);
//adding record to the record
store
int RecordId= rs.addRecord(b,
0, b.length);
}
catch (RecordStoreException
rse) {
System.out.println(rse);
rse.printStackTrace();
}
Alert alt= new Alert("Contact
Saved");
alt.setString("New contact is
added to the phonebook.");
Display.getDisplay
(PhonebookMidlet.instance).setCur
rent(alt,menu);
}
private void viewPhoneBook()
throws IOException {
RecordEnumeration re;
names= new List("Contacts",
List.IMPLICIT);
cmdBack=new Command("Back",
Command.BACK,1);
names.addCommand(cmdBack);
names.setCommandListener
(this);
try {
rs =
RecordStore.openRecordStore
(RS_NAME, true);
re = rs.enumerateRecords(null,
null, false);
String str;
int id;
//reading all records of a
record store
while (re.hasNextElement( )) {
id = re.nextRecordId( );
byte[] b = rs.getRecord(id);
ByteArrayInputStream byteIn =
new ByteArrayInputStream(b);
DataInputStream in = new
DataInputStream(byteIn);
str=in.readUTF();
names.append(str, null);
}
} catch (RecordStoreException
e) {

}
Display.getDisplay
(PhonebookMidlet.instance).setCur
rent(names);
}
private void DeletePhoneBook()
{
int id;
RecordEnumeration renum;
try {
rs= RecordStore.openRecordStore
(RS_NAME, true);
renum = rs.enumerateRecords
(null, null, false);
//deleting all records from a
record store
while(renum.hasNextElement())
{
id = renum.nextRecordId( );
rs.deleteRecord(id);
}
rs.closeRecordStore();
} catch (RecordStoreException
ex) {
ex.printStackTrace();
}
Alert alt=new Alert("Contacts
Deleted");
alt.setString("All contacts
deleted.");
Display.getDisplay
(PhonebookMidlet.instance).setCur
rent(alt,menu);
}
}

Task 3: Building and Executing the


Project
To build and execute the PhoneBookApp project, you
need to perform the following steps:
1. Select BuildBuild Main Project to build the
PhoneBookApp project.
2. Select RunRun Main Project to execute the
PhoneBookApp project. The DefaultColorPhone
emulator window is displayed, as shown in the
following figure.

The DefaultColorPhone Emulator Window


3. Click the soft key below Launch to launch the
PhonebookMidlet MIDlet. The Phonebook
screen is displayed, as shown in the following
figure.

The Phonebook Screen


4. Select AddContact by using down arrow key of
the emulator.
5. Click the soft key below OK. The AddContact
screen is displayed, as shown in the following
figure.

The Add Contact Screen


6. Type John in the Name text box by clicking the
keys in the emulator keypad.
7. Click the down-arrow key in the emulator.
8. Type 9364892788 in the Number text box by
clicking the keys in the emulator keypad.
9. Click the soft key below Save. The
ContactSaved alert screen is displayed for some
time, and then the Phonebook screen is
displayed.
10. Select ViewContacts by using the up arrow key
of the emulator.
11. Click the soft key below OK. The Contacts
screen is displayed, as shown in the following
figure.

The Contacts Screen

Note
You will be able to view this contact
even after you close the emulator
window and run the project once
again.
12. Click the soft key below Back to return to the
Phonebook screen.
13. Select Delete All Contacts by using the down
arrow key of the emulator.
14. Click the soft key below OK. The Contacts

Deleted alert screen is displayed for few seconds


and then the Phonebook screen is displayed.
15. Select MIDletExit to close the
DefaultColorPhone emulator window.
16. Select FileExit to close the NetBeansIDE.

Summary
In this chapter, you learned that:
Persistent storage is a permanent storage space
that is used to store objects and their states.
The MIDP RMS is a mechanism that provides
persistent storage for MIDlets.
A record store is implemented in MIDlet suites
by using an instance of the RecordStore
class.
The following exceptions are raised while
managing record stores:
InvalidRecordIDException
RecordStoreException
RecordStoreFullException
RecordStoreNotFoundException
RecordStoreNotOpenException
The RecordStore class manages record stores
within a MIDlet suite by using the following
methods:
OpenRecordStore(): Is used to open,
create, or share a record store.
CloseRecordStore(): Is used to close
a record store.
DeleteRecordStore(): Is used to
delete a record store.
A record store consists of individual units of
storage called records.
When a record is created, the record store assigns
a unique identifier called recordID to the
created record.
A new record can be added to a record store by
using the addRecord() method of the
RecordStore class.
To convert data into a byte array, you can use the
methods provided by the
ByteArrayOutputStream and
DataOutputStream classes.
You can retrieve a record from a record store by
using the getRecord() method of the
RecordStore class.
To convert a byte array to primitive data types,
you can use the methods provided by the
ByteArrayInputStream and
DataInputStream classes.
You can modify an existing record by using the
setRecord() method.
You can delete records in a record store by using

the deleteRecord() method.


The following interfaces are provided by the
javax.microedition.rms package:
RecordFilter: Provides a filter to
check if a record matches a specific
criterion.
RecordComparator: Provides
comparison between two records in a
record store.
RecordListener: Provides an event
listener that is notified when records are
added, deleted, or modified in a record
store.
RecordEnumeration: Provides
navigation in both directions on a record
store.

Exercises
Exercise 1
Global Bees Inc. is an organization that specializes in
developing mobile applications by using the Java ME
platform. As a part of the development team at Global
Bees Inc., you have been assigned the task to develop a To
Do List application for mobile users. The mobile users
should be able to add, view, and delete tasks by using the
application.

Reference Reading
Implementing Persistent Storage in
MIDlets
Reference Reading: Books
Wireless J2ME Platform
Programming
By Vartan Piroumian
Publisher: Prentice Hall
PTR.
Enterprise J2ME:
Developing Mobile Java
Applications
By John W. Muchow
Publisher: Prentice Hall
PTR.

Reference Reading: URLs


http://developers.sun.com/
techtopics/mobility/midp/
articles/persist/
http://www-128.ibm.com/
developerworks/wireless/
library/wi-rms/index.html

Glossary
C
CBS
Cell Broadcast Service is a protocol which enables the
network carriers to broadcast messages to all mobile
devices reachable from a certain cell station.
CLDC
Connected Limited Device Configuration (CLDC) is a
configuration supported by Java ME for wireless mobile
devices with very limited hardware capabilities.
Clip
It is a rectangular region consisting of a set of pixels.
These set of pixels are painted by a Graphics object.
Configuration
It defines class libraries for a range of devices that have
similar requirements for memory, processing power, and
network connectivity.
D
Double buffering
It is a technique in which you draw graphical objects on
the off screen buffer of a mobile device, and display the
content of the off screen buffer as and when required. This
technique reduces the flickering effect and enables you to
create high quality graphics and animations.
E
EDGE
It is a 3G wireless technology that provides broad
bandwidth and faster data transfer as compared to the 2G
wireless technology in mobile devices.
Emulator
It is a testing environment for testing the MIDlets.
Event Handling
It is the process of handling the user interactions by using
the user interface an application.
G
GCF
GCF provides a common API that is used for wireless
network communication. GCF itself does not provide any
protocol implementation, but it allows the vendors
implementing the MIDP profiles, to implement the
required protocol by implementing the corresponding
interface.
GPRS
Is a data service that sends and receives information across
a wireless mobile telephone network.
GSM
It is the global standard for digital mobile communication.
Game API

It is a set of APIs used specifically to develop gaming


applications for mobile devices.
H
High level UI API
It defines a set of classes and interfaces, which help in
creating portable UI components, which can be deployed
on a variety of mobile devices.
I
IR port
Infra Red (IR) port allows a computer and a mobile device
to communicate without using wires. IR port can be used
to transfer a mobile application from a computer to a
mobile device.
J
Java EE
It is a Java 2 Platform, Enterprise Edition (Java EE),
which defines the standard for developing componentbased multitier enterprise applications.
Java ME
It is Java 2 Micro Edition (Java ME) is a Java-based
platform that provides an environment for developing
applications for mobile devices.
Java SE
It is a Java platform to create Java applets and applications
that are stand alone and Web-based. It is a core collection
of tools and APIs.
JAD
It is a Java Application Descriptor file that specifies the
properties of a MIDlet application.
JTWI
Java Technology for the Wireless Industry (JTWI)
specification defines a standard for the Java ME runtime
environment to develop and deploy mobile applications
for mobile devices.
K
KVM Layer
It represents a virtual machine similar to the Java Virtual
Machine (JVM). The KVM is a compact JVM that is
designed for resource-restricted devices.
L
Low Level UI API
It defines a set of to classes and interfaces, which help in
creating highly customized UI components.
M
MIDlet Security
Security in a MIDlet is implemented by applying security
to MIDlet applications, downloading the resources from
trusted MIDlets, and implementing secure HTTP
connection over SSL.
MIDlet
It is a mobile application developed by using Java ME
APIs. It is a Java class file packaged into a JAD (Java
descriptor) file.

MIDP
It is a set of Java APIs that provide a complete Java ME
application runtime environment for mobile phones.
MMAPI
It provides a set of classes and interfaces, which can be
used to create and play multimedia content on a mobile
device.
MP3
MPEG layer 3 (MP3) is a popular sound file format that is
supported by the MMAPI.
MMS
Multimedia Message Service (MMS) is a protocol for
sending and receiving various types of multimedia
contents, such as images and audio and video clips.
O
Obfuscation
The compiled class files of Java can be reverse engineered
to produce the Java source files by using a tool called
decompiler. This process is a threat to the Java source
files. Obfuscation prevents this threat by preventing
reverse engineering.
Optional Package
It is a set of classes and interfaces providing specific
functionality, such as database access or multimedia.
OTA
Over The Air (OTA) provisioning is a technique for
deploying and distributing mobile applications.
P
Persistent Storage
Persistent storage is a permanent storage space that is used
for storing data and objects. The data in the persistent
storage persists even after the application that created the
data is terminated.
Profile
It defines class libraries for a narrower category of devices
within the framework of a chosen configuration.
PDAP
Personal Digital Assistant Profile (PDAP) is a profile
defined for Personal Digital Assistants (PDA).
PNG
Portable Network Graphics (PNG) is an image format that
is used to store the graphical objects in a mobile device.
Preverification
This process is done before loading a class file into the
memory of a mobile device and it reduces the amount of
work done by the mobile device.
R
Record store
It is an ordered collection of records storing the data about
a particular MIDlet.
RMS
Record Management System (RMS) is a record-based
database, which is used to persistently store the data

associated with a MIDlet.


S
SMS
Simple Message Service (SMS) is a protocol that allows
you to send and receive messages by using a mobile
device.
SSL
Secure Socket Layer (SSL) is a socket protocol that
secures the data to be transferred over the network by
encrypting it.
Sprite
MIDP Game API is a set of APIs used specifically to
develop gaming applications for mobile devices.
T
TCP/IP
It is the standard Internet protocol that allows you to send
and receive data over wired or wireless networks.
TDMA
Time Division Multiple Access (TDMA) is a secondgeneration modulation standard that uses bandwidth in the
800 MHz, 900 MHz, and 1900MHz ranges.
Ticker
It is a constantly moving piece of text that is displayed on
the UI of a mobile device.
Trusted MIDlet suite
It is a MIDlet suite for which a mobile device can reliably
determine source, authenticity, and integrity of the JAR
file.
W
WAP
Is a protocol for browsing the Internet on a mobile device.
WMA
Wireless Messaging API (WMA) is an optional package
that is used to send and receive messages from mobile
devices.
WML
Wireless Markup Language (WML) is a markup language
used to create applications for small wireless devices, such
as mobile phones.
X
X.509 certificate
It is a certificate profile that is used for implementing
trusted MIDlet suites.

You might also like