high level display screens in j2me quotation

There is a great increase in the number of mobile phoneusers in India , nowadays.Mobile phones are increasingly being used not only for talking but for games, data access , networking and web access. J2me is the leading technology used in mobile devices.

Recently, Google has created Androidplatform for mobile devices. We can develop programs using Android SDK, using Java,though it is slightly different from J2me. Myaim is tocover the basics of j2me development first and then to explore the recent developments.Students, developers and employers alike are now interested in practical skills in j2me. I hope that the experiments given here, will help.These tutorials are meant for learners with good knowledge of core java( especially iostreams & networking) and basic servlets.

These experiments arebased on well-known books on J2me. More importance is given to coding and execution,instead ofmuchtheory, which , readers can get frombooksor fromwebsites(can be got by google search for j2me ).

We begin with declarations of display, form, textfields and buttons. This is followed by the constructor, where we define the gui elements.The textboxes can take "ANY" type of data ( string, number etc). Very often , the first parameter is the label for the control. For instance,we have specified that there is null label for text1 and text2. The second parameter is the content ( blank string). The button has three parameters. ( caption, type, priority). The buttons will not appear inside the display but just outside. These are known as "soft keys".Finally , we add the command listenerto the form.Thefunctions like startApp, stopAppand destroyApp follow. Finally, we have the event handler. This will be the pattern of all the midlet programs, whatever be their purpose.We can avoid unnecessary repetition, if we remember this basic structure.

c:\wtk104\binand type "ktoolbar".We will get the IDE screen. Click on new project button and give name for the project. It can be "deviq".You will then be informed thatfolders like src,lib,res have been created and you must place your midlet source code in wtk\apps\deviq\src folder.

We can have multiple midlets in a single project. However, it is better to remove existing midlet from the project "deviq" and add the new midlet ,by using the settings tab in the IDE and test our demos one at a time.The midlet source files can remain in src folder. It is enough if we just remove the existing midlet from the project bundle

and add the new midlet, through the settings tab in IDE.But, if you prefer, you can go on adding your midlets to the same project bundle, as I have done.

That is enough for Graphics in j2me.Let us move on to the all-important topic of j2me networking. The cell-phone is a very limited memory device(at present!).But, it can be avery effective tool if used in network mode for serious work, because the business logic and data will be in the server and the j2me device will work just like a browser or a simple network client. It makes the device an equal and efficient partner in Enterprise computing as well as Entertainment field!

and executed. Whatever we type in text1 is sent to the socket server and is echoed. The echo is displayed in text2. Tested and found to work smoothly.

c:\inetpub\wwwroot.This is the root directory of personal webserver, in Windows-98. ( I am working in windows-98).This is an illustration for Http method of "GET and the correct syntax.It makes use of the webserver but reads the file by socket method as in demo6, where we created our own socket server listening at port 1234.

In the above example(demo-7), I have made use of socket connection to connect to a webserver, using http protocol. But, there is an easier method. It is to use the HttpConnection class.

(ie) the root directory of personal webserver.( I have chosen PWS as it is always running. If I use Tomcat or Apache, I have to start them.). This is an interesting and important demo. It makes use of HttpConnection. Secondly, note how the bytes are read into an array and an image constructed out of that array.The image thus created is attached to an ImageItem and the imageitem is appended to the form.

Let us now make use of the same HttpConnection class to read the urlfile(textfile) as in demo-8.The code will be almost same except that the thecharacters read are appended to a string and displayed.

If the host field is missing in the connection string,the connection is created in "server" mode.For example, here is how a server modeconnection is created:

A "server" mode connection means that the connection can be used both sending and receiving datagrams via same port.So we specify only one port number.( the receiving port is dynamically created and allotted).

Now we are having two instances of the IDE. Type in text1 of the dgmclient and click "show".( this will send the message to the other IDE.).We will be able to see the sent string in the dgmserver IDE.

The BEST method ofcourse is to connect to a servlet from the midlet. Let us now see a program for sending a query to the servlet and getting the result.

It will be noticed that we are using a querybean component based on jdbc. As it is presumed that readers will be familiar with simplejdbc code, it is not repeated here.

This will work with tomcat3.2(I am using tomcat3.2 to avoid the drudgery of making xml entries in web.xml as in Tomcat4 and Tomcat5). It is not required here and will only add one more layer of work and difficulty, for learners.

( set classpath=c:\deviq;c:\tomcat3.2\lib\servlet.jar).Compile the bean and servlet. Copy the bean and servlet class files to tomcat3.2\webapps\root\web-inf\classes.

full-blown database system in the device. But the user needsatleast a small database in the device however, for things like games, contacts info , appointments schedule, etc. For this purpose, J2me has prividedRMS( Record Management System). It is a very simple and primitive database which stores strings as bytearrays. The API has provision for adding , editing , deletingand finding records. We can alsofind the total number of records and display all of them.

Basically, when we add a record, an id as int is returned by RMS. Thisid is automatically generated. Using this id, we can edit, show and delete the concerned record.

I have provided a list for 4 operations(add,edit,find and delete). There are two text fields( text1 and text2). text1 is used for entering the record string. and text2 is used for entering the id value for operations like find,edit and delete.

The recordstore is available for all the midlets within a the same project. This is a nice feature.But, it cannot be accessed from other projects. That preserves the integrity of the database.While defining the RecordEnumeration, the first parameter is RecordFilter, the second is RecordComparator and the third is "updated"). Using these , the search becomes more efficient , if our database has a lot of records( ofcourse, within the constraints of the device). For simplicity, we have omitted these options.

I have been influenced by an earlier tutorial by Devasena in DeveloperIQ on J2ME graphics andpiechart . And for coding style and presentation by my guide Sri.R.S.Ramaswamy, through his articles in DeveloperIQback issues.

high level display screens in j2me quotation

This is one in a series of tutorial lessons designed to teach you how to write programs using the Sun Java Wireless Toolkit for CLDC. The first lesson was titled Getting Started with MIDlets and the Sun Java Wireless Toolkit for CLDC. The previous lesson was titled Back to Basics with MIDlets and the Sun Java Wireless Toolkit for CLDC (see Resources).

In the first lesson I provided and explained a MIDlet development framework that makes experimenting with MIDlet programming easy. In the second lesson, I taught you how to capture and display the standard output and the error output produced by programs executing in a child process. I also applied that knowledge to upgrade the MIDlet development framework from the earlier lesson.

In the previous lesson, I tackled two topics. First, I taught you how the CLDC and the MIDP fit into the grand scheme of things when programming MIDlets. Second, I explained and demonstrated the life cycle of a MIDlet.

In this lesson, I will use an object of the TextBox class to teach you the fundamentals of user interfaces for MIDlets. I will show you how to instantiate user interface components and how to cause them to become visible on the cell phone screen. I will explain the difference between a Screen and a Display. I will explain how to use restrictive constraints and modifier flags to control the manner in which text can be edited. I will discuss the class hierarchy for that portion of the hierarchy that deals with user interface components. I will briefly explain the methods of the various classes that can be used to manipulate user input and output.

I recommend that you open another copy of this document in a separate browser window and use the following links to easily find and view the figures and listings while you are reading about them.

I recommend that you also study the other lessons in my extensive collection of online Java tutorials. You will find a consolidated index at www.DickBaldwin.com.

I will illustrate this discussion on MIDlet user interfaces with a very simple MIDlet named TextBox01. A complete listing of this MIDlet is shown in Listing 4 near the end of the lesson.

The execution of this MIDlet in the MIDlet development framework that I provided in the earlier lesson titled Capturing Output Produced by Programs Running in a Child Process

As is my custom, I will discuss and explain this MIDlet in fragments. The first fragment is shown in Listing 1, shows the beginning of the startApp method.

You will recall that this is one of the three methods declared as abstract methods in the MIDlet class. These methods are used to control the life cycle of a MIDlet.

A MIDlet is originally in the paused state when it is launched by the user. The startApp method is called when the cell phone’s Application Management Software (AMS) moves the MIDlet from the paused state to the active state.

Hopefully, given what you already know about Java programming in general, you have already figured out that after displaying a preliminary message, the code in Listing 1 applies the new operator to the constructor for a class named TextBox to instantiate a new object of type TextBox.

TextBox is the name of a class in the javax.microedition.lcdui package. It exists in both MIDP 1.0 and MIDP 2.0. Here is part of what Sun has to say about the TextBox class:

Screen is also the name of a class in the javax.microedition.lcdui package. This class is the immediate superclass of the TextBox class (see Figure 4). In MIDP 2.0, the direct subclasses of Screen are:

Form – A Screen that contains an arbitrary mixture of items: images, read-only text fields, editable text fields, editable date fields, gauges, choice groups, and custom items.

Objects instantiated from each of these classes are user interface objects. As of MIDP 2.0, none of these classes have subclasses. I will have more to say about the first three classes in the above list in future lessons. In this lesson, I will concentrate on the TextBox class.

The Screen class is a direct subclass of the Displayable class, which in turn is a subclass of Object (see Figure 4). Therefore, since the four classes in the above list are subclasses of the Displayable class, objects of these classes are Displayables or Displayable objects.

Listing 1 applies the new operator to the constructor for the TextBox class to instantiate a new TextBox object. As of MIDP 2.0, the TextBox class has a single constructor with the following parameters:

In other words, even though the programmer may specify a capacity of 100 characters for a TextBox object, the actual cell phone in use may limit the capacity of the object to a smaller number of characters.

The TextField class and the Form class will be major topics of a future lesson. Our main interest in the TextField class in this lesson has to do with the fourth constructor parameter in the above list (constraints). This interest stems from the fact that the TextField class shares the concept of input constraints with the TextBox class. The explanation of input constraints in the API documentation appears in the documentation for the TextField class. A reference to that material is provided in the documentation for the TextBox class.

We are also interested in the TextField class in this lesson because that is where Sun elected to define the constant values that we need to use for the fourth parameter to the TextBox constructor (see Listing 1). It is important to note that this MIDlet does not contain a TextField object.

“The different constraints allow the application to request that the user’s input be restricted in a variety of ways. The implementation is required to restrict the user’s input as requested by the application. For example, if the application requests the NUMERIC constraint on a TextField, the implementation must allow only numeric characters to be entered.”

The actual contents of the text object are set and modified by and are reported to the application through the TextBox and TextField APIs. The displayed contents may differ from the actual contents if the implementation has chosen to provide special formatting suitable for the text object’s constraint setting.”

For example, a PHONENUMBER field might be displayed with digit separators and punctuation but the actual contents of the text object available to the application would simply be a string of digits.

“Some constraints, such as DECIMAL, require the implementation to perform syntactic validation of the contents of the text object. The syntax checking is performed on the actual contents of the text object, which may differ from the displayed contents as described above…

The methods and constructors throw IllegalArgumentException if they would result in the contents of the text object not conforming to the required syntax.

The value … consists of a restrictive constraint setting described above, as well as a variety of flag bits that modify the behavior of text entry and display.”

I will leave it as an exercise for the student to examine Sun’s documentation to get a full understanding of each of the restrictive constraints in the above list. Example MIDlets in this lesson will illustrate the use of the ANY and NUMERIC input constraints. For the ANY constraint, the user is allowed to enter any text into the TextBox or the TextField. For the NUMERIC constraint, the user is only allowed to enter numeric characters.

As the name implies, the modifier flags modify the restrictive constraints in the above list to provide additional specialization. The available modifier flags in MIDP 2.0 are

Once again, I will leave it as an exercise for the student to examine Sun’s documentation to get a full understanding of each of the modifier flags. Example MIDlets in this lesson will illustrate the use of the UNEDITABLE modifier flag. According to Sun, the UNEDITABLE modifier flag

“Indicates that editing is currently disallowed. When this flag is set, the implementation must prevent the user from changing the text contents of this object. The implementation should also provide a visual indication that the object’s text cannot be edited.”

The modifier flags can be combined with restrictive constraints by using the bit-wise inclusive OR operator. For example, to specify an input constraint of UNEDITABLE NUMERIC data, use the syntax shown in Listing 2 for the fourth parameter to the TextBox constructor.

When displayed in Sun’s cell phone emulator, the TextBox created and populated by the code in Listing 2 appears as shown in Figure 3. Note that the numeric contents of the TextBox are gray instead of black, indicating that the contents of the TextBox cannot be edited by the user.

If you substitute “abc” for “123” in Listing 2, the prescribed TextBox contents won’t satisfy the NUMERIC constraint and the MIDlet will throw a java.lang.IllegalArgumentException when you launch the MIDlet in the Sun cell phone emulator.

“… the application can request that the entry of certain characters be made convenient. It can do this by passing the name of a Unicode character subset to the setInitialInputMode() method. Calling this method requests that the implementation set the mode of the text entry user interface so that it is convenient for the user to enter characters in this subset. The application can also request that the input mode have certain behavioral characteristics by setting modifier flags in the constraints value.”

I’m not even going to try to explain this beyond providing the above partial quotation of Sun’s explanation. Rather, I will simply refer you to the Sun documentation if you need to know how to implement Input Modes in the input constraints.

What is the difference between a Screen and a Display? This question can probably be answered by examining the partial class hierarchy for MIDP 2.0 shown in Figure 4. I will discuss and illustrate the classes shown in boldface in this lesson. I will discuss and illustrate the remaining classes in Figure 2 in future lessons. I will also update the partial class hierarchy to include additional classes and refer to the modified version in future lessons.

As you can see in Figure 4, the Screen class is a subclass of the Displayable class and is also the superclass of the TextBox class and its siblings (Alert, Form, and List). Therefore, a TextBox object is a Displayable object. It is also a Screen object or simply a Screen.

Neither the Screen class nor the Displayable class are abstract. However, neither of them provides a public constructor, so it is not possible to instantiate an object of either class. As a result, it appears that there are only three ways to create a Displayable object:

According to Sun, the Screen class is the common superclass of all high-level user interface classes. (Canvas and GameCanvas are not considered to be high-level user interface classes.)

Whereas a Screen object is limited to objects of the TextBox, Alert, Form, and List classes (and their subclasses), aDisplayable object also includes objects instantiated from subclasses of the Canvas and GameCanvas classes.

A Displayable object is an object that has the capability of being placed on the cell phone’s physical display. The physical display is represented by an object of the class Display.

A Display object represents the manager of the display and input devices of the system. It includes methods for retrieving properties of the device and for requesting that objects be displayed on the device.

To a first degree of approximation, the relationship between a TextBox object and a Display object in the WTK is similar to the relationship between an AWT TextField object and an AWT Frame object.

That brings us to the point where you should be able to understand the last statement in Listing 1. The Display class defines several methods, one of which is a static method named getDisplay. The getDisplay method gets access to a Display object that is unique to the MIDlet object that is passed as a parameter to the method (this is this MIDlet).

Once access to the Display object is obtained, a variety of instance methods can be called on the object. One of those methods is setCurrent. MIDP 2.0 contains two overloaded versions of this method. One version, which is the version called in Listing 1, requires an incoming parameter of type Displayable.

In addition to the above, Sun has a great deal to say about timing issues when this method is called. I strongly recommend that you strive to understand those timing issues before attempting to develop a J2ME product.

The remaining code in the MIDlet named TextBox01 is straightforward and shouldn’t require further explanation. You can view the remaining code in Listing 4 near the end of the lesson.

Now let’s discuss things in more general terms. Because Displayable is the superclass of all objects that can be displayed by the WTK on the cell phone screen, all of the methods defined in the Displayable class are inherited into and can be called on those objects.

If you are an experienced Java OOP programmer, you should be able to predict the behavior of the five methods in the first group based simply on their names and brief descriptions. If not, you should take a serious look at the MIDP 2.0 API documentation and/or possibly step back and polish your Java OOP programming skills.

The same may also be true for the two methods in the second group, but just to be sure, I will present and explain a simple MIDlet that implements a Ticker.

The methods in the third group with the word command in their names are used to create interactive MIDlets, similar to the use of event listeners and event sources in J2SE. This is a very important topic, and I will dedicate an entire future lesson to this topic.

The description of the last method at the bottom of Figure 5 isn’t difficult to understand. This method is intended to be overridden. However, at this point in time, I’m unable to describe a practical situation where this method would be called and therefore, I am also unable to describe what the behavior of the overridden method should be.

Now let’s take a look at a sample MIDlet that uses the ticker methods. Figure 6 shows the top portion of the cell phone emulator output for the MIDlet named Ticker01. A complete listing of this MIDlet is provided in Listing 5.

If you run this MIDlet, you will see the text in the horizontal white strip at the top of the screen scrolling from right to left like a “ticker tape.”

This MIDlet program is an update to the earlier MIDlet named TextBox01. I highlighted the changes required to create and attach the Ticker object to the TextBox object. The process is straightforward and shouldn’t require further explanation.

Remember, all of the classes that are subclasses of the Displayable class shown in Figure 4 inherit the ticker methods. Presumably therefore, a Ticker object can be attached to any object instantiated from any of those classes.

The same Ticker object can be attached to more than one Displayable object. Therefore, you can create a situation where the same Ticker continues to scroll and to be visible as your MIDlet switches from one Screen to the next. There are a number of other interesting ramifications to the Ticker class, so I recommend that you study the documentation for that class in detail.

Next, we will take a look at the methods of the Displayclass to get an idea of the manner in which this class makes it possible for our MIDlet to communicate with the hardware. Once again, I have grouped the methods into several categories.

setCurrent(Alert alert, Displayable nextDisplayable) – Requests that this Alert be made current, and that nextDisplayable be made current after the Alert is dismissed.

setCurrentItem(Item item) – Requests that the Displayable that contains this Item be made current, scrolls the Displayable so that this Item is visible, and possibly assigns the focus to this Item

getBorderStyle(boolean highlighted) – Returns the stroke style used for border drawing depending on the state of the component (highlighted/non-highlighted).

getColor(int colorSpecifier) – Returns one of the colors from the high level user interface color scheme, in the form 0x00RRGGBB based on the colorSpecifier passed in.

callSerially(Runnable r) – Causes the Runnable object r to have its run() method called later, serialized with the event stream, soon after completion of the repaint cycle.

There are a fairly large number of methods, which appear to be somewhat overwhelming when you view them in alphabetical order in the documentation. However, once they are grouped by general function, they don’t look so overwhelming after all.

The fourth method in this group goes a little further and establishes not only which Displayable object will become visible, but also establishes which item in that object will be scrolled into view. For example, this method could be used to cause a specific item in a long list of items to become visible.

The first method in the second group is the getDisplay method, which we discussed earlier. The remaining seven methods in that group simply query the system to determine the value of seven different properties. If you are familiar with the use of properties in JavaBeans components, these methods should also be understandable on the basis of the names and the brief descriptions.

The two methods in the third group allow you to ask the hardware to either flash the backlight on the display or cause the cell phone to vibrate for a specified period of time. There doesn’t seem to be anything too complex here.

This method in the fourth group appears to be used with graphics and the Canvas class, so I will defer a discussion of this method until a future lesson when I discuss graphics and the Canvas class.

There is only one instance of Display per MIDlet, but each MIDlet can have any number of Displayable objects, often referred to as screens or canvases. However, only one Displayable object can become visible by way of the Display object at any time. That object is referred to as the current object. What this means is that unlike standard Java user interfaces where many items can be visible at any time, only one of the following Displayable objects can be visible at a time under J2ME.

Form – A Screen that contains an arbitrary mixture of items: images, read-only text fields, editable text fields, editable date fields, gauges, choice groups, and custom items.

Note, however, that a Form can contain an arbitrary number of other items. Therefore, it is possible to display two or more items at the same time by adding them to the Form. Items are added to the Form by calling the set, append, or insert method on the Form. I will have a lot more to say about the Form class in a future lesson.

MIDlet code can get access to the Display object at any point during the execution of the MIDlet by calling the static getDisplay method of the Display class. Once the MIDlet code has access to the MIDlet object, it can call any of the methods listed in Figure 7 on that object.

For example, we saw in Listing 1 how the setCurrent method can be used to cause a particular Displayable object to become visible on the cell phone screen. The MIDlet code can use this approach to switch among any number of Displayable objects making different Displayable objects visible at different points in time during the execution of the MIDlet program.

A MIDlet may be running in the foreground, in which case its current Displayable objects will probably be visible. On the other hand, a MIDlet may run in the background behind another MIDlet, in which case none of its Displayable objects will be visible. However, it will still have a current Displayable object. The current Displayable object is the object that will become visible if the MIDlet is allowed to move to the foreground.

We have seen the methods of the Display class that make it possible for the MIDlet to communicate with the hardware relative to the display. We have also seen how behavior can be imparted to all Displayable objects by methods of the Displayable class.

The Screen class, which extends Displayable serves only to distinguish high level user interface capabilities from the low level graphics capabilities provided by the Canvas class. The Screen class doesn’t define any methods in MIDP 2.0.

Therefore, other than the behavior imparted to all Displayable objects by the methods shown in Figure 5, the behavior of each different type of Displayable object is imparted by the methods defined in that object’s class: Canvas, TextBox, Alert, Form, and List. I will discuss the methods of the TextBox class in this lesson and will discuss the methods of the other four classes in future lessons.

setInitialInputMode(String characterSubset) – Sets a hint to the implementation as to the input mode that should be used when the user initiates editing of this TextBox.

The four methods in the first group are setter methods that make it possible to establish the values of the same four properties for which parameters are provided in the constructor.

The four methods in the second group can be used to modify the contents of the TextBox by deleting characters, inserting characters, or replacing characters in the text string contained in the TextBox.

The two methods in the third group are used to extract the data contained in the TextBox in either of two formats: a String or an array of characters.

The setTicker method in the fifth group seems to be redundant with the method having the same name in the Displayable class. Although I didn’t make a word-for-word comparison, the description of this method in the documentation for the TextBox class seems to be the same as, or very similar to the description of the method in the documentation for the Displayable class.

You may recall that I punted when time came to explain the concept of input modes earlier in this lesson, and I will do the same again here. I will simply refer you to the Sun documentation for the method named setInitialInputMode if you need to know about input modes.

I encourage you to copy the code from Listing 4 and Listing 5 and run it in the MIDlet development framework that I provided in the earlier lesson titled Capturing Output Produced by Programs Running in a Child Process

In Listing 1 and Listing 3 above, I showed you code for two very short MIDlets that were designed to illustrate specific MIDlet programming concepts involving the user interface. Those MIDlets made very little effort to satisfy the rules for compliance with the life cycle requirements of a MIDlet.

In the second part of this lesson, I will present and explain two MIDlets that show how to write user interface code while complying with the life cycle requirements of a MIDlet.

The second MIDlet will differ from the first in that it will also attempt to minimize the memory footprint of the MIDlet while the MIDlet is in the paused state.

Copyright 2008, Richard G. Baldwin. Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

is a college professor (at Austin Community College in Austin, TX) and private consultant whose primary focus is a combination of Java, C#, and XML. In addition to the many platform and/or language independent benefits of Java and C# applications, he believes that a combination of Java, C#, and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects and he frequently provides onsite training at the high-tech companies located in and around Austin, Texas. He is the author of Baldwin’s Programming Tutorials, which have gained a worldwide following among experienced and aspiring programmers. He has also published articles in JavaPro magazine.

In addition to his programming expertise, Richard has many years of practical experience in Digital Signal Processing (DSP). His first job after he earned his Bachelor’s degree was doing DSP in the Seismic Research Department of Texas Instruments. (TI is still a world leader in DSP.) In the following years, he applied his programming and DSP expertise to other interesting areas including sonar and underwater acoustics.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

high level display screens in j2me quotation

In Wireless J2ME Platform Programming, one of the leading wireless application consultants at Sun has written a step-by-step guide to successful wireless development with the J2ME platform. Vartan Piroumian illuminates every key feature of the J2ME platform, and the entire development process: planning, design, architecture, coding, user interface development, compilation, debugging, execution, provisioning, gateway integration, internationalization, application provisioning, and more.

Table of Content Table of Content ........................................................................................................ii Copyright ..................................................................................................................iv RESTRICTED RIGHTS LEGEND ...................................................................iv TRADEMARKS...................................................................................................iv Credits..................................................................................................................iv Dedication.............................................................................................................v Foreword ....................................................................................................................v Preface.......................................................................................................................vi Acknowledgments....................................................................................................vii Introduction............................................................................................................ viii Book Content and Organization.......................................................................ix Audience...............................................................................................................x Conventions Used In This Book ......................................................................xi Where to Download J2ME ................................................................................xi Where to Find the Code Examples From This Book ....................................xi Chapter 1. Introduction to the Java 2 Micro Edition (J2ME) Platform .....................1 Defining a Java Platform for Pervasive Devices ............................................1 Configurations and Profiles ...............................................................................3 Device Application Management Systems....................................................11 Chapter Summary .............................................................................................12 Chapter 2. The MIDP Application Development Process .......................................13 Designing and Coding ......................................................................................14 Compilation ........................................................................................................15 Preverification ....................................................................................................16 Packaging...........................................................................................................17 Deployment and Execution..............................................................................21 Using the J2ME Wireless Toolkit ....................................................................21 Chapter Summary .............................................................................................31 Chapter 3. MIDP Application Program Structure....................................................32 The Application Execution Lifecycle...............................................................32 MIDlet Program Structure ................................................................................36 The MIDlet State Model ...................................................................................38 The MIDP UI Component Model.....................................................................40 System Properties.............................................................................................44 Application Properties.......................................................................................46 Chapter Summary .............................................................................................48 Chapter 4. The MIDP High-Level API....................................................................49 Command Processing ......................................................................................49 Command-Processing Scenario .....................................................................50 Screen Navigation.............................................................................................60 Command Organization ...................................................................................61 Chapter Summary .............................................................................................67 Chapter 5. The MIDP UI Components ....................................................................68 MIDP UI Component Hierarchy ......................................................................68 Screens and Screen Elements .......................................................................69 Screen Navigation.............................................................................................80 More Item Components....................................................................................82 ii

Chapter Summary ...........................................................................................100 Chapter 6. The MIDP Low-Level API ..................................................................102 Command and Event Handling .....................................................................103 Graphics Drawing............................................................................................109 Chapter Summary ...........................................................................................139 Chapter 7. Persistent Storage Support in MIDP ....................................................140 Device Support for Persistent Storage ........................................................140 RMS Data Storage Model..............................................................................140 Records.............................................................................................................142 An Example Application .................................................................................142 Chapter Summary ...........................................................................................158 Chapter 8. MIDP Networking and Communications.............................................159 The MIDP Networking Model ........................................................................159 Generic Connection Framework Classes and Interfaces .........................162 Differences between J2ME and J2SE Networking ....................................200 Chapter Summary ...........................................................................................201 Chapter 9. Internationalization...............................................................................203 Concepts...........................................................................................................203 Internationalization Support in MIDP ...........................................................206 Designing an I18N Solution for a MIDP Application ..................................209 Chapter Summary ...........................................................................................251 Chapter 10. Application Provisioning....................................................................253 Concepts...........................................................................................................253 The Provisioning Process ..............................................................................256 Preparing Applications for Provisioning Systems ......................................262 Chapter Summary ...........................................................................................264 Chapter 11. The Wireless Internet Environment ...................................................265 Background, Terminology, and Concepts ...................................................265 The Wireless Application Environment ........................................................267 Wireless Applications......................................................................................269 Application Architecture .................................................................................272 Chapter Summary ...........................................................................................280 Appendix A. References ........................................................................................281 Glossary .................................................................................................................282

Copyright © 2002 Sun Microsystems, Inc.— Printed in the United States of America. 901 San Antonio Road, Palo Alto, California 94303 U.S.A. All rights reserved. This product and related documentation are protected by copyright and distributed under licenses restricting its use, copying, distribution, and decompilation. No part of this product or related documentation may be reproduced in any form by any means without prior written authorization of Sun and its licensors, if any.

RESTRICTED RIGHTS LEGEND Use, duplication, or disclosure by the United States Government is subject to the restrictions set forth in DFARS 252.227-7013 (c)(1)(ii) and FAR 52.227-19. The products described may be protected by one or more U.S. patents, foreign patents, or pending applications.

TRADEMARKS Sun, Sun Microsystems, the Sun logo, Java, and all Java-based trademarks are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries. The publisher offers discounts on this book when ordered in bulk quantities. For more information, contact Corporate Sales Department, Prentice Hall PTR , One Lake Street, Upper Saddle River, NJ 07458. Phone: 800-382-3419; FAX: 201- 236-7141. E-mail: [email protected]

Credits Editorial/production supervision: Carol Wheelan Cover design director: Jerry Votta Cover designer: Anthony Gemmellaro Cover illustration: Karen Strelecki Manufacturing manager: Alexis R. Heydt-Long Marketing manager: Debby vanDijk Acquisitions editor: Gregory G. Doench Associate editor: Eileen Clark Editorial assistant: Brandt Kenna

Dedication To Maans, Mom, Weesa, and Feem To my parents, for the vastness, intensity, and quality of their love; for their unending commitment and responsibility as parents; for their sacrifice and dedication to providing the best possible environment, education, and life for their children; and for their guidance and the lessons and memories that last a lifetime. And to my brother and sister, my utmost respect for their values, intelligence, love, support, faith, and loyalty. Without them, nothing else really seems meaningful in this life.

Foreword When we announced Java 2 Micro Edition (J2ME) a few years ago, we believed that Java had an important role to play in handheld devices. Some were skeptical that Java would be small enough for such limited devices. But no longer. Java for the small device is a success. J2ME has emerged strongly in the wireless market. Java"s portability and extensibility have brought about rapid adoption in this market. Tens of millions of Java-enabled phones have already been sold, with adoption accelerating and much growth to come. The success of Java beyond desktop computers is significant to developers. Java literacy is now more important than ever, as Java is used more and more to program a whole range of new computing devices—not only wireless handsets but also personal digital assistants, set-top boxes, cameras, automobiles, home control, and more types of devices not yet dreamed of. J2ME will be in many if not most of these devices; an understanding of J2ME and development of J2ME applications will increase the proficiency and effectiveness of any software developer. This book is an excellent introduction to J2ME. Its tutorial structure promotes rapid learning and hands-on experience. It"s especially interesting to see how the small device constraints on input, display, memory, and CPU all require skills different from those needed for the desktop environment. Common practices from the minicomputer and earlier eras are applicable once again. We hope you enjoy this book and enjoy J2ME. Have fun! Bill Joy, Mike Clary Sun Microsystems, Inc. San Francisco, January 2002

Preface Undoubtedly, you already know that the Java 2 Micro Edition (J2ME) platform defines an environment that supports Java on so-called pervasive devices such as TV set-top boxes and on personal mobile devices such as PDAs, mobile phones, and pagers. This book teaches you how to design and develop Java applications for the J2ME platform. Several motivations precipitated the creation of this book. First, I felt the need for a good book that cultivates a solid technical foundation for professional J2ME programmers by building upon concepts and idioms. I believe that such a book would be particularly useful in light of the explosive growth of the wireless computing paradigm. Wireless environments offer their own challenges to application developers because of their user interfaces, resource constraints, underlying wireless network characteristics, and the interface between the wireless and fixed network infrastructures. Concepts help organize this complexity. Moreover, concepts apply to all platforms. I"m a firm believer that the best learning occurs when one first acquires a conceptual foundation and then complements it with practical application of concepts through pertinent techniques. In software, a platform"s concepts and abstractions form the foundation needed to enable the developer to employ techniques and utilize toolkit idioms. This set of pragmatics comprises the core tools in the software engineer"s arsenal. The engineer is then able to use a toolkit the way its designers intended it to be used. This discipline leads to better code. With a view toward inculcating such discipline, this book is tutorial in nature and takes a somewhat pedagogical approach to the introduction of J2ME. Topics are presented in a logical progression, in the order in which one needs to understand concepts to design real applications from scratch. Each chapter builds upon those that precede it. Examples reflect the concepts and application of programming idioms. This practical approach helps you understand what you need to do and why you need to do it. Armed with the knowledge of how things work, you can successfully design and build complex professional J2ME applications in the absence of suitable examples from reference manuals. Although reference manuals are valuable for demonstrating the mechanical manipulation of APIs on a small scale, they have greater difficulty demonstrating the foundation of concepts that are central to the design and organization of large-scale applications. Nor can they anticipate the design challenges you"ll encounter in an arbitrarily complex, real-world application. The two approaches—reference and tutorial—are complementary, but I believe that conceptual learning is the first step. The popularity and presence of wireless communications has been increasing steadily over the past few years. Worldwide omnipresence of third-generation systems that include Java is imminent. Personal devices that host practical applications will become available to the masses. Java in general, and J2ME in particular, have been influential in advancing the availability of a standard platform that supports the construction and deployment of nontrivial applications on personal mobile devices. As technology advances in often unpredictable ways, the nature of future systems is uncertain at best. Platforms might merge, diverge, or become obsolete as new breakthroughs usher laboratory technology into the engineering mainstream. One thing is certain, though: The concepts underlying the engineering are more constant than the engineering details themselves. Momentum is always influential in the world of technology. Because Java and J2ME define a worthwhile computing model, the longevity of J2ME is assured despite the constantly evolving

technology in the industry. A solid foundation will enable you to navigate the changing landscape successfully. I hope you enjoy this book and your entry into a computing arena that is as much just plain fun as it is dynamic. And I hope you will find this book useful as you begin your journey through the world of mobile computing. Vartan Piroumian Palo Alto, California January 2002

Acknowledgments As always, many people other than the author participate in the creation and success of a book from genesis through distribution to the bookshelves. First and foremost, I would like to thank Rachel Borden of Sun Microsystems, to whom I first spoke about this project and who was instrumental in selling it to Prentice Hall. I would also like to thank Michael Alread of Sun for his efforts as continuing liaison with Prentice Hall. It was a pleasure to work with all of the Prentice Hall staff—Eileen Clark, Gail Cocker, Greg Doench, and Debby vanDijk. Not only did they conduct themselves professionally but they also maintained open and productive lines of communication, coordination, and support throughout the project. I am looking forward to continuing to work with them in the future. I also would like to thank Sybil Ihrig of Helios Productions for her excellent work in the copyediting, page composition, and production stages. I always marvel at how good copyeditors can make authors seem eloquent. Special thanks go to my colleagues from the Sun Santa Clara Java Center. Manisha Umbarje helped unearth localization resources for chapter 9. Marina Fisher helped by providing the Russian translations. Thanks to Rita Abrahamian and also to my mother, Edith Piroumian, for their help with the Armenian translations and for not scolding me for not being able to do it myself. I also would like to thank Brendan McCarthy, chief methodologist of the Sun Java Centers worldwide, for his input on chapter 11. Brendan is the principal author of Sun Microsystems" SunTone Architectural Methodology, and his input was invaluable in helping me explain a difficult topic clearly. I also would like to give wholehearted thanks to Ms. Emiko Koyama for her timely Japanese translations. As usual, Koyama-san responded willingly and cheerfully to produce accurate translations in the ridiculously short time in which she had to work. My thanks also go out to Ms. Junko Sunamura for her quick response in providing some additional Japanese translations. I also would like to express my sincere appreciation to some friends for graciously helping with the Chinese translations and allowing me to interrupt their family reunion during the Christmas and New Year seasons. Special thanks go out to Ms. Renee Tan for her guidance on how to efficiently navigate through more than forty thousand Chinese ideographs and eighty thousand unified Han ideographs and syllabaries, and for teaching me the finer points of radical indexing and six different ideographic organizational schemes. Likewise, special thanks go out to Mr. Sheng Song Tan for his help with Chinese and Japanese translations, and to Ms. Frances Han for her help with the simplified Chinese translations and pinyin indexing. Mike Moumoutjis of CrispWireless in New York City gets special mention, not only for his standing offer to treat me to a sumptuous Greek dinner in New York, but also for introducing me to Pat Pyette, who took on the role of technical reviewer for this book. Pat is an accomplished

J2ME developer and one of the two original founders of KVMWorld.com. Pat graciously took on this book project amidst his desperately busy schedule that includes running his consulting company, periMind Corporation (one of the founding companies of the Micro Java Network) as well as writing for the Micro Java Network. I thank Pat for his professionalism, sharp eye, meticulous attention to detail, and encouraging comments. Pat took the time to carefully examine each line of text and source code. His comments in every chapter have been invaluable in helping me improve the quality and usefulness of this book. Gary Adams of Sun was kind enough to patiently answer all my questions about the subtleties of working in constrained resource environments. Of course, I can"t forget John Rizzo of the Vodafone Global Platform Group in California for his insight and useful feedback on chapter 10. Not only have I enjoyed working with John professionally for the past year—I"ve also enjoyed his inimitable style. I would like to sincerely thank my manager, Alex Wong of the Sun Santa Clara Java Center, for not only supporting me during this project but also for continuing to encourage me to pursue the project. Likewise, I would like to thank Jeffrey Johnson, manager of the Western Region Java Centers at Sun, and Stu Stern, Worldwide manager for the Sun Java Centers, for their support, and for their belief in the value of this book for our practice and for Sun. Finally, I would like to thank Mike Clary of the Java Software division of Sun Microsystems and Bill Joy of Sun Microsystems for writing the foreword to this book. These gentlemen were the originators of the concept of the J2ME platform. I thank them for their support and for their willingness to be a part of this book project.

Introduction This book teaches you how to develop software for the Sun Microsystems J2ME platform. It follows a tutorial-style approach; it"s not a reference manual. The aim is to give you a solid foundation in concepts and techniques that will enable you to venture off and develop quality applications independently. Consistent with this approach, this book doesn"t provide endless pages of API documentation; I leave that offering to the Sun Microsystems Java Software Web site, which maintains the latest and most accurate API documentation. The reader might find it useful, therefore, to have access to the official Java Software J2ME API documentation while reading this book, which can be found at http://java.sun.com/j2me/docs. You can either download the full API documentation or read it online. Additionally, Prentice Hall publishes as part of its Java series a J2ME reference manual that complements this book. Also absent by design from this book are specific details of J2ME development tools offered by third-party vendors. In concert with the book"s tutorial approach, I only introduce you to the Sun Microsystems J2ME Wireless Toolkit, which is the reference development toolkit for J2ME. It"s available free of charge from Sun Microsystems at the Java Developer Connection Web site, which you must access by logging in. Follow the developer connection link from http://java.sun.com/. In this way, you can become familiar with a J2ME development environment and emulator and build and test real applications. Device manufacturers often provide development tools of their own that are similar to Sun"s J2ME Wireless Toolkit. Additionally, other third party software companies offer J2ME development tools. This book doesn"t discuss those tools because they don"t add anything to the concepts or pragmatics of how to design and develop J2ME applications.

This book also defines and discusses wireless application provisioning systems and covers application deployment and provisioning from a conceptual perspective, without becoming mired in the details of specific vendor offerings of provisioning server software. The notion of application deployment is more visible—and more critical—with J2ME than with other platforms such as J2SE. In fact, understanding deployment issues is a crucial element of the J2ME application development process. Finally, I expose the reader to ideas surrounding application architecture. As we rely more heavily on computing devices that are continually becoming more pervasive, it becomes increasingly important for developers to think about reliability, performance, scalability, security, manageability, and so forth. This book gives you an introduction to these concepts and to the notion that developers must think about these characteristics from the outset. Although this book introduces elements comprising the breadth of the J2ME platform, it focuses on the CLDC and MIDP, which support personal, mobile, and independent devices—those with intermittent network connectivity, such as mobile phones. Programming examples and API discussions address this subset of the J2ME platform. The reason for this choice is that, as a J2ME developer, you will most likely be called upon to develop applications for this class of devices.

Chapter 1: Introduction to the Java 2 Micro Edition (J2ME) Platform Chapter 2: The MIDP Application Development Process Chapter 3: MIDP Application Program Structure Chapter 4: The MIDP High-Level API Chapter 5: The MIDP UI Components Chapter 6: The MIDP Low-Level API Chapter 7: Persistent Storage Support in MIDP Chapter 8: MIDP Networking and Communications Chapter 9: Internationalization Chapter 10: Application Provisioning Chapter 11: The Wireless Internet Environment

Chapter 1 introduces you to the J2ME computing platform. It defines much of the J2ME terminology and gives you a general orientation to the concepts that surround the design and organization of the J2ME platform. Chapter 2 describes the J2ME application development process. You learn how to create, compile, prepare, execute, and debug J2ME applications. This chapter doesn"t cover the toolkit or APIs. Coverage of those items begins in Chapter 3. Chapter 3 describes the J2ME MIDP platform from the software developer"s point of view. Here you learn the organization of the APIs and the basic programming abstractions and models defined by the MIDP platform. Chapter 4 continues where Chapter 3 left off. It covers the MIDP high-level API, which encompasses the bulk of the UI components defined by the MIDP. You learn how to manipulate the various UI components and also how to do event handling, called command processing in MIDP terminology.

Chapter 5 covers the MIDP user interface (UI) components. After learning the basic abstractions defined by the MIDP in Chapter 4, you"re ready to learn how to use the components that are built upon those abstractions. Chapter 6 covers the MIDP low-level API, which is implemented by the balance of the MIDP UI components not covered in Chapter 5. Chapter 7 covers the persistent storage mechanisms available to you using the MIDP. Chapter 8 is dedicated to networking and communications. Here you learn how to use the networking and distributed processing services and functionality defined by the CLDC and MIDP. You will also acquire some insight on the decisions for design and support of connectivity services in J2ME. Chapter 9 gives you an introduction to internationalization. This is a topic of considerable breadth and depth that requires more than even a single, dedicated volume. Here, you"ll learn about some of the issues that you"ll encounter while building real-world MIDP applications. This chapter covers the extent of the internationalization support in the CLDC and MIDP and shows some examples of how to employ their features. You"ll also learn how to configure your device environment to support internationalization and localization. Chapter 10 covers application management and provisioning systems. Conceptual familiarity with these systems is important to the J2ME application developer, particularly MIDP developers, because these systems affect your interaction with application and content providers, wireless network carriers, and even end users. Chapter 11 discusses the wireless Internet environment. It discusses the integration between wireless and fixed networks, the wireless Internet from the application developer"s perspective, and the context in which applications execute. You"ll get an introduction to wireless Internet gateways, Internet portal interfaces, and wireless application interfaces and services—all things that you"re likely to encounter as a wireless application developer. This chapter also introduces basic architectural concepts and how they influence the J2ME application developer.

Audience This book is intended for Java developers. It"s suitable for professional software developers and advanced students alike. More precisely, this book expects the reader to be fluent with the Java programming language but doesn"t assume programming experience with particular APIs beyond the core Java APIs. Notwithstanding a lack of experience in any particular area of Java programming beyond fluency with the language, it"s helpful if readers have at least an understanding of the concepts and vernacular that surrounds various Java technologies, such as those terms related to virtual machines, garbage collection, class loading, class verification, native code interfaces, just-in-time compilation, AWT, RMI, JDK, JRE, and so forth. I also assume, however, that the reader has a decent background in object-oriented programming. For this reason, I don"t explain object-oriented concepts when they arise during the process of discussing the J2ME APIs, classes, programming idioms, and so forth. Of course, the more experience the reader has, the better. Throughout the book, various references are made to AWT and Swing. A significant part of MIDP programming involves manipulating user-interface components. The reader with knowledge of AWT or Swing toolkit abstractions can quickly glean useful insights into the organization and abstractions of the MIDP"s UI

Conventions Used In This Book Table I.1 shows the typographical conventions used throughout this book. Table I.2 lists the conventions used for all source code included in this book. Table I.1. Typographical Conventions Description of Data Typography Used Fixed width Courier font Java source code, computer-generated text First use of a new term Palatino italic font Regular prose Palatino regular font Table I.2. Source Code Conventions Used Throughout This Book Type of Data Example Print protected int variableName Java method names, variable names: initial public void lowercase first word, initial capital letter for lookAtThisMethodName() subsequent words public class Java class names: initial capital letter for all words AllWordsFirstCapital

Where to Download J2ME You can download the J2ME Wireless Toolkit and full API documentation by following the links to the Java Developer Connection from http://java.sun.com/. There, you"ll find full API documentation for CDC, the Foundation Profile and the CLDC/MIDP, as well as the toolkit for all platforms such as Solaris, Linux, Windows NT, and Windows 2000.

Where to Find the Code Examples From This Book All the code examples that you encounter in this book can be found on the Prentice Hall Web site at http://www.phptr.com/piroumian

The inception of the J2ME platform arose from the need to define a computing platform that could accommodate consumer electronics and embedded devices. These devices are sometimes referred to collectively as pervasive devices. The creators of the J2ME platform delineated pervasive devices into two distinct categories: • •

Personal, mobile information devices that are capable of intermittent networked communications—mobile phones, two-way pagers, personal digital assistants (PDAs), and organizers Shared-connection information devices connected by fixed, uninterrupted network connection—set-top boxes, Internet TVs, Internet-enabled screen phones, high-end communicators, and car entertainment/navigation systems

The first category describes devices that have a special purpose or are limited in function; they are not general-purpose computing machines. The second categ