You are on page 1of 13

1.

Wireless Development Tutorial Part I


by Jonathan Knudsen and Dana Nourie September 2003 Download:

HelloMIDlet.java

This article contains everything you need to know to get started developing in the Java 2 Platform, Micro Edition (J2ME) environment. You'll learn how to install the development tools, how to write your first J2ME application, how to build it, and how to test the application in an emulator. The application you'll build, a MIDlet, runs on implementations of the Mobile Information Device Profile, one of the J2ME specifications. (For a background on wireless Java technology, read Introduction to Wireless.) Most MIDlets will connect to some type of network service, so Part II of this tutorial describes how to set up a servlet development environment and how to write, compile, and test a servlet. The final step is creating a MIDlet that makes a network connection to the servlet. 1.1. What You Need You have lots of choices for a MIDP development environment. Many Integrated Development Environments (IDEs) support MIDP development, including Code Warrior Wireless Studio, Borland's JBuilder. Sun One Studio, Mobile Edition has its own tutorial that will get you started, and more documentation is available here. In this article you'll use Sun's J2ME Wireless Toolkit, which is both free and lightweight. The J2ME Wireless Toolkit can be integrated into IDEs but it can also run standalone, which is how I'll describe it in this article. MIDP development tools are widely available for Windows, Linux, OS X, and Solaris. In this article, you'll assemble a development environment based on three pieces of software: Java 2 Standard Edition (J2SE) SDK version 1.3 or higher. J2ME Wireless Toolkit. This is a package of tools for building and testing MIDlets. Text editor. This can be something as rudimentary as Notepad (on Windows) or something more elaborate like jEdit. (The J2ME Wireless Toolkit isn't available for OS X, but you can still do MIDP development. For more information, read Do-It-Yourself MIDP on Mac OS X.) What editor you use is, of course, entirely up to you. On Unix-like systems, emacs or vi are popular choices. Some Windows devlopers use Notepad, but you'll likely want something a little more sophisticated if you do much development work. jEdit is a very capable editor that runs in a Java 2 runtime and works well on different systems like Windows 2000 and Mac OS X. Most IDEs include their own editor. 1.2. Installing the J2SE SDK You'll need the J2SE SDK to form the foundation of your development environment. (You will sometimes hear developers refer to this as the JDK, or Java Developer's Kit, but the current name is J2SE SDK.) You can download the current version from

http://java.sun.com/j2se/. The current version is 1.4.2. The J2SE SDK is available for Linux, Solaris, and Windows. How does the J2SE SDK help you develop wireless applications? First, it provides the Java platform upon which the J2ME Wireless Toolkit runs. Second, it includes a Java compiler and other tools that the toolkit uses to build your projects. Once you've finished downloading the J2SE SDK, you'll need to install it. In Windows, run the file you just downloaded. The installer asks you some questions and installs the software. If you accept the defaults, J2SE is installed in a directory like c:\j2sdk1.4.2. You should add the bin subdirectory to your path, either in your autoexec.bat file (Windows 95/98) or in the System Properties (Windows NT/2000). To test your installation, open up a command prompt. Type java -version and see what happens. Here's the output on my computer:
C:\>java -version java version "1.4.0" Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0-b92) Java HotSpot(TM) Client VM (build 1.4.0-b92, mixed mode) C:\>

1.3. Installing the J2ME Wireless Toolkit The next step is to install the J2ME Wireless Toolkit, a set of tools that make it easy to build and test MIDP applications. (You can think of the toolkit as a miniature IDE; it automates several of the tasks related to building MIDP applications.) Begin by downloading the J2ME Wireless Toolkit from http://java.sun.com/products/j2mewtoolkit/ . Execute the installation file. The installer tries to locate your J2SE SDK; if it's having trouble, make sure you are pointing it to the directory where you installed the J2SE SDK. You will also need to specify whether the toolkit will run by itself (standalone) or be integrated with an IDE. This article assumes you will be running the toolkit in standalone mode. The files for the toolkit will go into c:\WTK20 unless you specify a different directory, and the installer creates shortcuts for various parts of the toolkit. To run the toolkit itself, select the KToolbar shortcut. You should see the following screen.

Opening screen of the J2ME Wireless Toolkit (Click for a full-size image.) The J2ME Wireless Toolkit works with projects, where the end result of each project is one MIDlet suite. The toolkit works with one project at a time. You can change properties of the current project, build the project, and run the project in a device emulator. Several example projects come installed with the toolkit; we'll look at these later.

Let's jump right in the water by creating a new project. Click on New Project in the button bar. The toolkit prompts you for a project name and the name of a MIDlet class in the project. Fill in HelloSuite and HelloMIDlet as shown below.

Creating a new project Once you fill in the project name and first MIDlet name, the toolkit gives you a chance to edit the project settings. Just accept the defaults for now; press OK to finish creating the new project. In the text output pane of the J2ME Wireless Toolkit, you'll see several helpful messages telling you where to store the project's source files. On my machine, these messages are:
Creating project "HelloSuite" Place Java source files in "C:\WTK20\apps\HelloSuite\src" Place Application resource files in "C:\WTK20\apps\HelloSuite\res" Place Application library files in "C:\WTK20\apps\HelloSuite\lib"

The toolkit stores each project in a subdirectory of the appsdirectory. The name of the subdirectory is the same as the name of the project. Here, the toolkit has created a new directory, c:\WTK20\apps\HelloSuite. Each project subdirectory has a standard structure:

Project directory structure The bin directory contains the compiled MIDlet suite (a .jar file) and the MIDlet suite descriptor (a .jad file). The lib directory is the location for any additional JAR files you would like to include in your project. res is the location for resource files, like images or text files, that should be bundled with your MIDlet suite. Finally, the src directory is the place where your source code should be saved. The standard rules about packages and directories apply; for example, source code for a users.Root class would go in src/users/Root.java. When you use KToolbar to build a project, several additional directories are created:

Project directory structure after building As you can see, the J2ME Wireless Toolkit has created classes, tmpclasses, and tmplib. For the most part you can ignore these directories; the toolkit uses them internally.

1.4. Create a MIDlet To get you started with MIDlet development, let's write a simple MIDlet. Once you've chosen a text editor, type, cut and paste, or download the following code:
import javax.microedition.lcdui.*; import javax.microedition.midlet.*; public class HelloMIDlet extends MIDlet implements CommandListener { private Form mMainForm; public HelloMIDlet() { mMainForm = new Form("HelloMIDlet"); mMainForm.append(new StringItem(null, "Hello, MIDP!")); mMainForm.addCommand(new Command("Exit", Command.EXIT, 0)); mMainForm.setCommandListener(this); } public void startApp() { Display.getDisplay(this).setCurrent(mMainForm); } public void pauseApp() {} public void destroyApp(boolean unconditional) {} public void commandAction(Command c, Displayable s) { notifyDestroyed(); } }

Save this code as HelloMIDlet.java in the src directory of your project. On my computer, this file is saved in c:\WTK20\apps\HelloSuite\src\HelloMIDlet.java. Next, press the Build button in KToolbar. The toolkit will attempt to compile your project. If there are any compiler errors, you'll see them in the text output area of KToolbar. Fix the errors until the project builds successfully. Now you're ready to test your MIDlet suite. Click on the Run button. You should see a mobile phone emulator pop up:

HelloSuite running on the emulator The emulator is showing a list of MIDlets in the MIDlet suite. This example shows only one MIDlet. Although the name you see here is HelloSuite, the class that will be run is HelloMIDlet. To see where this mapping occurs, go to KToolbar and select Settings.... Then click on the MIDlets tab to see a list of the MIDlets in the project. Back in the emulator, click on the soft button below Launch to start up the MIDlet. It will display a simple screen like the one below. Click on Exit to leave the MIDlet. Close the emulator window or hit the Escape key to end the emulator session.

HelloMIDlet running on the emulator The emulator you've just used is the DefaultColorPhone. The J2ME Wireless Toolkit has other emulators as well. Try running HelloMIDlet on some other devices to see how the user interface adapts. Simply select the emulator you'd like in the combo box in KToolbar, then click on Run again. Once you've had your fill of playing with HelloMIDlet, you might want to check out some of the other projects that come bundled with the toolkit. Feel free to try out the demos, games, and photoalbum sample projects.

1.5. A Quick Look Under the Hood Now that you've had some fun, let's take a step back and talk about what it is that the J2ME Wireless Toolkit does for you. None of it is too complicated, but the toolkit takes several potentially aggravating steps and condenses them into a single button push. First, what happens when you press the Build button? The toolkit finds all the .java files in the src directory of your project and compiles them. This is no ordinary compilation, however, because the source files must be compiled in a MIDP environment rather than a J2SE environment. To understand this departure, think of a MIDlet that uses the java.lang.System class. This class has different APIs in J2SE and MIDP. When the toolkit compiles your MIDlet class, you want it to use the MIDP java.lang.System, not the J2SE version of the class. You could make this selection yourself, using the command javac and the -bootclasspath option, but it's much simpler just to let the toolkit worry about it. Beyond compilation, MIDP classes must be preverified before they can be run on a MIDP device. You may recall that J2SE has a bytecode verifier that checks .class files before they are loaded. In the MIDP world, verification is split into two phases. The toolkit performs an initial verification at build time, then the device's runtime system performs a second verification when it loads the classes. You could perform the first verification yourself using the command line preverify tool, but it's much easier to leave this detail to the toolkit. Finally, MIDlets are bundled into MIDlet suites for distribution to actual devices. This process entails JARing the MIDlet suite class files and the resource files, and putting some extra information in the JAR manifest. Again, these chores are best left to the J2ME Wireless Toolkit. To bundle up your MIDlet suite, select Project | Package from the menu. The .jad and .jar files for the MIDlet suite will be generated and placed in the bin directory of the project.

2. Just Wait 'til Next Time


You now understand the rudiments of MIDP development and have the software you need to build your own MIDlet suites. That's pretty spectactular all by itself. But MIDP client programming is only half the picture. With some exceptions, most of the really interesting MIDlets will be those that connect to some network service. In Part II of this article, you'll learn how to install, configure and run a server environment. You'll write a simple Java servlet and modify the MIDlet so that it makes a network connection to the servlet. After that, the world is yours for the taking. 2.1. Resources The user guide that comes with the J2ME Wireless Toolkit contains useful information about the application development cycle, MIDlet attributes, the files in each of the installed directories, and device types and portability. It also includes instruction on configuring the emulator and using the Wireless Toolkit from the command line. If you're new to MIDP programming, you might also find these articles helpful: Introduction to Wireless Learning Path: Getting Started With MIDP All MIDP articles

3. Wireless Development Tutorial Part II


In Part I of this tutorial, you learned how to write a simple Java 2, Micro Edition (J2ME) application. The application, a MIDlet, was designed for the Mobile Information Device Profile, one of the J2ME specifications. Now you're going to expand your horizons dramatically. You'll learn how to write and deploy a servlet, and then how to hook up a MIDlet with the servlet. By the time you finish reading this, you'll have all the tools you need to develop end to end wireless Java applications. There are two versions of this article, depending on which platform you wish to use for servlet development. Tomcat is the freely available reference implementation of the Java servlet and JavaServer Pages (JSP) specifications. Although it is not meant to be a production quality server, Tomcat is an excellent platform for developing and testing servlets. The Java 2, Enterprise Edition (J2EE) Reference Implementation (J2EE RI) server is a full implementation of the J2EE specification. Like Tomcat, it is not intended to be a production quality server, but it serves as a good place for developers to learn, prototype, test, and experiment. Again, you can't beat the price: like Tomcat, the J2EE RI server is freely downloadable. There are pros and cons for each server, of course. Tomcat is easier to use for servlet development. However, its capabilities are limited to servlets and JSPs. By constrast, the J2EE RI server implements the full spectrum of J2EE technologies, including servlets, JSPs, EJB, JMS, JNDI, and more. The article you are reading demonstrates servlet development using Tomcat. Click here for the J2EE RI version of the article. 3.1. Installing and Running Tomcat Tomcat is distributed as a ZIP archive, available from the Apache Jakarta project. As of this writing, the current version is 4.1.27. Installation of Tomcat is simple: just unzip the download file. You can put it wherever you want. I unzipped it to a root-level directory, c:\jakarta-tomcat-4.1.27\. Tomcat itself is written in Java. To run Tomcat you'll need to tell it where to find your J2SE installation. To do this, put the location of your J2SE installation in the JAVA_HOME environment variable. On my machine, the variable has the value c:\j2sdk1.4.0. To run Tomcat, open a command window. Change directories to Tomcat's bin directory. Type startup and stand back. A new window will open up and display copious initialization messages:

Tomcat's initialization messages (Click for a full size image.) You can use a browser to test if Tomcat is really running. Try to open the URL http://localhost:8080/ and see what happens. If Tomcat is running correctly you'll see a default page from Tomcat with links to some servlet and JSP examples. To shut down Tomcat, open another command window. Change directories to Tomcat's bin directory and run the shutdown command. Starting and stopping Tomcat this way is a little clumsy. I recommend creating Windows shortcuts to run the startup and shutdown commands. 3.2. Writing Servlet Source Code Writing the source code for your servlet is much like writing any other Java source code: use the text editor of your choice to create .java source files. In this example, you'll write a very simple servlet called HitServlet. Its source code is shown below. HitServlet simply counts the number of times it's been invoked and writes back to the client a message containing the count. (It's not thread-safe, but that doesn't matter here.)
import javax.servlet.http.*; import javax.servlet.*; import java.io.*; public class HitServlet extends HttpServlet { private int mCount; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String message = "Hits: " + ++mCount; response.setContentType("text/plain"); response.setContentLength(message.length()); PrintWriter out = response.getWriter(); out.println(message); } }

Later, you're going to build a web application with a very specific directory structure. This directory structure makes it easy for the server to find the pieces of your application. For now, take it on faith and save the source code in a file under the Tomcat root directory named webapps/midp/WEB-INF/classes/HitServlet.java. (Go ahead and create the midp directory and its subdirectories now.)

Compiling the Servlet Compiling servlet code is pretty much the same as for other Java development, except for an important twist. Because the servlet API is not a core part of the J2SE platform, you'll need to add it to your CLASSPATH before you can compile servlets. The servlet API is contained in common/lib/servlet.jar under the Tomcat root directory. Simply add this file to your CLASSPATH and you will be able to compile HitServlet.java using javac. You can edit the CLASSPATH in the system properties or do it on the command line, as this Windows example demonstrates:
C:\>set CLASSPATH=\jakarta-tomcat-4.1.27\common\lib\servlet.jar C:\>javac HitServlet.java

3.3. Deploying the Servlet To deploy your servlet, you'll first need to understand something about web applications. A web application is a collection of static content, like HTML and image files, servlets, and other resources that can be made accessible via a web interface. Tomcat comes with several web applications already installed. Go look in the webapps directory under your Tomcat installation directory and you'll see a few: examples and webdav, for instance. We're going to create a new web application and place our servlet inside. First, let's create the web application. You already created a new diretory inside webapps called midp, where you saved the servlet source code. Now you'll need to edit one of Tomcat's configuration files to tell Tomcat about the new web application. Open the conf/server.xml file with a text editor. In this file, web applications are called contexts. Scroll down to find the Context entry for the examples web application, which begins like this:
<!-- Tomcat Examples Context --> <Context path="/examples" docBase="examples" debug="0" reloadable="true" crossContext="true"> Above or below this lengthy context entry (it's closed by </Context>, many lines down),

create a new context entry for your new web application. It will look similar to the opening tag for the examples context, but you'll change the names to midp as appopriate and close the tag inline.
<!-- MIDP Context --> <Context path="/midp" docBase="midp" reloadable="true"/>

Once you're finished adding the context entry, save the file. What these steps do is map incoming HTTP requests to a web application in a particular directory. Specifically, any incoming HTTP request that begins with "/midp" (the path) will be handed off to the web application located at webapps/midp (the docBase). The reloadable attribute helps a lot with debugging; it tells Tomcat to reload automatically any servlet class you change so you don't have to restart the server. Now that you've created a web application, fill it up. Web applications have a standard directory structure, mandated by the servlets specification. We won't get into too much detail here. The essential piece of a web application is a web.xml file that describes the various parts of the web application. This file lives in a standard location in every web application; it's always stored as WEB-INF/web.xml It's time to create a web.xml file for your new application. You want to make the servlet accessible to the outside world. You know the class name of the servlet, HitServlet, and you'd like to make it available under a path like /hits. Note that the path for the servlet is

relative to the path for the web application, so the full path to the servlet will be http://localhost:8080/midp/hits. Copy the following text (or download it) and save it as webapps/midp/WEB-INF/web.xml under the Tomcat root directory:
<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <servlet> <servlet-name>bob</servlet-name> <servlet-class>HitServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>bob</servlet-name> <url-pattern>/hits</url-pattern> </servlet-mapping> </web-app>

This file tells Tomcat to map the servlet called HitServlet to the path /hits. The servletname is internal to web.xml; it links the servlet element to the servlet-mapping element. The name bob is only a friendly example; you can choose whatever name you want. You recall that you had saved your servlet source code in a standard directory underneath WEB-INF called classes. This is where Tomcat expects to find servlet class files, so when you compiled the source code, the servlet class was stored in the right place. Your servlet is now deployed in the new web application you created, but note that you must restart Tomcat to have it recognize the changes you made in server.xml. To test your handiwork, go to a browser and navigate to http://localhost:8080/midp/hits. You should see the output of HitServlet. Reload the page a few times and watch the hit counter increase. For more information on servlet development, see Java Servlet Technology, part of the J2EE Tutorial. 3.4. Hooking Up a MIDlet to the Servlet This part is fun. Now that you have a development environment that supports both MIDP and servlets, you are going to hook the two worlds together to create an end to end Java application. MIDlets can connect to the world at large via HTTP, and the servlet you just wrote is available to the world at large via HTTP, so it's a pretty simple matter to have a MIDlet connect to the servlet. Start KToolbar (part of the J2ME Wireless Toolkit) and open the MIDlet project that you created in Part I of this tutorial. You're going to create a new MIDlet that connects to your servlet, retrieves its output, and displays it. If you haven't created a J2ME Wireless Toolkit project yet, go back to Part I and do it now. The full source code for the MIDlet that connects to HitServlet is shown below.

import java.io.*; import javax.microedition.io.*; import javax.microedition.lcdui.*; import javax.microedition.midlet.*; public class HitMIDlet extends MIDlet implements CommandListener { private Display mDisplay; private Form mMainForm; private StringItem mMessageItem; private Command mExitCommand, mConnectCommand; public HitMIDlet() { mMainForm = new Form("HitMIDlet"); mMessageItem = new StringItem(null, ""); mExitCommand = new Command("Exit", Command.EXIT, 0); mConnectCommand = new Command("Connect", Command.SCREEN, 0); mMainForm.append(mMessageItem); mMainForm.addCommand(mExitCommand); mMainForm.addCommand(mConnectCommand); mMainForm.setCommandListener(this); } public void startApp() { mDisplay = Display.getDisplay(this); mDisplay.setCurrent(mMainForm); } public void pauseApp() {} public void destroyApp(boolean unconditional) {} public void commandAction(Command c, Displayable s) { if (c == mExitCommand) notifyDestroyed(); else if (c == mConnectCommand) { Form waitForm = new Form("Waiting..."); mDisplay.setCurrent(waitForm); Thread t = new Thread() { public void run() { connect(); } }; t.start(); } } private void connect() { HttpConnection hc = null; InputStream in = null; String url = getAppProperty("HitMIDlet.URL"); try { hc = (HttpConnection)Connector.open(url); in = hc.openInputStream(); int contentLength = (int)hc.getLength(); byte[] raw = new byte[contentLength]; int length = in.read(raw); in.close(); hc.close(); // Show the response to the user. String s = new String(raw, 0, length); mMessageItem.setText(s); } catch (IOException ioe) { mMessageItem.setText(ioe.toString()); } mDisplay.setCurrent(mMainForm); } }

The main screen of HitMIDlet is similar to HelloMIDlet, but it includes two commands, Exit and Connect. Connect sets up a separate thread and calls the connect() method, which takes care of making a network connection and retrieving the results. Copy the code above (or download it) into your editor. Save it as HitMIDlet.java inside the apps/HelloSuite/src directory underneath the J2ME Wireless Toolkit root directory. There are two other things to configure to get HitMIDlet working. First, you need to tell the toolkit about this new MIDlet. Click on Settings..., then select the MIDlets tab. Click on Add and fill in "HitMIDlet" for both the MIDlet name and class name. You can leave Icon blank. Click on OK and you should see both HelloMIDlet and HitMIDlet listed. Next, you need to define a system property that HitMIDlet uses as the URL for its network connection. (This property is retrieved in the third line of the connect() method.) In the toolkit, click on Settings..., then select the User Defined tab. Click on the Add button. Fill in the property name as HitMIDlet.URL; the value should be the URL that invokes HitServlet, the same URL you used in a browser to test the servlet. When you're finished, click on OK to dismiss the project settings window. Now, in the J2ME Wireless Toolkit, click on Build to build the project. Assuming you don't see any error messages, you are now ready to test the application. Make sure your server is running first. Then click on Run and select HitMIDlet. Select the Connect command. If everything goes well, HitMIDlet will invoke HitServlet and display the results on the device emulator screen:

Success!

4. Development Notes
Now that you've created your own web application, you can easily modify and test HitServlet. Just change the source code and recompile. Next time you invoke the servlet from your browser or from HelloMIDlet, Tomcat will use the new version of the servlet class. (Remember that reloadable attribute in Tomcat's server.xml file? That's what reloadable means.) If you want to write additional servlets, you probably will need to make changes to your web application's web.xml file. If so, you will need to bounce the server (restart it) to have the changes take effect. Summary

This article showed how to round out an end to end Java development environment. Part I demonstrated the setup and use of a MIDlet development environment, while this part of the tutorial showed how to configure and use a servlet development environment. You learned how to install and run a server and how to write and deploy a servlet. Then you hooked up the world of MIDlets to the world of servlets, creating a simple end to end Java solution. The servlet serves as a jumping-off point to the rest of the world, as it gives you access to the full power of J2SE and J2EE. This is the path to creating powerful end to end Java applications. MIDP clients are relatively small and simple, but by talking to servlets they can accomplish great things. For more information on end to end Java application design, see the Wireless Blueprints, a white paper and example application built using end to end Java technology.

You might also like