Professional Documents
Culture Documents
DMAJ - I/SG/10-M06-V02
COURSE DESIGN
Objectives
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.
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
Introducing Java ME
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.
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.
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
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.
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
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.
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
Describing CLDC
The CLDC is the basic building block on which the Java
ME profile, MIDP, is built. CLDC specifies the features
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).
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.
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.
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
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
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
By John W. Muchow
Publisher: Prentice Hall
PTR.
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,
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.
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.
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.
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.
MIDlet-Info-URL
MIDlet-<n>
MIDlet-Jar-URL
MIDlet-Jar-Size
MIDlet-Data-Size
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.
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.
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
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.
Note
You can find the JAR file in the dist folder of
the projects root directory.
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.
Solution
To check whether the installation is performed correctly,
Steve needs to execute the sample application, Hello
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.
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.
following figure.
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
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.
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
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.
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.
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
Just a minute:
State whether the following statement is true
Answer:
True
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
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
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.
setPreferredSize
Sets the preferred size of the
(int
width,
int item, which is specified in
height)
terms of width and height.
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.
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
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.
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.
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
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.
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.
append(Item
itemname)
append(String
stringobject)
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)
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() {
IllegalStateException exception is
thrown.
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
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.
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.
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.
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
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.
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,
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
form1.
The following figure shows the output of the preceding
code when the MIDlet is launched.
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.
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)
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.
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()
Solution
10.
11.
public ReservationMIDlet()
{
instance=this;
}
public void startApp() {
displayable= new
MovieReservation();
}
public void pauseApp() {
}
8.
9.
12.
13.
14.
Display.getDisplay
(ReservationMIDlet.instance).setC
urrent(alt,bookTickets);
}
}
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
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.
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.
Objectives
In this chapter, you will learn to:
Handle high-level UIs
Implement animation-based UI components in a
MIDlet application
Note
You can also navigate screens in MIDP
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.
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()
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.
Just a minute:
Which method of the Command class returns
an integer value to indicate the type of the
current Command object?
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
Implementing Animation-Based UI
Components
The high-level UI API also defines animation-based UI
components. These components include:
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.
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.
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
unconditional){
notifyDestroyed();
}
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.
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.
Solution
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();
}
}
}
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
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
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.
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.
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
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.
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.
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.
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).
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.
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)
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.
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.
Drawing Shapes
The following figure shows the result of the code
g.drawLine(4, 1, 19, 7);.
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).
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.
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.
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
(this);
displayable = new MyCanvas1();
}
public void startApp() {
display.setCurrent(displayable);
}
Answer:
int width = getWidth (); int
height = getHeight (); Image
buffer = Image.createImage
(width, height);
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);}
Key Events
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
Solution
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;
Summary
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.
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
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.
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.
Objectives
In this chapter, you will learn to:
Implement persistent storage in MIDlets
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)
Just a minute:
Which method of the RecordStore class
deletes the record store with the specified
record store name?
Answer:
deleteRecordStore(String
recordStoreName)
Just a minute:
State whether the following statement is true
or false.
Answer:
False
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();
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.
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.
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.
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
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
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
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.
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
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.
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.
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.
8.
9.
10.
11.
12.
13.
14.
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);
}
}
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
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
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.
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
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