BlackBerry Java Development Environment Version 3.2. Developer Guide

Size: px
Start display at page:

Download "BlackBerry Java Development Environment Version 3.2. Developer Guide"

Transcription

1 BlackBerry Java Development Environment Version 3.2 Developer Guide

2 BlackBerry Java Development Environment Version 3.2 Developer Guide Part number: PDF Last modified: 24 January Research in Motion Limited The BlackBerry and RIM families of related marks, images and symbols are the exclusive properties of Research In Motion Limited. RIM, Research In Motion, 'Always On, Always Connected', the envelope in motion symbol and the BlackBerry logo are registered with the U.S. Patent and Trademark Office and may be pending or registered in other countries. All other brands, product names, company names, trademarks and service marks are the properties of their respective owners. The handheld and/or associated software are protected by copyright, international treaties and various patents, including one or more of the following U.S. patents: 6,278,442; 6,271,605; 6,219,694; 6,075,470; 6,073,318; D,445,428; D,433,460; D,416,256. Other patents are registered or pending in various countries around the world. Please visit for a current listing of applicable patents. Warning: This document is for licensed users only. Any unauthorized copying, distribution or disclosure of information is a violation of copyright laws. While every effort has been made to ensure technical accuracy, information in this document is subject to change without notice and does not represent a commitment on the part of Research In Motion Limited. Research In Motion Limited 295 Phillip Street Waterloo, Ontario Canada N2L 3W8 Tel. (519) Fax. (519) Web site: info@rim.net Produced in Canada

3 Contents About this guide... 7 Other resources...7 CHAPTER 1 Getting started... 9 About the BlackBerry JDE...9 Installing the BlackBerry JDE...10 Starting the IDE...12 Using the sample workspace...13 IDE workspace overview...14 CHAPTER 2 Understanding the BlackBerry UI BlackBerry application framework...19 Basic UI architecture...20 Developing BlackBerry applications...23 CHAPTER 3 Using the IDE Using the IDE workspace...25 Managing your work...30 Setting up the IDE...31 CHAPTER 4 Working in the IDE Working with projects...35 Building projects...38 CHAPTER 5 Testing applications Debugging applications...39 Using the simulator...41 Setting simulator options...43 Using breakpoints...43 Using the debugging tools...45

4 Optimizing programs...53 Finding memory leaks...58 Analyzing code coverage...61 CHAPTER 6 Setting up resources for localization Localizing applications...63 Working with resources in the IDE...64 Setting up resource files in the IDE...66 Using the resource editor...68 Using resources...71 Managing resources for multiple applications...72 CHAPTER 7 Writing HelloWorld Getting started...75 Writing HelloWorld...76 Example: HelloWorld.java...81 Adding internationalization...83 Example: HelloWorld.java (with internationalization)...87 CHAPTER 8 Writing a base class for UiApplication Writing a UIApplication class...91 Example: BaseApp.java...95 CHAPTER 9 Using HTTP connections Retrieving requested content Example: HTTPDemo.java Receiving pushed content Example: HTTPPushDemo.java Using HTTPS Handheld security...132

5 CHAPTER 10 Creating custom fields Implementing layout() Returning a preferred field size Implementing paint() Handling focus issues Using set and get methods Example: CustomButtonField.java CHAPTER 11 Programming tips Writing efficient code Managing UI interactions General coding tips Working with time CHAPTER 12 Deploying applications Loading applications for testing Deploying applications CHAPTER 13 Converting MIDlets Index

6

7 About this guide This guide explains how to use the BlackBerry Java Development Environment (JDE) to develop applications for the BlackBerry Wireless Handheld. This guide assumes that you have experience with Java programming. This guide explains these topics: integrated development environment (IDE) architecture of the BlackBerry user interface steps for writing, testing, and debugging user interface (UI) applications IDE internationalization support programming guidelines and tips Other resources These other resources can help you develop Java applications for the BlackBerry Wireless Handheld. Background information To design and develop applications for the BlackBerry Wireless Handheld, you might find it helpful to learn about Java 2 Platform, Micro Edition (J2ME), including the Connected Limited Device Configuration (CLDC) and Mobile Information Device Profile (MIDP). You can find information on these specifications on the Sun Microsystems web site:

8 About this guide In addition, you should understand general design guidelines for mobile devices. We recommend that you read the white papers published by Sun Microsystems, which are available at For general programming guidelines for wireless devices, refer to Programming Wireless Devices with the Java 2 TM Platform, Micro Edition, by Riggs, Taivalsaari, Vandenbrink, and Holliday, published by Addison-Wesley (ISBN: ). Other documentation The BlackBerry JDE also includes the following documentation: IDE Online Help The IDE Online Help provides detailed procedures for using the IDE. You can access context-sensitive Help by pressing F1 in any IDE window. Use the table of contents, index, or full-text search to find specific information. API Reference Application Programming Interface (API) Reference documentation provides detailed descriptions of interfaces, classes, methods, and fields for APIs that are included with the BlackBerry JDE. On the IDE Help menu, click API Reference. README.txt The README.txt file is installed with the BlackBerry JDE. It provides information on any known issues and workarounds, as well as last-minute documentation updates. Mobile Data Service Administration Guide This guide explains how to install, configure, and administer the BlackBerry Enterprise Server Mobile Data Service to support BlackBerry applications that require a connection to IP networks. Mobile Data Service Network Programmer s Guide This guide explains how to manage mobile data services between the IP and wireless networks, including how to write transcoders to compress and manipulate this data, and how to write server-side applications to push data from corporate networks to handhelds. RIM developer support Visit the RIM Developer Zone at for technical updates, FAQs, and a developer s discussion forum. 8 BlackBerry JDE Developer Guide

9 Chapter 1 Getting started This chapter provides the following information: the contents of the BlackBerry JDE how to install and start the IDE how to start using the IDE sample workspace About the BlackBerry JDE The BlackBerry Wireless Handheld provides a J2ME run-time environment based on the CLDC 1.0 and MIDP 1.0 specifications. The BlackBerry JDE provides a complete set of APIs and tools for you to develop Java applications to run on the BlackBerry Wireless Handheld, version 3.2 and later. The BlackBerry JDE package includes the following items: integrated development environment (IDE) BlackBerry simulation tools Mobile Data Service simulation tools RIM run-time APIs Required CLDC and MIDP APIs Sample applications The handheld uses an optimized virtual machine (VM) instead of the virtual machine provided as part the CLDC specification. For this reason, you must use the RIM IDE to develop BlackBerry applications. You can also use the IDE to convert standard MIDP applications (called MIDlets) into BlackBerry applications.

10 Chapter 1: Getting started Run-time APIs In addition to the CLDC and MIDP class libraries, the BlackBerry JDE includes the required RIM run-time and UI APIs for features related to the operating system, user interface, and internationalization. Integrated development environment The integrated development environment (IDE) includes a full suite of editing and debugging tools that are optimized for developing BlackBerry applications. The IDE provides several advanced debugging features: setting breakpoints and watches viewing memory statistics viewing current objects in memory to audit memory leaks profiling code execution to optimize programs analyzing code coverage to design rigorous test cases The BlackBerry and Mobile Data Service simulation tools, which are integrated with the IDE, provide a complete Windows-based environment in which to simulate user interfaces, user interaction, and network conditions. Installing the BlackBerry JDE System requirements Your computer must meet the following requirements to support the BlackBerry JDE: Pentium III running Windows NT 4.0 or Windows MHz CPU (800 MHz recommended) 128 MB of RAM (512 MB recommended) 50 MB of available hard disk space Java 2 software development kit (SDK), Standard Edition, version (you can download the SDK from Java Communications API, version 2.0 (you can download this API from 10 BlackBerry Java Development Environment

11 Installing the BlackBerry JDE To install from the web site You can install the BlackBerry JDE from the RIM Developer Zone web site. 1. Download the BlackBerry JDE.exe file to your computer. 2. Locate and double-click the.exe file. The InstallShield Wizard Welcome screen appears. 3. Click Next. The License Agreement associated with the IDE package appears. 4. Review the license agreement. If you agree to its terms, select I accept this license agreement. 5. Click Next. The Customer Information window appears. Type your user name and company name. From the options at the bottom of the window, select whether to restrict use of the BlackBerry JDE to your own user account, or whether to permit access for any user. 6. Click Next. The Setup Type screen appears. 7. Select Complete to install the entire BlackBerry JDE package. 8. Click Next. The Destination Folder screen appears. 9. Accept the default folder, or click Browse to select another folder. We recommend that you install the BlackBerry JDE in the default location. 10. Click Install. The InstallShield Wizard installs the IDE on your computer. 11. Click Finish. 12. Review the readme.txt file for important information: On the Windows Start menu, select Programs > Research In Motion > BlackBerry Java Development Environment 3.2 > readme.txt. All developer documentation is installed in the docs folder as.pdf files. Developer Guide 11

12 Chapter 1: Getting started Starting the IDE To start the IDE On the Windows Start menu, select Programs > Research In Motion > BlackBerry Java Development Environment 3.2 > JDE. The IDE main window appears. Alternatively, at the command prompt, you can run the ide.bat file in the c:\research_in_motion\blackberry_jde_3.2\bin folder. To start the Mobile Data Service simulator If you want to test applications that require an HTTP network connection, you must start the Mobile Data Service simulator. On the Windows Start menu, select Programs > Research In Motion > BlackBerry Java Development Environment 3.2 > BlackBerry Mobile Data Service. A DOS window appears to indicate that the process is running. Tip: You can configure the IDE to start the Mobile Data Service automatically for simulations. On the Edit menu, click Preferences. Select Launch the MDS (ipproxy) when simulating. To view API reference documentation On the Windows Start menu, select Programs > Research In Motion > BlackBerry Java Development Environment 3.2 > Documentation. Alternatively, on the IDE Help menu, click API Reference. The API reference documentation, in standard HTML javadoc format, appears in a browser window. 12 BlackBerry Java Development Environment

13 Using the sample workspace Using the sample workspace The IDE includes a workspace with several sample programs. In the IDE, your projects are organized in a workspace. A workspace enables you to define dependencies between projects and build and run related projects at the same time. To open the sample workspace 1. On the File menu, click Open Workspace. 2. Select samples.jdw in the samples folder (in the main installation folder for the BlackBerry JDE). Click Open. The workspace appears. 3. In the IDE workspace pane, expand the com\rim\samples\device\helloworld folder, then expand the com_rim_helloworld project. 4. Double-click HelloWorld.java. The source file appears in the text edit pane on the right (figure 1). Workspace Text edit Output Figure 1: IDE sample workspace Developer Guide 13

14 Chapter 1: Getting started IDE workspace overview The sample workspace has three panes: a workspace pane, a text edit pane, and an output pane (figure 1). These are the primary panes that you use for writing programs. The workspace pane displays all projects in this workspace (figure 2). Figure 2: Workspace pane In this example, all project files are organized into folders. The folder name shows the location of each folder relative to where the workspace file (samples.jdw) is located. Each folder contains the actual project file, such as net_rim_contacts. The project file is represented by a.jdp file. When you expand the project file, folders appear for any associated resources, such as graphics, and the source file(s) for the project. Expand a source file to see a logical view of the code structure, including each class and its constructors, methods, and fields. Double-click any of these objects to open the source file at the appropriate location. 14 BlackBerry Java Development Environment

15 IDE workspace overview Getting help Press F1 to view context-sensitive Help for any IDE window. The IDE Online Help appears in a separate window. Use the table of contents, index, or full-text search to find the information you need. On the Help menu, click API Reference to view reference documentation for APIs included in the BlackBerry JDE. Your first build of the sample applications When you first install the IDE, the applications in the sample workspace are not updated. Build and run these applications now. On the Debug menu, click Go. In the output pane, you can see the progress of the IDE as its builds and compiles each application into Java bytecode, stored in.cod files instead of.class files. The RIM Handheld Simulator appears. Its Java virtual machine connects to the IDE and loads the compressed class files (which have a.cod extension) for each sample application. The RIM Handheld Simulator displays a Home screen with sample applications loaded. Note: A Radio Simulation Control Panel also appears. This simulator enables you to test applications under different network conditions. Refer to "To simulate the radio" on page 41 for more information. For now, minimize this window. Developer Guide 15

16 Chapter 1: Getting started Getting started with the simulator The RIM Handheld Simulator starts automatically when you run programs. The simulator first loads the application manager, which manages all Java applications on the handheld. The application manager displays the Home screen (figure 3). Application icons Home screen Trackwheel ESCAPE key Application title ALT key SHIFT/NUM key Backspace key ENTER key Figure 3: RIM Handheld Simulator The simulator works similarly to an actual BlackBerry Wireless Handheld. Like the handheld, the simulator displays icons on the Home screen for all applications that it has loaded. When you select an icon, its application title appears at the bottom of the screen. Refer to "To add icon files" on page 36 for more information. Using the trackwheel in the simulator The trackwheel is the handheld user s primary input mechanism. The trackwheel enables users to navigate, view, and select items on each screen. Users roll the trackwheel to scroll through menu items or text, and click the trackwheel to select applications or menu options. When the simulator window is active, you can roll the wheel button on your mouse to simulate rolling the trackwheel, and click the wheel button to simulate clicking the trackwheel. If your mouse does not have a wheel button, use the UP ARROW and DOWN ARROW keys on your keyboard to simulate rolling the trackwheel, and press the left or right arrow key to simulate clicking the trackwheel. 16 BlackBerry Java Development Environment

17 IDE workspace overview Using the keyboard Press the keys on your computer keyboard or click the keys on the simulator keyboard to simulate pressing handheld keys. You do not need to press the ALT key to type numbers and symbols; use the number keys on your computer keyboard. You can change this input method. On the simulator Keyboard menu, click Pager. In Pager mode, you can only use the keys on your keyboard that exist on the handheld. To type numbers and symbols, press CTRL on your computer keyboard and its associated letter on the handheld. Using the ESCAPE key Handheld users press ESC to close the current menu or screen and return to the previous screen. Press ESC on your computer keyboard to simulate pressing ESC on the handheld. To run a sample application To run a sample application, roll the trackwheel to select the appropriate icon and click the trackwheel. The application s main screen appears. Click the trackwheel to view the application menu. Roll the trackwheel to scroll to a menu item and click the trackwheel again to select it. Click Close to exit an application to return to the Home screen. Developer Guide 17

18

19 Chapter 2 Understanding the BlackBerry UI This chapter provides the following information: BlackBerry framework for managing applications BlackBerry UI architecture BlackBerry application development process BlackBerry application framework This section provides a brief overview of the BlackBerry framework for user interface (UI) applications. Application Manager The virtual machine (VM) on the BlackBerry Wireless Handheld loads an Application Manager when the handheld starts. The Application Manager is a specialized Java application that manages all Java applications on the handheld. It functions as the central dispatcher of operating system events for other Java applications. The base class for all BlackBerry applications that provide a user interface is net.rim.device.api.ui.uiapplication. This class (and its Application super class) provides methods for applications to register event listeners, manage threads, and manage UI components. When an application starts, its main thread calls the entereventdispatcher() method to start handling events. This thread runs all drawing and event-handling code, and waits on the application queue for events.

20 Chapter 2: Understanding the BlackBerry UI When the Application Manager receives an event, it copies it to the appropriate queues, which enables the Application Manager to direct messages to certain programs. For example, only the foreground application receives user input messages. Event listeners Event listener interfaces are divided by event type. Each application registers to receive specific types of events. The application s event queue then dispatches events to the appropriate listeners. Applications can implement the appropriate listener interfaces or override the listener methods on the various Screen objects. Most applications implement the KeyListener and TrackwheelListener interfaces and register the listeners to receive keyboard and trackwheel events. The keyboard and trackwheel are users primary means of interacting with applications. Threads An application can access the UI only on the event thread, or with the event lock held. Only one thread at a time (usually the event-dispatching thread) can gain access to an interface component. Background threads can access the UI from outside the main event-handling or UI drawing code in two ways: acquire and hold the event lock use invokelater() or invokeandwait() to run on the event dispatch thread Refer to "Programming tips" on page 145 for more information. Basic UI architecture The BlackBerry UI architecture has three main classes: Class Field Manager Screen Description The Field class represents rectangular areas that can be drawn. The Manager class contains fields and manages the layout and scrolling of fields. Managers are fields, so nesting is possible. The Screen class provides the base class for all screens that present the interface to the user, including the main screen, menus, and dialog boxes. 20 BlackBerry Java Development Environment

21 Basic UI architecture Figure 4 shows part of the class hierarchy for UI architecture. Managers Figure 4: Partial UI class hierarchy The BlackBerry UI framework uses Manager objects to contain fields. Various Manager subclasses, such as VerticalFieldManager, manage specific kinds of field layouts. For example, all applications have at least one Screen object, such as MainScreen, that appears when the user starts the application. MainScreen typically uses a top-level VerticalFieldManager to manage and lay out other fields, including other field managers. If necessary, you can implement your own manager by extending the Manager class. Refer to the API Reference documentation for more information. Developer Guide 21

22 Chapter 2: Understanding the BlackBerry UI Fields All UI components are represented by fields rectangular regions contained by a manager. The field sizes itself according to its layout requirements. The manager, instead of the contained fields, handles scrolling. The BlackBerry JDE provides a library of prebuilt interface controls and components in the net.rim.device.api.ui.component package. In most cases, you can use these objects to construct UI applications. If you need a specialized field component, you can extend the Field class to create your own custom types. Refer to the API Reference documentation for the Field class for more information. Note: The net.rim.device.api.ui.component.textfield class, which extends the Field class, is not public. You must use one of its subclasses, such as EditField or RichTextField, to create a UI field that displays text or enables a user to enter text. Screens Each UI application maintains a stack of Screen objects. It presents an interface to the user by pushing screens onto its display stack and popping them off when the user has finished interacting with the managed fields on that screen. Each Screen object has a delegate manager, the single Manager object directly controlled by the Screen to manage layout and scrolling for the entire screen. When a user selects an application, the application responds by displaying or pushing its main screen onto the UI. When the user clicks Close or presses ESC, the application responds by closing or popping the active (top) screen. As the application 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 at the top of the stack (the active screen) receives input events. Each screen can appear only once in the display stack. The application throws a run-time exception if you attempt to push a single screen onto the stack more than once. Note: When you write programs, remember that it is important to pop (close) screens when users finish interacting with them. Otherwise, the display stack continues to grow until the handheld runs out of memory. Most applications have one MainScreen object that is loaded when the application starts. The MainScreen typically contains a title section, a separator element, and a main scrollable area. The MainScreen uses a VerticalFieldManager to arrange other fields, such as label fields or lists. 22 BlackBerry Java Development Environment

23 Developing BlackBerry applications Other screens are pushed onto the UI stack in response to user interactions. For example, in a contact management application, a New Contact screen might appear when the user selects the New menu option. This screen is popped off the UI stack when the user clicks Close. Developing BlackBerry applications This section provides a brief overview of the process for developing BlackBerry applications. About the BlackBerry Java environment As in any standard Java environment, source files for BlackBerry applications are compiled into Java bytecode by a Java compiler. This bytecode is loaded onto the handheld and run by the Java virtual machine (VM), which translates the Java bytecode into instructions that the processor can understand. There are two main differences between the BlackBerry Java environment and a standard Java environment. The BlackBerry Java environment uses smaller, more efficient bytecode that is designed for transmission over low-bandwidth networks and storage on small handhelds. Source files are compiled into handheld code files (represented by the.cod file name extension instead of the.class file name extension). These.cod files are loaded onto the handheld and run by its virtual machine. The BlackBerry Java environment uses an optimized virtual machine instead of the standard KVM provided as part of the CLDC specification. For this reason, you must use the IDE to convert MIDlet applications (.jar and.jad files) to run on the BlackBerry handheld. Refer to "Converting MIDlets" on page 161 for more information. Developer Guide 23

24 Chapter 2: Understanding the BlackBerry UI Application development process Follow the steps in figure 5 to develop a BlackBerry application. 1. Design your application. 2. Use the IDE to set up projects for your application and its resources. 3. Edit source files using the IDE text editor. 4. Build your application. 5. Test your application using the handheld simulator. 6. Use the IDE debugging tools to find and correct any problems. 7. Load the application onto an actual handheld for final testing. Refer to "Loading applications for testing" on page 155 for more information. 8. Distribute the application with application loader (.alx) files for users to load onto their handhelds using the BlackBerry Desktop Manager. Refer to "Deploying applications" on page 157 for more information. Figure 5: BlackBerry application development process 24 BlackBerry Java Development Environment

25 Chapter 3 Using the IDE This chapter provides the following information: how to navigate your projects using the workspace pane how to manage your work using projects how to set IDE preferences Refer to the IDE Online Help for detailed procedures and reference information. Using the IDE workspace The integrated development environment (IDE) included with the BlackBerry JDE is similar to many other industry-standard IDEs. The IDE provides a complete development environment for writing BlackBerry applications. It includes tools for editing, building, and debugging programs, as well as integrated BlackBerry handheld and Mobile Data Service simulator tools. You can access the most common commands from the main menu or from the toolbar. You can set preferences to control which icons appear on the toolbar (on the Edit menu, click Preferences). As mentioned previously, the IDE workspace has three main panes: workspace pane text edit pane output pane

26 Chapter 3: Using the IDE Tip: On the Edit menu, click Toggle view (or press F2) to switch between the workspace files view, the workspace packages view, and the text edit pane. Workspace pane The workspace pane provides a tree view the projects in your workspace. The workspace pane has two tabs: Files and Packages. These tabs provide different views of your projects. Workspace Files view The Files tab (figure 6) provides a physical view of the folders and files in each project. Use the Files tab to manage project files, to include graphics and other resource files, and to set project properties. Figure 6: Workspace pane - Files view This view shows projects relative to the workspace.jdw file. You should create a folder structure on your computer similar to the one shown in the samples workspace, where the workspace is created in a root folder and each project is created in a subfolder. Expand the folder to view the main project file. Right-click the project file to build or clean the project, add files, or set project properties. 26 BlackBerry Java Development Environment

27 Using the IDE workspace Expand the project file to view image and resource folders and project source files. Expand the image or resource folder to view these files. Right-click source files to set specific source code properties. Double-click a source file to open it for editing Expand each source file to view its classes and then expand further to view its constructors, methods, and fields. Double-click any item to open the relevant source file at the location where the object appears. Tip: On the Edit menu, click Find to search for a file or project in the workspace. On the Edit menu, click Find in Files to search for text in a file within a particular project or folder. Both searches support Perl5 regular expressions. Refer to the IDE Online Help for more information. Right-click in the workspace and select Collapse All to collapse all folders in the workspace view. Two icons appear beside each constructor, method, or field: The first icon indicates whether the method or field is static (square) or non-static (circle). The second icon indicates the access level of the method or field: public (open lock), private (closed lock), protected (key), or package (red open lock). Tip: You can select a package, class, project, or workspace in the workspace view and press CTRL + C (on the Edit menu, click Copy). This copies the fully qualified class or package name to the clipboard. For example, you can use this for creating import statements into your code. Developer Guide 27

28 Chapter 3: Using the IDE Workspace Packages view The Packages tab (figure 7) provides a logical view of the package hierarchy across all projects in this workspace. Use this view for working with the logical structure of your programs. Figure 7: Workspace pane - Packages view Expand the folders to view each package, its member classes, and the constructors, methods and fields in each class. Double-click an object to open the source code at the location where the object is defined. All classes that do not have a package appear in a no package node. In the Search field, type a fully qualified name to find a package, such as com.rim.samples.device.httpdemo. After the package is displayed in the workspace pane, append the class name to select a specific class in the package. Tip: On the Edit menu, click Find to search for a specific package, class, method, or field in the workspace. This search supports Perl5 regular expressions. Refer to the IDE Online Help for more information. Tip: Double-click a class, method, or field in either of the workspace views to change the other workspace view to the same location. 28 BlackBerry Java Development Environment

29 Using the IDE workspace Text edit pane The text edit pane provides a text editor for your source files and other text files. By default, the text edit pane uses colors to identify source code syntactically. You can change the color codes. Refer to "Set IDE preferences" on page 33 for more information. To open a file, on the File menu, click Open. You can also double-click a file in the workspace pane. You can open multiple files at one time. Use the Window menu to switch between files. To close all files, on the File menu, click Close All. Note: A special editor is provided for editing resource files for localization. When you open a resource header (.rrh) or resource content (.rrc) file, the resource editor opens automatically. Refer to "Using the resource editor" on page 68 for more information. Tip: You can add bookmarks to your source code. On the Edit menu, click Bookmarks (ALT + F2). Click Add and type a name for the bookmark. Click OK to save the bookmark. To return to a bookmarked source file, on the Edit menu, click Bookmarks. Select a bookmark and click Go to. Debugging panes On the View menu, you can open several debug panes, for example, to set breakpoints, monitor threads, and watch the variables. In a workspace, you can open as many panes as you need to. You can control which panes are docked (embedded) in the workspace and which can float in the workspace area. On the Edit menu, click Preferences and click the Docking tab. Tip: If you select Allow docking windows to float behind main window, when you move docking windows, they can float behind the IDE main window instead of always appearing in front of the main window. These windows then appear on the Windows taskbar. Developer Guide 29

30 Chapter 3: Using the IDE Managing your work In the IDE, you organize work into projects in a workspace. A project organizes the files required to produce an application, including source files, resource files, and graphics. A workspace organizes one or more projects and defines your development environment, including various editing and debugging panes, build configurations, and active projects. Projects In the IDE, you work in a project. Each project is represented by a.jdp file. A project organizes the files required to produce an application or library, including source files, images and resources, so that you can work with them as a whole. When you compile a project, you compile its source files into a single.cod file. You should put the classes for each application into a unique package. Following the Java convention for package names, use your company s Internet domain name written in reverse. For example, the IDE samples workspace includes packages such as com.rim.samples.device.helloworld. You must create a folder structure on your computer with a folder for each part of the package name. You create and manage projects using the Project menu in the IDE main window. For each project, you can specify a set of properties, such as an application type, by right-clicking the project file in the workspace pane and using the shortcut menu. You can create files outside of a project and then add them to a project later. Workspaces In the IDE, your projects are organized in a workspace. A workspace enables you to define dependencies between projects and build and run related projects at the same time. You can also create unique build configurations that define which projects are built and run by default. You can create and save as many workspaces as you need. Each workspace is represented by a.jdw file. A project can belong to more than one workspace. When you exit the IDE, you can save the workspace. When you start the IDE, it opens the last workspace that you had open. The IDE remembers which panes and files you had open in this workspace, so everything appears as it did when you last used it. The IDE also maintains a history of workspaces so that you can easily switch from one workspace to another. 30 BlackBerry Java Development Environment

31 Setting up the IDE Setting up the IDE This section explains how to set up your development environment so that you can start programming. Organizing projects We recommend that you create your workspace in a main folder, and then create each project in a subfolder. You must create a folder structure for your source code that matches the package hierarchy that you use for your classes. Create a workspace 1. In the IDE, on the File menu, click New Workspace. A dialog box appears. 2. Type a workspace name. 3. Type the folder in which to create the workspace file (*.jdw). You should create the workspace in a root folder, and then create subfolders for each project. If you type a folder that does not exist, the IDE creates it for you. Create a project 1. On the Project menu, click Create New Project. 2. Type a project name. 3. Type the folder in which to create the project file (*.jdp). In the folder in which you created the workspace, you should create a separate folder for each project. If you type a folder name that does not exist, the IDE creates it for you. The project folder and file appear in the IDE workspace pane. Developer Guide 31

32 Chapter 3: Using the IDE Set project properties In the Workspace File view, double-click the project file to set project properties. The project properties dialog box has four tabs: General Application Build Resources Set properties for the project itself, such as the type of project and version. You can also include or exclude the project from builds. Set properties that apply to the application built from this project (not relevant if the project is a Library). The properties depend on the type of project. In particular, type an Application Title to display on the handheld Home screen. For a CLDC application, you can type arguments in the CLDC Arguments field. For a MIDlet application, you must type the main class in the MIDlet class field. Define settings to control the IDE build process for the project. In particular, you can type the Output File Name for the compiled.cod file (otherwise, by default, the compiled.cod file uses the project name). Enable the Title Resource Available option if you want to define a localized version of the application title to display on the handheld Home screen. Refer to "Setting an application title" on page 71 for more information. If you do not enable this option, the Application Title field on the Application tab is used. Set active projects New projects that you add to the workspace are active by default. Only active projects are included in builds. To change which projects are active, on the Project menu, click Set Active Projects. To make a single project active, right-click the project and click Activate Project. Create a source file 1. On the File menu, click New. 2. Select a folder. You should put all source files into the appropriate project folder and put other files, such as images and resource files, into separate subfolders. 3. Type a file name, including the.java file name extension. Click Create. The file appears in the text edit pane. 4. In the text edit pane, right-click the file and click Insert into project. Alternatively, on the Project menu, click Add File. The file now appears in the workspace files pane. As you write code, you will see classes, methods, and fields appear in the workspace pane, located under the file. 32 BlackBerry Java Development Environment

33 Setting up the IDE Set IDE preferences On the Edit menu, click Preferences to set general IDE preferences. Click the appropriate tab to set the following preferences: Tab Workspace Simulator Debug Source Control Editor Notifications Docking Toolbar Description Set preferences for workspace startup and auto-save. Set preferences for starting the simulator. Set preferences for debugging programs. Set preferences for source control integration. Set preferences for working in the text edit pane. Set preferences for notification when builds complete. Set preferences to control which panes are docked (embedded) in the main workspace; panes that are not docked can float in the workspace area. Set preferences for which icons should appear on the workspace toolbar. Developer Guide 33

34

35 Chapter 4 Working in the IDE This chapter explains how to use the IDE to manage and build projects. Working with projects This section explains how to work with your projects in the IDE workspace. To add a new project to a workspace 1. Open an existing workspace or create a new workspace (on the File menu, click Open Workspace or New Workspace). 2. On the Project menu, click Create New Project. 3. Click Browse to specify the folder in which to create the project file. 4. Type a name for the project file and click Open. The project file appears in the workspace window. To activate or deactivate a project You can make projects active or inactive. You can choose only to include active projects in a build. Refer to "Building projects in the IDE" on page 38 for more information. Active projects appear in bold in the workspace pane. On the Projects menu, click Set Active Projects to specify which projects to make active. Alternatively, you can right-click a project file and click Activate Project to make it active.

36 Chapter 4: Working in the IDE To set project dependencies Application projects can depend on other library projects in the same workspace. You define projects as libraries in the project properties. To set project dependencies, right-click the project and click Project Dependencies. You can then select one or more library projects on which this project depends. When you build a project, the IDE also rebuilds any libraries on which the project depends. To add icon files The BlackBerry Wireless Handheld only supports graphics in PNG format. If you add a GIF or JPG graphic to a project, the IDE converts it to PNG format automatically when it compiles the project. Note that if an application accesses raw image data on the handheld, it retrieves PNG image data. You can add a graphic to your project to display as the application icon on the handheld Home screen. 1. Create a graphic in GIF, JPG or PNG format. The size of the graphic should be either 16-by-16 or 28-by-28 pixels. 2. In the IDE, select the project. On the Project menu, click Add File to Project. The graphic file appears under the project in the IDE workspace. 3. Right-click the graphic file and click Properties. Select Use as application icon. This graphic appears as the application icon on the handheld Home screen. Tip: In the IDE workspace, when you double-click a graphic file, or another type of file, the IDE opens the file in the associated application. To set alternate entry points The IDE enables you define multiple entry points for an application. For example, the BlackBerry Wireless Handheld s Compose Message, Search Messages, and Saved Messages applications provide alternate entry points to the Messaging application. 1. Create a new project. 2. Right-click the project file and click Properties. The project properties window appears. 3. On the General tab, set the Project Type to Alternate MIDlet Entry Point or Alternate CLDC Application Entry Point. 36 BlackBerry Java Development Environment

37 Working with projects 4. On the Application tab, from the Alternate Entry for drop-down list, select the existing application for which this new project is an entry point. Only projects of the appropriate type for this entry point are listed. 5. On the Application tab, in the CLDC Arguments field, type the appropriate argument. This is the argument that is passed into the main() method of the application to which this project is an alternate entry point. 6. Set other properties for the entry point, including an Application Title. 7. Click OK. When you build and run the applications, this alternate entry point appears on the handheld Home screen as a separate application, but it starts the application for which it is an entry point. An alternate entry point still calls a main(string args[]) method, it just passes in a different args[] parameter. For example, in the code for the main application, you would write the main() method to accept multiple arguments: public static void main(string[] args) if( args!= null && args.length == 1 ) if( args[0].equals( "saved" ) ) screenchangenotify( SAVED_VIEW ); else if( args[0].equals( "mainview" ) ) screenchangenotify( MAIN_MESSAGE_CENTRE_VIEW ); else if( args[0].equals( "search" ) ) screenchangenotify( SEARCH_EDIT_SCREEN );... You can then create projects for the Saved Messages and Search Messages entry points. You set project properties for each to specify the CLDC arguments as saved and search, respectively. Developer Guide 37

38 Chapter 4: Working in the IDE Building projects This section explains how to build projects. Building projects in the IDE Using the IDE, you can build your projects in several ways. When you build a project, the IDE also rebuilds any libraries on which the project depends. To build all active projects, on the Build menu, click Build. (In the workspace, active project names appear in bold.) To build a single project, select the project and on the Build menu, click Build Selected (or right-click the project file and click Build Project). To build all projects, on the Build menu, click Build All. Note: In project properties, you can specifically exclude a project from builds. In this case, the project is not included in the Build All command. To build all projects and run them in the simulator, on the Build menu click Build All and Run. Building with a makefile You can use the IDE to create a workspace makefile, which you can use to build projects without using the IDE. To create a makefile, on the Build menu, click Generate Makefile and Resources. Using build configurations You can set a number of build configurations for your projects. In each build configuration, you can select which projects are active. You can use this to quickly and easily create a set of active projects to build for particular purposes. To create a new configuration, on the Build menu, select Configuration > Edit. In the dialog box that appears, click Add and type a name for the configuration. When you create a new configuration, all projects are set to inactive by default. Removing builds You can delete all compiled code (.cod) files from your projects in several ways: On the Build menu, click Clean All to clean all projects. On the Build menu, click Clean to clean only active projects. On the Build menu, click Clean Selected to clean only projects that you have selected (or right-click the project file and click Clean Project). 38 BlackBerry Java Development Environment

39 Chapter 5 Testing applications This chapter provides the following information: how to run applications in the simulator how to use various IDE debugging tools Debugging applications This section explains how to run programs in debug mode. To start debugging On the Debug menu, click Go. The IDE builds all active projects, if necessary, and then runs them either in the simulator or on a connected handheld. Tip: To run both inactive and active projects in the simulator, on the Build menu, click Build All and Run. The output pane displays build progress, program status, and any errors that might have resulted during a process. Use the output pane to monitor and debug running processes.

40 Chapter 5: Testing applications You can run programs either in the simulator or on a connected handheld. On the Debug menu, select Attach to > Simulator to run the programs in the simulator or Attach to > COM <n> to run the program on a handheld connected to the selected port, where <n> is the port. Note: To attach the IDE to a handheld, you must install the Java Communications API, version 2.0. You can download the API from To pause debugging To use any of the debugging tools, you must stop running programs. There are several ways to do this: You can set a breakpoint to stop the program at a particular point in the code. Refer to "Using breakpoints" on page 43 for more information. You can stop the program manually during debugging. On the Debug menu, click Break Now. The program stops running but the IDE remains attached to the simulator or handheld, in debug mode. You can then use the debugging tools on the View menu to retrieve detailed information. Refer to "Using the debugging tools" on page 45 for more information. To resume debugging If programs have been paused, you can restart them at the point at which they stopped. On the Debug menu, click Continue. To stop debugging When you have finished debugging your programs, you must detach the IDE from the debugging tools and exit the simulator. On the Debug menu, click Stop Debugging. You must stop debugging before you can edit source files. 40 BlackBerry Java Development Environment

41 Using the simulator Using the simulator The RIM Handheld Simulator starts automatically when you run programs (on the Debug menu, click Go). To erase the simulator file system When debugging applications, you can erase the simulator s file system to simulate resetting the handheld. You might need to erase the simulator file system after trying to run programs that contain errors. On the File menu, click Erase the simulator s file system. To improve the speed of simulator startup, do not erase the simulator file system between runs. To simulate handheld conditions The simulator enables you to simulate various handheld battery conditions. On this menu, select the conditions that you want to apply to the handheld. On the Simulation menu, click In Holster or Out of Holster to simulate whether the handheld is in or out of the holster. Users can set different notification settings based on whether the handheld is in or out of the holster. When the handheld is in the holster, the screen display turns off. You can also simulate various battery conditions. On the Simulation menu, click Good Battery, Low Battery, Dead Battery or Charging. To simulate the radio You can set various radio simulation options to test applications under different wireless network conditions. Developer Guide 41

42 Chapter 5: Testing applications On the Simulation menu, click Show Radio Simulation Control Panel (figure 8). Reception Figure 8: Radio Simulation Control Panel The Reception panel enables you to simulate different wireless network coverage conditions for receiving data. When you select Out of coverage, the handheld is out of wireless network contact, and cannot send or receive data. When you select In coverage, you can use the slide bar to control the received signal strength indicator (RSSI) reported to applications. The signal strength varies from 120 dbm to 50 dbm (dbm expresses power level in decibels with reference to a power of one milliwatt). A signal of 120 dbm is very weak, and an actual handheld typically loses wireless network coverage before reaching this number. A signal of 50 dbm is stronger than you are likely to see on the actual wireless network. Transmission The Transmission panel enables you to control the simulated transmission of data from the handheld. When you select All transmits succeed, data is sent successfully from the handheld to the network. On an actual network, under good coverage conditions, most data is sent successfully. When you select Prompt for Tx success, every time the simulator sends data to the network, a prompt appears for you to select whether the data is transmitted successfully. The data is pending until you select Yes or No. You can use this mode to simulate very long transmission delays. When you select Random success, you can use the slide bar to select the probability of data being sent successfully from the handheld. You can use this mode to simulate variable wireless network coverage. 42 BlackBerry Java Development Environment

43 Setting simulator options Setting simulator options You can set simulator command line options in the IDE. On the Edit menu, click Preferences. In most cases, you do not need to change the default simulator options set in the IDE. For more information on simulator options, refer to the IDE Online Help. Click the Simulator tab (figure 9). Figure 9: Simulator preferences In the Simulator Command line field, add options after the OsLoader.exe OsHh3G.dll entry. Using breakpoints When you debug your applications, you typically use breakpoints to stop running an application at specific places in your code. Alternatively, on the Debug menu, you can click Break Now to stop running a program at any time. In many cases, the most effective debugging method is to start by setting only a few breakpoints at critical sections of your code, and then gradually set breakpoints at shorter intervals to identify the problem. Developer Guide 43

44 Chapter 5: Testing applications To add or remove a breakpoint Insert the cursor at the appropriate line of code. On the Debug menu, click Breakpoint > Toggle Breakpoint at Cursor to add or remove a breakpoint. You can also press F9. A breakpoint appears in the code as a red stop sign. To manage breakpoints On the View menu, click Breakpoints to open the breakpoints pane (figure 10). Figure 10: Breakpoints pane This pane displays the breakpoints that you have set in code in this workspace. In this pane, you can perform the following tasks: Disable breakpoints that you want to remove but save for later use. Select or clear the check box beside a breakpoint, or click Enable All or Disable All. A disabled breakpoint appears in the code as a gray stop sign. Set a conditional breakpoint to pause program execution when a specified condition evaluates to true. In the Condition cell for a breakpoint, type an expression that evaluates to true, such as x == 100. Set an iteration to stop the application only after a certain number of iterations through the breakpoint. In the Iteration cell for a breakpoint, type a positive number. Note: If you set both an iteration count (i) and a condition (c), the IDE stops the application only after the specified number of iterations where the condition evaluates to true (that is, the ith time that c==true). Note: Changing the value in the Iteration cell does not cause the Hits value to reset to 0. Double-click a breakpoint to open the source code at the location at which the breakpoint is set. 44 BlackBerry Java Development Environment

45 Using the debugging tools To set breakpoint preferences In addition to setting breakpoints in specific locations of your source code, you can set general breakpoint preferences to stop program execution when specific events occur. On the Debug menu, click Breakpoint and select one or more of the following options: On startup When any exception is thrown On object creation On application load Before garbage collection After garbage collection To use breakpoints On the Debug menu, click Go to run the program in the simulator. When the application reaches the breakpoint, program execution is paused. In the breakpoints pane (figure 11), you can see the section of code and line number at which the program has been paused. The breakpoints pane displays the total number of hits for each breakpoint. Figure 11: Breakpoints pane On the Debug menu, click Continue (or press F5) to resume running the program. Using the debugging tools You can access several debugging tools on the View menu. This section provides an overview of IDE debugging capabilities. Refer to the IDE Online Help for additional information. For these tools, you typically set one or more breakpoints at the end of a section of code that you want to debug. Run the application in the simulator. When it reaches the breakpoint, access the appropriate tool for detailed debugging information. Developer Guide 45

46 Chapter 5: Testing applications You can control which windows are docked (embedded) in the workspace and which float in the workspace area. On the Edit menu, click Preferences and click the Docking tab. Note: To use the debugging tools, you must run your programs in the debugger. On the Debug menu, click Go (or press F5). Before you can continue editing your source code, you must stop debugging. On the Debug menu, click Stop Debugging (or press SHIFT + F5). Working with source code When you are debugging, you can use several features in the text edit pane to work with source code. For example, when you point your mouse at an expression in your source code, the IDE displays the current value of this expression as a ToolTip. To specify whether this value is displayed in hexadecimal or integer format, on the Edit menu, click Preferences. On the Debug tab, select or clear Display editor tooltips in hex. Setting watches On the View menu, click Watches. The watches pane enables you to specify variables and expressions to watch continuously while debugging your program (figure 12). Figure 12: Watches pane To set a new watch, right-click in the table and select Add Watch (or press Insert). To remove a watch, right-click and select Delete (or press Delete). Right-click a watch to change the display of the Value cell, view the source code in which the variable is defined, or stop the program when the value changes. 46 BlackBerry Java Development Environment

47 Using the debugging tools Viewing local variables On the View menu, click Locals. The local variables pane displays local variables and their current values in the context of the current thread (figure 13). Figure 13: Locals pane You can click in a Value cell to change the value of a variable. When you continue running the program, any variables whose values have changed appear in red. Right-click anywhere in the table to change the display. Right-click in a cell to perform the following actions: Set a watch on the variable or array element; it then appears in the watches pane. Refer to "Setting watches" on page 46 for more information. Stop the program when the value of the variable changes. It then appears in the breakpoints pane. Refer to "To manage breakpoints" on page 44 for more information. View the source code where the variable is defined. Click the locals tab to see local variables and their current values in the context of the current thread. Click the auto tab to view local variable names and expressions at and around the executing line. Click the this tab to see an expanded view of the current object (this). Click the watch tab to set a watch on a particular local variable. Right-click a row and select Add Watch (or press the Insert key). In the dialog box that appears, type an expression. For example, you could add a watch for this._array[18] to show its value during program execution. This is the same as adding a watch in the watches pane. Refer to "Setting watches" on page 46 for more information. Developer Guide 47

48 Chapter 5: Testing applications Viewing threads On the View menu, click Threads. The threads pane displays all current threads (figure 14). Figure 14: Threads pane The current thread is highlighted in yellow. The Thread column displays each thread in the format: nnnnnnn: Thread status, Process pid nnnnnnn is the object name status is the thread status (one of: running, sleeping, waiting for notify, acquiring lock) pid is the ID of the process that started the thread Here is what each thread status means: 48 BlackBerry Java Development Environment

49 Using the debugging tools Thread Status Description running sleeping waiting for notify acquiring lock thread is running thread is calling Thread.sleep() thread is calling Object.wait() thread is executing a synchronized statement and is forced to wait Double-click a thread to view the source code in the text edit pane. The line in the source code that started the thread is marked with an arrow. You can follow thread dependencies by expanding a thread to view the object on which it is waiting or with which it is synchronizing. Expanding thread objects You can expand thread objects to follow thread dependencies: in the threads pane double-click the thread object. For example, if the VM detects any cycles in the thread waiting structure (thread A owns object a and is waiting for b; thread B owns object b and is waiting for a), it marks those threads as deadlocked (neither thread A or B can proceed) in the Type cell, and highlights the thread in red. The following fields indicate the status of a thread object: object is being synchronized (Aquiring lock object for which the thread is waiting (Waiting for notify object that currently owns the thread being synchronized (Owns lock Expanding objects In the threads pane, the following fields indicate the status of an object: thread that currently owns the object (Thread owning thread calling Object.wait() (Thread waiting for thread is attempting to enter a synchronized block for the object (Thread acquiring Tip: Threads, and objects whose threads are deadlocked, are also displayed in the following panes: objects, local variables, watch, static data, processes, and locks. In the threads pane, right-click a thread and click Make current to update the selected thread's context in these debugging panes. Developer Guide 49

50 Chapter 5: Testing applications Viewing calling methods You can use the threads pane together with the call stack pane. Refer to "Viewing the call stack" on page 50 for more information. When you double-click a thread in the threads pane, the call stack pane refreshes to display the calling methods for the selected thread, with the most recent calling method highlighted in blue. Viewing the call stack On the View menu, click Call Stack. The call stack pane displays the calling methods at the current point of execution (figure 15). Double-click a method to view its source code. Figure 15: Call stack pane To view the relevant source code, right-click a calling method and select Show Source. The source file appears in the text edit pane at the line of code that implements the class of the selected item. Navigating the call stack Use the CTRL key with the UP ARROW and DOWN ARROW keys to move up and down the call stack. The calling method at the bottom of the call stack appears first in the call stack pane. The method at the top of the call stack appears last in the call stack pane. For example, when you press CTRL and the UP ARROW, the cursor moves down in the call stack pane (up the call stack). As you navigate the call stack, the source code for each method appears in the text edit pane. 50 BlackBerry Java Development Environment

51 Using the debugging tools Viewing processes On the View menu, click Processes. The processes pane lists all processes currently running within the IDE (figure 16). You can expand each process to view its data members. Right-click anywhere in the table to change the display. Expand a process and right-click a field either to set a watch on the value of the field or to set a breakpoint when the field value changes. Figure 16: Processes pane The Process column displays each process in the following process_name(pid) nnnnnnnn is the object name process_name is the name of the process pid is the process ID Click the plus sign in the Process column to view the data members of a process. Developer Guide 51

52 Chapter 5: Testing applications Viewing locks The Locks pane displays all objects with an active lock; that is, objects for which a thread is executing a synchronized block (figure 17). Figure 17: Locks pane Double-click an object to view threads that are interacting with the lock. The following fields indicate the status of threads that are interacting with a lock: thread that currently owns the object's lock (Thread owning thread that is calling Object.wait() (Thread waiting for thread that is attempting to enter a synchronized block (Thread acquiring Tip: The active lock status of objects is also displayed in the following panes: objects, local variables, watch, static data, processes and threads. In the locks pane, threads that appear when you expand an object can also be expanded to investigate their state. Refer to "Viewing threads" on page 48 for more information. Right-click a lock to change the display of the Value cell, set a watch, view source code, or stop program execution when the lock changes. 52 BlackBerry Java Development Environment

53 Optimizing programs Viewing classes and methods On the View menu, click Classes to view an index of all classes in the system. Enter the first part of the class name to find a specific class. Double-click a class to view the source code that implements this class. Right-click a class to set a breakpoint that is triggered when an exception class is thrown or when a new object of the selected class is instantiated. On the View menu, click Methods to view all methods called during program execution. Double-click a method to view the source code that implements this method. Tip: When you double-click a class in the classes pane, the methods pane shows all methods in this class. Optimizing programs You can use the IDE profiler tool to optimize your code. The profiler tool displays the percentage of time spent in each code area, up to the current point of execution. Note: When you run the profiler, you should exit other Windows applications to ensure reliable results. To run the profiler 1. On the View menu, click Profile. 2. In the profile pane, click Options. Select the type of method attribution, a sorting method, and the type of information that you want to profile. Click OK. Refer to "Setting profile options" on page 56 for more information. 3. In the profile pane, click Clear. This removes profiler data and resets the execution time of all Java code to Set a breakpoint (press F9) at the end of the section of code that you want to profile. 5. On the Debug menu, click Go (or press F5) to run the application. Use the application in the simulator to run the appropriate code. Developer Guide 53

54 Chapter 5: Testing applications 6. In the profile pane, click Refresh. This retrieves all accumulated profile data from the Java VM. This operation does not clear the profiler data, so running a program again adds to the data. A profile report appears (figure 18). Figure 18: Profile pane The profile pane has four columns: The Details column identifies an item of execution, such as a method. The Percent column indicates the percentage of time spent on that item. The third column depends on what you profile; by default it displays time in CPU clock ticks. Refer to "Setting profile options" on page 56 for more information. The Count column displays the number of times that the item has been run. Understanding the Profile views The profile pane has three views: Summary Methods Source Summary view The Summary view displays general statistics about the system and the garbage collector. It displays the percentage of time that the Java VM has spent idle, running code, and performing quick and full garbage collection. The Percent column displays the percentage of total VM running time, including idle and collection time. 54 BlackBerry Java Development Environment

55 Optimizing programs Methods view The Methods view displays a list of modules, sorted either by the information that you are profiling or by the number of times each item has been executed. Refer to "Setting profile options" on page 56 for more information. Expand the All item to see a list of all methods. Expand a specific module to see only its methods. Double-click a method (or right-click and click Profile Source) to view source lines in the Source view. Right-click a method and click Show Source to view source code in the Edit window. In this view, the Percentage column displays the percent of VM execution time only, not including idle and garbage collection time. Source view The Source view displays the source lines of a single method. You can then navigate through the methods that call, and are called by, that method. The Source view color-codes the lines: source lines are yellow; bytecode is cyan; and all other lines are white. You can change the colors in the Profile Options. Refer to "Setting profile options" on page 56 for more information. In this view, the Percent column displays the percentage of total VM execution time, not including idle and garbage collection time. The Source view first displays a list of callers to the method, including the number of times that they have made the call and the total time spent on these calls. Next, it displays a list of source lines for the method and the total time spent on these lines. You can expand a source line to display individual bytecode. You can further expand any bytecode that corresponds to a method invocation to display the target(s) of the method invocation. Double-click a line (or right-click and click Show Source) to view the source code in the text edit pane. Click the Back and Forward buttons to follow the history of methods that you have visited in the Source view. Developer Guide 55

56 Chapter 5: Testing applications Setting profile options 1. Click the Options tab to view and change profile options. The Profile Options dialog box appears (figure 19). Figure 19: Profile options 56 BlackBerry Java Development Environment

57 Optimizing programs 2. On the General tab, you set three options: Option Choices Description Method attribution Sort method by What to profile Cumulative In method only Count Profiled data (as selected in What to profile ) Time (clock ticks) Number of objects created Size of objects created Number of objects committed Size of objects committed Number of objects moved to RAM Size of objects moved to RAM User counting This option controls how execution times are calculated for methods. Select Cumulative to calculate the amount of time spent executing bytecode in a method and all methods invoked by that method. Select In method only to calculate the amount of time spent executing bytecode in that method only. The timer effectively stops when a call is made to another method. Sort methods in the Profile views either by the number of times the item was executed or by the data specifically being profiled. Select which type of data to profile. This data appears in the third column of the Profile view. 3. Click the Colors tab to change the colors for color-coding source code and bytecode in the Source view. Developer Guide 57

58 Chapter 5: Testing applications Finding memory leaks You can use two tools to find memory leaks: Memory Statistics Objects Using the Memory Statistics tool The Memory Statistics tool displays statistics on the number of objects and bytes in use for object handles, RAM, and flash memory. On the View menu, click Memory statistics. The memory statistics pane appears (figure 20). Figure 20: Memory statistics pane Typically, you would set two or more breakpoints in your code. Run your application to the first breakpoint. Click Refresh to refresh the memory statistics and then click Snapshot to take a snapshot. Continue running the application to the next breakpoint; click Refresh again, and then click Compare to Snapshot. If you are debugging a specific problem, you would typically set breakpoints far apart, and then gradually set breakpoints at shorter intervals to identify where the memory leak occurs. Using the Objects tool The Objects tool displays all objects in memory to help you locate object leaks. Object leaks can cause the VM eventually to run out of flash memory, which resets the handheld. 1. On the Debug menu, click Go to run your application in the simulator. 2. On the Debug menu, click Break Now. 3. On the View menu, click Objects. The Objects window appears. 58 BlackBerry Java Development Environment

59 Finding memory leaks 4. In the Objects window, click GC. The Objects window displays all objects in memory (figure 21). Figure 21: Objects window The Name column displays the following information for each attributes ( Process: pid ) nnnnnnnn attributes the object handle any of Add, Delete, Referenced by code, Referenced by static, Grouped, Persistent, In RAM Add or Delete appear when you perform a Compare to Snapshot to indicate the objects that have been added or deleted since the snapshot. Referenced by code/static indicates that the variable is being referenced by code (a local variable) or a static data member. pid process id You can print the contents of this window to a text file. On the Window menu, click Print to file. Developer Guide 59

60 Chapter 5: Testing applications Right-click in the Object window to change the display; for example, you can disable the Hexadecimal and Show byte[], char[] as String options. Right-click an object and click Show References To or Show References From to narrow the view to show only the objects that have references to or from this object. You can continue up the reference chain by right-clicking one of these objects and showing references again. Double-click the line Code or Static to display that code or static. Use the Forward and Back buttons to move in either direction through the reference chain. 5. Click Snapshot. 6. On the Debug menu, click Continue. 7. Perform operations in the application that are not supposed to increase the number of reachable objects; for example, create a new contact and then delete it. 8. On the Debug menu, click Break Now. 9. In the Objects window, click GC, then click Compare to Snapshot. The Objects window displays the number of objects deleted and added since the previous snapshot. If the number of objects added is not the same as the number of objects deleted, you might have an object leak. You can use the Type and Process filters to view specific objects. Finding memory leaks in loops One of the most common causes of memory leaks is when a code loop creates an object on every iteration and then adds that object to a hash table, vector, or another collection that stays in memory for a long time. If none of the code that subsequently runs frees the allocated object, that object is effectively leaked. To find this leak, you need to set a breakpoint at the beginning of the code loop, and then run through the loop twice to take at least three consecutive snapshots. Remember that the first few iterations of a loop perform initialization allocations, which are not really leaks. To get an accurate listing of the real leaks, allow the code to run through several iterations before taking the three consecutive snapshots. 60 BlackBerry Java Development Environment

61 Analyzing code coverage Analyzing code coverage You can use the Coverage tools to display a summary of which code has been run. This is particularly useful when designing and running test cases, because you can see exactly what has been tested. 1. Set two or more breakpoints in your code. 2. On the View menu, click Coverage. 3. In the coverage pane, click Clear. 4. Run your application to the next breakpoint. 5. In the coverage pane, click Refresh. The coverage pane displays the percentage of code that has been run (figure 22). Figure 22: Coverage pane Developer Guide 61

62 Chapter 5: Testing applications The coverage pane displays a hierarchical view of packages, classes, and methods, and the percentage of code that has been run in each of them. Double-click a specific method to open the source code at this location. Green bars indicate that the source code was executed; red bars indicate that the source code was not executed (figure 23). Figure 23: Source code showing code coverage 62 BlackBerry Java Development Environment

63 Chapter 6 Setting up resources for localization This chapter provides the following information: using the IDE resource mechanism for localization setting up resource files in the IDE using the resource editor using resource strings in your applications managing resources for multiple applications Localizing applications The BlackBerry JDE includes a built-in resource mechanism for localizing text strings. This is an important part of designing applications so that they can be localized (adapted to specific languages and regions) without coding changes. Do not include textual elements, such as status messages and UI component labels, directly in your source code. Instead, store text strings in separate resource files. In your source code, use unique identifiers to map to the appropriate text. This approach has two benefits: Text translation is much more efficient because all text strings for a given locale are stored in a single file, outside of your source code. Applications can dynamically retrieve the appropriate text to display to the user, based on the user s locale.

64 Chapter 6: Setting up resources for localization This chapter explains how the BlackBerry JDE resource mechanism works, and how you can use it for your own applications. All internationalization APIs are included in the net.rim.device.api.i18n package. Note: MIDlet applications do not support localization. Working with resources in the IDE The resources for a given locale are stored in a ResourceBundle object. A ResourceBundleFamily object contains a collection of ResourceBundles, which groups together the resources for an application. The application can then switch languages, depending on the user s locale, without requiring new resource bundles. The IDE compiles each resource bundle into a separate compiled.cod file. You can then load the appropriate.cod files onto a handheld with the other code files for the application. 64 BlackBerry Java Development Environment

65 Working with resources in the IDE Resource files For each BlackBerry application, create the following files: File Description Example Resource header file Resource content file (root locale) Resource content file (specific locales) Initialization file This file defines descriptive keys for each localized string. During compilation, the IDE automatically creates a resource interface using the same name as the.rrh file with Resource appended. For example, if you use AppName.rrh, then the interface is AppNameResource. This file maps numeric keys to string literals for the root (global) locale. This file has the same name as the resource header file. This file maps numeric keys to string literals for specific locales (language and country). Files must have the same name as the resource header file, followed by an underscore (_) and the language code, and then, optionally, an underscore (_) and country code. Two-letter language and country codes are specified in ISO-639 and ISO-3166, respectively. This field initializes the resource bundle mechanism. AppName.rrh AppName.rrc AppName_en.rrc AppName_en_GB.rrc AppName_fr.rrc init.java Developer Guide 65

66 Chapter 6: Setting up resources for localization Resource inheritance Resources are organized in a hierarchy based on inheritance (figure 24). The resources that most closely match the user s locale are used. If a string is not defined in that locale, then the next closest is used, and so on, up to the root (global) locale. Figure 24: Resource hierarchy For example, suppose that a user s handheld locale is set to use Great Britain English. In this case, any strings defined for the English Great Britain locale are used first, then English, and then the root locale. Setting up resource files in the IDE You must set up projects and resource files to ensure that resources are compiled correctly. After you create files and add them to the appropriate projects, you can use the resource editor to define resources. Tip: If you are creating a suite of applications, you can manage resources efficiently by organizing them into separate projects for each locale. The samples workspace included in the JDE provides on example of this. Refer to "Managing resources for multiple applications" on page 72 for more information. 66 BlackBerry Java Development Environment

67 Setting up resource files in the IDE Create an initialization file 1. Create an initialization file (for example, init.java). This file is used to initialize resource bundles for each locale in each of your projects. The IDE provides a built-in initialization mechanism, so you only need to create an empty initialization class with an empty main() method. Here is a sample init.java file: /** * A sample resource package initializer. * Copyright (c) 2001 Research In Motion Ltd. */ package com.rim.samples.device.resource; import net.rim.device.api.i18n.*; public class init public static void main (String[] args) 2. Add the init.java file to the project for your application. Right-click in the file and click Insert into project. Create a resource header file 1. In the IDE, create a resource header (.rrh) file. On the File menu, click New. Type the name and location for the file. 2. At the prompt, type the package name. 3. At the prompt, click OK to open the file in the text editor. 4. Leave the file empty except for the package statement. 5. Add the file to the application project. Right-click in the file and click Insert into project. Create resource content files 1. In the IDE, create a resource content (.rrc) file for each locale, including the root locale. Follow the naming convention explained on page 65. On the File menu, click New. Type the name and location for the file. 2. Click OK. Developer Guide 67

68 Chapter 6: Setting up resources for localization 3. At the prompt, click OK to open the file in the text editor. Leave the file empty. 4. Add each.rrc file to the application project. Right-click in the file and click Insert into project. Using the resource editor Double-click the.rrh or.rrc file for the appropriate resource bundle. The IDE opens the file in the resource editor (figure 25). Figure 25: Resource editor The resource editor enables you to define the text resources that you want to localize in your applications, such as field labels, menu items, and messages. The resource editor displays a tab for each supported locale, based on the.rrc files that you created and added to projects in this workspace. Each row defines a single resource. The Keys column shows a descriptive name for the resource. This is the name that you use in your code to retrieve the localized text. The Values column shows the text for this resource in a particular locale. Adding resources In the resource editor, click the Root tab. The Root tab represents the global locale. You should define resources here to ensure global support for all locales. If you add a resource to a particular locale, the resource appears highlighted in yellow in all other locales. This is a warning that the resource is not defined in these locales. 68 BlackBerry Java Development Environment

69 Using the resource editor In an empty Key cell, type a resource key name that describes the resource; for example, APPLICATION_EXITSTRING. This is the key that you use in your application code to retrieve this resource. In the Value cell in the same row, type the text string for the root locale. Note: If the Value column does not appear when you open a resource header file in the IDE, you must first create resource content files for the resource bundle and add them to the appropriate project. Refer to "Setting up resource files in the IDE" on page 66 for more information. When you add a resource on the Root tab, the resource key is added to all other locales automatically. You can then select the tab for each locale to specify a different value. To specify a different text string in other locales, select the tab for a locale, such as en for the English language. In the Value cell for the resource, type the text string for this locale. If you do not define a value for a resource in a particular locale, the value for the root locale is used. Tip: You can enter unicode characters directly into the Value cell. For example, to create the word résumé, in the Value cell, type r\u00e9sum\u00e9. Refer to for more information. Viewing or setting resource properties Right-click a resource and click Properties. The properties window shows the following information (figure 26): the resource key and value for this resource (also shown in the resource editor) a comment field, in which you can type information for future reference Figure 26: Resource properties Developer Guide 69

70 Chapter 6: Setting up resources for localization Changing the resource key To change the resource key, you must right-click the resource and click Properties. In the Properties window, you can change the name in the Key field (figure 26). Note: Applications use the resource key to retrieve the resource. If you change the resource key, you must ensure that you also update your application code. Changing the package name In the resource editor, click Edit Package. In the dialog box that appears, type a new package declaration for this set of resources. Note: If you change the package declaration for resources, you must also change the import statement for any source code files that use these resources. Working with arrays You can add an array of values for a single resource key. This lets you specify two or more values for the key in an array, which your application can access. Right-click the resource and click Convert to Multiple Values. The resource properties dialog box appears. Type a value and click Add. To change a resource back to single value, right-click and select Convert to Single Value. This converts the multiple values in the array into a single string. Deleting resources To delete a resource from all locales, right-click the row for the resource and select Delete Value from All. To delete a resource from a particular locale only, click the tab for the locale at the bottom of the resource editor. Right-click the row for the resource and select Delete Value. The resource now appears highlighted in yellow to indicate that the resource is defined in one or more locales, but is not defined in the current locale. You should avoid this situation. Note: If you delete a resource from the Root tab, the resource is also deleted from all other locales. 70 BlackBerry Java Development Environment

71 Using resources Using resources Setting an application title You can provide a localized application title to display on the handheld Home screen. This is optional. If you do not provide a resource for the application title, then the Title field, set in project properties on the Application tab, is used. 1. Using the resource editor, add a resource for the application title, such as APPLICATION_TITLE. Type a value for this resource in each locale that you support. 2. In the IDE, right-click the application project and click Properties. 3. Click the Resources tab. 4. Select Title Resource Available. 5. From the Resource Bundle drop-down list, select the resource header file name to use for this application. 6. From the Resource Id drop-down list, select the resource to use for the application title, such as APPLICATION_TITLE. The following example demonstrates how to use resource files to manage text strings in an application. Chapter 7 provides another example using a simple HelloWorld application. Refer to "Adding internationalization" on page 83 for more information. 1. Import the resource package. This is the package that you specified when you created the resource header (.rrh) file. import com.rim.samples.device.resource.*; 2. Implement the resource interface. The application must implement its resource interface, which the IDE creates automatically when it compiles the program. The name of the interface is derived from the name of the resource header file, appended with Resource. public class Contacts extends UiApplication implements HelloWorldResResource, KeyListener, TrackwheelListener 3. Create a ResourceBundle variable. Declare a new ResourceBundle class variable. Later, initialize this variable by calling the getbundle() method and providing the BUNDLE_ID and BUNDLE_NAME constants as parameters. These constants are created automatically when the compiler generates the resource interface. private static ResourceBundle _resources;... static Developer Guide 71

72 Chapter 6: Setting up resources for localization _resources = ResourceBundle.getBundle(BUNDLE_ID, HelloWorldResResource.BUNDLE_NAME); 4. Substitute resources for strings. Throughout your code, where you would typically supply a text string, you instead call the getstring() method on the _resources object and provide the key for the resource.... mainscreen.settitle(new LabelField(_resources.getString(HELLOWORLD_TITLE), LabelField.ELLIPSIS LabelField.USE_ALL_WIDTH)); mainscreen.add(new RichTextField(_resources.getString(HELLOWORLD_CONTENTSTRING))); public void onexit() Dialog.alert(_resources.getString(HELLOWORLD_EXITSTRING)); Managing resources for multiple applications If you are working with a large suite of applications, you can set up projects in the IDE to group together all resources files for each locale. Create resource projects Create a project for each resource bundle (locale), including the root locale. These projects enable you to organize resources for a given locale across all applications. You should name the projects for each locale so that they have the same name as the project for the root locale, followed by a double underscore ( ), the language code, and, optionally, an underscore (_) followed by the country code. For example, if the root locale project is named com_company_app, the projects for each locale would be named com_company_app en, com_company_app en_gb, com_company_appres fr, and so on. Note: The IDE compiles a separate code (.cod) file for each resource project. By default, the IDE makes the output.cod file name the same as that of the project. The BlackBerry run-time environment uses the.cod file names to determine if resources are present for a given locale. If you do not name projects as described above, you must specify the appropriate output file names in project properties, as described below. 72 BlackBerry Java Development Environment

73 Managing resources for multiple applications Specifying output file names You can specify an output file name that is different from the project name: 1. Right-click the project and click Properties. 2. In the project properties window, click the Build tab. 3. In the Output file name field, type a name for the compiled file, without an extension. You must ensure that the output file name for all resource locale projects are the same as for the root locale, followed by a double underscore with the appropriate language and country codes appended. Add files to appropriate resource projects You still need to create the initialization, resource header, and resource content files. Refer to "Setting up resource files in the IDE" on page 66 for more information. You create one resource header file for each application and resource content files for each application, for each supported locale. You then organize the resource files in projects as follows: 1. Add the initialization file (init.java) to each resource project. Do not include the initialization file in the application projects. 2. Add the resource header (.rrh) files to the projects for each application and also to each resource project. This is necessary to define the dependency between the application projects and its resource projects. In each resource project, right-click each.rrh file and click Properties. In the file properties window, select Dependency only. Do not build. The.rrh file is built as part of the application project. 3. Add the resource content (.rrc) files to the resource projects for the appropriate locales. Tip: If you must support large numbe r of locales, you can also create a single library project for all resource header (.rrh) files. You must set the project type to Library. You must also define a dependency for projects for each resource locale on this project. Developer Guide 73

74

75 Chapter 7 Writing HelloWorld Getting started This chapter explains the following tasks: using the IDE to write an application that interacts with the BlackBerry UI framework using the IDE resource mechanism to add internationalization support to your application Set up an IDE workspace Refer to "Managing your work" on page 30 for more information. 1. On the IDE File menu, click New Workspace. 2. On the IDE Project menu, click Create New Project. Create a source file 1. In the IDE workspace, select a project file. Project files have this icon:. 2. On the Project menu, click Create New File in Project. 3. Type the HelloWorld.java file name. You must include the.java file name extension.

76 Chapter 7: Writing HelloWorld Writing HelloWorld 4. Type the folder name in which to create the file. The folder path must match the name of the package that you will use for this class. For example, a class in the package test.samples.helloworld must be in the folder test\samples\helloworld and this folder must be searchable from your CLASSPATH. If you specify a folder that does not exist, the IDE creates it. 5. Put the class in a unique package and import the required packages: package test.samples.helloworld; 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.i18n.*; import net.rim.device.api.system.*; This section explains how to write a basic application that implements a user interface on the BlackBerry Wireless Handheld. Extend UiApplication Every application that provides a user interface must extend the UiApplication base class. The UiApplication class defines methods for applications to display and maintain Screen objects and to establish an event thread. The application must also implement the KeyListener and TrackwheelListener interfaces to accept trackwheel and keyboard events from the user. public class HelloWorld extends UiApplication implements KeyListener, TrackwheelListener Declare a MenuItem variable Declare a variable for each application menu item. In this case, only a Close menu item is required. private Runnable _closeitem; Cache the menu item, rather than creating it each time, because caching results in less object garbage. 76 BlackBerry Java Development Environment

77 Writing HelloWorld Define the main() method In the main() method, you create a new object for the application and then call the entereventdispatcher() method to have the application enter the event thread and start processing messages: public static void main(string[] args) HelloWorld theapp = new HelloWorld(); theapp.entereventdispatcher(); Add an application menu Define a method to display the application menu. protected void makemenu( Menu menu ) Field focus = UiApplication.getUiApplication(). getactivescreen().getleaffieldwithfocus(); if(focus!= null) ContextMenu contextmenu = focus.getcontextmenu(); if(!contextmenu.isempty()) menu.add(contextmenu); menu.addseparator(); menu.additem(_closeitem.tostring(), _closeitem, 10); Create a Field object to store the non-manager ( leaf ) field with the focus on the active screen. Create a ContextMenu object and call the getcontextmenu() method on the active field to add its context menu. A context menu provides different menu items, depending on the type of field object and the current execution state. Each UI Field object provides different menu items. For example, if the field in focus is an EditField, it provides Cut, Copy and Paste menu items (if an object is on the clipboard). A RichTextField only provides Copy. All selectable fields provide Select and Cancel Selection items. Each application supports a single context menu. Each time the getcontextmenu() method is invoked on a Field in the application, the context menu is reset with the menu items appropriate for that field. The context menu contents remain set until the next time getcontextmenu() is invoked. Invoke menu.add() to add this context menu, and invoke menu.addseparator() to add a separator line. Invoke menu.additem() to add the Close menu item; in the method arguments, use tostring() to return the text to display for this menu item and to provide a cookie object to associate with the new item. Developer Guide 77

78 Chapter 7: Writing HelloWorld Define standard user interactions Define the standard behavior when the user interacts with the application through the trackwheel, keyboard, or ESCAPE key. Menu selection Define the standard behavior when a menu item is selected. public void menuselected( Menu menu, Object cookie, int id ) if ( cookie instanceof Runnable) ((Runnable)cookie).run(); Trackwheel Implement methods in the TrackwheelListener interface for handling trackwheel events. For this application, return false to the application when the trackwheel is released or rolled to indicate that the listener has not consumed the event. public boolean trackwheelunclick( int status, int time ) return false; public boolean trackwheelroll(int amount, int status, int time) return false; When the trackwheel is clicked, you create and display the menu, and invoke the menuselected method. You return true to the application to indicate that the event has been consumed. public boolean trackwheelclick( int status, int time ) Menu menu = new Menu(); makemenu( menu ); menu.show(); menuselected( menu, menu.getselectedcookie(), menu.getselectedid() ); return true; 78 BlackBerry Java Development Environment

79 Writing HelloWorld ESCAPE key Implement the keychar() method to intercept the ESCAPE key and exit the application. To support different locales in the future, you should always use keychar notification to determine which characters a user has pressed. In some languages, there might not be a high correspondence between keys and characters. public boolean keychar(char key, int status, int time) boolean retval = false; switch (key) case Characters.ESCAPE: onexit(); System.exit(0); retval = true; break; return retval; Keyboard Implement methods in the KeyListener interface for handling keyboard events: /** Implementation of KeyListener.keyDown */ public boolean keydown(int keycode, int time) return false; /** Implementation of KeyListener.keyRepeat */ public boolean keyrepeat(int keycode, int time) return false; /** Implementation of KeyListener.keyStatus */ public boolean keystatus(int keycode, int time) return false; /** Implementation of KeyListener.keyUp */ public boolean keyup(int keycode, int time) return false; Developer Guide 79

80 Chapter 7: Writing HelloWorld Define a constructor Define the default constructor for the application to create all BlackBerry UI components and to place the application s main screen onto the UI stack. Create a MainScreen object The MainScreen class provides the basic screen for an application. This is the first screen that users typically see when they start an application. public HelloWorld() MainScreen mainscreen = new MainScreen(); Initialize menu items Initialize the _closeitem variable as a Runnable object. _closeitem = new Runnable () public void run() onexit(); System.exit(0); public String tostring() return "Close"; ; Add a title Add a field to the title region of mainscreen. For example, you can use a LabelField. The ellipsis parameter truncates the label text with... if the text is too long for the space available. mainscreen.settitle(new LabelField( Hello World!, LabelField.ELLIPSIS LabelField.USE_ALL_WIDTH)); Add a text field Add a read-only text field by adding RichTextField to the field portion of mainscreen. By default, the RichTextField can receive focus. mainscreen.add(new RichTextField( Hello World! )); Register for keyboard and trackwheel events For the application to receive keyboard and trackwheel events, you must register the application on mainscreen as a key listener and a trackwheel listener. mainscreen.addkeylistener(this); mainscreen.addtrackwheellistener(this); 80 BlackBerry Java Development Environment

81 Writing HelloWorld Display the main screen Finally, push the mainscreen instance onto the UI stack for display. pushscreen(mainscreen); Define an onexit() method Define an onexit() method to control the behavior of the application when it exits. In this case, a dialog box appears to indicate that the application is exiting. public void onexit() Dialog.alert( Exiting Application ); Example: HelloWorld.java /** * Copyright (C) Research In Motion Limited. */ package test.samples.helloworld; 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.i18n.*; import net.rim.device.api.system.*; public class HelloWorld extends UiApplication implements KeyListener, TrackwheelListener private Runnable _closeitem; public static void main(string[] args) HelloWorld theapp = new HelloWorld(); theapp.entereventdispatcher(); protected void makemenu( Menu menu ) Field focus = UiApplication.getUiApplication().getActiveScreen(). getleaffieldwithfocus(); if(focus!= null) ContextMenu contextmenu = focus.getcontextmenu(); if(!contextmenu.isempty()) menu.add(contextmenu); menu.addseparator(); Developer Guide 81

82 Chapter 7: Writing HelloWorld menu.additem(_closeitem.tostring(), _closeitem, 10); public boolean trackwheelclick( int status, int time ) Menu menu = new Menu(); makemenu( menu ); menu.show(); menuselected( menu, menu.getselectedcookie(), menu.getselectedid() ); return true; public boolean trackwheelunclick( int status, int time ) return false; public boolean trackwheelroll(int amount, int status, int time) return false; public void menuselected( Menu menu, Object cookie, int id ) if ( cookie instanceof Runnable) ((Runnable)cookie).run(); public boolean keychar(char key, int status, int time) //intercept the ESC key - exit the application on its receipt boolean retval = false; switch (key) case Characters.ESCAPE: onexit(); System.exit(0); retval = true; break; return retval; public boolean keydown(int keycode, int time) return false; public boolean keyrepeat(int keycode, int time) return false; public boolean keystatus(int keycode, int time) return false; 82 BlackBerry Java Development Environment

83 Adding internationalization public boolean keyup(int keycode, int time) return false; public HelloWorld() MainScreen mainscreen = new MainScreen(); _closeitem = new Runnable () public void run() onexit(); System.exit(0); public String tostring() return "Close"; ; mainscreen.settitle(new LabelField("Hello World!", LabelField.ELLIPSIS LabelField.USE_ALL_WIDTH)); mainscreen.add(new RichTextField("Hello World!")); mainscreen.addkeylistener(this); mainscreen.addtrackwheellistener(this); pushscreen(mainscreen); public void onexit() Dialog.alert("Exiting Application"); Adding internationalization This section shows how you can internationalize the HelloWorld application. Refer to "Setting up resources for localization" on page 63 for more information. In HelloWorld.java, there are four places where text is displayed to the user: the Close menu item, the text field label, the application title, and the exit message. Instead of providing text strings directly in the code, you can store text strings in separate resource files for specific locales. In your source code, use unique identifiers to map to the appropriate text. Create resource files Create the following files in the IDE. Refer to "Setting up resource files in the IDE" on page 66 for more information. Developer Guide 83

84 Chapter 7: Writing HelloWorld 1. Create an initialization file called init.java. Add this file to the HelloWorld project. 2. Create a resource header file called HelloWorld.rrh. At the package prompt, enter test.samples.helloworld. Create the file in the same test\samples\helloworld folder in which you created the HelloWorld.java source file. Add this file to the HelloWorld project. 3. Create three empty resource content files in the test\samples\helloworld folder: HelloWorld.rrc (root locale) HelloWorld_en.rrc (English) HelloWorld_fr.rrc (French) 4. Add these files to the HelloWorld project. Define resources Refer to "Using the resource editor" on page 68 for more information. 1. Double-click on the HelloWorld.rrh file. 2. Click the Root tab and type the following resource keys: Key Value MENUITEM_CLOSE APPLICATION_EXITSTRING APPLICATION_CONTENTSTRING APPLICATION_TITLE Close Goodbye! Hello World Hello World Sample App In an actual application, you would also click the fr and en tabs to define different values for those locales. 84 BlackBerry Java Development Environment

85 Adding internationalization Change the HelloWorld.java code This section describes how to change the HelloWorld.java code to retrieve strings from the resource file. Changes are shown in bold. Implement the resource interface For internationalization, you must implement the appropriate resource interface. The IDE compiles this interface from the resource header file (.rrh) file automatically. The interface has the same name as the.rrh file, appended with Resource. public class HelloWorld extends UiApplication implements HelloWorldResource, KeyListener, TrackwheelListener... Declare a ResourceBundle variable Declare a class variable to hold the resource bundle for this application. A ResourceBundle object contains all localized resources, such as strings, for an application. This enables an application to choose the appropriate bundles at run time, based on its locale. private static ResourceBundle _resources = ResourceBundle.getBundle(BUNDLE_ID, BUNDLE_NAME); Call the getbundle method to retrieve the appropriate bundle family. The IDE creates the BUNDLE_ID and BUNDLE_NAME constants when it creates the resource interface at compile time. Initialize the menu item using the MenuItem class Initialize the _closeitem variable. Instead of using Runnable, you can use the MenuItem class: private MenuItem _closeitem;... _closeitem = new MenuItem(_resources, MENUITEM_CLOSE, , 10) public void run() onexit(); System.exit(0); ; Developer Guide 85

86 Chapter 7: Writing HelloWorld The MenuItem constructor accepts four parameters: Parameter bundle id ordinal priority Description The bundle parameter specifies a resource bundle for internationalization. Here you provide the _resource variable you defined to return the appropriate bundle. The id parameter specifies an identifier for this menu item. Here you provide a descriptive ID, which is mapped to an integer key in the.rrh file. This key is used to locate the string literal in the.rrc file for the appropriate locale, which is displayed to the user. The ordinal parameter specifies the order of menu items, where lower values are placed closer to the top of the menu. Here you provide a high value to ensure the Close menu item appears at the bottom. The priority parameter specifies the priority of menu items. The menu item with the lowest value receives the default focus. Add a title Add a field to the title region of mainscreen. For example, you can use a basic LabelField. The ellipsis parameter truncates the label text with... if the text is too long for the space available. mainscreen.settitle(new LabelField(_resources.getString(APPLICATION_TITLE), LabelField.ELLIPSIS LabelField.USE_ALL_WIDTH)); Add a text field Add a read-only text field by adding RichTextField to the field portion of mainscreen. mainscreen.add(new RichTextField(_resources.getString(APPLICATION_CONTENTSTRING))); Define an onexit() method Define an onexit() method to control the behavior of the application when it exits. In this case, a dialog box appears to indicate that the application is exiting. Instead of providing the text string in the alert method, you retrieve the string from the resource file. public void onexit() Dialog.alert(_resources.getString(APPLICATION_EXITSTRING)); 86 BlackBerry Java Development Environment

87 Adding internationalization Build your application On the Debug menu, click Go. Verify that your project builds and runs successfully. Example: HelloWorld.java (with internationalization) /** * A Hello World example with support for internationalization. * Copyright (C) Research In Motion Limited. */ package test.samples.helloworld; 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.i18n.*; import net.rim.device.api.system.*; public class HelloWorld extends UiApplication implements HelloWorldResource, KeyListener, TrackwheelListener private static ResourceBundle _resources = ResourceBundle.getBundle(BUNDLE_ID, HelloWorldResource.BUNDLE_NAME); private MenuItem _closeitem; public static void main(string[] args) HelloWorld theapp = new HelloWorld(); theapp.entereventdispatcher(); protected void makemenu( Menu menu ) Field focus = UiApplication.getUiApplication(). getactivescreen().getleaffieldwithfocus(); if(focus!= null) ContextMenu contextmenu = focus.getcontextmenu(); if(!contextmenu.isempty()) menu.add(contextmenu); menu.addseparator(); menu.additem(_closeitem.tostring(), _closeitem, 10); Developer Guide 87

88 Chapter 7: Writing HelloWorld public boolean trackwheelclick( int status, int time ) Menu menu = new Menu(); makemenu( menu ); menu.show(); menuselected( menu, menu.getselectedcookie(), menu.getselectedid() ); return true; public boolean trackwheelunclick( int status, int time ) return false; public boolean trackwheelroll(int amount, int status, int time) return false; public void menuselected( Menu menu, Object cookie, int id ) // menu automatically invokes Runnable.run() on MenuItem instances public boolean keychar(char key, int status, int time) //intercept the ESC key - exit the application on its receipt boolean retval = false; switch (key) case Characters.ESCAPE: onexit(); System.exit(0); retval = true; break; return retval; public boolean keydown(int keycode, int time) return false; public boolean keyrepeat(int keycode, int time) return false; public boolean keystatus(int keycode, int time) return false; public boolean keyup(int keycode, int time) return false; 88 BlackBerry Java Development Environment

89 Adding internationalization public HelloWorld() MainScreen mainscreen = new MainScreen(); _closeitem = new MenuItem(_resources, MENUITEM_CLOSE, , 10) public void run() onexit(); System.exit(0); ; mainscreen.settitle(new LabelField(_resources.getString(HELLOWORLD_TITLE), LabelField.ELLIPSIS LabelField.USE_ALL_WIDTH)); mainscreen.add(new RichTextField(_resources.getString(HELLOWORLD_CONTENTSTRING))); mainscreen.addkeylistener(this); mainscreen.addtrackwheellistener(this); pushscreen(mainscreen); public void onexit() Dialog.alert(_resources.getString(HELLOWORLD_EXITSTRING)); Developer Guide 89

90

91 Chapter 8 Writing a base class for UiApplication This chapter explains how to write an abstract base class to implement and reuse common functionality across a suite of applications. Writing a UIApplication class If you are writing a suite of UI applications, you can write an abstract base class to implement the most common UI functionality. In this example, you create an abstract class called BaseApp. Your application classes can then extend this base class. You add the base class to a library project in the IDE and set up a dependency between application projects and this library. This base class could do the following: extend UiApplication implement KeyListener and TrackwheelListener define variables, such as common menu items implement KeyListener and TrackwheelListener methods define a method to create an application menu define a method for menu selection define an abstract method for exiting the application Explanations of each of these items are provided in the HelloWorld example. Refer to "Writing HelloWorld" on page 76 for more information.

92 Chapter 8: Writing a base class for UiApplication Create resource files You must create resource files for any localized strings in your base class. Refer to "Setting up resources for localization" on page 63 for more information. In this example, you must add one resource key, MENUITEM_CLOSE, with a value of Close. Extend UiApplication and implement interfaces This base class must extend UiApplication and implement the TrackwheelListener and KeyboardListener interfaces. It must also implement its resource interface for localization. public abstract class BaseApp extends UiApplication implements BaseAppResource, KeyListener, TrackwheelListener Define common fields Define any variables that can be used across multiple applications, such as common menu items. In this example, you define a variable for the Close menu item. private MenuItem _closeitem; Define a constructor In the constructor for this base class, initialize variables. Here you create a new MenuItem object for the Close menu item. public BaseApp() _closeitem = new MenuItem(_resources, MENUITEM_CLOSE, , 10) public void run() onexit(); System.exit(0); ; The example above requires that you define MENUITEM_CLOSE resource for the BaseApp project. If you do not want to localize your applications, you can create a menu item as a Runnable object: _closeitem = new Runnable () public void run() 92 BlackBerry Java Development Environment

93 Writing a UIApplication class onexit(); System.exit(0); public String tostring() return "Close"; ; Define a method to create menus Define a method to display the application menu. In a specific application, you can override this method to add custom menu items. protected void makemenu( Menu menu ) Field focus = UiApplication.getUiApplication(). getactivescreen().getleaffieldwithfocus(); if(focus!= null) ContextMenu contextmenu = focus.getcontextmenu(); if(!contextmenu.isempty()) menu.add(contextmenu); menu.addseparator(); menu.add(_closeitem); Define trackwheel behavior Implement methods in the TrackWheel interface to define application behavior when the trackwheel is rolled, clicked, or released. /* Invoked when the trackwheel is clicked */ public boolean trackwheelclick( int status, int time ) Menu menu = new Menu(); makemenu( menu ); menu.show(); menuselected( menu, menu.getselectedcookie(), menu.getselectedid() ); return true; /* Invoked when the trackwheel is released */ Developer Guide 93

94 Chapter 8: Writing a base class for UiApplication public boolean trackwheelunclick( int status, int time ) return false; /* Invoked when the trackwheel is rolled. */ public boolean trackwheelroll(int amount, int status, int time) return false; Define keyboard behavior Implement methods in the KeyListener interface to define application behavior when keys are pressed or released. /* Implementation of KeyListener.keyDown */ public boolean keydown(int keycode, int time) return false; /* Implementation of KeyListener.keyRepeat */ public boolean keyrepeat(int keycode, int time) return false; /* Implementation of KeyListener.keyStatus */ public boolean keystatus(int keycode, int time) return false; /* Implementation of KeyListener.keyUp */ public boolean keyup(int keycode, int time) return false; public boolean keychar(char key, int status, int time) //intercept the ESC key - exit the app on its receipt boolean retval = false; switch (key) case Characters.ESCAPE: onexit(); System.exit(0); retval = true; break; return retval; 94 BlackBerry Java Development Environment

95 Writing a UIApplication class Define menu selection Define a method to invoke when a menu item is selected. public void menuselected( Menu menu, Object cookie, int id ) Define an exit method Define an abstract method that each application must implement to specify its behavior on exit. public abstract void onexit(); Example: BaseApp.java /* * Copyright (c) Research In Motion Limited. */ package test.samples.baseapp; import net.rim.device.api.i18n.*; import net.rim.device.api.system.*; import net.rim.device.api.ui.container.*; import net.rim.device.api.ui.*; import net.rim.device.api.ui.component.*; public abstract class BaseApp extends UiApplication implements BaseAppResource, KeyListener, TrackwheelListener private MenuItem _closeitem; private static ResourceBundle _resources = ResourceBundle.getBundle(BUNDLE_ID, BUNDLE_NAME); /* The constructor for the abstract base class */ public BaseApp() _closeitem = new MenuItem(_resources, MENUITEM_CLOSE, , 10) public void run() onexit(); System.exit(0); ; Developer Guide 95

96 Chapter 8: Writing a base class for UiApplication /* Override this to add custom menu items. */ protected void makemenu( Menu menu ) Field focus =UiApplication.getUiApplication(). getactivescreen().getleaffieldwithfocus(); if(focus!= null) ContextMenu contextmenu = focus.getcontextmenu(); if(!contextmenu.isempty()) menu.add(contextmenu); menu.addseparator(); menu.add(_closeitem); /* Invoked when the trackwheel is clicked */ public boolean trackwheelclick( int status, int time ) Menu menu = new Menu(); makemenu( menu ); menu.show(); menuselected( menu, menu.getselectedcookie(), menu.getselectedid() ); return true; /* Invoked when the trackwheel is released */ public boolean trackwheelunclick( int status, int time ) return false; /* Invoked when the trackwheel is rolled. */ public boolean trackwheelroll(int amount, int status, int time) return false; /* Invoked when a menu item is selected. */ public void menuselected( Menu menu, Object cookie, int id ) 96 BlackBerry Java Development Environment

97 Writing a UIApplication class public boolean keychar(char key, int status, int time) //intercept the ESC key - exit the app on its receipt boolean retval = false; switch (key) case Characters.ESCAPE: onexit(); System.exit(0); retval = true; break; return retval; /* Implementation of KeyListener.keyDown */ public boolean keydown(int keycode, int time) return false; /* Implementation of KeyListener.keyRepeat */ public boolean keyrepeat(int keycode, int time) return false; /* Implementation of KeyListener.keyStatus */ public boolean keystatus(int keycode, int time) return false; /* Implementation of KeyListener.keyUp */ public boolean keyup(int keycode, int time) return false; public abstract void onexit(); Developer Guide 97

98

99 Chapter 9 Using HTTP connections This chapter explains how to write applications that send and receive data over an HTTP connection. These applications require the Mobile Data Service to provide the gateway between the wireless and IP networks. The BlackBerry JDE includes a Mobile Data Service simulator tool that you can use to test applications that require an HTTP connection. Note: The examples in this chapter show how to open a connection using the IP Proxy Protocol (IPPP), which uses the Mobile Data Service. To use the Wireless Application Protocol (WAP) instead, you must include the WAP Gateway IP address in the Connector.open method. For example: Connector.open(" No other WAP parameters are currently supported.

100 Chapter 9: Using HTTP connections Retrieving requested content The following example demonstrates how to create an application that uses an HTTP connection to retrieve data. The main class for this application extends the UiApplication base class, which implements common UI functionality. Refer to "Writing a base class for UiApplication" on page 91 for more information. In this application, you must perform the following tasks: create a thread class that handles the HTTP connection create another thread class that handles status messages create and display UI components Refer to "HTTPDemo.java" on page 113 for more information. Note: The following example requires that you create resource files in the application project and define the required resource keys. Refer to "Setting up resources for localization" on page 63 for more information. Creating a connection thread You should always create a separate thread to send and receive data so that you do not block the application s event thread while data is being sent or received. Create a thread class to manage the HTTP connection. In this example, HTTP get operations are not queued; however, if a call is active and another call is made, the second request will stall until the previous request completes. The ConnectionThread class does the following: private class ConnectionThread extends Thread Define variables Define variables to store the URL string that users enter, and the start and stop states for the connection thread: private String _theurl; private volatile boolean _start = false; private volatile boolean _stop = false; The volatile keyword indicates that, because the data is shared, the value of each variable must always be read and written from memory, instead of cached by the VM. This technique is equivalent to wrapping the shared data in a synchronized block, but it produces less overhead. 100 BlackBerry Java Development Environment

101 Retrieving requested content Define a method to retrieve the URL Define a method to retrieve the URL. This method must be synchronized to ensure that only one thread at a time can call this method on a ConnectionThread object. This method returns the _theurl variable. public synchronized String geturl() return _theurl; Define a method to fetch a page Define a method to retrieve data from a specified URL. This method initializes _theurl to the parameter passed into the method, and sets _start to true. This method must be synchronized to ensure that fetch requests are not missed. The fetch method is invoked on the connection thread by the fetchpage method, which you will define later. The fetchpage method is invoked when the user selects the Fetch menu item. public synchronized void fetch(string url) _start = true; _theurl = url; Define a stop() method Define a method to shut down the connection thread. This method sets the _stop variable to true. This method is invoked when the application exits. public void stop() _stop = true; Define a run() method Override the Thread.run() method to open an input stream and extract data. The run() method synchronizes the thread so that only one connection is open at a time. The run() method is invoked when the thread is started. 1. Control the thread to avoid looping continuously. While no connections are open for fetch requests (_start == false), but the thread has not been stopped (_stop == false), invoke the sleep method to pause thread execution for 500 milliseconds. This reduces the CPU load to a negligible level. If the thread is not running (_stop == false), exit the method. Developer Guide 101

102 Chapter 9: Using HTTP connections public void run() for(;;) while(!_start &&!_stop) try sleep(500); catch (InterruptedException e) System.err.println(e.toString()); //exit condition if ( _stop ) return; Use a synchronized block to wrap the code for opening the connection and retrieving data. This ensures that fetch requests are not missed while received data is being processed. Create a StreamConnection object. Invoke the Connector.open method, using the geturl() method to pass in the URL that the user entered. Cast the returned object as a StreamConnection. synchronized(this) //open the connection and extract the data StreamConnection s = null; try s = (StreamConnection)Connector.open(getUrl());... Note: In many cases, you will want to cast the object returned by Connector.open as an HttpConnection object instead. HttpConnection is a StreamConnection that provides access to specific HTTP functionality, including headers and other HTTP resources. 3. Invoke openinputstream() on the StreamConnection object to open and return an input stream for the connection. Store this input stream in a variable called input. InputStream input = s.openinputstream(); 4. Extract data from the input stream in 256-byte chunks and write it into a string buffer. byte[] data = new byte[256]; int len = 0; StringBuffer raw = new StringBuffer(); while ( -1!= (len = input.read(data)) ) raw.append(new String(data, 0, len)); 102 BlackBerry Java Development Environment

103 Retrieving requested content 5. Create a string object to store the data after it has been parsed using the preparedata method. Refer to "Define a method to parse HTML data" on page 107 for more information. String parsedhtml = null; if ( raw.length() == 0 ) //basic error handling HttpConnection hc = (HttpConnection)s; //error if this fails parsedhtml = hc.getresponsemessage(); else parsedhtml = preparedata(raw.tostring()); 6. After the parsing operation is complete, invoke the stopstatusthread method to pause the status thread. Then invoke the updatecontent method to display the parsed HTML text on screen. (Refer to "Updating the content field" on page 107 for more information.) You must pause the status thread first to ensure that it does not overwrite the text on screen. Then you close the connection (s). stopstatusthread(); updatecontent(parsedhtml); input.close(); s.close(); Finally, reset the start state to indicate that the connection is finished. _start = false; Define a method to pause the status thread Define a method to pause the status thread. This method is invoked by the connection thread run() method while it displays HTML text on screen. This method invokes the pause() method on the _statusthread object. You should check the paused condition in case a notify is sent prior to the wait. private void stopstatusthread() _statusthread.pause(); try synchronized(_statusthread) while (!_statusthread.ispaused() ); _statusthread.wait(); catch (InterruptedException e) System.err.println(e.toString()); Developer Guide 103

104 Chapter 9: Using HTTP connections Creating a status thread Define thread class to manage the display of status messages to the user while the application is receiving data. Define variables 1. Define constants to store interval and timeout values. private class StatusThread extends Thread private static final int INTERVAL = 6; private static final int TIMEOUT = 500; //milliseconds private static final int THREAD_TIMEOUT = 500; 2. Define variables to store thread states. private volatile boolean _stop = false; private volatile boolean _running = false; private volatile boolean _ispaused = false; Define a method to start the thread Define a method to start the thread. This method is invoked by the fetchpage method to display status messages during a fetch request. public void go() _running = true; _ispaused = false; Define a method to pause the thread Define a method to pause the status thread. This method sets the _running variable to false. This method is invoked by the stopstatusthread method to display the results of a page request. public void pause() _running = false; You can also write a method to determine whether or not the thread is paused. public boolean ispaused() return _ispaused; 104 BlackBerry Java Development Environment

105 Retrieving requested content Define a method to stop the thread Define a method to shut down the status thread. This method sets the _stop variable to true. This method is invoked when the application exits. public void stop() _stop = true; Define the run() method Override Thread.run() to display status messages to the user during a fetch request. 1. Set up the status message in a string buffer. public void run() int i = 0; String[] statusmsg = new String[6]; StringBuffer status = new StringBuffer( Working ); statusmsg[0] = status.tostring(); for ( int j = 1; j < 6; ++j) statusmsg[j] = status.append(_resources.getstring (HTTPDEMO_STATUS_MESSAGE_APPEND)).toString(); for (;;) while (!_stop &&!_running) try sleep(500); catch ( InterruptedException e) System.err.println(e.toString()); if ( _stop ) return; i = 0; status.delete(0, status.length()); //clear status buffer Developer Guide 105

106 Chapter 9: Using HTTP connections 2. If the connection thread has been shut down (_stop == true), exit from this method; if the status thread has been paused (_running == false), invoke notify(). for ( ;; ) if ( _stop ) return; if (!_running ) _ispaused = true; synchronized(this) this.notify(); break; 3. Invoke the updatecontent method to display the status message on screen. updatecontent(statusmsg[++i%6]); try this.sleep(timeout); //wait for a bit catch (InterruptedException e) System.err.println(e.toString()); Retrieving web content Define a method to retrieve data from the URL entered by the user. 1. Perform basic validation of the URL that the user has typed. Set all characters to lowercase and add the or string if it is not present. This prefix string is defined in the HTTP_PROTOCOL constant. Refer to "Define constants" on page 107 for more information. private void fetchpage(string url) String lcase = url.tolowercase(); boolean validheader = false; int i = 0; for (i = HTTP_PROTOCOL.length - 1; i >= 0; --i) if ( -1!= lcase.indexof(http_protocol[i]) ) validheader = true; break; 106 BlackBerry Java Development Environment

107 Retrieving requested content if (!validheader ) url = HTTP_PROTOCOL[0] + url; //add protocol specifier 2. Invoke the fetch method to start a new thread for the connection. You cannot open a connection on the event thread. _connectionthread.fetch(url); 3. Invoke the go() method to create a thread to display the status message. _statusthread.go(); Updating the content field Define a method that updates the _content field on the main screen. This method is invoked by the connection thread to display text that has been retrieved, and also by the status thread to display status messages. private void updatecontent(final String text) // This creates significant garbage, but avoids threading issues // (compared with creating a static Runnable and setting the text). UiApplication.getUiApplication().invokeLater(new Runnable() public void run() _content.settext(text); ); Define a method to parse HTML data Define a method to accept HTML data that has been received and to prepare the text for display to the user, such as removing HTML tags, replacing <br> tags with new lines, and removing comments. Define constants Define constants that enable the application to transform raw HTML data into text suitable for display. Refer to "Define a method to parse HTML data" on page 107 for more information. private static final String[] HTTP_PROTOCOL = " " " " private static final char HTML_TAG_OPEN = '<'; private static final char HTML_TAG_CLOSE = '>'; private static final int STATE_0 = 0; private static final int STATE_1 = 1; Developer Guide 107

108 Chapter 9: Using HTTP connections private static final int STATE_2 = 2; private static final int STATE_3 = 3; private static final int STATE_4 = 4; private static final int STATE_5 = 5; private static final char CR = 0x000D; private static final char LF = 0x000A; Parsing the data private String preparedata(string text) final int text_length = text.length(); StringBuffer data = new StringBuffer(text_length); int state = STATE_0; int count = 0; int writeindex = -1; char c = (char)0; //cache the text length and increment the counter first for ( int i = 0; i < text_length; ++i) c = text.charat(i); switch ( state ) case STATE_0: if ( c == HTML_TAG_OPEN ) ++count; state = STATE_1; else if ( c == ' ' ) data.insert(++writeindex, c); state = STATE_5; else if (!specialchar(c) ) data.insert(++writeindex, c); break; case STATE_1: if ( c == '!' && text.charat(i + 1) == '-' && text.charat(i + 2) == '-' ) System.out.println("Entering Comment state"); i += 2; state = STATE_3; else if ( Character.toLowerCase(c) == 'p' ) 108 BlackBerry Java Development Environment

109 Retrieving requested content state = STATE_4; else if ( c == HTML_TAG_CLOSE ) --count; state = STATE_0; else state = STATE_2; break; case STATE_2: if ( c == HTML_TAG_OPEN ) ++count; else if ( c == HTML_TAG_CLOSE ) if( --count == 0 ) state = STATE_0; break; case STATE_3: if ( c == '-' && text.charat(i+1) == '-' && text.charat(i + 2) == HTML_TAG_CLOSE ) --count; i += 2; state = STATE_0; System.out.println("Exiting comment state"); break; case STATE_4: if ( c == HTML_TAG_CLOSE ) --count; data.insert(++writeindex, '\n'); state = STATE_0; else state = STATE_1; break; case STATE_5: if ( c == HTML_TAG_OPEN ) ++count; Developer Guide 109

110 Chapter 9: Using HTTP connections state = STATE_1; else if ( c!= ' ' ) state = STATE_0; if (!specialchar(c) ) data.insert(++writeindex, c); break; return data.tostring().substring(0, writeindex + 1); private boolean specialchar(char c) return c == LF c == CR; Implement the onexit() method Implement the abstract onexit() method that you defined in the base class to shut down the status and connection threads. This method is invoked when the user closes the application. public void onexit() _statusthread.stop(); _connectionthread.stop(); Create thread objects Create new thread objects to handle status messages and the HTTP connection. StatusThread _statusthread = new StatusThread(); ConnectionThread _connectionthread = new ConnectionThread(); Define UI components 1. Define variables for UI screen and field components. A RichTextField is a read-only field that supports a variety of text formatting. An EditField is an editable text field that displays a label in front of the text contents. When you initialize the field, you can specify the EditField.FILTER_URL style to customize the field so that it only permits users to type characters that are valid in a URL. 110 BlackBerry Java Development Environment

111 Retrieving requested content private MainScreen _mainscreen; private EditField _url; private RichTextField _content; 2. Define menu items. The MenuItem class implements the Runnable interface to enable the dispatching of menu actions on activation. private MenuItem _fetchmenuitem = new MenuItem(_resources, HTTPDEMO_MENUITEM_FETCH, 100, 10) public void run() //do not execute on a blank URL if ( _url.gettext().length() > 0 ) fetchpage(_url.gettext()); ; private MenuItem _clearcontent = new MenuItem(_resources, HTTPDEMO_MENUITEM_CLEARCONTENT, 105, 10) public void run() _content.settext(_resources.getstring(httpdemo_content_default)); ; Implement the keychar method In the BaseApp class, you implemented the keychar method to handle the ESCAPE key. For this application, you must also handle the situation when the user presses ENTER in the URL field. This action should invoke run() on the Fetch menu item. public boolean keychar(char key, int status, int time) if ( UiApplication.getUiApplication(). getactivescreen().getfieldwithfocus() == _url && key == Characters.ENTER ) _fetchmenuitem.run(); return true; else return super.keychar(key, status, time); Developer Guide 111

112 Chapter 9: Using HTTP connections Define a method to add menu items You must overload the makemenu method, which you defined in the base class, to add the Fetch and Clear menu items to the menu. You can then invoke makemenu on the base class to retrieve context menus. protected void makemenu(menu menu) menu.add(_fetchmenuitem); menu.add(_clearcontent); menu.addseparator(); super.makemenu(menu); Putting it all together The constructor for your class must create the main UI components (including a main screen, a title, and display fields), start the status and connection threads, and then push the main screen onto the UI stack. public HTTPDemo() _mainscreen = new MainScreen(); _mainscreen.settitle( new LabelField(_resources.getString(HTTPDEMO_TITLE), LabelField.ELLIPSIS LabelField.USE_ALL_WIDTH)); _url = new EditField(_resources.getString(HTTPDEMO_LABEL_URL), null, Integer.MAX_VALUE, EditField.FILTER_URL); _mainscreen.add(_url); _mainscreen.add(new SeparatorField()); _content = new RichTextField(_resources.getString(HTTPDEMO_CONTENT_DEFAULT)); _mainscreen.add(_content); _mainscreen.addkeylistener(this); //implemented by the super _mainscreen.addtrackwheellistener(this); //implemented by the super //start the helper threads _statusthread.start(); _connectionthread.start(); pushscreen(_mainscreen); 112 BlackBerry Java Development Environment

113 Retrieving requested content Example: HTTPDemo.java /** * A sample program that demonstrates using the HTTP connection * Copyright (c) Research In Motion Limited. */ package test.samples.httpdemo; 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.i18n.*; import net.rim.device.api.system.*; import javax.microedition.io.*; import java.io.*; import test.samples.baseapp.*; public class HTTPDemo extends BaseApp implements HTTPDemoResource //constants private static final String[] HTTP_PROTOCOL = " " private static final char HTML_TAG_OPEN = '<'; private static final char HTML_TAG_CLOSE = '>'; private static final int STATE_0 = 0; private static final int STATE_1 = 1; private static final int STATE_2 = 2; private static final int STATE_3 = 3; private static final int STATE_4 = 4; private static final int STATE_5 = 5; private static final char CR = 0x000D; private static final char LF = 0x000A; //members private MainScreen _mainscreen; private EditField _url; private RichTextField _content; Developer Guide 113

114 Chapter 9: Using HTTP connections //cache the Fetch menu item for reuse private MenuItem _fetchmenuitem = new MenuItem(_resources, HTTPDEMO_MENUITEM_FETCH, 100, 10) public void run() //do not execute on a blank url if ( _url.gettext().length() > 0 ) fetchpage(_url.gettext()); ; //cache the Clear Content menu item for reuse private MenuItem _clearcontent = new MenuItem(_resources, HTTPDEMO_MENUITEM_CLEARCONTENT, 105, 10) public void run() _content.settext(_resources.getstring(httpdemo_content_default)); ; StatusThread _statusthread = new StatusThread(); ConnectionThread _connectionthread = new ConnectionThread(); //statics private static ResourceBundle _resources = ResourceBundle.getBundle(HTTPDemoResource.BUNDLE_ID, HTTPDemoResource.BUNDLE_NAME); public static void main(string[] args) HTTPDemo theapp = new HTTPDemo(); theapp.entereventdispatcher(); //inner classes /** * The ConnectionThread class manages the HTTP connection * Fetch operations are not queued; however, if a fetch call * is made and, while active, another request made, * the second request stalls until the previous request completes. */ private class ConnectionThread extends Thread private static final int TIMEOUT = 500; //ms private String _theurl; private volatile boolean _start = false; private volatile boolean _stop = false; 114 BlackBerry Java Development Environment

115 Retrieving requested content //retrieve the URL public synchronized String geturl() return _theurl; //fetch a page // synchronized so that requests are not missed public synchronized void fetch(string url) _start = true; _theurl = url; //shut down the thread public void stop() _stop = true; public void run() for(;;) // thread control while(!_start &&!_stop) try sleep(timeout); catch (InterruptedException e) System.err.println(e.toString()); //exit condition if ( _stop ) return; // block is synchronized to ensure fetch requrests are not missed synchronized(this) //open the connection and extract the data StreamConnection s = null; try s = (StreamConnection)Connector.open(getUrl()); InputStream input = s.openinputstream(); byte[] data = new byte[256]; int len = 0; StringBuffer raw = new StringBuffer(); while ( -1!= (len = input.read(data)) ) raw.append(new String(data, 0, len)); Developer Guide 115

116 Chapter 9: Using HTTP connections String parsedhtml = null; if ( raw.length() == 0 ) //some basic error handling //if this fails, it is an error HttpConnection hc = (HttpConnection)s; parsedhtml = hc.getresponsemessage(); else parsedhtml = preparedata(raw.tostring()); // The long operation is the parsing above, // after the parsing is complete, shut down the status thread // before setting the text to ensure that the status thread does // not overwrite data (both threads modify the content pane). stopstatusthread(); updatecontent(parsedhtml); input.close(); s.close(); catch (IOException e) System.err.println(e.toString()); stopstatusthread(); updatecontent(e.tostring()); //One connection is complete so reset the start state _start = false; private void stopstatusthread() _statusthread.pause(); try synchronized(_statusthread) //Check the paused condition, //in case the notify fires prior to the wait while (!_statusthread.ispaused() ); _statusthread.wait(); catch (InterruptedException e) System.err.println(e.toString()); 116 BlackBerry Java Development Environment

117 Retrieving requested content /* * The StatusThread class manages display of the status message while * lengthy HTTP and HTML operations occur. */ private class StatusThread extends Thread private static final int INTERVAL = 6; private static final int TIMEOUT = 500; //ms private static final int THREAD_TIMEOUT = 500; private volatile boolean _stop = false; private volatile boolean _running = false; private volatile boolean _ispaused = false; //resume the thread public void go() _running = true; _ispaused = false; //pause the thread public void pause() _running = false; //query the paused status public boolean ispaused() return _ispaused; //shut down the thread public void stop() _stop = true; public void run() int i = 0; // Set up the status messages String[] statusmsg = new String[6]; StringBuffer status = new StringBuffer(_resources.getString(HTTPDEMO_STATUS_MESSAGE)); statusmsg[0] = status.tostring(); // Increment first to improve efficiency for ( int j = 1; j < 6; ++j) statusmsg[j] = status.append( _resources.getstring Developer Guide 117

118 Chapter 9: Using HTTP connections (HTTPDEMO_STATUS_MESSAGE_APPEND)).toString(); for (;;) while (!_stop &&!_running) try sleep(thread_timeout); catch ( InterruptedException e) System.err.println(e.toString()); if ( _stop ) return; i = 0; status.delete(0, status.length()); //clear the status buffer for ( ;; ) if ( _stop ) return; if (!_running ) _ispaused = true; synchronized(this) this.notify(); break; updatecontent(statusmsg[++i%6]); try this.sleep(timeout); //wait for a bit catch (InterruptedException e) System.err.println(e.toString()); //constructors public HTTPDemo() _mainscreen = new MainScreen(); _mainscreen.settitle( new 118 BlackBerry Java Development Environment

119 Retrieving requested content LabelField(_resources.getString(HTTPDEMO_TITLE), LabelField.ELLIPSIS LabelField.USE_ALL_WIDTH)); _url = new EditField(_resources.getString(HTTPDEMO_LABEL_URL), null, Integer.MAX_VALUE, EditField.FILTER_URL); _mainscreen.add(_url); _mainscreen.add(new SeparatorField()); _content = new RichTextField(_resources.getString(HTTPDEMO_CONTENT_DEFAULT)); _mainscreen.add(_content); _mainscreen.addkeylistener(this); _mainscreen.addtrackwheellistener(this); //start the helper threads _statusthread.start(); _connectionthread.start(); pushscreen(_mainscreen); //methods public boolean keychar(char key, int status, int time) if ( UiApplication.getUiApplication(). getactivescreen().getfieldwithfocus() == _url && key == Characters.ENTER ) _fetchmenuitem.run(); return true; //event has been consumed else return super.keychar(key, status, time); protected void makemenu(menu menu) menu.add(_fetchmenuitem); menu.add(_clearcontent); menu.addseparator(); super.makemenu(menu); private void fetchpage(string url) // first, normalize the URL String lcase = url.tolowercase(); boolean validheader = false; Developer Guide 119

120 Chapter 9: Using HTTP connections int i = 0; // Predecrementing on the counter saves some instructions. // Winding down and comparing to 0 saves even more. for (i = HTTP_PROTOCOL.length - 1; i >= 0; --i) if ( -1!= lcase.indexof(http_protocol[i]) ) validheader = true; break; if (!validheader ) url = HTTP_PROTOCOL[0] + url; //prepend the protocol specifier //create a thread to display the status of the operation _connectionthread.fetch(url); _statusthread.go(); private void updatecontent(final String text) //This will create significant garbage, but avoids threading issues // (compared with creating a static Runnable and setting the text) UiApplication.getUiApplication().invokeLater(new Runnable() public void run() _content.settext(text); ); private boolean specialchar(char c) return c == LF c == CR; private String preparedata(string text) // Perform operations on the html data // a basic state machine to remove tags, comments and blank space, // and to insert newlines for the <p> tag. final int text_length = text.length(); StringBuffer data = new StringBuffer(text_length); int state = STATE_0; int count = 0; int writeindex = -1; char c = (char)0; 120 BlackBerry Java Development Environment

121 Retrieving requested content //cache the text length and increment the counter first for ( int i = 0; i < text_length; ++i) c = text.charat(i); switch ( state ) case STATE_0: if ( c == HTML_TAG_OPEN ) ++count; state = STATE_1; else if ( c == ' ' ) data.insert(++writeindex, c); state = STATE_5; else if (!specialchar(c) ) data.insert(++writeindex, c); break; case STATE_1: if ( c == '!' && text.charat(i + 1) == '-' && text.charat(i + 2) == '-' ) System.out.println("Entering Comment state"); i += 2; state = STATE_3; else if ( Character.toLowerCase(c) == 'p' ) state = STATE_4; else if ( c == HTML_TAG_CLOSE ) --count; state = STATE_0; else state = STATE_2; break; case STATE_2: if ( c == HTML_TAG_OPEN ) ++count; else if ( c == HTML_TAG_CLOSE ) Developer Guide 121

122 Chapter 9: Using HTTP connections if( --count == 0 ) state = STATE_0; break; case STATE_3: if ( c == '-' && text.charat(i+1) == '-' && text.charat(i + 2) == HTML_TAG_CLOSE ) --count; i += 2; state = STATE_0; System.out.println("Exiting comment state"); break; case STATE_4: if ( c == HTML_TAG_CLOSE ) --count; data.insert(++writeindex, '\n'); state = STATE_0; else state = STATE_1; break; case STATE_5: if ( c == HTML_TAG_OPEN ) ++count; state = STATE_1; else if ( c!= ' ' ) state = STATE_0; if (!specialchar(c) ) data.insert(++writeindex, c); break; return data.tostring().substring(0, writeindex + 1); public void onexit() _statusthread.stop(); _connectionthread.stop(); 122 BlackBerry Java Development Environment

123 Receiving pushed content Receiving pushed content The following example demonstrates how to create an application that receives inbound data pushed from a server. The application listens for image data on the specified port and displays it when it arrives. A complete example of the code is shown at the end of this section. You can view sample server-side code in the BlackBerry JDE installation folder in samples\com\rim\samples\server\httppushdemo. Refer to the Mobile Data Service Network Programmer s Guide for more information on writing server-side push applications. This application extends the BaseApp class, which implements common UI functionality. Note: The following example requires that you create resource files in the application project and define the required resource keys. Refer to "Setting up resources for localization" on page 63 for more information. Creating a listening thread You should always create a separate thread to send and receive data so that you do not block the application s main event thread. For this thread, you create a variable to store the state of the thread status and a StreamConnectionNotifier object. private class ListeningThread extends Thread private boolean _stop = false; private StreamConnectionNotifier _notify; Add a stop() method Define a method to shut down the listening thread. This method simply sets the _stop variable to true and invokes the Connection.close() method on the _notify object to close the connection. This method is invoked when the application exits. public synchronized void stop() _stop = true; try _notify.close(); //close the connection so the thread will return catch (IOException e) System.err.println(e.toString()); Developer Guide 123

124 Chapter 9: Using HTTP connections Add a run() method Override the Thread.run() method to open an input stream and extract data. The run() method synchronizes the thread so that only one connection is open at a time. The run() method is invoked when the thread is started. 1. Create StreamConnection and InputStream objects. public void run() StreamConnection stream = null; InputStream input = null; 2. Unless the thread has already been shut down (_stop == true), invoke the Connector.open method, passing in the target URL for the connection. This parameter string takes the form scheme:[target][parms], where scheme is the name of a protocol, such as http. Cast the returned object as a StreamConnectionNotifier. try for(;;) synchronized(this) if ( _stop ) return; _notify = (StreamConnectionNotifier)Connector.open(" 3. Invoke the acceptandopen() method on the StreamConnectionNotifier object to return a StreamConnection object that represents a server-side socket connection. The acceptandopen() method returns only when data is available. Store this object in a variable called stream. Then invoke openinputstream() on the StreamConnection object to open and return an input stream for the connection. Store this input stream in a variable called input. stream = _notify.acceptandopen(); input = stream.openinputstream(); 4. Extract data from the input stream, in 256-byte chunks. DataBuffer db = new DataBuffer(); byte[] data = new byte[256]; int chunk = 0; while (-1!= (chunk = input.read(data)) ) db.write(data, 0, chunk); 124 BlackBerry Java Development Environment

125 Receiving pushed content 5. Close the input stream and then close the stream connection notifier. input.close(); _notify.close(); 6. Invoke the updatebitmap method to display the image that has been received. You will define this method in the next section. data = db.getarray(); updatebitmap(data); Define a method to display data Define a method to query the user when a new image is received to choose whether to update the bitmap and then render the image on the handheld screen. This method is invoked by a ListeningThread object when an image is received. You use the invokelater method to access the UI on the event dispatch thread after any pending events are processed. Refer to "Handling threads" on page 148 for more information. Note that _infofield is a RichTextField object and _imagefield is a BitmapField object. Invoking invalidate() specifies that the entire field requires repainting. private void updatebitmap(final byte[] data) Application.getApplication().invokeLater(new Runnable() public void run() //query the user to load the received image String[] choices = _resources.getstring(httppushdemo_dialog_ok), _resources.getstring(httppushdemo_dialog_cancel); if ( 0!= Dialog.ask (_resources.getstring(httppushdemo_queryforrender), choices, 0) ) return; _infofield.settext( Image received - size: + data.length); _imagefield.setbitmap(bitmap.createbitmapfrompng(data, 0, data.length)); _imagefield.invalidate(); ); Developer Guide 125

126 Chapter 9: Using HTTP connections Putting it all together Define objects for the required UI and thread objects. RichTextField is a read-only text field that supports a variety of fonts and formatting. BitmapField is specifically designed to display a bitmap image; by default, the field only uses enough area to accommodate the bitmap it contains. private ListeningThread _listeningthread; private MainScreen _mainscreen; private RichTextField _infofield; private BitmapField _imagefield; Display the UI In the constructor for your main application class, create UI components and register the key and trackwheel listeners. public HTTPPushDemo() _mainscreen = new MainScreen(); _mainscreen.settitle(new LabelField (_resources.getstring(httppushdemo_title), LabelField.USE_ALL_WIDTH)); _infofield = new RichTextField(); _mainscreen.add(_infofield); _mainscreen.add(new SeparatorField()); _imagefield = new BitmapField(null,BitmapField.HCENTER BitmapField.TOP); _mainscreen.add(_imagefield); _mainscreen.addkeylistener(this); _mainscreen.addtrackwheellistener(this);... Start the listening thread Also in the constructor for your application class, create and start a new listening thread. You can then display a message to the user that the thread has started. _listeningthread = new ListeningThread(); _listeningthread.start(); _infofield.settext(_resources.getstring (HTTPPUSHDEMO_LISTENTHREADSTARTED)); pushscreen(_mainscreen); 126 BlackBerry Java Development Environment

127 Receiving pushed content Define an exit method Implement the abstract onexit() method that you defined in the base class. In this example, you stop the listening thread. As defined in the base class, this method is invoked when the user selects the Close menu item. public void onexit() _listeningthread.stop(); try _listeningthread.join(); catch (InterruptedException e) System.err.println(e.toString()); Example: HTTPPushDemo.java /** * This is a sample program that demonstrates the client side of a basic * HTTP Push system. This application listens for image data on the * specified port and renders the data when it arrives. * * Copyright (c) Research In Motion Limited. */ package test.samples.httppushdemo; import java.io.*; import javax.microedition.io.*; 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.i18n.*; import net.rim.device.api.system.*; import net.rim.device.api.util.*; import test.samples.baseapp.*; public class HTTPPushDemo extends BaseApp implements HTTPPushDemoResource //constants private static final String URL = " //PORT 100 private static final int CHUNK_SIZE = 256; //members private ListeningThread _listeningthread; private MainScreen _mainscreen; private RichTextField _infofield; private BitmapField _imagefield; //statics Developer Guide 127

128 Chapter 9: Using HTTP connections private static ResourceBundle _resources = ResourceBundle.getBundle(HTTPPushDemoResource.BUNDLE_ID, HTTPPushDemoResource.BUNDLE_NAME); public static void main(string[] args) HTTPPushDemo theapp = new HTTPPushDemo(); theapp.entereventdispatcher(); //inner classes private class ListeningThread extends Thread private boolean _stop = false; private StreamConnectionNotifier _notify; public synchronized void stop() _stop = true; try _notify.close(); //close the connection so the thread returns. catch (IOException e) System.err.println(e.toString()); public void run() StreamConnection stream = null; InputStream input = null; try for(;;) synchronized(this) if ( _stop ) return; //synchronize to avoid creating a connection that never closes _notify = (StreamConnectionNotifier)Connector.open(URL); //NOTE: the following operation blocks until data is received stream = _notify.acceptandopen(); input = stream.openinputstream(); 128 BlackBerry Java Development Environment

129 Receiving pushed content //Extract the data from the input stream DataBuffer db = new DataBuffer(); byte[] data = new byte[256]; int chunk = 0; while (-1!= (chunk = input.read(data)) ) db.write(data, 0, chunk); input.close(); _notify.close(); data = db.getarray(); updatebitmap(data); catch (IOException e) //likely the stream was closed System.err.println(e.toString()); //constructor public HTTPPushDemo() _mainscreen = new MainScreen(); _mainscreen.settitle(new LabelField(_resources.getString(HTTPPUSHDEMO_TITLE), LabelField.USE_ALL_WIDTH)); _infofield = new RichTextField(); _mainscreen.add(_infofield); _mainscreen.add(new SeparatorField()); _imagefield = new BitmapField(null, BitmapField.HCENTER BitmapField.TOP); _mainscreen.add(_imagefield); _mainscreen.addkeylistener(this); _mainscreen.addtrackwheellistener(this); //spin off the listening thread _listeningthread = new ListeningThread(); _listeningthread.start(); _infofield.settext(_resources.getstring (HTTPPUSHDEMO_LISTENTHREADSTARTED)); pushscreen(_mainscreen); private void updatebitmap(final byte[] data) Application.getApplication().invokeLater(new Runnable() public void run() //query the user to load the received image Developer Guide 129

130 Chapter 9: Using HTTP connections String[] choices = _resources.getstring(httppushdemo_dialog_ok), _resources.getstring(httppushdemo_dialog_cancel); if ( 0!= Dialog.ask (_resources.getstring(httppushdemo_queryforrender), choices, 0) ) return; _infofield.settext(_resources.getstring(httppushdemo_imageinfo) + data.length); _imagefield.setbitmap(bitmap.createbitmapfrompng(data, 0, data.length)); ); public void onexit() //stop the listening thread _listeningthread.stop(); try _listeningthread.join(); catch (InterruptedException e) System.err.println(e.toString()); 130 BlackBerry Java Development Environment

131 Using HTTPS Using HTTPS Applications can open HTTPS connections by specifying https as the protocol; for example: HttpConnection stream = (HttpConnection)Connector.open( ); Refer to the Mobile Data Service Administration Guide for information on configuring HTTPS access and managing trusted certificates. Authentication If the Mobile Data Service has been configured to allow unauthenticated connections, an application can connect using HTTPS without authenticating the server by adding the trustall parameter: HttpConnection stream = (HttpConnection)Connector.open( ); Redirection The Mobile Data Service can handle HTTP forwarding automatically to minimize communication with the handheld. To enable automatic forwarding, use the RdHTTPS parameter: HttpConnection stream = (HttpConnection)Connector.open( ); If redirection occurs, the Mobile Data Service adds the x-rim-redirect-https header to the HTTP response to indicate this. Developer Guide 131

132 Chapter 9: Using HTTP connections Handheld security The BlackBerry Wireless Handheld includes built-in security to prevent third-party applications from sending or receiving data without the user s knowledge. When an untrusted application attempts to open a connection, the handheld user is presented with a dialog asking them if they want to allow the connection. The user must choose to allow or deny the connection. The user can also select one of the options to allow connections of this type or connections to the this destination in the future without prompting. These options apply only to the specific application. The user can change these settings later in handheld Options > Firewall. 132 BlackBerry Java Development Environment

133 Chapter 10 Creating custom fields UI components are represented by fields rectangular regions contained by a manager. The BlackBerry APIs enable you to create custom types of fields. To design a custom field, you must perform the following steps: extend the Field class (or one of its subclasses) implement a constructor implement the layout and paint abstract methods add further capabilities by implementing Field get and set methods You can also optionally implement the DrawStyle interface, which provides drawing styles that you can use for field objects. Your custom field should listen to all relevant system styles. For example, USE_ALL_WIDTH and USE_ALL_HEIGHT are appropriate for many fields.

134 Chapter 10: Creating custom fields Implementing layout() Any class that extends Field must implement the layout method to define its specific behavior. The field s manager invokes this method during the layout process to instruct this field to arrange its contents, given the amount of available space. The width and height parameters specify the amount of available horizontal and vertical space, respectively. You can calculate the available width and height by invoking the Math.min method to return either the specified width and height or the field s preferred width and height, whichever is smaller. Refer to "Returning a preferred field size" on page 135 for more information. You must then invoke setextent(int, int) to set the required size for the field. The following example demonstrates how to implement the layout method: protected void layout(int width, int height) // update the cached font in case it has been changed _font = getfont(); _labelheight = _font.getheight(); _labelwidth = _font.getadvance(_label); // calculate width width = Math.min( width, getpreferredwidth() ); // calculate height height = Math.min( height, getpreferredheight() ); // set dimensions setextent( width, height ); Tip: Arrange field data so that you do most complex calculations in layout(), not in paint(). You must ensure that the paint() method is as efficient as possible. Tip: You should always recalculate pixel layout, cached fonts and locale strings in the Field.layout method. The framework invokes this method whenever system preferences change. For instance, when the system default font changes, all fields in the system are updated automatically if their layout method is implemented correctly. The same is true for locale changes and date format changes. 134 BlackBerry Java Development Environment

135 Returning a preferred field size Returning a preferred field size In most cases, you should override the getpreferredwidth() and getpreferredheight() methods to ensure proper layout in certain layout managers. These methods return the preferred width and height of a field. The following example demonstrates how to implement getpreferredwidth(). public int getpreferredwidth() switch(_shape) case TRIANGLE: if (_labelwidth < _labelheight) return _labelheight << 2; else return _labelwidth << 1; case OCTAGON: if (_labelwidth < _labelheight) return _labelheight + 4; else return _labelwidth + 8; case RECTANGLE: default: return _labelwidth + 8; The following example demonstrates how to implement the getpreferredheight(). public int getpreferredheight() switch(_shape) case TRIANGLE: if (_labelwidth < _labelheight) return _labelheight << 1; else return _labelwidth; case RECTANGLE: return _labelheight + 4; case OCTAGON: return getpreferredwidth(); return 0; Developer Guide 135

136 Chapter 10: Creating custom fields Implementing paint() Any class that extends Field must implement the paint method to define its specific behavior. When an area of the field has been marked as invalid, the manager of the field invokes the paint method to instruct the field to redraw itself. Follow these guidelines when implementing paint(): Ensure that your paint method is as fast as possible because the UI framework calls paint whenever necessary. For large fields, use Graphics.getClippingRect to save drawing time by only painting within the visible region. Avoid allocating in paint(). Arrange field data so that complex calculations are performed in layout() instead of in paint(). The following example demonstrates how to implement the paint method to redraw a custom field. protected void paint(graphics graphics) int textx, texty, textwidth; int w = getwidth(); switch(_shape) case TRIANGLE: int h = (w>>1); int m = (w>>1)-1; graphics.drawline(0, h-1, m, 0); graphics.drawline(m, 0, w-1, h-1); graphics.drawline(0, h-1, w-1, h-1); textwidth = Math.min(_labelWidth,h); textx = (w - textwidth) >> 1; texty = h >> 1; break; case OCTAGON: int x = 5*w/17; int x2 = w-x-1; int x3 = w-1; graphics.drawline(0, x, 0, x2); graphics.drawline(x3, x, x3, x2); graphics.drawline(x, 0, x2, 0); graphics.drawline(x, x3, x2, x3); graphics.drawline(0, x, x, 0); graphics.drawline(0, x2, x, x3); graphics.drawline(x2, 0, x3, x); graphics.drawline(x2, x3, x3, x2); textwidth = Math.min(_labelWidth, w - 6); textx = (w-textwidth) >> 1; texty = (w-_labelheight) >> 1; break; 136 BlackBerry Java Development Environment

137 Handling focus issues case RECTANGLE: default: graphics.drawrect(0, 0, w, getheight()); textx = 4; texty = 2; textwidth = w - 6; break; graphics.drawtext(_label, textx, texty, (int)( getstyle() & DrawStyle.ELLIPSIS DrawStyle.HALIGN_MASK ), textwidth ); Handling focus issues You can support focus by using the Field.FOCUSABLE style and implementing the Field.moveFocus method. If you want your field to receive the focus, you must override Field.isFocusable to return true. The framework invokes onfocus when the field gains focus, and onunfocus when the field loses focus. You can override these methods if your field requires specific behavior for these events. The framework invokes movefocus to handle focus movements within a field. This corresponds to the trackwheelroll event. You can override movefocus for special behavior. You can change the appearance of the default focus indicator by overriding drawfocus. Using set and get methods You can add further capabilities for your field by implementing the various get and set methods of Field. Note: All accessor and mutator methods should work before and after the field has been added to a Screen. For example, a setlabel method should update the display with the new value if the field is currently on screen by invoking invalidate() or updatelayout() as appropriate. The following examples demonstrate how to implement common get and set methods for a custom field. /** * Returns the label. */ public String getlabel() return _label; Developer Guide 137

138 Chapter 10: Creating custom fields /** * Returns the shape. */ public int getshape() return _shape; /** * Sets the label. */ public void setlabel(string label) _label = label; _labelwidth = _font.getadvance(_label); updatelayout(); /** * Sets the shape. */ public void setshape(int shape) _shape = shape; updatelayout(); 138 BlackBerry Java Development Environment

139 Using set and get methods Example: CustomButtonField.java /** * CustomButtonField.java * * Copyright (C) Research In Motion Limited. */ package com.rim.samples.device.custombuttons; import net.rim.device.api.ui.*; import net.rim.device.api.system.*; /** * CustomButtonField - class which creates button fields of various * shapes. Demonstrates how to create custom UI fields. */ class CustomButtonField extends Field implements DrawStyle public static final int RECTANGLE = 1; public static final int TRIANGLE = 2; public static final int OCTAGON = 3; private String _label; private int _shape; private Font _font; private int _labelheight; private int _labelwidth; /** * Constructs a button with specified label, and default style and shape. */ public CustomButtonField(String label) this(label, RECTANGLE, 0); /** * Constructs a button with specified label and shape, and default style. */ public CustomButtonField(String label, int shape) this(label, shape, 0); /** * Constructs a button with specified label and style, and default shape. */ public CustomButtonField(String label, long style) this(label, RECTANGLE, style); Developer Guide 139

140 Chapter 10: Creating custom fields /** * Constructs a button with specified label, shape, and style. */ public CustomButtonField(String label, int shape, long style) super(style); _label = label; _shape = shape; _font = getfont(); _labelheight = _font.getheight(); _labelwidth = _font.getadvance(_label); /** * Draws the focus indicator for this button. Inverts the inside region * of the shape. * graphics Graphics context used for drawing the focus. on True if the focus should be set; otherwise, false */ protected void drawfocus(graphics graphics, boolean on) switch(_shape) case TRIANGLE: int w = getwidth(); int h = w >> 1; for (int i=h-1; i>=2; --i) graphics.invert(i, h - i, w - (i << 1), 1); break; case RECTANGLE: graphics.invert(1, 1, getwidth() - 2, getheight() - 2); break; case OCTAGON: int x3 = getwidth(); int x = 5 * x3 / 17; int x2 = x3 - x; x3 = x3-1; x2 = x2-1; graphics.invert(1, x, getwidth() - 2, x2 - x + 1); for (int i=1; i<x; ++i) graphics.invert(1+i, x-i, getwidth() - ((i+1)<<1), 1); graphics.invert(1+i, x2+i, getwidth() - ((i+1)<<1), 1); break; 140 BlackBerry Java Development Environment

141 Using set and get methods /** * Returns the label. */ public String getlabel() return _label; /** * Returns the shape. */ public int getshape() return _shape; /** * Sets the label. */ public void setlabel(string label) _label = label; _labelwidth = _font.getadvance(_label); updatelayout(); /** * Sets the shape. */ public void setshape(int shape) _shape = shape; updatelayout(); /** * Gets the preferred width of the button. */ public int getpreferredwidth() switch(_shape) case TRIANGLE: if (_labelwidth < _labelheight) return _labelheight << 2; else return _labelwidth << 1; case OCTAGON: if (_labelwidth < _labelheight) return _labelheight + 4; else return _labelwidth + 8; case RECTANGLE: default: return _labelwidth + 8; Developer Guide 141

142 Chapter 10: Creating custom fields /** * Gets the preferred height of the button. */ public int getpreferredheight() switch(_shape) case TRIANGLE: if (_labelwidth < _labelheight) return _labelheight << 1; else return _labelwidth; case RECTANGLE: return _labelheight + 4; case OCTAGON: return getpreferredwidth(); return 0; /** * Lays out this button's contents. * <p> This field's manager invokes this method during the layout process * to instruct this field to arrange its contents, given an amount of * available space. * width Amount of available horizontal space. height Amount of available vertical space. * */ protected void layout(int width, int height) // update the cached font in case it has been changed _font = getfont(); _labelheight = _font.getheight(); _labelwidth = _font.getadvance(_label); // calculate width width = Math.min( width, getpreferredwidth() ); // calculate height height = Math.min( height, getpreferredheight() ); // set dimensions setextent( width, height ); 142 BlackBerry Java Development Environment

143 Using set and get methods /** * Redraws this button. * <p> This field's manager invokes this method during the repainting * process to instruct this field to repaint itself. * graphics Graphics context for repainting this field. * */ protected void paint(graphics graphics) int textx, texty, textwidth; int w = getwidth(); switch(_shape) case TRIANGLE: int h = (w>>1); int m = (w>>1)-1; graphics.drawline(0, h-1, m, 0); graphics.drawline(m, 0, w-1, h-1); graphics.drawline(0, h-1, w-1, h-1); textwidth = Math.min(_labelWidth,h); textx = (w - textwidth) >> 1; texty = h >> 1; break; case OCTAGON: int x = 5*w/17; int x2 = w-x-1; int x3 = w-1; graphics.drawline(0, x, 0, x2); graphics.drawline(x3, x, x3, x2); graphics.drawline(x, 0, x2, 0); graphics.drawline(x, x3, x2, x3); graphics.drawline(0, x, x, 0); graphics.drawline(0, x2, x, x3); graphics.drawline(x2, 0, x3, x); graphics.drawline(x2, x3, x3, x2); textwidth = Math.min(_labelWidth, w - 6); textx = (w-textwidth) >> 1; texty = (w-_labelheight) >> 1; break; case RECTANGLE: default: graphics.drawrect(0, 0, w, getheight()); textx = 4; texty = 2; textwidth = w - 6; break; graphics.drawtext(_label, textx, texty, (int)( getstyle() & DrawStyle.ELLIPSIS DrawStyle.HALIGN_MASK ), textwidth ); Developer Guide 143

144

145 Chapter 11 Programming tips This chapter provides guidelines for developing BlackBerry applications, including the following topics: writing efficient code managing UI interactions general coding tips working with time Writing efficient code Persistent storage on the BlackBerry Wireless Handheld is limited. The following programming tips should help minimize the size of your compiled code (.cod files) and maximize program speed. Set appropriate access When you create code libraries, using the appropriate access modifiers for fields and methods can significantly reduce the size of your compiled code. In particular, perform the following actions: Declare fields as private whenever possible. In addition to being good coding practice, this enables the compiler to optimize the.cod file. When possible, use the default (package) access rather than public access (that is, omit the public and protected keywords).

146 Chapter 11: Programming tips Use shorthand for evaluating Boolean conditions Use this efficient shorthand for evaluating Boolean conditions. Instead of writing the code as in example 1, you could write the code as in example 2: // Example 1 - Avoid this if( something_that_evaluates_to_true ) return true; else return false; // Example 2 - Do this return( something_that_evaulates_to_true ); The resulting compiled code is shorter. Avoid creating interfaces When creating API libraries, avoid creating interfaces unless you foresee multiple implementations of the API. Interfaces produce larger, slower code. Use static inner classes When you use an inner class to hide one class inside another, but you do not need the inner class to reference the outer class object, declare the inner class static. This suppresses the creation of the reference to the outer class. For example, this code requires a reference to the outer class object: class outer int i; class inner inner() int example() return i; In contrast, this code only scopes the name of the inner class: class outer static class inner The previous example is a shorter version of this code: class outer class outer$inner 146 BlackBerry Java Development Environment

147 Writing efficient code The only time you should use a non-static inner class is when you need access to data in the outer class from within methods of the inner class. If you are using an inner class only for name scoping, make it static. Make classes final When creating code libraries, ensure that you mark a class as final if you know it will never be extended. The presence of the final keyword enables the compiler to generate faster code. Note: The BlackBerry JDE compiler (rapc) automatically marks any classes as final that are not extended in an application.cod file. Use int instead of long In Java, a long is a 64-bit integer. Because the BlackBerry Wireless Handheld uses a 32-bit processor, operations run two to four times faster if you use an int instead of a long. Using static strings When defining static fields (also called class fields) of type String, you can increase program speed by using static variables (not final) instead of constants (final). The opposite is true for primitive data types, such as int. For example, you might create a String object: private static final String x = "example"; For this static constant (denoted by the final keyword), a temporary String instance is created every time you use the constant. The compiler eliminates x and replaces it with the string example in the bytecode, so that the VM has to perform a hash table lookup each time you reference x. In contrast, for a static variable (no final keyword), the string is created once. The VM performs the hash table lookup only when it initializes x, so access is faster. Note: It is acceptable to have public constants (that is, final fields), but you should always make variables private. Developer Guide 147

148 Chapter 11: Programming tips Managing UI interactions The following programming guidelines apply to managing UI interactions. Managing screens You should be careful not to mismatch the pushscreen() and popscreen() when managing your application screens on the UI stack. You must pop screens off the UI stack when the user finishes interacting with them. Otherwise, the display stack continues to grow until the handheld runs out of memory. You should not use more than a few modal screens at one time, because each screen uses a thread. You should pop the screen only once. Handling threads An application can access the UI only on the event thread, or with the event lock held. Only one thread at a time (usually the event-dispatching thread) can gain access to an interface component. There are two ways for background threads to access the UI from outside the main event-handling or UI drawing code: acquire and hold the event lock use invokelater() or invokeandwait() to run on the event dispatch thread Holding the event lock The event dispatcher sets a lock on the event thread while it processes a message. Background threads (that is, non-event dispatch threads) can access the UI by acquiring this lock for a short time, without interfering with processing by the event dispatcher. A worker thread can call Application.getEventLock() to retrieve the event lock and then synchronize with this object to ensure serialized access to the UI. You should only hold this lock for short periods of time because the event dispatcher is paused. An application should never call notify() or wait() on this object. 148 BlackBerry Java Development Environment

149 Managing UI interactions For example, in a timer task, you could write code such as this: class MyTimerTask extends TimerTask public void run() synchronized( Application.getEventLock() ) _label.settext( "new text " + System.currentTimeMillis() ); In most cases, this is the most efficient way to access the UI. Running on the event dispatch thread In some cases, holding the event lock is not appropriate, particularly if the application has its own locking operations to manage. In this case, you must create a class that implements the Runnable interface. You can then invoke its run() method on the event dispatch thread using one of these three methods: Use invokeandwait(runnable runnable) to have run() called on the event dispatch thread immediately. The call blocks until the run() method has completes. Use the invokelater(runnable runnable) to have run() called on the event dispatch thread after all pending events are processed. Use invokelater(runnable runnable, long time, boolean repeat) to have run() called on the event dispatch thread after a specified amount of time, where time specifies the number of milliseconds to wait before adding Runnable to the event queue. If repeat is true, the Runnable is added to the event queue every time milliseconds. Using activate() The system calls the activate() method when it brings an application to the foreground. For most applications, you should not override activate(). Perform any initialization, including any required pushscreen() calls, in the application s constructor. If you must override activate(), ensure that you call super.activate() from within the overridden method; otherwise, your application does not repaint correctly. Since activate() can be called multiple times for the same application, it is not appropriate to perform a one-time initialization within this method. For example, you should not do things, such as call pushscreen() from within activate(), unless you verify that you have done so already. Developer Guide 149

150 Chapter 11: Programming tips Exiting applications General coding tips When the user closes an application (for example, by selecting the Close menu item), most applications should shut down using System.exit() before returning the user to the Home screen. This conserves space on the handheld. This section provides miscellaneous coding tips to help you write faster, smaller programs. Avoid the Object.getClass() method Avoid using the Object.getClass() method, because it is not efficient and produces garbage (the Class object) that is never collected. Avoid using the example.class literal. This generates Class.forName( Example ). Writing efficient loops You should always factor loop invariant code out of a loop, as in the following example: for( int i = 0; i < vector.size(); i++ )... This code results in vector.size() getting called each time through the loop, which is inefficient. If your container is likely to have more than one element, it is much faster to assign the size to a local variable. The optimized code appears below: int size = vector.size(); for( int i = 0; i < size; ++i )... Alternatively, if the order in which you iterate over items is not important, you can iterate backwards. This avoids the extra local on the stack, and the comparison is also faster: for( int i = vector.size() - 1; i >= 0; --i ) BlackBerry Java Development Environment

151 General coding tips Optimizing subexpressions If you ever use the same expression twice, do not rely on the compiler to optimize it for you. Use a local variable, as in the following example: one( i+1 ); two( i+1 ); // Avoid int tmp = i+1; one( tmp ); two( tmp ); // Prefer Avoid java.util.enumeration Avoid using java.util.enumeration unless you are using it to hide data (in other words, returning an Enumeration of data rather than the data itself). This example shows a typical use of an Enumeration: for (Enumeration e = v.elements(); e.hasmoreelements();) o = e.nextelement();... Asking a vector or hash table for an Enumeration object creates unnecessary garbage and is slow. Instead, you can iterate the elements yourself, as in this example: for( int i = v.size() - 1; i >=0; --i ) o = v.elementat( i );... If the vector might be modified by another thread, you need to synchronize the iteration: synchronized( v ) for( int i = v.size() - 1; i >=0; --i ) o = v.elementat( i );... In Java 2 Platform, Standard Edition (J2SE), you would use an Iterator for this, but Iterators are not available in Java 2 Platform, Mobile Edition (J2ME). Returning null If you are writing a public method that returns an object, it should never return null unless the following occurs: a null is expected during normal program operation the parameter states that null is a possible return value Developer Guide 151

152 Chapter 11: Programming tips If a null is not normally expected, then the method should throw an appropriate exception, which forces the caller to deal explicitly with the problem. The caller is not expected to check for a null return value, unless the documentation says otherwise. Passing null into methods Do not pass null parameters into an API method unless the API Reference documentation explicitly states that the method supports them. Passing null into a constructor To avoid ambiguity when passing null into a constructor, you should use this form: new someobject ( (Object)null ); A class can have two or more constructors, such as SomeObject(String) and SomeObject(Object), where passing in a null does not identify which constructor to use. As a result, the compiler reports an error. Not all supported constructors necessarily appear in the API Reference documentation, because some constructors are for internal use only. By casting the null to the appropriate object, you indicate precisely which constructor the compiler should use. This practice also ensures forward compatibility if later releases of the API add new constructors. Optimizing division operations Division operations can be slow on the BlackBerry Wireless Handheld because its processor does not have a hardware divide instruction. When you write code that divides a positive number by two, you should use shift right by one instead. For example: midpoint = width / 2; //avoid this int = width >> 1; //prefer this Only use the shift right (>>) when you know you are dealing with a positive value. It does not work for negative values. Managing garbage collection Avoid calling System.gc() to perform garbage collection. This operation can take too much time, especially on a handheld with limited free memory. Let the VM collect garbage automatically. 152 BlackBerry Java Development Environment

153 General coding tips Casting using instanceof It is more efficient to use instanceof than classcastexception to evaluate whether a cast succeeds. Here is an example of using a try/catch block to catch the classcastexception: try (String)x.whatever(); catch( ClassCastException e ) // something else Alternatively, you can use instanceof operator: if( x instanceof String ) (String)x.whatever(); else // something else Using instanceof is faster. The only time you should use the try/catch block is when the failure of the cast is an exceptional circumstance. The BlackBerry JDE compiler and the virtual machine are optimized to perform only one class check in the first block of code. This is true of any code where the cast is run immediately following a branch determined by an instanceof check. Always perform the cast immediately after the branch to ensure that the optimization can be performed. Using longs for unique identifiers You should use longs rather than strings for unique constants, such as Globally Unique Identifiers (GUIDs), hash table keys, and state/context identifiers. To ensure that unique identifiers remain unique across all third-party application developers, you should use randomly generated keys based on a hash of some string. In the input string, you should include enough information to ensure uniqueness. One way to do this is to include the fully qualified package name; for example, com.rim.samples.device.helloworld. Developer Guide 153

154 Chapter 11: Programming tips Working with time Here are several tips for coding time-sensitive applications, such as a calendar application. Your goal in designing applications should be to not depend on time zones for anything other than displaying local time to the user. Calculating time on the handheld The BlackBerry Wireless Handheld operating system calculates absolute time as milliseconds since midnight, January 1, 1970 UTC (Universal Time Coordinate). Time on the handheld is typically measured in either CPU ticks or milliseconds. Handling system time zone changes If you are caching a time-sensitive object for performance reasons, remember that the system time zone can change on the handheld. When the time zone changes, the system sends out a global event message to the applications. To catch it, implement the GlobalEventListener interface and register the listener by calling Application.addGlobalEventListener(). Your eventoccurred() method should look similar to this: public void eventoccurred( long guid, int data0, int data1, Object object0, Object object1 ) if( guid == DateTime.GUID_TIMEZONE_CHANGED ) _cal.settimezone( TimeZone.getDefault() ); 154 BlackBerry Java Development Environment

155 Chapter 12 Deploying applications This chapter provides the following information: loading.cod files onto a handheld for testing purposes deploying production applications to load with desktop tools You can load applications that were developed using the BlackBerry JDE onto a BlackBerry Wireless Handheld version 3.2 or later. Loading applications for testing The JavaLoader.exe tool provides a command line tool to add or update applications on a handheld. This tool is intended for use by developers for development and testing purposes only. To deploy production applications, you should use the Application Loader, which is part of the BlackBerry Desktop Manager. Refer to "Deploying applications" on page 157 for more information.

156 Chapter 12: Deploying applications Warning: If your handheld contains any important information, such as messages or Address Book entries, you should create a backup of this data on your computer before continuing. 1. Insert the handheld into the cradle. 2. Move to bin folder in the JDE installation folder. 3. Type: JavaLoader [-p<port>] [-b<bps>] [-w<password>] <command> where: <port> is the serial port to which the handheld is connected <bps> is the bit rate speed to the serial port (default is ) <password> specifies the password for your handheld, if you have set one <command> is one of the following command line options Command line options dir [-d] The dir command lists all applications currently loaded on the handheld. The -d option lists dependency information for each. cod file. deviceinfo The deviceinfo command lists information about the handheld, such as hardware ID, personal identification number (PIN), OS version, and VM version. load <file> The load command loads new applications or the application environment onto the handheld. Any existing applications with the same name are erased. You can also specify a directory from which to load all files. info [-d] <file> The info command provides information about a local.cod file, including the name, version, size, and creation date. The -d option lists the other.cod files on which the specified.cod file depends. 156 BlackBerry Java Development Environment

157 Deploying applications wipe [-f -a] The wipe command erases either the file system or the application region of flash memory. The -f option erases the file system only. The -a option erases the application environment. If no option is specified, both regions are erased. erase [-f] <module> The erase command removes applications currently loaded on a handheld. Modules names are case-sensitive and can be obtained using the JavaLoader dir command. The -f flag forces the specified modules to be erased, even if it is in use. eventlog The eventlog command displays the handheld event log. Deploying applications The Application Loader, which is part of the BlackBerry Desktop Manager, allows users to load new applications onto the handheld. To deploy applications in this manner, you must create an application loader (.alx) file for each application and then distribute the.alx and.cod files to your users. For information on using the Application Loader, refer to the Updating your handheld s applications topic in the Application Loader Online Help. To obfuscate applications The compiler that is included with the IDE provides a level of obfuscation in.cod files. For example, the IDE compiler automatically obfuscates internal, private members and removes debugging information. The following procedure explains how to further obfuscate your code. 1. Compile a jar file for your application using the RIM API libraries. This includes RIM versions of Java language implementations, such as java.lang, java.io and java.util. 2. Use standard tools to obfuscate the.jar file. 3. In the IDE, create a new project. Add the obfuscated.jar file to this project. 4. In the IDE, build the project. The.cod files are now obfuscated. Developer Guide 157

158 Chapter 12: Deploying applications About the.alx file format The following information is provided only as a supplementary reference. In most cases, you do not need to edit the.alx files generated in the IDE. The.alx file uses an XML format. This is an example of a.alx file for one application: <loader version="1.0"> <application id="com.rim.samples.device.contacts"> <name>sample Contacts Application</name> <description>provides ability to store a list of contacts. </description> <version>1.0</version> <vendor>research In Motion</vendor> <copyright>copyright Research In Motion</copyright> <language langid="0x000c"> <name>application D'Échantillon Pour des Contacts</name> <description>enregistre une liste de contacts.</description> </language> <fileset Java="1.0"> <directory>samples/contacts</directory> <files> net_rim_contacts.cod net_rim_resource.cod net_rim_resource en.cod net_rim_resource fr.cod </files> </fileset> </application> </loader> 158 BlackBerry Java Development Environment

159 Deploying applications The following table describes each element (tag) and attribute. All elements are mandatory unless otherwise noted. Element Attributes Description loader version The loader element contains one or more application elements. The version attribute specifies the version of the Application Loader. The version in this release is 1.0. application id The application element contains the elements for a single application. The application element can also contain additional nested application elements. Nesting enables you to ensure that when a specific application is loaded, its prerequisite modules are also loaded. The id attribute specifies a unique identifier for the application. You should use an ID that includes your company domain, in reverse, to ensure uniqueness (for example, com.rim.samples.device.contacts). name The name element provides a descriptive name for the application, which appears in the Application Loader. It does not appear on the handheld. description The description element provides a brief description of the application, which appears in the Application Loader. It does not appear on the handheld. version The version element provides the version number of the application. This version number appears in the Application Loader. vendor The vendor element provides the name of the company that created the application. The vendor name appears in the Application Loader. copyright The copyright element provides copyright information, which appears in the Application Loader. Developer Guide 159

160 Chapter 12: Deploying applications Element Attributes Description language langid The language tag enables you to specify additional languages for application information that appears in the desktop loader when the desktop language is other than the default language. You can nest the name, description, version, vendor, and copyright tags in the language tag. You can specify multiple language tags, one for each language that you want to support. The langid attribute specifies the Win32 langid code for the language to which this information applies. For example, some Win32 langid codes are: 0x0009 (English), 0x0007 (German), 0x000a (Spanish), 0x000c (French). fileset Java model The fileset element includes one directory element and one files element. It specifies a set of.cod files, in a single directory, to load onto the handheld. If you need to load files from more than one directory, you can include one or more fileset elements in the.alx file. The Java attribute specifies the minimum version of the BlackBerry Java virtual machine (VM) with which the.cod files are compatible. The current VM is version 1.0. The Java attribute is required. The model attribute enables you to load different applications or modules depending on the type of handheld. The model attribute is optional. directory The directory element provides the location of a set of files. The directory element is optional. If you do not specify a directory, then the files must be in the same location as the.alx file. You can specify a directory element for an application or for each fileset. The directory is specified relative to the location of the.alx file. files The files element provides a list of one or more.cod files, in a single directory, to load onto the handheld for an application. 160 BlackBerry Java Development Environment

161 Chapter 13 Converting MIDlets This chapter explains how to convert existing MIDlets into BlackBerry applications. To convert MIDlets The IDE enables you to convert MIDlet.jad and.jar files into the.cod file format supported by the BlackBerry environment. 1. In the IDE, open a workspace or create a new workspace. 2. Create a new project for the MIDlet application. The IDE project name must match the MIDlet-Name attribute in the.jad file and.jar manifest. 3. Add the MIDlet.jad and.jar files to the project. 4. Right-click the project file and click Activate Project to make the project active. 5. Right-click the project file and click Properties In the properties window, click the General tab and perform the following tasks: Set Project type to MIDlet. In Version, type a version number. This number must match the MIDlet-Version attribute in the.jad file and.jar manifest. In Vendor, type a vendor name. This name must match the MIDlet-Vendor attribute in the.jad file and.jar manifest. 7. In the properties window, click the Application tab. In Name of main MIDlet class, type the fully qualified name of the MIDlet s main class, such as com.company.demos.midletdemo. This entry must match the class specified by the MIDlet-<n> attribute in the.jar manifest.

162 Chapter 13: Converting MIDlets 8. Click OK to save the project properties. 9. On the Build menu, click Build to build the project. The IDE generates the necessary.cod files. You can now load the.cod files onto a BlackBerry Wireless Handheld. Refer to "Deploying applications" on page 155 for more information. 162 BlackBerry Java Development Environment

163 Index A activate() method, 149 adding icon graphics to a project, 36 project to a workspace, 35 resource files, 66 source files to a project, 32 alx files, 157 APIs reference documentation, 12 run-time, 10 application development Java environment, 23 process, 24 application manager, 19 architecture of BlackBerry user interface, 19 B BlackBerry JDE about, 9 APIs, 10 installing, 10 Java environment, 23 system requirements, 10 breakpoints adding, 44 removing, 44 using, 43 build configurations, 38 building projects build configurations, 38 generating a makefile, 38 removing builds, 38 sample application, 15 setting active projects, 32 setting project dependencies, 36 C call stack, 50 CLDC, 7 cleaning, See removing cod files, 23 compiling, See building context menus, 77 Creating, 158 creating custom fields, 133 projects, 30 source files, 32 workspace, 31 D debugging about, 39 breakpoints, 43 finding memory leaks in loops, 60 pausing, 40 restarting, 40 starting, 39 stopping, 40 viewing call stack, 50 viewing memory statistics, 58 viewing objects in memory, 58 viewing processes, 51 viewing threads, 48 watches, 46 deploying applications alx files, 158 obfuscation, 157 using the application loader, 157 docking windows, 45 E editing source code, 29 source files, 32 Enumeration class, 151 erasing simulator file system, 41 examples BaseApp.java, 95 CustomButtonField.java, 139 HelloWorld.java, 81 HelloWorld.java (with internationalization), 87 Developer Guide 163

164 Index F HTTPDemo.java, 113 HTTPPushDemo.java, 127 fields, 133 files.alx files, 158.cod files, 23.jad files, 23.jar files, 23.rrc files, 65.rrh files, 65 G getclass() method, 150 H HTTP handheld security, 132 receiving pushed data, 123 requesting data, 100 I IDE about, 10 active projects, 32 adding projects to workspace, 35 building projects, 38 debugging, 45 installing, 11 memory statistics, 58 preferences, 25, 33 project dependencies, 36 project properties, 32 projects, 30 resources, 63 sample workspace, 13 simulator, 16 starting, 12 text editor, 29 workspace, 25 workspace files view, 26 workspace packages view, 28 installing, 10 integrated development environment See IDE IPPP, 99 J J2ME, 7 jad files, 23 jar files, 23 JavaLoader, See loading applications jdp files, 30 jdw files, 30 K keyboard listener, 80 L listeners, 20 registering, 80 loading applications, 155 localization See resources localization, See resources M MainScreen class, 80 makefile, 38 memory finding leaks in loops, 60 viewing objects in memory, 58 MenuItem class, 76, 86 menus initializing menu items, 80, 85 programming, 77 MIDlets converting, 161 MIDP, 7 O obfuscation, 157 objects tool, 58 P processes viewing, 51 programming access modifiers, 145 activate() method, 149 adding application titles, 80, 86 adding text fields, 80, 86 application menus, 77 casting, 153 code libraries, 147 creating custom fields, 133 division operations, 152 Enumeration, 151 evaluating Boolean conditions, 146 event dispatch thread, 149 event lock, BlackBerry Java Development Environment

165 Index exiting applications, 81, 86, 150 fetching a web page, 106 final classes, 147 garbage collection, 152 guidelines, 145 HTML parsing, 107 HTTP connections, 123 identifiers, 153 inner classes, 146 listeners, 80 loops, 150 menu selection, 78 Object.getClass() method, 150 parsing HTML data, 107 popping screens, 148 pushing screens, 81, 148 receiving pushed HTTP data, 123 returning null, 151 static strings, 147 subexpressions, 151 threads, 110, 148 time, 154 time zones, 154 tips, 145 UiApplication class, 76 user interaction, 78 using interfaces, 146 projects activating, 35 adding icon files, 36 adding to workspace, 35 building, 38 dependencies, 36 making active, 32 properties, 32, 71 R references API documentation, 12 CLDC, 7 J2ME, 7 MIDP, 7 RIM documentation, 8 RIM web site, 8 removing builds, 38 ResourceBundle class, 85 resources adding, 66, 68 application title, 71 deleting, 70 editing, 68 inheritance, 66 initialization file, 65 ResourceBundle class, 85 rrc file, 65 rrh file, 65 rrc files, 65 rrh files, 65 run() method, 124 running, See debugging S simulator erasing file system, 41 ESCAPE key, 17 keyboard, 17 options, 41 trackwheel, 16 using, 16 source files editing, 32 starting BlackBerry Mobile Data Service simulator, 12 debugging, 39 IDE, 12 stopping debugging, 40 system requirements, 10 T testing analyzing code coverage, 61 simulator, 41 See also debugging threads, 20, 48, 110 event dispatch thread, 149 event lock, 148 tips, 148 ticks, 154 time origin time, 154 ticks, 154 trackwheel listener, 80 U UiApplication, 76 user interface architecture, 19, 20 ContextMenu class, 77 Field class, 20 Manager class, 20 Screen class, 20 Developer Guide 165

166 Index V viewing, 46 breakpoints, 44 call stack, 50 coverage, 61 local variables, 47 memory statistics, 58 objects, 58 processes, 51 threads, 48 virtual machine about, 9 VM, See virtual machine W WAP, 99 watches, 46 workspace adding projects, 35 creating, BlackBerry Java Development Environment

167 Research In Motion Limited Produced in Canada

BlackBerry Wireless Handheld. Attachment Service Guide

BlackBerry Wireless Handheld. Attachment Service Guide BlackBerry Wireless Handheld Attachment Service Guide BlackBerry Wireless Handheld Attachment Service Guide Last modified: 21 October 2002 Part number: PDF-05531-005 At the time of publication, this documentation

More information

BlackBerry Handheld Tips and Tricks

BlackBerry Handheld Tips and Tricks Contents Handheld Reference... 1 Home screen... 2 Searching... 2 Clearing fields... 2 Navigating screens... 3 Typing... 3 Editing text... 3 Messages... 4 Attachments... 5 Phone... 5 Direct Connect... 6

More information

BlackBerry Wireless Handheld. User Guide

BlackBerry Wireless Handheld. User Guide BlackBerry Wireless Handheld User Guide User Guide BlackBerry 7750 Wireless Handheld : 800/1900 MHz CDMA Network Model Number: RAN21CN Last modified: 7 January 2004 Part number: PDF-04780-014 At the time

More information

BlackBerry Wireless Handheld Getting Started Guide

BlackBerry Wireless Handheld Getting Started Guide BlackBerry Wireless Handheld Getting Started Guide Phone button Open the phone screen Earpiece Headset jack USB port Notification LED Trackwheel Select or click an item Escape button Exit a screen Alt

More information

BlackBerry Wireless Handheld. User Guide

BlackBerry Wireless Handheld. User Guide BlackBerry Wireless Handheld User Guide BlackBerry 7230 Wireless Handheld User Guide 900/1800/1900 MHz GSM GPRS Networks Model Number: R6230GE Last modified: 12 May 2003 Part number: PDF-06312-006 At the

More information

BlackBerry Wireless Handheld. User Guide

BlackBerry Wireless Handheld. User Guide BlackBerry Wireless Handheld User Guide User Guide BlackBerry 7210 Wireless Handheld, BlackBerry 7230 Wireless Handheld and BlackBerry 7280 Wireless Handheld. BlackBerry 7210 : 900/1900 MHz GSM GPRS Networks

More information

Trend Micro Incorporated reserves the right to make changes to this document and to the products described herein without notice. Before installing and using the software, please review the readme files,

More information

BlackBerry Wireless Handheld Getting Started Guide

BlackBerry Wireless Handheld Getting Started Guide BlackBerry Wireless Handheld Getting Started Guide Phone button Open the phone screen Earpiece Headset jack USB port Notification LED Trackwheel Select or click an item Escape button Exit a screen Alt

More information

BlackBerry. 7100g. Tips and Tricks

BlackBerry. 7100g. Tips and Tricks BlackBerry TM 7100g Tips and Tricks TYPING (continued) Turn on NUM lock Turn off NUM lock To switch between SureType and multi-tap input methods in a text field Press Shift + Alt Press Alt Hold* NAVIGATING

More information

BlackBerry Wireless Handheld. User Guide

BlackBerry Wireless Handheld. User Guide BlackBerry Wireless Handheld User Guide User Guide BlackBerry 7730 Wireless Handheld and BlackBerry 7780 Wireless Handheld. BlackBerry 7730 : 900/1800/1900 MHz GSM GPRS Networks BlackBerry 7780 : 850/1800/1900

More information

BlackBerry Wireless Handheld. User Guide

BlackBerry Wireless Handheld. User Guide BlackBerry Wireless Handheld User Guide User Guide BlackBerry 7210 Wireless Handheld, BlackBerry 7230 Wireless Handheld and BlackBerry 7280 Wireless Handheld. BlackBerry 7210 : 900/1900 MHz GSM GPRS Networks

More information

BlackBerry Enterprise Server for Lotus Domino 2.1 Service Pack 1 Readme file

BlackBerry Enterprise Server for Lotus Domino 2.1 Service Pack 1 Readme file BlackBerry Enterprise Server for Lotus Domino 2.1 Service Pack 1 Readme file PLEASE READ THE LEGAL NOTICES SET OUT AT THE END OF THIS DOCUMENT. This document provides information about BlackBerry Enterprise

More information

BlackBerry Wireless Handheld Getting Started Guide

BlackBerry Wireless Handheld Getting Started Guide BlackBerry Wireless Handheld Getting Started Guide Headset jack Earpiece Notification LED Phone button Open the phone screen Trackwheel Select or click an item Escape button Exit a screen Alt key Type

More information

Top Producer SellPhone Quick Setup

Top Producer SellPhone Quick Setup Top Producer SellPhone Quick Setup Top Producer Systems Phone number: 1.800.830.8300 Email: support@topproducer.com www.topproducer.com Fax: 604.270.6365 Top Producer SellPhone Quick Setup Information

More information

STOP READ THIS FIRST. Creating Your BlackBerry Account Guide

STOP READ THIS FIRST. Creating Your BlackBerry  Account Guide STOP READ THIS FIRST Creating Your BlackBerry E-Mail Account Guide Welcome to your BlackBerry handheld set-up. Follow these next few steps to create your BlackBerry Web Client account. Once completed,

More information

BlackBerry Enterprise Server for Lotus Domino 2.0 Service Pack 5 Readme file

BlackBerry Enterprise Server for Lotus Domino 2.0 Service Pack 5 Readme file BlackBerry Enterprise Server for Lotus Domino 2.0 Service Pack 5 Readme file PLEASE READ THE LEGAL NOTICES SET OUT AT THE END OF THIS DOCUMENT. This document provides information about BlackBerry Enterprise

More information

User s Manual. Version September 2011 Impatica Inc.

User s Manual. Version September 2011 Impatica Inc. Version 1.1.7 September 2011 Impatica Inc. Legal Notice Copyright 2011 Impatica Inc. All rights reserved. The contents of this manual and associated Impatica software are the property of Impatica Inc.

More information

BlackBerry Wireless Handheld from Nextel. User Guide

BlackBerry Wireless Handheld from Nextel. User Guide BlackBerry Wireless Handheld from Nextel User Guide User Guide BlackBerry 7510 Wireless Handheld from Nextel. 800 MHz IDEN Networks Model Number: RAL10IN Last modified: 7 November 2003 Part number: PDF-06786-003

More information

Attachment Service. Installation and Getting Started Guide

Attachment Service. Installation and Getting Started Guide Attachment Service Installation and Getting Started Guide Attachment Service Installation and Getting Started Guide Last revised: 23 October 2002 Part number: PDF-05733-001 At the time of publication,

More information

Application Security for Java-based BlackBerry Handhelds

Application Security for Java-based BlackBerry Handhelds Application Security for Java-based Originally posted: February 2003 Latest revision: May 2003 Introduction Corporate data access capabilities supported by the BlackBerry platform enable wireless connectivity

More information

ActiveSpaces Transactions. Quick Start Guide. Software Release Published May 25, 2015

ActiveSpaces Transactions. Quick Start Guide. Software Release Published May 25, 2015 ActiveSpaces Transactions Quick Start Guide Software Release 2.5.0 Published May 25, 2015 Important Information SOME TIBCO SOFTWARE EMBEDS OR BUNDLES OTHER TIBCO SOFTWARE. USE OF SUCH EMBEDDED OR BUNDLED

More information

Computer Shortcut Keys

Computer Shortcut Keys Powered By Computer Shortcut Keys Let s kickstart the list with the most common shortcuts that you ll often use. F1 [Display Help] F2 [Rename the selected item] F3 [Search for a file or folder] F4 [Display

More information

Getting Started Tutorial - Eclipse Edition. Sybase Unwired Platform 1.2

Getting Started Tutorial - Eclipse Edition. Sybase Unwired Platform 1.2 Getting Started Tutorial - Eclipse Edition Sybase Unwired Platform 1.2 DOCUMENT ID: DC01017-01-0120-01 LAST REVISED: March, 2009 Copyright 2009 by Sybase, Inc. All rights reserved. This publication pertains

More information

Getting Started. Microsoft QUICK Source 7

Getting Started. Microsoft QUICK Source 7 Microsoft QUICK Windows Source 7 Getting Started The Windows 7 Desktop u v w x u Icon links to a program, file, or folder that is stored on the desktop. v Shortcut Icon links to a program, file, or folder

More information

BlackBerry Wireless Handheld. User Guide

BlackBerry Wireless Handheld. User Guide BlackBerry Wireless Handheld User Guide User Guide, BlackBerry 7290 Wireless Handheld BlackBerry 7290 Wireless Handheld Model Number: RAP40GW Last modified: 13 September 2004 Part number: PDF-07783-001

More information

Series 40 6th Edition SDK, Feature Pack 1 Installation Guide

Series 40 6th Edition SDK, Feature Pack 1 Installation Guide F O R U M N O K I A Series 40 6th Edition SDK, Feature Pack 1 Installation Guide Version Final; December 2nd, 2010 Contents 1 Legal Notice...3 2 Series 40 6th Edition SDK, Feature Pack 1...4 3 About Series

More information

DS-5 ARM. Using Eclipse. Version Copyright ARM. All rights reserved. ARM DUI 0480L (ID100912)

DS-5 ARM. Using Eclipse. Version Copyright ARM. All rights reserved. ARM DUI 0480L (ID100912) ARM DS-5 Version 5.12 Using Eclipse Copyright 2010-2012 ARM. All rights reserved. ARM DUI 0480L () ARM DS-5 Using Eclipse Copyright 2010-2012 ARM. All rights reserved. Release Information The following

More information

Chapter 1: Introduction About the User Manual Intended Audience Conventions Used Revision History 4

Chapter 1: Introduction About the User Manual Intended Audience Conventions Used Revision History 4 CLINCK Speed Manager User Manual Contents Chapter 1: Introduction 3 1.1 About the User Manual 3 1.2 Intended Audience 3 1.3 Conventions Used 3 1.4 Revision History 4 1.5 Overview of the CLINCK Speed Manager

More information

BlackBerry Enterprise Server 2.1 Service Pack 5 Hotfix 1 for Microsoft Exchange Readme file

BlackBerry Enterprise Server 2.1 Service Pack 5 Hotfix 1 for Microsoft Exchange Readme file BlackBerry Enterprise Server 2.1 Service Pack 5 Hotfix 1 for Microsoft Exchange Readme file December 2002 PLEASE READ THE LEGAL NOTICES SET OUT AT THE END OF THIS DOCUMENT. This document provides late-breaking

More information

Attachment Service. Installation and Getting Started Guide

Attachment Service. Installation and Getting Started Guide Attachment Service Installation and Getting Started Guide Attachment Service Installation and Getting Started Guide Last revised: 23 October 2002 Part number: PDF-05356-001 At the time of publication,

More information

SQL Server. Management Studio. Chapter 3. In This Chapter. Management Studio. c Introduction to SQL Server

SQL Server. Management Studio. Chapter 3. In This Chapter. Management Studio. c Introduction to SQL Server Chapter 3 SQL Server Management Studio In This Chapter c Introduction to SQL Server Management Studio c Using SQL Server Management Studio with the Database Engine c Authoring Activities Using SQL Server

More information

BCI.com Sitecore Publishing Guide. November 2017

BCI.com Sitecore Publishing Guide. November 2017 BCI.com Sitecore Publishing Guide November 2017 Table of contents 3 Introduction 63 Search 4 Sitecore terms 66 Change your personal settings 5 Publishing basics 5 Log in to Sitecore Editing 69 BCI.com

More information

AutoCAD 2009 User InterfaceChapter1:

AutoCAD 2009 User InterfaceChapter1: AutoCAD 2009 User InterfaceChapter1: Chapter 1 The AutoCAD 2009 interface has been enhanced to make AutoCAD even easier to use, while making as much screen space available as possible. In this chapter,

More information

BlackBerry Enterprise Server for Microsoft Exchange

BlackBerry Enterprise Server for Microsoft Exchange BlackBerry Enterprise Server for Microsoft Exchange Version 3.5 Service Pack 1 Hotfix 2 December 2002 PLEASE READ THE LEGAL NOTICES SET OUT AT THE END OF THIS DOCUMENT. This document provides information

More information

OpenText RightFax 10.6

OpenText RightFax 10.6 OpenText RightFax 10.6 Connector for IBM Filenet Administrator Guide Edition OpenText RightFax 10.6 Connector for IBM Filenet. This document was last updated January 22, 2014. Trademarks OpenText is a

More information

Introduction. Key features and lab exercises to familiarize new users to the Visual environment

Introduction. Key features and lab exercises to familiarize new users to the Visual environment Introduction Key features and lab exercises to familiarize new users to the Visual environment January 1999 CONTENTS KEY FEATURES... 3 Statement Completion Options 3 Auto List Members 3 Auto Type Info

More information

Upgrading from Call Center Reporting to

Upgrading from Call Center Reporting to Upgrading from Call Center Reporting to Reporting for Call Center Upgrade Document Reporting for Call Center Release 2.2.1xx Document Number: 200-0400-110 Document Status: Standard Document Version: 3.02

More information

Bridgit Conferencing Software User s Guide. Version 3.0

Bridgit Conferencing Software User s Guide. Version 3.0 Bridgit Conferencing Software User s Guide Version 3.0 ii Table Of Contents Introducing Bridgit Conferencing Software... 1 System Requirements... 1 Getting Bridgit Conferencing Software... 2 The Bridgit

More information

CS520 Setting Up the Programming Environment for Windows Suresh Kalathur. For Windows users, download the Java8 SDK as shown below.

CS520 Setting Up the Programming Environment for Windows Suresh Kalathur. For Windows users, download the Java8 SDK as shown below. CS520 Setting Up the Programming Environment for Windows Suresh Kalathur 1. Java8 SDK Java8 SDK (Windows Users) For Windows users, download the Java8 SDK as shown below. The Java Development Kit (JDK)

More information

GoAmerica for RIM Wireless Handhelds

GoAmerica for RIM Wireless Handhelds GoAmerica for RIM Wireless Handhelds User s Guide GoAmerica for RIM Wireless Handhelds TM Contents WELCOME TO GO.WEB TM........................................... 4 RIM WIRELESS HANDHELD..........................................

More information

BlackBerry Java Development Environment (JDE)

BlackBerry Java Development Environment (JDE) 1 BlackBerry Java Applications for Accessing SAP Applications BlackBerry Java Development Environment The BlackBerry Java Development Environment (JDE) is a fully integrated development and simulation

More information

Last Updated: October 12, Learning Ally ReadHear by gh for PC, Quick Start Guide

Last Updated: October 12, Learning Ally ReadHear by gh for PC, Quick Start Guide Learning Ally ReadHear by gh for PC Quick Start Guide Last Updated: October 12, 2012 1 Page Table of Contents Introduction...3 What is Learning Ally ReadHear?...3 Overview...3 Minimum PC System Requirements...3

More information

BlackBerry Desktop Software Version 4.0 Service Pack 1 Release Notes

BlackBerry Desktop Software Version 4.0 Service Pack 1 Release Notes BlackBerry Desktop Software Version 4.0 Service Pack 1 Release Notes BlackBerry Desktop Software Version 4.0 Service Pack 1 2 of 9 NOTE This document is provided for informational purposes only, and does

More information

USER GUIDE MADCAP CAPTURE 7. Getting Started

USER GUIDE MADCAP CAPTURE 7. Getting Started USER GUIDE MADCAP CAPTURE 7 Getting Started Copyright 2018 MadCap Software. All rights reserved. Information in this document is subject to change without notice. The software described in this document

More information

StudioPrompter Tutorials. Prepare before you start the Tutorials. Opening and importing text files. Using the Control Bar. Using Dual Monitors

StudioPrompter Tutorials. Prepare before you start the Tutorials. Opening and importing text files. Using the Control Bar. Using Dual Monitors StudioPrompter Tutorials Prepare before you start the Tutorials Opening and importing text files Using the Control Bar Using Dual Monitors Using Speed Controls Using Alternate Files Using Text Markers

More information

BlackBerry Wireless Handheld. User Guide

BlackBerry Wireless Handheld. User Guide BlackBerry Wireless Handheld User Guide User Guide, BlackBerry 7520 Wireless Handheld BlackBerry 7520 Wireless Handheld Model Number: RAL11IN Last modified: 12 October 2004 Part number: SWD_X_HH(EN)-007.000

More information

1 Ctrl + X Cut the selected item. 2 Ctrl + C (or Ctrl + Insert) Copy the selected item. 3 Ctrl + V (or Shift + Insert) Paste the selected item

1 Ctrl + X Cut the selected item. 2 Ctrl + C (or Ctrl + Insert) Copy the selected item. 3 Ctrl + V (or Shift + Insert) Paste the selected item Tips and Tricks Recorder Actions Library XPath Syntax Hotkeys Windows Hotkeys General Keyboard Shortcuts Windows Explorer Shortcuts Command Prompt Shortcuts Dialog Box Keyboard Shortcuts Excel Hotkeys

More information

Switch between open apps Close the active item, or exit the active app

Switch between open apps Close the active item, or exit the active app Ctrl + X Ctrl + C (or Ctrl + Insert) Ctrl + V (or Shift + Insert) Ctrl + Z Alt + Tab Alt + F4 L D F2 F3 F4 F5 F6 F10 Alt + F8 Alt + Esc Alt + underlined letter Alt + Enter Alt + Spacebar Alt + Left arrow

More information

OPTOTERMINAL QLARITY FOUNDRY USER'S MANUAL REVISION 2.5

OPTOTERMINAL QLARITY FOUNDRY USER'S MANUAL REVISION 2.5 OPTOTERMINAL QLARITY FOUNDRY USER'S MANUAL REVISION 2.5 Opto 22 43044 Business Park Drive Temecula, CA 92590-3614 USA Phone 800.321.OPTO (6786) or 951.695.3000 Fax 800.832OPTO (6786) or 951.695.2712 Email:

More information

NiceForm User Guide. English Edition. Rev Euro Plus d.o.o. & Niceware International LLC All rights reserved.

NiceForm User Guide. English Edition. Rev Euro Plus d.o.o. & Niceware International LLC All rights reserved. www.nicelabel.com, info@nicelabel.com English Edition Rev-0910 2009 Euro Plus d.o.o. & Niceware International LLC All rights reserved. www.nicelabel.com Head Office Euro Plus d.o.o. Ulica Lojzeta Hrovata

More information

USER GUIDE. CTERA Agent for Windows. June 2016 Version 5.5

USER GUIDE. CTERA Agent for Windows. June 2016 Version 5.5 USER GUIDE CTERA Agent for Windows June 2016 Version 5.5 Copyright 2009-2016 CTERA Networks Ltd. All rights reserved. No part of this document may be reproduced in any form or by any means without written

More information

User s Guide. Creative Desktop Wireless 8000

User s Guide. Creative Desktop Wireless 8000 User s Guide Creative Desktop Wireless 8000 Information in this document is subject to change without notice and does not represent a commitment on the part of Creative Technology Ltd. No part of this

More information

Client Installation and User's Guide

Client Installation and User's Guide IBM Tivoli Storage Manager FastBack for Workstations Version 7.1 Client Installation and User's Guide SC27-2809-03 IBM Tivoli Storage Manager FastBack for Workstations Version 7.1 Client Installation

More information

Installing AppleWorks 6 FOR WINDOWS

Installing AppleWorks 6 FOR WINDOWS apple Installing AppleWorks 6 FOR WINDOWS 1 Installing AppleWorks 6 This booklet provides instructions for m installing and uninstalling AppleWorks m setting up an AppleWorks Installer on a server, so

More information

dbdos PRO 2 Quick Start Guide dbase, LLC 2013 All rights reserved.

dbdos PRO 2 Quick Start Guide dbase, LLC 2013 All rights reserved. dbdos PRO 2 Quick Start Guide 1 dbase, LLC 2013 All rights reserved. dbase, LLC may have patents and/or pending patent applications covering subject matter in this document. The furnishing of this document

More information

Work Smart: Windows 7 New Features

Work Smart: Windows 7 New Features About Windows 7 New Features The Windows 7 operating system offers several new features to help you work faster and more efficiently, and enable you to access the files, folders, programs, and applications

More information

icms Pro USER s MANUAL Ver 1.0

icms Pro USER s MANUAL Ver 1.0 icms Pro USER s MANUAL Ver 1.0 Contents Target Audience for this Document... 5 Copyright, Trademarks and Important Information... 5 Copyright... 5 Disclaimer... 5 Introduction... 6 Tabs... 6 Panes... 7

More information

User s Guide. Creative Desktop Wireless 9000 Pro

User s Guide. Creative Desktop Wireless 9000 Pro User s Guide Creative Desktop Wireless 9000 Pro Information in this document is subject to change without notice and does not represent a commitment on the part of Creative Technology Ltd. No part of this

More information

Silk Performance Manager Installation and Setup Help

Silk Performance Manager Installation and Setup Help Silk Performance Manager 18.5 Installation and Setup Help Micro Focus The Lawn 22-30 Old Bath Road Newbury, Berkshire RG14 1QN UK http://www.microfocus.com Copyright 2004-2017 Micro Focus. All rights reserved.

More information

Module 3: Working with C/C++

Module 3: Working with C/C++ Module 3: Working with C/C++ Objective Learn basic Eclipse concepts: Perspectives, Views, Learn how to use Eclipse to manage a remote project Learn how to use Eclipse to develop C programs Learn how to

More information

WINDOWS NT BASICS

WINDOWS NT BASICS WINDOWS NT BASICS 9.30.99 Windows NT Basics ABOUT UNIVERSITY TECHNOLOGY TRAINING CENTER The University Technology Training Center (UTTC) provides computer training services with a focus on helping University

More information

Menu Symbols. Menu Symbol. Key on Keyboard

Menu Symbols. Menu Symbol. Key on Keyboard Menu Symbols Menu Symbol Key on Keyboard Command/Apple Key (like Control on a PC) Also written as Cmd Option (like Alt on a PC) Shift Control (Control-click = Right-click) Tab Return Enter (on Number Pad)

More information

Supplement H.1: JBuilder X Tutorial. For Introduction to Java Programming, 5E By Y. Daniel Liang

Supplement H.1: JBuilder X Tutorial. For Introduction to Java Programming, 5E By Y. Daniel Liang Supplement H.1: JBuilder X Tutorial For Introduction to Java Programming, 5E By Y. Daniel Liang This supplement covers the following topics: Getting Started with JBuilder Creating a Project Creating, Compiling,

More information

BlackBerry Java Application UI and Navigation Version: 5.0. Development Guide

BlackBerry Java Application UI and Navigation Version: 5.0. Development Guide BlackBerry Java Application UI and Navigation Version: 5.0 Development Guide Published: 2010-08-20 SWD-810476-0820021303-001 Contents 1 Creating a UI that is consistent with standard BlackBerry UIs...

More information

Supplement II.B(1): JBuilder X Tutorial. For Introduction to Java Programming By Y. Daniel Liang

Supplement II.B(1): JBuilder X Tutorial. For Introduction to Java Programming By Y. Daniel Liang Supplement II.B(1): JBuilder X Tutorial For Introduction to Java Programming By Y. Daniel Liang This supplement covers the following topics: Getting Started with JBuilder Creating a Project Creating, Compiling,

More information

Enterprise Architect. User Guide Series. Tutorial. Author: Sparx Systems. Date: 26/07/2018. Version: 1.0 CREATED WITH

Enterprise Architect. User Guide Series. Tutorial. Author: Sparx Systems. Date: 26/07/2018. Version: 1.0 CREATED WITH Enterprise Architect User Guide Series Tutorial Author: Sparx Systems Date: 26/07/2018 Version: 1.0 CREATED WITH Table of Contents Tutorial 3 Startup 4 Create a Project 5 Add a View to your Model 6 Add

More information

Adlib PDF FileNet Connector Guide PRODUCT VERSION: 5.1

Adlib PDF FileNet Connector Guide PRODUCT VERSION: 5.1 Adlib PDF FileNet Connector Guide PRODUCT VERSION: 5.1 REVISION DATE: January 2014 Copyright 2014 Adlib This manual, and the Adlib products to which it refers, is furnished under license and may be used

More information

A Guide to Quark Author Web Edition 2015

A Guide to Quark Author Web Edition 2015 A Guide to Quark Author Web Edition 2015 CONTENTS Contents Getting Started...4 About Quark Author - Web Edition...4 Smart documents...4 Introduction to the Quark Author - Web Edition User Guide...4 Quark

More information

TECH-NOTE. The Keyboard Macro Editor. The Keyboard Macro Editor Dialog Box

TECH-NOTE. The Keyboard Macro Editor. The Keyboard Macro Editor Dialog Box The Keyboard Macro Editor The Keyboard Macro Editor is a feature in the Designer TM for Windows TM software package that allows the user to associate specific functions with keys or touchcells on a UniOP

More information

ChemSense Studio Client Version 3.0.7

ChemSense Studio Client Version 3.0.7 Quick Start Guide: ChemSense Studio Client Version 3.0.7 January 5, 2005 Comments/Questions/Bug Report? E-mail: chemsense-contact@ctl.sri.com Background The ChemSense Studio Client software supports the

More information

Using Eclipse for Java. Using Eclipse for Java 1 / 1

Using Eclipse for Java. Using Eclipse for Java 1 / 1 Using Eclipse for Java Using Eclipse for Java 1 / 1 Using Eclipse IDE for Java Development Download the latest version of Eclipse (Eclipse for Java Developers or the Standard version) from the website:

More information

Enterprise Architect. User Guide Series. Tutorial

Enterprise Architect. User Guide Series. Tutorial Enterprise Architect User Guide Series Tutorial How do I build a model in Enterprise Architect? Follow this tutorial to build a simple model in a Firebird Repository, using Enterprise Architect. Author:

More information

IBM(R) Lotus(R) Domino(R) Document Manager 7.0 Desktop Enabler Release Notes September 18, 2009

IBM(R) Lotus(R) Domino(R) Document Manager 7.0 Desktop Enabler Release Notes September 18, 2009 IBM(R) Lotus(R) Domino(R) Document Manager 7.0 Desktop Enabler Release Notes September 18, 2009 1. Table of Contents 1. Table of Contents 2. Introduction 3. What's New? 4. System Requirements 5. Installing

More information

User Guide. BlackBerry Workspaces for Windows. Version 5.5

User Guide. BlackBerry Workspaces for Windows. Version 5.5 User Guide BlackBerry Workspaces for Windows Version 5.5 Published: 2017-03-30 SWD-20170330110027321 Contents Introducing BlackBerry Workspaces for Windows... 6 Getting Started... 7 Setting up and installing

More information

Multi-NVR Manager. Quick Start Configuration Usage

Multi-NVR Manager. Quick Start Configuration Usage Multi-NVR Manager Quick Start Configuration Usage 2014. All rights are reserved. No portion of this document may be reproduced without permission. All trademarks and brand names mentioned in this publication

More information

Avalanche Remote Control User Guide. Version 4.1

Avalanche Remote Control User Guide. Version 4.1 Avalanche Remote Control User Guide Version 4.1 ii Copyright 2012 by Wavelink Corporation. All rights reserved. Wavelink Corporation 10808 South River Front Parkway, Suite 200 South Jordan, Utah 84095

More information

CRYPTOCard BlackBerry Token Implementation Guide

CRYPTOCard BlackBerry Token Implementation Guide CRYPTOCard BlackBerry Token Implementation Guide Copyright Copyright 2007 CRYPTOCard Corp. All Rights Reserved. No part of this publication may be reproduced, transmitted, transcribed, stored in a retrieval

More information

Software User s Manual

Software User s Manual 1 About the manual 2 Navigating the manual 2 3 Opening the control panel 3 Control panel overview 4 Control panel settings 5 Calibrating the interactive pen display 6 Adjusting frequency and tracking (VGA

More information

Setting Up Your BlackBerry 8703e TM, Powered by Sprint PCS

Setting Up Your BlackBerry 8703e TM, Powered by Sprint PCS Setting Up Your BlackBerry 8703e TM, Powered by Sprint PCS 2006 Sprint Nextel. All rights reserved. SPRINT, the Going Forward logo, and other trademarks are trademarks of Sprint Nextel. The BlackBerry

More information

BlackBerry Software Development Kit

BlackBerry Software Development Kit BlackBerry Software Development Kit Version 2.5 Radio API Reference Guide (DataTAC) BlackBerry Software Development Kit Version 2.5 Radio API Reference Guide Last modified: 12 June 2002 Part number: PDF-04639-001

More information

Reporting for Contact Center Setup and Operations Guide. BCM Contact Center

Reporting for Contact Center Setup and Operations Guide. BCM Contact Center Reporting for Contact Center Setup and Operations Guide BCM Contact Center Document Number: Document Status: Standard Document Version: 05.01 Date: September 2006 Copyright 2005 2006 Nortel Networks, All

More information

Agent and Agent Browser. Updated Friday, January 26, Autotask Corporation

Agent and Agent Browser. Updated Friday, January 26, Autotask Corporation Agent and Agent Browser Updated Friday, January 26, 2018 2018 Autotask Corporation Table of Contents Table of Contents 2 The AEM Agent and Agent Browser 3 AEM Agent 5 Privacy Mode 9 Agent Browser 11 Agent

More information

Module Road Map. 7. Version Control with Subversion Introduction Terminology

Module Road Map. 7. Version Control with Subversion Introduction Terminology Module Road Map 1. Overview 2. Installing and Running 3. Building and Running Java Classes 4. Refactoring 5. Debugging 6. Testing with JUnit 7. Version Control with Subversion Introduction Terminology

More information

Palm Reader Handbook

Palm Reader Handbook Palm Reader Handbook Copyright 2000-2002 Palm, Inc. All rights reserved. Graffiti, HotSync, the Palm logo, and Palm OS are registered trademarks of Palm, Inc. The HotSync logo and Palm are trademarks of

More information

DesignPro Tools for Xerox Elixir Technologies Corporation. All rights reserved.

DesignPro Tools for Xerox Elixir Technologies Corporation. All rights reserved. Follow the Crop Marks DesignPro Tools for Xerox Getting Started Guide C 1998-2008 Elixir Technologies Corporation. All rights reserved. Elixir Technologies Corporation 721 East Main Street Ventura, CA

More information

Client Installation and User's Guide

Client Installation and User's Guide IBM Tivoli Storage Manager FastBack for Workstations Version 7.1.1 Client Installation and User's Guide SC27-2809-04 IBM Tivoli Storage Manager FastBack for Workstations Version 7.1.1 Client Installation

More information

Relativity Designer Installation Guide

Relativity Designer Installation Guide Liant Software Corporation Relativity Designer Installation Guide Version 5 Copyright 1994-2003 by Liant Software Corporation. All rights reserved. Printed in U.S.A. No part of this publication may be

More information

BlackBerry 7100v from Vodafone Installation Guide

BlackBerry 7100v from Vodafone Installation Guide BlackBerry 7100v from Vodafone Installation Guide Contents Contents 2 Introduction 3 BlackBerry Enterprise Solution 3 Using your BlackBerry 7100v Handheld 3 Installing the BlackBerry Desktop Manager 3

More information

Datacard XPS Card Printer Driver Guide

Datacard XPS Card Printer Driver Guide Datacard XPS Card Printer Driver Guide November 2012 Part No. 527280-001 Rev. B Notice This publication and the accompanying software are proprietary to DataCard Corporation and are protected by U.S. patent

More information

Local deployment consists of locally storing the IT Policy file on each user s workstation.

Local deployment consists of locally storing the IT Policy file on each user s workstation. Implementing the IT Policy Manager for Originally posted: March 2002 Summary The IT policy manager enables you to define and restrict the settings for users desktop software. It enables you to provide

More information

GRS Enterprise Synchronization Tool

GRS Enterprise Synchronization Tool GRS Enterprise Synchronization Tool Last Revised: Thursday, April 05, 2018 Page i TABLE OF CONTENTS Anchor End User Guide... Error! Bookmark not defined. Last Revised: Monday, March 12, 2018... 1 Table

More information

Parallels Remote Application Server

Parallels Remote Application Server Parallels Remote Application Server Parallels Client for Mac User's Guide v16 Parallels International GmbH Vordergasse 59 8200 Schaffhausen Switzerland Tel: + 41 52 672 20 30 www.parallels.com Copyright

More information

Software Instruction Manual

Software Instruction Manual 2 About This Manual This manual will provide a comprehensive look at the JAVS software application. The first part of the manual will provide a general overview followed by a more detailed approach in

More information

FileWay User s Guide. Version 3

FileWay User s Guide. Version 3 FileWay User s Guide Version 3 Copyright (c) 2003-2008 Everywhere Networks Corporation, All rights reserved. Complying with all applicable copyright laws is the responsibility of the user. Without limiting

More information

Enterprise Architect. User Guide Series. Portals. Author: Sparx Systems. Date: 19/03/2018. Version: 1.0 CREATED WITH

Enterprise Architect. User Guide Series. Portals. Author: Sparx Systems. Date: 19/03/2018. Version: 1.0 CREATED WITH Enterprise Architect User Guide Series Portals Author: Sparx Systems Date: 19/03/2018 Version: 1.0 CREATED WITH Table of Contents Portals 3 Perspective Portal 6 Workspace Portal 7 Window Portal 9 Status

More information

Network Management Utility

Network Management Utility 4343-7705-02 Network Management Utility Foreword Welcome Network Management Utility is utility software that provides central control over printers, copiers, and other devices on a network. With Network

More information

DSS User Guide. End User Guide. - i -

DSS User Guide. End User Guide. - i - DSS User Guide End User Guide - i - DSS User Guide Table of Contents End User Guide... 1 Table of Contents... 2 Part 1: Getting Started... 1 How to Log in to the Web Portal... 1 How to Manage Account Settings...

More information

Getting Started (1.8.7) 9/2/2009

Getting Started (1.8.7) 9/2/2009 2 Getting Started For the examples in this section, Microsoft Windows and Java will be used. However, much of the information applies to other operating systems and supported languages for which you have

More information

IT Essentials v6.0 Windows 10 Software Labs

IT Essentials v6.0 Windows 10 Software Labs IT Essentials v6.0 Windows 10 Software Labs 5.2.1.7 Install Windows 10... 1 5.2.1.10 Check for Updates in Windows 10... 10 5.2.4.7 Create a Partition in Windows 10... 16 6.1.1.5 Task Manager in Windows

More information

User Guide. BlackBerry 8707 Series

User Guide. BlackBerry 8707 Series User Guide BlackBerry 8707 Series SWD-129381-0116055452-001 Contents BlackBerry basics... 9 Switch applications... 9 Assign an application to a Convenience key... 9 Set owner information... 9 About links...

More information