Getting Started with BlackBerry J2ME Development Blog

Version 2


    Java's "write once, run anywhere" concept has made Java attractive to vendors who develop applications for handheld devices. This fact has pushed device manufacturers to make their devices Java-enabled by equipping them with the K Virtual Machine(KVM), a small a Java Virtual Machine. BlackBerry phones manufactured by Research in Motion (RIM) are no exception. Not only are BlackBerry phones Java-enabled, but RIM has issued a huge collection of BlackBerry APIs that can be used to develop BlackBerry applications like native applications. This article helps you get started with J2ME development for BlackBerry phones: setting up the development environment, deploying the applications to the devices, and writing a Hello World application. Also, we'll write two other programs, based on persistence and network operation.

    A Few Bits to Bear in Mind

    • RIM's support for J2ME includes development for its own JVM, which supports the Connected Limited Device Configuration (CLDC) and the Mobile Information Device Profile (MIDP). It comes with additional BlackBerry-specific APIs that give the application a native BlackBerry look. These applications are often calledRIMlets in contrast to MIDlets.
    • APIs specific to CLDC, MIDP, and BlackBerry, generally, can be used together in one application, with the exception of UI APIs: the two packages javax.microedition.lcdui andnet.rim.device.api.ui cannot be used together in one application. RIM's UI API provides more control over screen layouts; however, this makes the application no longer a standard MIDlet, and hence porting is require for devices not supporting the BlackBerry APIs.
    • In RIM, UI operations take place on the event thread, in contrast to MIDP's UI classes.
    • For persistence, you can use either BlackBerry Persistence APIs or MIDP Record Management System (RMS) APIs.
    • MIDP's Generic Connection Framework can be used for networking operations.
    • In MIDlets, the main MIDlet class extends theMIDlet class, while for RIMlets, the main class extends either net.rim.system.Application (if it's a background application requiring no user interaction) ornet.rim.system.UiApplication (if the RIMlet requires user interaction).
    • Unlike a MIDlet's starting point, the entry point into a RIMlet is the main() method.
    • A RIMlet screen is not a movable window. To display it, you simply push it on the display stack usingpushScreen(). According to the BlackBerry API specification:

      A UI application maintains a stack of screen objects. As it pushes screens onto the stack, it draws them on top of any other screens already on the stack. When the application pops a screen off the stack, it redraws the underlying screens as necessary. Only the screen on the top of the stack receives input events.

    • To run a standard MIDlet on a BlackBerry device, jad andjar files have to be converted to jads andcods, a proprietary format, using the rapccommand line tool.

    Command Line Tools

    The rapc command line tool is used for converting Java Application Descriptor (JAD) and JAR files into .cod format. The following command converts a jar to a cod:

    rapc import="c:\BlackBerryJDE3.6\lib\net_rim_api.jar" codename=HelloWorld -midlet jad= HelloWorld.jad HelloWorld.jar

    The javaloader command line tool is used to loadcod files to the BlackBerry device over a USB cable, as shown below:

    javaloader -usb load HelloWorld.cod

    The same tool is used to delete an application from the device:

    javaloader -usb erase -f LoginMIDlet.cod

    The command line tools can be found in the bin directory beneath the BlackBerry Java Development Environment (JDE) installation directory. For these tools to work, JDE's binmust be in the PATH environment variable.

    RIM's Java Development Environment (JDE)

    The BlackBerry JDE is an integrated development environment (IDE) that provides a complete set of tools and APIs for you to develop Java applications that run on BlackBerry devices. The latest version of JDE can be downloaded from the BlackBerry Developer site. Applications developed using the BlackBerry JDE are forward-compatible but not backward-compatible. In other words, an application developed with JDE 4.1 will run on BlackBerry devices with device software version 4.1 and later; however, they will not run on device software 4.0. For more details, please see the BlackBerry JDE versions page.

    View of BlackBerry JDE
    Figure 1. View of BlackBerry JDE

    The BlackBerry JDE requires Java 1.5 or higher to be installed on the host system. The bin directory of the Java 2 SDK must also be part of the system's PATH variable.

    Say Hello to World

    Your very first program is going to be the Hello World application. This will give you an idea of the structure and flow of a BlackBerry application. First, let's discuss how to create a workspace, project, and source in the JDE.

    Creating a Workspace

    • 1. In the JDE, click File -> New -> Workspace(Tab).
    • 2. Enter a name for the workspace and a location to save it.
    • 3. Press OK.

    Creating a Workspace
    Figure 2. Creating a workspace

    Creating a Project

    • 1. From the Project menu, chooseCreate New Project.
    • 2. Enter a name for the project and a location to save it.
    • 3. Press OK.

    Creating a Project
    Figure 3. Creating a Project

    Creating Source Files

    • 1. From the Project menu, chooseCreate New File in Project.
    • 2. Give a name to the file.
    • 3. Enter the pathname of the project directory to save it. (Note: if you want to create package, you have to enter the complete path with package directories.)
    • 4. Press OK.

    Creating a Source File
    Figure 4. Create a Source File

    Writing Code for the HelloWorld Application

    In the editor pane, you can enter, or simply copy and paste, the following code:

    /* * * * Developed by Atif Razzaq * * */ package com.client.bberry; import net.rim.device.api.ui.*; import net.rim.device.api.ui.component.*; import net.rim.device.api.ui.container.*; import net.rim.device.api.system.*; public class HelloWorld extends UiApplication { public static void main(String[] args) { HelloWorld theApp = new HelloWorld(); theApp.enterEventDispatcher(); } public HelloWorld() { pushScreen(new HelloWorldScreen()); } } final class HelloWorldScreen extends MainScreen { public HelloWorldScreen() { super(); LabelField title = new LabelField("HelloWorld:My First Application", LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH ); setTitle(title); add(new RichTextField("Hello World!!!!!")); } public boolean onClose() { Dialog.alert("Bye to HelloWorld"); System.exit(0); return true; } } 

    How HelloWorld Works

    Recall that if an application involves user interaction, the main class (HelloWorld in this case) extendsUiApplication. Also recall that the entry point to the application is the main() method. main()creates an instance of the main class and callsenterEventDispatcher(), a method in theUiApplication class, to start event handling;enterEventDispatcher() executes all drawing and event-handling code. The constructor in the main()method also pushes a screen, HelloWorldScreen in this case, onto the display stack before the event handler is launched. The HelloWorldScreen class constitutes the display of the application and extends MainScreen class.MainScreen is used in almost every application that involves user interaction to create the application's display. TheonClose() method is also an inherited method fromMainScreen that is overridden here; that method is called by the event handler when the screen exits. Please see BlackBerry API JavaDocs in the Resourcessection.

    Running the HelloWorld application
    Figure 5. Running the HelloWorld application

    Running the Application

    Selecting Build -> Build All performs compilation and preverification, and packages the application. The JDE generates HelloWorld.jad, HelloWorld.jar, andHelloWorld.cod. Now you can run the application by selectingBuild -> Build All and Run. The application appears in the emulator. Just select it, and it displays a welcome message. When you exit, you'll see the message "Bye to HelloWorld."

    Deploying the Application on a BlackBerry Device

    An application can be deployed on BlackBerry device through one of the following ways:

    • The javaloader command-line tool (described above).
    • The BlackBerry Desktop Manager, using an alx file. This file can be created choosing Project -> Generate ALX file in the JDE. An ALX file is an XML-based BlackBerry application descriptor and contains a reference to a codfile.
    • With Over the Air (OTA), through a browser you can select ajad file that downloads the application using a codfile.

    NOTE: If you access the network through a WAP gateway, you can download only cod files. To download standard MIDlets to a BlackBerry, the Mobile Data Service feature of the BlackBerry Enterprise Server (BES) must be enabled; this provides a built-in transcoder that converts jar files into cod files. Note that the web server must identify the MIME types forjad and cod files usingtext/ andapplication/vnd.rim.cod respectively. Please see the Resources section for links to the documentation.

    About JAD with BlackBerry JDE

    The JDE-generated jad file includes both standard-JAD and RIM-specific properties. It serves two purposes: the downloading of MIDlets to BlackBerry devices, and to other devices as well. The properties RIM-COD-URL andMIDlet-Jar-URL ensure that BlackBerry users download the cod file, while other users download thejar.

    Save Your Stuff: Storage

    This sample application is based on persistent storage. The application asks the user to enter his/her name and email address in the provided editable text fields and saves the data, which persists through resets (see Figure 6). The next time the application is launched, the application retrieves the persisted data and populates the editable text fields. The user can edit and save the data again. Before we think about the code, it will be a good idea to have a look at the following points, which provide a comparison of MIDP RMS and BlackBerry's persistent mechanism.

    • MIDP RMS has a size restriction on the RMS size: 64KB for a single RMS data store. This has been largely removed in BlackBerry's persistent model.
    • The BlackBerry persistence model requires the use of signed APIs, while this is not the case with MIDP RMS.
    • With MIDP RMS, each record is a byte array, so you need to serialize the data in this format for storage; however, with BlackBerry's APIs you store the Java objects.
    Persistence application
    Figure 6. Persistence application

    Please read "BlackBerry Storage" for a detailed description on how to use BlackBerry Persistence APIs and their comparison with MIDP RMS.

    How Storage Works

    It is strongly recommended that you download and view the sample code for persistence from the Resourcessection, so you can effectively follow this description. Moreover, this description discusses only the storage mechanism and not the UI part of the application, for example, the MenuItemclass used in the application, for which you can consult the BlackBerry API JavaDocs in the Resourcessection.

    Two important classes, PersistentObject andPersistentStore, play a vital role in the process of persistence. There is an interface, Persistable; for any object of a class to be persistable, it must implement this interface. For example, PersistentInfo in our code implements this interface. Notice that this is an empty interface, as we didn't implement any method from the interface. This simply states that the object is persistable. The primitive data types are implicitly persistable. According to BlackBerry API specification:

    "PersistentStore" is a store for persistent objects. The persistent store provides a means for objects to persist across device resets. A persistent object consists of a key-value pair. When a persistent object is committed to the persistent store, that object's value is stored in flash memory via a deep copy. The value can then be retrieved at a later point in time via the key.

    The key mentioned above that references the object in the persistent model to access and update the object is unique. Please see the following extract from "BlackBerry Storage":

    Note that "long_ key" must be a unique long value. The easiest way to create a unique value is to create a hash of your fully qualified package name. If you use more than one persistent store object within your application, append a descriptive table identifier to your package name before deriving the hash. The steps required to create a hash value from within the BlackBerry IDE are:

    • 1. Type a string value, such as com.rim.bbdj.mystore('com.bberry.persistence' in our case)
    • 2. Highlight the entire string
    • 3. Right-click then click "Convert 'com.rim.bbdj.mystore' to long"

    The long value appears (0xa406067aeb8ca6ebL). Make sure to include a comment in your code to indicate the string used to generate the long key.

    The PersistentObject object contents can persist between device resets. They are committed in aPersistentStore object. PersistentStore's method getPersistentObject(key) returns aPersistentObject object, referenced by the providedkey, stored in the PersistentStoreobject. The PersistentObject object acts as a wrapper over the actual object to be persisted, as can be seen in the subsequent code where the PersistInfo object is persisted. PersistentObject's methodsetContents(java.lang.Object) is used to set or replace the contents of the object to be persisted; then it calls the commit() method to write the contents of the persistable object to persistent memory.PersistentObject's method getContents()can be used to retrieve the contents of thePersistentObject object.

    Talk to the Outside World: HTTP Connection

    Just like MIDP, applications involving network connections are based on the Generic Connection framework. The following code snippet is used to make an HTTP connection to a server using theGET method, and read the response from the server.

    // Assign a URL to string 'url' String url; HttpConnection hc = (HttpConnection); hc.setRequestMethod(HttpConnection.GET); int response = hc.getResponseCode(); 

    Please download the code for the HTTP Connection application from the sample code .zip in the Resourcessection. This application makes an HTTP connection with a server, downloads a picture, and displays it on the BlackBerry device (see Figure 7). The objective of this application is to introduce the method for making network connections, not displaying the image. However, by studying the code, you should be able to understand how the picture is displayed and the classes involved in accomplishing that. Refer to the BlackBerry API JavaDocs in the Resources section.

    NOTE: For this last sample program to work, you need to launch MDS, a server program that accompanies the JDE installation package; MDS emulates the network operation mechanism of BlackBerry devices. You should take care regarding the port MDS is listening on. MDS by default listens on port 8080. The above program may be a little slow depending upon your internet connection.

    HTTP Connection application
    Figure 7. HTTP Connection application


    In this article, we covered setting up the development environment for BlackBerry phones using the BlackBerry APIs. We also covered how to create the HelloWorld application, running it in the emulator and deploying on an actual BlackBerry device. Most of the sample application development revolves around some basic components, which include UI, storage, and network operation. Therefore, the article also covered basics of storage and network operation. The UI component is not covered here, as that really involves the developer's own creativity and has been left for the reader to explore through the BlackBerry UI APIs. I hope this article helps you kick off custom J2ME application development for BlackBerry devices.