Read Microsoft Word - Lab2.doc text version

Wireless Java with J2ME

Student Name: Richard K. Gilbert

Telecommunications Program

Wireless Java with J2ME

Part I: Objective

The goal of this lab is to introduce the student to a Java programming for wireless devices such as mobile phone and the personal digital assistants (PDAs). Student will learn about the programming with Java 2 Platform, Micro Edition (J2ME) wireless toolkit. Basic graphic user interface example is introduced and converted into Palm OS application.

Part II: Equipment List

1. A personal Computer with Windows OS 2. A handheld device (Palm Pilot or Handspring Visor) with Palm OS 3.5 or higher with higher than 4 MB memory 3. Java 2 Standard Edition Development Kit (JDK) Version 1.4.2 or higher 4. Java 2 Micro Edition Wireless Toolkit Version 2.2 or higher 5. IBM WebSphere Micro Environment Toolkit Software 6. Palm Desktop software 7. Any text editor of your choice

Richard K. Gilbert

Telcom 2936 Telecommunications Program, SIS, University of Pittsburgh

Lab 2

Part III: Introduction

The popularity of cellular phones and personal digital assistants and their increasing capability suggests that more people will adopt these small devices and use them extensively in daily life. However, these devices have limited capabilities such as small display screen, limited memory, and low end computing processors. The applications running on these devices have to be programmed differently from normal computer applications. Fortunately, there is a simple way to develop the applications for small mobile devices using Java language and mobile device emulator. An application created in Java for mobile devices is called a MIDlet. Developing MIDlets consists of the following steps [1]: 1. Write the MIDlet code in Java language. 2. Compile the MIDlet's source code into Java byte code. 3. Preverify the MIDlet's .class file to ensure that non-support commands are not included in the program. 4. Package the application in a Java Archive (JAR) file. 5. Create a Java Application Descriptor (JAD) file to describe the Java application. These steps can be done manually using the command-line technique (e.g., in Part IV) or done with an integrate development environment called KToolbar which is part of the J2ME Wireless Toolkit (e.g., in Part V). The life cycle of a MIDlet is shown in Fig. 1. The cycle consists of paused, active, and destroyed states. The list of methods in the code is denoted on the arrows from one state to another state.

Paused

pauseApp()

startApp()

Active

destroyApp()

destroyApp()

Destroyed

Figure 1: MIDlet State Transitions [1] The source code of all MIDlets consists of four main parts: the constructor part, the startapplication part, the pause-application part, and the destroy-application part. The MIDlet skeleton is shown below.

Version 1.0 (2/28/2005)

Wireless Java with J2ME

Page 1 of24

Richard K. Gilbert

Telcom 2936 Telecommunications Program, SIS, University of Pittsburgh

Lab 2

import javax.microedition.midlet.*; public class MyMIDlet extends MIDlet { public MyMIDlet() { // constructor } public void startApp() { // entering active state } public void pauseApp() { // entering paused state } public void destroyApp(boolean unconditional) { // entering destroyed state } }

Developing applications for mobile devices should adhere to the followings guidelines [1]: · Use local variables instead of fields. Accessing local variables is quicker than accessing class members. · Minimize unnecessary method calls · Avoid string concatenation. That is avoiding object creation and garbage collection. Reduce memory usage. · Minimize object creation. Try to recycle objects. Considering passing in a reference to returning object and modifying its values. · Avoid synchronization. If an operation takes longer than a fraction of a second to run, consider placing it in a separate thread.

Version 1.0 (2/28/2005)

Wireless Java with J2ME

Page 2 of24

Richard K. Gilbert

Telcom 2936 Telecommunications Program, SIS, University of Pittsburgh

Lab 2

Before Getting Started:

Before starting the lab, please do the followings: 1. Delete the following directories (if exists) on PC. · C:\WTK22\apps\hellomidlet · C:\WTK22\apps\testgui · C:\WTK22\apps\fetchpagemidlet 2. Delete the "testgui" application (if exists) on Palm device. 2.1 Tap Home icon 2.2 Tap the clock display located at the top left of the screen and then choose "Delete" 2.3 Select "testgui" and then tap "Delete" button to delete the testgui application from a palm device.

Home icon HotSync icon

Version 1.0 (2/28/2005)

Wireless Java with J2ME

Page 3 of24

Richard K. Gilbert

Telcom 2936 Telecommunications Program, SIS, University of Pittsburgh

Lab 2

Part IV: Procedure for Manual Development (Optional)

This part introduces a procedure to develop a MIDlet application manually using a command-line technique. You may skip this part and continue at Part V (developing a MIDlet application with KToolbar). However, you are recommended to read through this part.

1. Setup System Parameters

For Windows OS

SET PATH = %PATH%; C:\wtk22\bin SET J2MEWTK_HOME = C:\wtk22 SET MIDPAPI = %J2MEWTK_HOME%\lib\midpapi10.jar; %J2MEWTK_HOME%\lib\cldcapi10.jar SET J2MECLASSPATH = %J2MEWTK_HOME%\wtklib\kenv.zip; %J2MEWTK_HOME%\wtklib\kvem.jar; %J2MEWTK_HOME%\wtklib\lime.jar

2. Hello World Example

Use any text editor to input following code and save the file name as "HelloMidlet.java."

import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class HelloMidlet extends MIDlet { private Display display; TextBox box = null; public HelloMidlet() { } public void startApp() { display = Display.getDisplay(this); box = new TextBox("Simple Example", "Hello World", 20, 0); display.setCurrent(box); } public void pauseApp(){ } public void destroyApp(boolean unconditional){ } }

Version 1.0 (2/28/2005)

Wireless Java with J2ME

Page 4 of24

Richard K. Gilbert

Telcom 2936 Telecommunications Program, SIS, University of Pittsburgh

Lab 2

3. Compile and Verify Java Code

3.1 Create a directory to hold a compile Java's .class file:

c:\current_dir> mkdir tmpclasses

3.2 Create a directory to hold a verified Java's .class file:

c:\current_dir> mkdir classes

3.3 Compile the MIDlet from command line without any debugging info and set the appropriate boot and J2ME classpath and put the result in \tmpclasses: For Windows OS

C:\current_dir> javac ­g:none ­d tmpclasses ­bootclasspath %MIDPAPI% -classpath %J2MECLASSPATH% HelloMidlet.java

3.4 Preverify java code For Windows OS

C:\current_dir>c:\wtk22\bin\preverify ­classpath %MIDPAPI%; tmpclasses -d classes tmpclasses

4. Create Manifest file and Compress Java Code

Change the current directory into \classes directory and use text editor to create the following file saving it as HelloMidlet.mf.

Manifest-Version: 1.0 MIDlet-1: Hello,,HelloMidlet MIDlet-Name: HelloMidlet MIDlet-Version: 1.0 MIDlet-Vendor: PITT MicroEdition-Profile: MIDP-1.0 MicroEdition-Configuration: CLDC-1.0

Change the current directory into \classes directory and compress the .class file together with the manifest file (.mf) using the jar command. For Windows OS

classes> jar cvfm HelloMidlet.jar HelloMidlet.mf HelloMidlet.class

Version 1.0 (2/28/2005)

Wireless Java with J2ME

Page 5 of24

Richard K. Gilbert

Telcom 2936 Telecommunications Program, SIS, University of Pittsburgh

Lab 2

5. Create Java Application Descriptor (JAD) file

Use text editor to create the following file and save it as HelloMidlet.jad. Find the MIDletJar-Size from the size of the real file by using command "dir" in the command line prompt and enter the correct Size in this file.

MIDlet-1: Hello,,HelloMidlet MIDlet-Name: HelloMidlet MIDlet-Version: 1.0 MIDlet-Vendor: PITT MIDlet-Jar-URL: HelloMidlet.jar MIDlet-Jar-Size: 930 MicroEdition-Profile: MIPD-1.0 MicroEdition-Configuration: CLDC-1.0

6. Run the Application on Mobile Phone Emulator

Make sure that you are in \classes directory and enter following command: For Windows OS

>c:\wtk22\bin\emulator ­Xdescriptor:HelloMidlet.jad

Use your mouse to click on the select button in the emulator.

Figure 2: Mobile Phone Emulator with the HelloMidlet.class

Version 1.0 (2/28/2005)

Wireless Java with J2ME

Page 6 of24

Richard K. Gilbert

Telcom 2936 Telecommunications Program, SIS, University of Pittsburgh

Lab 2

Part V: Procedure for Development with KToolbar

This section introduces a simpler method to develop a MIDlet application using the J2ME Wireless Toolkit and the same source code of HelloMidlet.java (see source code in Part IV)

1. Starting KToolbar

For Windows OS · Choose Start Programs J2ME Wireless Toolkit KToolbar.

2. Create New Project

For Windows OS · Click on the New Project button and enter the Project Name "hellomidlet" and fill in the MIDlet Class Name as "HelloMidlet" (must be the same name as the .java file name). · Click on the Create Project button. A window of settings for project "hellomidlet" will pop up.

3. MIDlet Attributes

A setting project window will pop up after the creation of the project. The user can modify both required and optional attributes by selecting the tabs. For Windows OS · Change the Target Platform drop-down menu from JTWI to MIDP1.0. · Accept the default setting for both required and optional attributes by clicking on OK button.

4. Source Code Directory

The original KToolbar screen will provide the information of the directory that the user should put the source code and the resource files. For Windows OS · Copy the HelloMidlet.java into "C:\WTK22\apps\hellomidlet\src" directory. · If the java program has any resource such as icon file or picture files, copy them into "C:\WTK22\apps\hellomidlet\res" directory. (Current project has no additional resource so you can skip this step.)

Version 1.0 (2/28/2005)

Wireless Java with J2ME

Page 7 of24

Richard K. Gilbert

Telcom 2936 Telecommunications Program, SIS, University of Pittsburgh

Lab 2

The KToolbar program will automatically perform the necessary steps that are compiling, preverifying, compressing the code into JAR, and creating the corresponding JAD file with only one command button. For Windows OS · Click Build button on the KToolbar window and check for any errors report in the KToolbar window.

5. Compile MIDlet

If there is no error during the compile process in step 5, the MIDlet application is ready to run. For Windows OS · Click Run button on the KToolbar. The default emulator will be loaded with the application.

6. Run MIDlet with Emulator

7. Change Emulator

The user can select different emulator by selecting testing device from the device drop-down menu on the KToolbar.

8. Save the MIDlet's JAD/JAR Files

For Windows OS · Click on the Project menu and navigate to the Package submenu. · Select the Create Package command (the corresponding JAD/JAR files would be created automatically).

Version 1.0 (2/28/2005)

Wireless Java with J2ME

Page 8 of24

Richard K. Gilbert

Telcom 2936 Telecommunications Program, SIS, University of Pittsburgh

Lab 2

Part VI: Testing GUI Components with MIDlet

This section demonstrates how the high-level GUI component can be implemented using MIDlet. Use any text editor to create following source code and save the file name as "testGUI.java." Please follow previous procedure of KToolbar in Part V to compile and run this application (use "testgui" as a project name).

import javax.microedition.lcdui.*; import javax.microedition.midlet.*; public class testGUI extends MIDlet implements CommandListener { // display manager Display display = null; // a menu with items List menu = null; // main menu // list of choices List choose = null; // textbox TextBox input = null; // ticker Ticker ticker = new Ticker("Test GUI Components"); // alerts final Alert soundAlert = new Alert("sound Alert"); // date DateField date = new DateField("Today's date: ", DateField.DATE); // form Form form = new Form("Form for Stuff"); // gauge Gauge gauge = new Gauge("Gauge Label", true, 10, 0); // text field TextField textfield = new TextField("TextField Label", "abc", 50, 0); // command static final Command backCommand = new Command("Back", Command.BACK, 0); static final Command mainMenuCommand = new Command("Main", Command.SCREEN, 1); static final Command exitCommand = new Command("Exit", Command.STOP, 2); String currentMenu = null; public testGUI() { // constructor } public void startApp() throws MIDletStateChangeException { display = Display.getDisplay(this); menu = new List("Test Components", Choice.IMPLICIT); menu.append("Test TextBox",null); menu.append("Test List",null); menu.append("Test Alert",null); menu.append("Test Date",null); menu.append("Test Form",null); menu.addCommand(exitCommand); menu.setCommandListener(this); menu.setTicker(ticker); mainMenu(); } public void pauseApp() { display = null; choose = null; menu = null; ticker = null; form = null; input = null; gauge = null; textfield = null; } public void destroyApp(boolean unconditional) { notifyDestroyed(); } //main menu void mainMenu(){ display.setCurrent(menu);

Version 1.0 (2/28/2005)

Wireless Java with J2ME

Page 9 of24

Richard K. Gilbert

Telcom 2936 Telecommunications Program, SIS, University of Pittsburgh

Lab 2

currentMenu = "Main"; } /** * Test the TextBox component */ public void testTextBox() { input = new TextBox("Enter Some Text:", "", 5, TextField.ANY); input.setTicker(new Ticker("testTextBox ")); input.addCommand(backCommand); input.setCommandListener(this); input.setString(""); display.setCurrent(input); currentMenu = "input"; } /** * Test the List component. */ public void testList() { choose = new List("Choose Items", Choice.MULTIPLE); choose.setTicker(new Ticker("listTest ")); choose.addCommand(backCommand); choose.setCommandListener(this); choose.append("Item 1",null); choose.append("Item 2",null); choose.append("Item 3",null); display.setCurrent(choose); currentMenu = "list"; } /** * Test the Alert component. */ public void testAlert() { soundAlert.setType(AlertType.ERROR); soundAlert.setString("** ERROR **"); display.setCurrent(soundAlert); } /** * Test the DataField component. */ public void testDate() { java.util.Date now = new java.util.Date(); date.setDate(now); Form f = new Form("Today's date"); f.append(date); f.addCommand(backCommand); f.setCommandListener(this); display.setCurrent(f); currentMenu = "date"; } /** * Test the Form component. */ public void testForm() { form.append(gauge); form.append(textfield); form.addCommand(backCommand); form.setCommandListener(this); display.setCurrent(form); currentMenu = "form"; } /** * Handle events. */ public void commandAction(Command c, Displayable d) { String label = c.getLabel(); if (label.equals("Exit")) { destroyApp(true); } else if (label.equals("Back")) { if(currentMenu.equals("list") || currentMenu.equals("input") || currentMenu.equals("date") || currentMenu.equals("form")) { // go back to menu mainMenu();

Version 1.0 (2/28/2005)

Wireless Java with J2ME

Page 10 of24

Richard K. Gilbert

Telcom 2936 Telecommunications Program, SIS, University of Pittsburgh

Lab 2

} } else { List down = (List)display.getCurrent(); switch(down.getSelectedIndex()) { case 0: testTextBox(); break; case 1: testList(); break; case 2: testAlert(); break; case 3: testDate(); break; case 4: testForm(); break; } } } }

Version 1.0 (2/28/2005)

Wireless Java with J2ME

Page 11 of24

Richard K. Gilbert

Telcom 2936 Telecommunications Program, SIS, University of Pittsburgh

Lab 2

Part VII: Simple HTTP Programming

A simple network application can be implemented using CLDC Generic Connection framework. A network connection can be created using a java class called javax.microedition.io.Connector. An "open()" method is called with a string of HTTP's URL to fetch a file from the world wide web. Create a file name "FetchPageMidlet.java" with any text editor and follow the KToolbar procedure to compile and run this application (use "fetchpagemidlet" as a project name).

import import import import java.io.*; javax.microedition.io.*; javax.microedition.lcdui.*; javax.microedition.midlet.*;

public class FetchPageMidlet extends MIDlet { private Display display; String url = "http://www.richisonthe.net/~rgilbert/hello.txt"; public FetchPageMidlet() { display = Display.getDisplay(this); } /** * This will be invoked when we start the MIDlet. */ public void startApp() { try { getViaStreamConnection(url); } catch (IOException e) { // Handle Exceptions System.out.println("IOException " + e); e.printStackTrace(); } } /** * Pause, discontinue .... */ public void pauseApp() { // no code } /** * Destroy must cleanup everything */ public void destroyApp(boolean unconditional) { // no code } /** * read url via stream connection */ void getViaStreamConnection(String url) throws IOException { StreamConnection c = null; InputStream s = null; StringBuffer b = new StringBuffer(); TextBox t = null; try { c = (StreamConnection)Connector.open(url); s = c.openInputStream(); int ch; while((ch = s.read()) != -1) { b.append((char) ch); } System.out.println(b.toString()); t = new TextBox("Fetch Page", b.toString(), 1024, 0); } finally { if(s != null) { s.close(); } if(c != null) {

Version 1.0 (2/28/2005)

Wireless Java with J2ME

Page 12 of24

Richard K. Gilbert

Telcom 2936 Telecommunications Program, SIS, University of Pittsburgh

c.close(); }

Lab 2

} // display the contents of the file in a text box. display.setCurrent(t); } }

Question: What is the content of the hello.txt file? (The content of the hello.txt file will displayed on the emulator after launching the "fetchpagemidlet" application)

Answer: Hello! Telcom 2936 class.

Version 1.0 (2/28/2005)

Wireless Java with J2ME

Page 13 of24

Richard K. Gilbert

Telcom 2936 Telecommunications Program, SIS, University of Pittsburgh

Lab 2

Part VIII: Converting to Palm OS Application Using IBM's WebSphere Micro Environment

The benefit of developing application using Java language is that it can run on any machine that supports Java Virtual Machine. The IBM WebSphere Micro Environment is a run-time platform compliant with Java 2 Micro Edition (J2ME). On Palm OS 5 (such as Palm Tungsten C, Zire 72 and Tungsten T5), WebSphere implements the J2ME specifications for the Connected Limited Device Configuration (CLDC) Version 1.1 and the Mobile Information Device Profile (MIDP) Version 2.0 [2]. This section demonstrates on how to install the Java platform on handheld device and convert a MIDlet application to a Palm OS application for Palm OS 5. Please use the same source code in Part VI. We will convert it into Palm Resource Code (PRC) file format, which is an executable format for Palm OS. A summary of Palm application development life cycle are [1]: 1. Develop a MIDlet or a MIDlet suite (multiple MIDlet files). 2. Convert the JAR/JAD file pair into a PRC file (executable Palm application). 3. Install the PRC file on the Palm and test the application.

1. Install the WebSphere Micro Environment Toolkit for Palm OS on PC

This procedure is optional. The lab machine is already installed for you. · Download a package called WME_Toolkit_MIDP2_GA.zip which is the MIDP runtime environment for new Palm OS from the following URL: http://pluggedin.palm.com/regac/pluggedin/Toolkit.jsp · Unzip the package into C:\webshpere\ and check for two Palm OS files called J9JavaVMMidpNG.prc and J9pref.prc. They should be found under the directory C:\websphere\03_09_04\IBM\Websphere Micro Environment\prc\ARM. The first file is a Java Virtual Machine. Both files must be transferred onto Palm device in the next step. These PRC files can also be found from the following URL: http://www.palmone.com/us/support/jvm/

2. Install the WebSphere Micro Environment run-time on the new Palm Device

This procedure is optional. The lab machine is already installed for you. · Make sure that the Palm cradle is connected to the PC's USB port. · Place the Palm device on the cradle. · Start the Palm desktop software and click on the Install icon and go to C:\websphere\03_09_04\IBM\Websphere Micro Environment\prc\ARM to choose the J9JavaVMMidpNG.prc and J9pref.prc. · Tap the HotSync icon on a Palm device (or press the HotSync button on the cradle) to install the file. · Look on the Palm device and make sure that the new Java Virtual Machine is present.

Version 1.0 (2/28/2005)

Wireless Java with J2ME

Page 14 of24

Richard K. Gilbert

Telcom 2936 Telecommunications Program, SIS, University of Pittsburgh

Lab 2

3. Convert a MIDlet into a PRC file for WebShpere

Locate a Windows based tool kit program called jartoprc_w.exe under the directory C:\websphere\03_09_04\IBM\Websphere Micro Environment\bin\. Use this PRC converter tool to convert the MIDlet JAR/JAD file into an executable Palm application. Start this PRC converter tool by clicking on the file icon under Windows or issue the following command line: For Windows OS

C:\websphere\03_09_04\IBM\Websphere Micro Environment\bin> jartoprc_w

· · · ·

After issue the command, an application Windows will pop-up for the JarToPRC tool. Click the Browse... button of JAD File or URL field, Navigate through file chooser for existing JAD file under C:\WTK22\apps\testgui\bin\. Select the file testgui.jad or other JAD file to be converted. Click OK to select the file. Note that some of the files are filled automatically. Optionally, users can add icon image and splash screen for their application. Click on the Generate PRC button to convert the file into a PRC file. The converted file will be saved in the same directory as the JAD/JAR file pair

4. Install and Test the PRC file on the Device

Use HotSync to install the "testgui.prc" file with the following procedure: · Connect Palm device to PC via USB port (or place Palm device in the cradle). · Start the Palm Desktop software on the PC by choosing Start All Programs Palm Desktop Palm Desktop · Click the Install icon and browse to C:\WTK22\apps\testgui\bin\testgui.prc. · Tap the HotSync icon (i.e., a star icon at the bottom right of the screen) on a Palm device (or press the HotSync button on the cradle) to install the file. · Tap the corresponding icon on the Palm device to test your application.

Version 1.0 (2/28/2005)

Wireless Java with J2ME

Page 15 of24

Richard K. Gilbert

Telcom 2936 Telecommunications Program, SIS, University of Pittsburgh

Lab 2

Part X: Assignments

Modify the testGUI.java example so that before displaying test component main menu, the user must enter a correct username and a correct password. Create a new form which is called "Sign in" and added two textfields with corresponding labels called "username" and "password" using the following code:

username = new TextField("Username:", "", 10, TextField.ANY); password = new TextField("Password:", "", 10, TextField.PASSWORD);

Also modify the two soft buttons on the mobile phone emulator to be "cancel" and "login" with the following code:

cancel = new Command("Cancel", Command.Cancel, 2); login = new Command("Login", Command.OK, 2);

If the user enters incorrect username or password, the program must show an alert that notify the user that the login is incorrect and should try again. Hints: · Use the same technique to create the alert as in the testGUI.java. · To check the user name and password strings, use the method ".equals" on String variable type. For this assignment, you have to create a new project with your first name as a project name. You need not to convert your application to a Palm OS application. GSA will test your application using Wireless Toolkit Emulator. Please enter your project name: LogInGUI.java

Version 1.0 (2/28/2005)

Wireless Java with J2ME

Page 16 of24

Richard K. Gilbert Source Code:

Telcom 2936 Telecommunications Program, SIS, University of Pittsburgh

Lab 2

/////////////////////////////////////////////////////////////////////////////////////////// // Richard K. Gilbert // // [email protected] // // http://www.sis.pitt.edu/~rgilbert // // // // Created on: 2-19-2005 // // Modified on: 2-24-2004 // // Created for Telcom 2936 Lab 2 // // // // LogIn GUI Components with MIDlet // // // // This code is a modified format of testGUI.java, but I have added a log-in form field // // which requires users to enter a username and password. The entered username and // // password are simply verified against a known text string (for demonstration only) // // // // This code has also been cleaned up to become more readable (at least according to me) // /////////////////////////////////////////////////////////////////////////////////////////// // // Java Library Declorations import javax.microedition.midlet.*; import javax.microedition.lcdui.*; // // // ============================================ // ============================================ // ======== BEGIN CLASS LogInGui ============== // ============================================ // ============================================ public class LogInGUI extends MIDlet implements CommandListener { // begin class LogInGUI // ===================================== // create and initalize class local variables TextField tfAct = null; // Get user account TextField tfPwd = null; // Get user password TextField tfForm = null; // textfield for textForm() subfunction TextBox tbInput = null; // textBox for textBox() subfunction Display display = null; // display manager List menu = null; // list main menu String currentMenu = null; // initalize currentMenu String username = new String("1"); // Username to compare against String password = new String("1"); // Password to compare against // ===================================== // Menu Commands and where they go static final Command backCommand = new Command("Back", Command.BACK, 0); static final Command mainMenuCommand = new Command("Main", Command.SCREEN, 1); static final Command exitCommand = new Command("Exit", Command.STOP, 2); static final Command logInCommand = new Command("Log In", Command.OK, 2); // // // // // ===================================== ===================================== ======== BEGIN PROGRAM ============== ===================================== =====================================

// STARTAPP() // ===================================== // public void startApp() throws MIDletStateChangeException { display = Display.getDisplay(this); // call the Log In () logIn(); } // end startApp() // =====================================

// PAUSE APPLICATION() // ===================================== // public void pauseApp() { // begin pauseApp() } // end pauseApp() // =====================================

// DESTROP APPLICATION() // ===================================== //

Version 1.0 (2/28/2005)

Wireless Java with J2ME

Page 17 of24

Richard K. Gilbert

Telcom 2936 Telecommunications Program, SIS, University of Pittsburgh

Lab 2

public void destroyApp(boolean unconditional) { // begin destroyApp(*) notifyDestroyed(); } // end destroyApp(*) // ===================================== // ;;;;;;;;;;;;;;;;;;;;;;;;;;;;; // ;;; BEGIN USER DEFINED () ;;; // ;;;;;;;;;;;;;;;;;;;;;;;;;;;;; // LOG IN() // ===================================== // public void logIn() { // begin logIn() // Create the form, add components and commands Form logInForm = new Form("logInForm"); tfAct = new TextField("Account:", "1", 5, TextField.NUMERIC); logInForm.append(tfAct); tfPwd = new TextField("Password:", "1", 10, TextField.PASSWORD | TextField.NUMERIC); logInForm.append(tfPwd); logInForm.append("Enter 1 for both username and password."); logInForm.addCommand(exitCommand); logInForm.addCommand(logInCommand); logInForm.setCommandListener(this); display.setCurrent(logInForm); currentMenu = "logInForm"; } // end logIn() // =====================================

// MAIN MENU() // ===================================== // public void mainMenu() { // begin mainMenu() menu = new List("Components", Choice.IMPLICIT); menu.append("Test TextBox",null); menu.append("Test List",null); menu.append("Test Alert",null); menu.append("Test Date",null); menu.append("Test Form",null); menu.addCommand(exitCommand); menu.setCommandListener(this); display.setCurrent(menu); currentMenu = "main"; } // end main menu // =====================================

// TEXT BOX() // ===================================== // public void testTextBox() { // begin testTextBox() tbInput = new TextBox("Enter Some Text:", "", 50, TextField.ANY); tbInput.setTicker(new Ticker("Test_Text_Box ")); tbInput.addCommand(backCommand); tbInput.setCommandListener(this); tbInput.setString(""); display.setCurrent(tbInput); currentMenu = "textBoxInput"; } // end testTextBox() // =====================================

// TEST LIST() // ===================================== // public void testList() { // begin testList() List listChoice = null; listChoice = new List("Choose Items", Choice.MULTIPLE); listChoice.setTicker(new Ticker("Display_Of_A_List ")); listChoice.addCommand(backCommand); listChoice.setCommandListener(this); listChoice.append("Item 1",null); listChoice.append("Item 2",null); listChoice.append("Item 3",null); display.setCurrent(listChoice);

Version 1.0 (2/28/2005)

Wireless Java with J2ME

Page 18 of24

Richard K. Gilbert

Telcom 2936 Telecommunications Program, SIS, University of Pittsburgh

Lab 2

currentMenu = "listChoice"; } // end testList() // =====================================

// TEST ALERT() // ===================================== // public void testAlert() { // begin testAlert() // display alert final Alert soundAlert = new Alert("ERROR!"); soundAlert.setType(AlertType.ERROR); soundAlert.setTicker(new Ticker("An_Error_Has_Occured ")); soundAlert.setString("** An error has occured **"); display.setCurrent(soundAlert); } // end testAlert() // =====================================

// TESTDATE() // ===================================== // public void testDate() { // begin testDate() DateField date = new DateField("Today's date: ", DateField.DATE); java.util.Date now = new java.util.Date(); date.setDate(now); Form f = null; f = new Form("Today's Date"); f.append(date); f.setTicker(new Ticker("Today's_Date ")); f.addCommand(backCommand); f.setCommandListener(this); display.setCurrent(f); currentMenu = "testDate"; } // end Test the DataField componenet // =====================================

// TESTFORM() // ===================================== // public void testForm() { // begin testForm() Gauge gauge = new Gauge("Gauge Label", true, 10, 0); Form fm = null; tfForm = new TextField("Text Form:", "", 15, TextField.ANY); fm = new Form("A Test Form"); fm.setTicker(new Ticker("Example_Of_A_Form ")); fm.append(gauge); fm.append(tfForm); fm.addCommand(backCommand); fm.setCommandListener(this); display.setCurrent(fm); currentMenu = "testForm"; } // end testForm() // =====================================

// COMMANDACTION(c,d) // ===================================== // public void commandAction(Command c, Displayable d) { String label = c.getLabel(); // when user selects "Exit" command if (label.equals("Exit")) { // begin if destroyApp(true); } // end if

// when user selects "Back" command else if (label.equals("Back")) { // begin else if (l.e("Back")) // display "Back" option to only the following screens if(currentMenu.equals("listChoice") ||

Version 1.0 (2/28/2005)

Wireless Java with J2ME

Page 19 of24

Richard K. Gilbert

Telcom 2936 Telecommunications Program, SIS, University of Pittsburgh

Lab 2

currentMenu.equals("textBoxInput") || currentMenu.equals("testDate") || currentMenu.equals("testForm")) { // begin inner if // call mainMenu() mainMenu(); } // end inner if } // end else if (l.e("back"))

// when user selects "Log In" command else if (label.equals("Log In")) { // begin else if (l.e(LogIn)) // if correct values for username and password are entered, display mainMenu(); // else, call testAlert(); if (tfAct.getString().equals(username) && tfPwd.getString().equals(password)) { // begin if // call mainMenu() mainMenu(); } // end if // error has occured else { // begin else testAlert(); } // end else } // end else if (l.e(LogIn))

// when user selects "Main" command else { // begin else List down = (List)display.getCurrent(); switch(down.getSelectedIndex()) { // call testTextBox() case 0: testTextBox(); break; // call testList() case 1: testList(); break; // call testAlert() case 2: testAlert(); break; // call testDate() case 3: testDate(); break; // call testForm() case 4: testForm(); break; // handle unacceptable input default: testAlert(); break; } // end switch } // end else } // end commandAction(c,d) // ===================================== } // // // // // // end Class LogInGui ============================================ ============================================ ========= END CLASS LogInGui =============== ============================================ ============================================

Version 1.0 (2/28/2005)

Wireless Java with J2ME

Page 20 of24

Richard K. Gilbert

Telcom 2936 Telecommunications Program, SIS, University of Pittsburgh

Lab 2

Questions:

1. Is there any advantage of using a KToolbar to create and test MIDlets versus using command lines? The KToolbar automatically pre-verifies the files. It allows for quick creation, compilation, and execution of MIDlets. 2. What is the purpose of having a JAD file in a MIDlet package? The JAD file serves two purposes, the first of which is to inform the user and the device about the size of the JAR file. The JAD also contains the URL that points to the location of the JAR file. 3. Briefly explain the following partial code from part VI. You may consult any J2ME book.

public void startApp() throws MIDletStateChangeException { display = Display.getDisplay(this); menu = new List("Test Components", Choice.IMPLICIT); menu.append("Test TextBox",null); menu.append("Test List",null); menu.append("Test Alert",null); menu.append("Test Date",null); menu.append("Test Form",null); menu.addCommand(exitCommand); menu.setCommandListener(this); menu.setTicker(ticker); mainMenu(); } . . void mainMenu(){ display.setCurrent(menu); currentMenu = "Main"; }

startApp() is called to create the MIDlet Display is displaying the list of menu items Menu.apppend() displays the menu options available The menu.addCommand() allows one of the soft keys to terminate program Meny.setCommandListener() is listening to see what option the user enters, whether it is one of the switch (menu) values, or the exit command. Of course, mainMenu() calls the function mainMenu(). The Main Menu function displays the values in the current men listed above. "Main" then becomes the current menu.

Version 1.0 (2/28/2005)

Wireless Java with J2ME

Page 21 of24

Richard K. Gilbert

Telcom 2936 Telecommunications Program, SIS, University of Pittsburgh

Lab 2

4. Briefly explain the following partial code from Part VI. You may consult any J2ME book.

. . Form form = new Form("Form for Stuff"); Gauge gauge = new Gauge("Gauge Label", true, 10, 0); TextField textfield = new TextField("TextField Label", "abc", 50, 0); static final Command backCommand = new Command("Back", Command.BACK, 0); . . public void testForm() { form.append(gauge); form.append(textfield); form.addCommand(backCommand); form.setCommandListener(this); display.setCurrent(form); currentMenu = "form"; }

A new object called form is created in this function. The new form is a "form for holding stuff". An object gauge is created on this form, with dimensions defined for it. An object textfield is created, with a label `Textfield Label", it has the text "abc" already in it, and has a pre-defined dimensions. The left soft button is defined to act as the `Back' button for the display screen. The function textform() calls the objects created in the above code, and with the display command, the objects are printed on the user's screen. The current menu is changed from the previous setting (probably `main') to `form'. 5. To establish an HTTP connection, what must you pass into the Connector.open() method? A valid string must be bassed to Connector.open(url). The url must be in a fully qualified identification form, such as http://www.richisonthe.net/~rgilbert/hello.txt. It is called by object `c'.

c = (StreamConnection)Connector.open(url);

Version 1.0 (2/28/2005)

Wireless Java with J2ME

Page 22 of24

Richard K. Gilbert

Telcom 2936 Telecommunications Program, SIS, University of Pittsburgh

Lab 2

Reference:

[1] Q. H. Mahmoud, Learning Wireless Java, Cambridge, O'Reilly, 2002. [2] --, palmOne Java Solutions with WebSphere, Online Available http://www-106.ibm.com/developerworks/websphere/partners/palmone/palmone.html

Appendix:

Procedure for Java SDK and J2ME installation: 1. Download the latest J2SE SDK from http://java.sun.com or http://java.sun.com/j2se/1.4.2/download.html 2. Install the Java SDK first. 3. Add "c:\j2sdk1.4.2_xx\bin" to PATH in User Variables under Environment Variables of Windows. 4. Download the J2ME Wireless Toolkit from the following URL: http://java.sun.com/j2me/ 5. Install the toolkit and specify the version of existing Java SDK installation in previous step.

Version 1.0 (2/28/2005)

Wireless Java with J2ME

Page 23 of24

Information

Microsoft Word - Lab2.doc

24 pages

Find more like this

Report File (DMCA)

Our content is added by our users. We aim to remove reported files within 1 working day. Please use this link to notify us:

Report this file as copyright or inappropriate

332969