Journal in PDF Format

Journal in PDF Format
Volume 2, Issue 2
July 2005
BlackBerry Resources
An Introduction to BlackBerry Development
Information about developing BlackBerry device software from
an introductory perspective
How to Create a Desktop add-in Using
Microsoft Visual Basic 6.0
Step by step tutorial on writing a desktop add-in in Visual Basic!
.NET: A Simple C# Push Application
Jennifer’s cHTML language tutorial
Pimp My Object: Creating a TextBox Field
How to establish capabilities an application should have when
executing on a specific BlackBerry device
cHTML In Depth
Using the Phone Logs API to extract phone activity information
BlackBerry Application Control
Technical introduction to the BlackBerry graphical user interface
Logging Your Calls with the Phone API
How to build a simple travel request form using ASP .NET that
sends form data to specific BlackBerry devices as email
BlackBerry Graphical User Interface Part 1
How to push data from Microsoft Excel, Access and SQL Server
to BlackBerry devices
.NET : Building Mobile Web Forms for BlackBerry
Step by step guide to writing a push application in C#
.NET: Pushing Microsoft Excel, Access or
SQL Server Data Using Multiple Interfaces
“Like Doctor Frankenstein, we will take elements from objects
and combine them into something that has a life of its own”
“The best way to predict the future is to invent it.” - Alan Kay (1971)
Larry Downes and Chunka Mui defined a ‘killer app’ as a “new good or service that single-handedly
rewrites the rules of an entire industry or a set of industries.” The tremendous changes through the ages,
and more specifically, over the past few decades, can be directly attributed to killer apps.
The transistor is a killer app that changed the world and blazed a path for the development of a constant
stream of killer apps. Microcomputers are killer apps that devastated the mainframe-centered business
model and changed the world in countless ways. VisiCalc, Adobe® PageMaker®, Mosaic™, the Internet, electronic mail and the BlackBerry® wireless solution are all killer apps that have greatly changed
the world.
Technological killer apps tend to follow Moore's Law, Metcalfe's Law, and a combination of both called
the Law of Disruption.
In its current form, Moore's Law states that processing power doubles every 18 months while cost holds
constant. This pattern has held true for decades, and applies to several areas of technology including telecom bandwidth. A few people have gone on record stating that this pace cannot be sustained over the
long haul because of power consumption and related heat dissipation. If so, then we will have to make do
with computers that are many times more powerful than anything we currently use.
Metcalfe's Law states that new technologies are valuable only if many people use them. The usefulness or
utility of a network equals the square of the number of users. Increased use accelerates the speed of adoption, which leads to a technological “critical mass.”
The Law of Disruption can be thought of as “atoms to bits” and is the second-order effect of killer apps in
the digital age. This law can be “faulted” for the sudden and dramatic disruption of social, political and
economic systems worldwide in that those systems change incrementally while technology changes
exponentially. In general terms, systems that make up human civilization tend to change slowly over time
on an incremental basis, whereas technological change follows Metcalfe's Law and is rapid. As the rate of
technological change increases relative to social rates of change, the incidence of killer apps increases.
We strongly believe that BlackBerry, a killer app in its own right, will indirectly spawn countless killer
apps over time. Take advantage of this unique opportunity to invent a future of your choosing.
As always we are interested in your comments, suggestions, letters, and anything else that you feel would
be of benefit to our developer community.
Please feel free to email us at [email protected]
BlackBerry Developer Journal team
BlackBerry Developer Journal
Volume 2, Issue 2
BlackBerry Resources
The following are third-party sites that BlackBerry developers may find beneficial in their eternal search for information, software, source code, reviews, and sage advice from like-minded souls. Please feel free to drop us a line at [email protected] if you would like us to consider the inclusion of your site in this column.
“Mobile PC Guide to BlackBerry” Book
by Bill Foust
ISBN: 0789733439
Paperback: 240 pages
Publisher: Que (May 17, 2005)
“Professional BlackBerry” Book
by Craig J. Johnston, Richard Evers
ISBN: 0-7645-8953-9
Paperback: 336 pages
Publisher: Wiley (July 2005)
Please Note: This information may contain references to third-party sources of information, applications and/or third-party
web sites (“Third-Party Information”). Research In Motion (RIM) does not control, and is not responsible for, any Third-Party Information, including, without limitation, the content, accuracy, copyright compliance, legality, decency, links, compatibility of the Third-Party Information with RIM products or any other aspect of Third-Party Information.
Volume 2, Issue 2
BlackBerry Developer Journal
An Introduction to BlackBerry Development
Richard Evers, Editor
Developing software for the BlackBerry® device is an
exciting area of development. Although it can be relatively
simple, the task can also be daunting depending on your
organization's requirements, technical talents, resources and
mindset. In this article we will explore the basics of enterprise solutions on the BlackBerry device.
communicating with remote databases is fairly straightforward
Although developing web based applications for Blackberry
devices can be relatively easy, there are two main drawbacks.
The first is connectivity where users will not be able to
access your web site when they are out of a wireless coverage area. This can occur when users are situated in network
A difficulty many people encounter is in visualizing how to
create a useful solution for a wireless device. With desktop-based solutions reigning supreme for so long, it’s often
hard to visualize creating something useful for a device with
a tiny screen, limited memory, and a relatively slow pipe to
the outside world.
To understand a “dead zone” let's explore how radio waves
As you know, some of the more popular desktop applications are web browsers, email clients, word processors, spell
checkers, text editors, calendar tools, spreadsheet applications, presentation tools, document viewers, music players,
instant messaging solutions, Customer Relationship Management (CRM) clients and Enterprise Resource Planning
(ERP) clients.
Radio waves travel easily through air, and fully penetrate
transparent materials such as windows, but are absorbed by
opaque materials such as concrete, and are reflected by shiny
material such as metal.
Network “nodes” must be located fairly close together to
allow for uninterrupted connectivity. Nodes may not fully
saturate remote regions causing network difficulties when
traveling in these regions.
Research In Motion® (RIM®) has created several of the
core solutions for the BlackBerry device, and third-party
developers have created, or are creating, many others. Over
time, most desktop functionality will be experienced on the
BlackBerry device, with the added bonus of wireless connectivity for features such as email, browser, calendar and
phone access, active throughout the world without reliance
on power cords or wired network hookups.
In high-density areas such as major cities, nodes are placed
fairly close together to compensate for the increased volume
of wireless activity. A network “dead zone” can occur in
high-traffic areas if wireless traffic exceeds the capability of
the network at any time.
If your users need constant access to your web site, consider
writing a “push” application to regularly update each user’s
Three Ways ...
There are three ways to create solutions for BlackBerry
Create a web site to be accessed using the BlackBerry
Develop a server-based application that “pushes” content such as a web page and images, or data in general,
to the BlackBerry device.
Write a software application that operates on the BlackBerry device and, possibly, also on a remote server
The second drawback is the speed of the wireless network.
The networks used by wireless devices, such as the BlackBerry device, are slow compared to traditional wired networks. In order to mitigate this issue, RIM compresses data
before transporting across the wireless network. Even then,
access speed will be compromised if web pages are large, if
they rely heavily on graphic images, if network traffic is
heavy, or if network coverage is spotty or weak.
Accessing a web site using
the BlackBerry Browser
It is only possible for a BlackBerry device to access the
Internet by making use of a gateway. A gateway works by
converting incoming content into a form suitable for the
BlackBerry device, and converting outgoing content into a
form suitable for the destination web server and site.
This is by far the easiest and fastest solution to put together.
There are several advantages to using the web to extend your
existing applications:
There are three gateways available for BlackBerry devices:
Wireless Application Protocol (WAP)
BlackBerry Mobile Data Service used in conjunction
with the BlackBerry Enterprise Server software
BlackBerry Internet Service™
the time to market is faster than developing an application from the ground up
it is easy to promote software changes
many organizations have web developing skills in house
that are available to do this type of work
Volume 2, Issue 2
BlackBerry Developer Journal
agram Protocol (UDP) for Integrated Dispatch
Enhanced Network (IDEN™) networks.
Wireless service providers usually provide a WAP gateway
for their subscribers. The following features are supported
by the BlackBerry Browser that operates through a WAP
BlackBerry Mobile Data Service feature of the
BlackBerry Enterprise Server
Supported image format:
The BlackBerry Mobile Data Service (MDS) gateway is provided with the BlackBerry Enterprise Server. The following
features are supported by the BlackBerry Browser operating
through a MDS gateway:
Wireless Bitmap (WBMP)
Supported web scripting languages:
Wireless Markup Language (WML)
• WMLScript
Supported server-side scripting languages include:
Supports the MIDP Over-The-Air (OTA) provisioning
standard for wireless application downloads
Supported image formats:
Active Server Pages (ASP)
Java™ Server Pages (JSP)
PHP: Hypertext Preprocessor (PHP)
Graphics Interchange Format (GIF)
• WMLScript (1.2.1)
Compact HTML (cHTML)
Portable Network Graphics (PNG)
Wireless Bitmap (WBMP)
Joint Photographic Experts Group (JPEG)
Note: JPEG only supported on color devices
Supported web scripting languages:
Note: The server must return supported markup language.
The device will not process scripting.
Supported server-side languages:
Anything used to create CGI applications
Supported mobile media:
XHTML Mobile Profile (XHTML-MP)
• JavaScript™
(version 1.3 and subsets of 1.4 and 1.5)
• Style Sheets (limited support)
Supported server-side scripting languages include:
Wireless Transport Layer Security (WTLS)
Class 1 (encryption only) and Class 2 (encryption and
server authentication)
WTLS root certificates
Protocol is WAP 1.2.2 and WAP 2.0 that features
WTLS and Wireless Session Protocol (WSP) header
Sends HTTP over Wireless-Profiled TCP (wTCP)
where the request is sent to a WAP 2.0 proxy which forwards it on to the web server
Plazmic™ PME and PMB formats
Supports the Password Authentication Protocol (PAP)
which is used for authentication against a remote
authentication dial-in user service (RADIUS) for Packet
Data Protocol
Protocol HTTP/IPPP
Service providers can provision BlackBerry devices
wirelessly to enable or disable WTLS support
Other features:
Supports certificate authority authentication to allow
connections to untrusted servers or to restrict access to
trusted servers only
Browser content is encrypted between the MDS and the
device using Triple DES or AES encryption, transported
using the same secure pipeline that is used for email
Supports three types of network authentication:
DES (40 and 56-bit) encryption
RC5 encryption (64, 128 and 168-bit)
Supported server-side languages:
Does not support the WMLScriptCrypto library
Anything used to create CGI applications
Supported mobile media:
Supports cookies on the BlackBerry device
One WAP Push Service record is issued for each bearer
that the device is allowed to receive WAP Pushes over.
This usually means Short Message Service (SMS) for
General Packet Radio Service (GPRS) and Code Division Multiple Access (CDMA) networks, and User Dat-
Volume 2, Issue 2
Secure Socket Layer (SSL) and Transport Layer Security (TLS) to connect to secure HTTP (HTTPS) servers
on an intranet or the Internet
Basic authentication
BlackBerry Developer Journal
Other features:
The BlackBerry Enterprise Server and Mobile Data Service are typically set up behind the corporate firewall so
that data is not encrypted and decrypted over the Internet
Supports cookies on the BlackBerry device, and maintains them in a cookie cache
All data transferred from the BlackBerry device to MDS
and back is encrypted and compressed for privacy and
to help speed up the rate of transmission
Supports MDS Push:
• Browser Push
• Client/Server Push
Supports the MIDP Over-The-Air (OTA) provisioning
standard for wireless application downloads. Note that
MDS will transcode .jar files into .cod format, which
allows users to download and install standard MIDlets.
BlackBerry Internet Service is made available through
selected BlackBerry service providers
Message List
• A link to the URL is stored as an email message.
Browser Cache
• Stores the data directly in the BlackBerry
Browser’s cache so that the BlackBerry Browser
uses the cached data rather than making a wireless
Channel Push
• Places an icon entry point on the BlackBerry
device’s home screen. When selected, the icon will
change state (optional) and then calls the browser to
load a cached page.
can be written in most server-side languages
data format is limited to what the BlackBerry Browser
can handle or what a custom developed application can
the push process is controlled from the server side
push applications are relaively easy to write
each push request is designed to refresh the currently
cached copy when network coverage permits
BlackBerry Internet Service does not support Triple
DES encryption, and secure sites (HTTPS) are not
BlackBerry Internet Service communicates with the BlackBerry Infrastructure using HTTP over the RIM IP Proxy Protocol (IPPP). Delivery of HTML is both faster and more
efficient than HTTP over WAP in most current implementations.
Software application on the BlackBerry
device and, possibly, also on a remote server
BlackBerry Internet Service was designed to provide the following functionality:
Custom software development is the most versatile way to
create a solution for BlackBerry devices. All Java-based
BlackBerry devices are programmed in Java 2 Micro Edition
(Java ME™) using the BlackBerry Java Development Environment (JDE), or your favorite Java ME kit.
preprocess and compress HTML or XHTML content
before sending it to the BlackBerry device to help speed
up transfers
Volume 2, Issue 2
transcode specific content types for appropriate display
on the BlackBerry device
Data Push
• Transmitted to the BlackBerry device with the
expectation that a custom listener, as opposed to the
browser, has been set up to accept the pushed data.
Advantages include:
process and transmit images with content to help reduce
network traffic
The key differences between the BlackBerry Internet Service
and MDS are as follows:
BlackBerry Internet Service is not used through a corporate firewall
optimize images for display on BlackBerry device
A server-side application is created to send content to one or
more BlackBerry devices through MDS and the BlackBerry
Enterprise Server. There are four push techniques available:
The features provided are similar to those provided through
MDS. As an example, both are designed to optimize web
content for wireless browsing, and both transcode content
types into appropriate formats for display on the device.
This is a powerful technique used to deliver content directly
on BlackBerry devices without user intervention.
The BlackBerry Internet Browser was developed to use the
BlackBerry Internet Service as a gateway to the Internet.
This component is hosted by the BlackBerry infrastructure
and is a service offered by certain carriers.
BlackBerry Internet Service does not require BlackBerry Enterprise Server
sends processed content to the device as soon as it is
available, rather than sending it only after all data has
been completely processed
Server-based application that
“pushes” content to the BlackBerry device
The BlackBerry Internet Service
BlackBerry Developer Journal
The main advantage of developing a custom application for
BlackBerry is that you have control over all features, functionality, look, feel, network handling and access to
server-side applications. Device applications written in Java
can also be deployed for Over-The-Air (OTA) installation.
Although these solutions can be more robust, they do require
development staff with Java ME experience, time and associated resources to see the entire process through to completion.
Often a key component in developing applications that take
advantage of BlackBerry device functionality is to use the
BlackBerry series of APIs. The following are many of the
APIs that are included in the latest 4.0 release of the BlackBerry Java Development Environment:
CLDC defines an underlying environment based on the
physical capabilities of the device
Application Invocation
Allows third-party applications to remotely invoke
BlackBerry applications
Provides serial communication support for
Bluetooth connections
Provides access to the BlackBerry Browser
application to create and display HTML or WML
pages and to set browser options
Browser Field
Provides access to browser-component
functionality to integrate in applications
Browser Plug-in
Defines the Plugin API used to add support for
specific MIME-types to the BlackBerry Browser
Defines basic functionality for data collections
Provides components for compressing and
decompressing data.
A collection of classes used to implement security
for BlackBerry applications. The following tasks
can be accomplished with the the Crypto API:
• encrypt and decrypt data
• digitally sign and verify data (secure the
integrity of your data)
• authenticate data
To support internationalization of applications
MIDP determines the core application functionality on
the device
Java ME is a configuration (CLDC) and a profile (MIDP)
that is specific to devices that share the following characteristics:
a minimum of 128kb to 512kb of memory, with a 16- or
32-bit CPU
it must provide an implementation of a small Virtual
Machine (VM)
is battery operated, with a low-level of power consumption
it has wireless network connectivity and restricted bandwidth
Java ME does not provide support for the following Java 2
Standard Edition (J2SE™) features:
floating point operations
Java Native Interface (JNI)
large user interface APIs such as Swing and AWT
thread groups
Daemon threads
Object serialization
Remote Method Invocation (RMI)
Java ME is limited to three error classes, restricts file handling to Record Management System (RMS) persistent storage, and does not provide a class loader.
A library of components to manage data
The latest release of the BlackBerry Handheld Software version 4.0 and JDE support MIDP 2.0. This release has been
greatly improved from previous MIDP releases in the following areas:
Over-The-Air provisioning
The BlackBerry API
Sun Microsystems® has defined configurations and profiles
within Java ME that include Connected Limited Device
Configuration (CLDC) and Mobile Information Device Profile (MIDP):
Network connectivity
IT Policy
Used to customize features that are common to all
users on a given BlackBerry Enterprise Server, such
as password details, mail forwarding options and
browser settings. IT policies provide an efficient
method to manage many different users
Push registration
Volume 2, Issue 2
BlackBerry Developer Journal
Lightweight Data Access Protocol (LDAP)
LDAP is a client-server protocol used for accessing
directories. It allows you to access and browse
through information on remote directory servers.
Low Memory
Maintains memory resources on the device when
the device becomes over-taxed and runs low on
Functionality for sending, receiving and accessing
email and PIN messages
A collection of fixed-point math routines, and
implementations of a stack for use in matrix
Menu Item
Used to add custom menu items to applications
For manipulating streams of MIME encoded data
Functionality to trigger event notifications through
Consequence (tone, vibration or LED) or
NotificationsEngineListener (dialogs or interaction
screens on the device)
Used to add items to the device Options screen
Interfaces that developers should implement to
conform to the Personal Digital Assistant Profile
(PDAP) specification on the BlackBerry device
(such as Address Book contacts and Calendar
entries). Also see the PIM package from the MIDP
Provides access to the BlackBerry Phone
application to initiate calls, receive related
notification events, and change phone options
Plazmic Media Engine
Contains necessary functionality to allow media on
the BlackBerry device to be downloaded and
A variety of system-level functionality such as:
interfaces classes that can be implemented to
listen for various system level events
base classes for application functionality, and
application management
base classes to describe persistable data
objects, and stores of such objects
system-level access to BlackBerry device
services such as the radio, phone, peripherals,
available networks, event logger, memory
manager, serial port, speaker, SIM card and
User Interface
Functionality for constructing a user interface
SAX and WBXML parsers
The BlackBerry JDE
The BlackBerry Java Development Environment (JDE) is
comprised of a series of development tools used to test and
create applications for BlackBerry.
The full environment consists of a Java ME compiler, editor,
debugger, profiler, BlackBerry device simulator, BlackBerry
Mobile Data Service (MDS) simulator and an email server
simulator. The BlackBerry JDE was designed to use any
source control system that has a command line. Note that the
device simulator can also be used to test commercial applications before corporate deployment.
JDE Compiler
The compiler has been designed to generate small destination files for wireless deployment. The contents of each .cod
file are optimized for byte code and then obfuscated. During
creation, images are also converted into .png format. Compiled files can be deployed directly through the BlackBerry
Desktop Manager, or deployed Over-The-Air on a web site,
or “pushed” to corporate devices with BlackBerry Enterprise
Server 4.0.
Note that .cod files must be compiled for specific ranges of
BlackBerry device OS revisions. The latest compiler must be
used for devices that are running BlackBerry Handheld Software version 3.8 or later. Earlier versions use .cod files compiled with JDE versions prior to version 4.0.
Service Book
Used to store setup and configuration information
on a BlackBerry device, and contains
ServiceRecords that define information about
BlackBerry connections. Service records are used
to manage the device’s CMIME (mail) and IPPP
(Internet connections) and are also valuable for
keeping track of network UIDs to more easily
manage MDS connections.
The editing environment is similar to most GUI editors with
the exception that you can directly set and deselect breakpoints and symbolic bookmarks, auto-complete methods,
show class definitions, and display methods in outline and
Provides functionality required to synchronize data
between the BlackBerry device and the BlackBerry
Desktop Software, and contains classes and
methods used to provide backup and restore
functionality to applications
Volume 2, Issue 2
BlackBerry Developer Journal
The Debugger
The Summary view shows general statistics about the system
and garbage collector.
The debugging stage is always the most difficult portion of
the development cycle. Where the physical act of writing
software can be a wonderful experience, debugging can be
the worst. The transition from lower-level languages such as
assembler and C, to higher-level languages such as C++ and
Java, has made it easier to create software solutions, but
more difficult to debug them. This is often due to the
increased complexity of working in an event-driven environment that relies heavily on externally developed components. The BlackBerry JDE comes with a debugger that will
ease debugging pain greatly.
The Methods view shows a list of modules, sorted either by
the information that you are profiling or by the number of
times each item has been executed.
The Source view shows the source lines of a single method.
You can navigate through the methods that call, and are
called by, that method.
BlackBerry Device Simulator
The BlackBerry device simulator is designed to function
similar to an actual BlackBerry device, and displays icons on
the Home screen for all applications that have been loaded.
Two debugging techniques can be used.
The first is to set a few breakpoints at critical sections of
your code, and then gradually set breakpoints at shorter
intervals to identify the source of the problem. Select Go
from the Debug menu to compile and run all active applications in the simulated environment. After the program has
paused at a breakpoint, use debugging tools to view various
application processes and statistics to identify the problem.
The device simulator should start automatically when you
run programs in the IDE. If it does not, select the Launch
simulator check box in simulator preferences.
If you are testing applications that require an HTTP connection, you must also start the BlackBerry Mobile Data Service
simulator. In the IDE simulator preferences, select Launch
Mobile Data Services (MDS) with simulator, or start the
MDS Simulator manually.
The second technique is to start a debugging session with the
BlackBerry device simulator, then click Break Now on the
Debug menu in the main window. The breakpoints pane will
display the section of code and the line number at which the
program is paused. The edit pane will display the source
code, with an arrow to indicate the line of code at which the
application is paused. And the output pane will display messages from the debugger
Start the simulator by clicking on Go on the Debug menu.
BlackBerry Mobile Data Service Simulator
The BlackBerry Mobile Data Service Simulator is designed
to provide a full simulation of the BlackBerry Mobile Data
Service so that you can test client/server applications with
your device simulator and MDS simulator.
To resume debugging after pausing at a breakpoint, click
Continue on the Debug menu. To stop the debugging session in the simulator, click Quit on the File menu.
Email Server Simulator
The memory statistics tool that becomes available during
debugging sessions can be used to find memory leaks.
The email simulator allows you to transmit and receive mail
using the BlackBerry device simulator and a local mail client
or remote mail server. It supports POP3 and SMTP.
Note that debugging can also be performed on a live BlackBerry device connected to the computer through the serial or
USB connection.
Take the time to learn more about BlackBerry development
by reviewing resources provided by Research In Motion
(such as webcasts, case studies and more), review articles
publishing in the BlackBerry Developer Journal and work
with the BlackBerry JDE to see what you can create. It truly
is less hard than it looks to create world-class software for
The Profiler tool shows the percentage of time spent in each
code area to the current point of execution. You can use it to
profile efficiency of code sections by setting a breakpoint at
the start and end of the section of code that you want to profile, start a debugging session with the simulator, run until
the first breakpoint is reached, then click Profile on the
View menu. Click Options in the profile plane, set the profile options, then click Go to continue running the application. When the second breakpoint is reached, click Profile
on the View menu, then click Refresh to retrieve accumulated profile data from the Java Virtual Machine (JVM™).
Use profile views to display information about the section of
code that you just ran.
In closing ...
Wireless development is still in its infancy relative to development in the wired world. With the right approach, this may
directly translate into countless opportunities to excel within
your industry and can provide your company with a competitive advantage.
Please email your comments, suggestions and editorial submissions to [email protected]
Volume 2, Issue 2
BlackBerry Developer Journal
How to Create a Desktop add-in
Using Microsoft Visual Basic 6.0
Dante Sarigumba
A common question asked by BlackBerry® developers who
want to write a desktop add-in is “Can I use Visual Basic?”
The answer is YES, and you are about to learn how.
What do you need?
I assume that you know what the BlackBerry Desktop Manager is and have it installed on your computer.
Before going into further detail, let’s review a couple of fundamentals to understand why we have language choices
when creating desktop add-ins.
You should also have Microsoft Visual Basic 6.0 installed
and know how to write VB code in the Microsoft Visual Studio IDE.
According to the BlackBerry Application Developer Guide,
Volume 1, an add-in has to be implemented within the following parameters:
It must be an in-process COM. This means that the
desktop add-in runs under the process space of the calling application. Because it is a COM component, the
BlackBerry Desktop Manager can easily instantiate it.
An add-in must implement the IRIMInterface, a COM
component which includes methods that must be implemented within your code. These methods provide access
to objects that can be manipulated to access the BlackBerry device. IRIMInterface informs the BlackBerry
Desktop Manager that your component is an add-in.
Foir the purposes of this article, I will primarily focus on
how to set up your environment for writing a desktop add-in
using VB, and will guide you on how to write an add-in in
VB. Use the SyncDemo Java sample that comes with the
BlackBerry JDE for the device side, and on the desktop side,
you will port the existing C++ sample into VB. In the end,
we’ll have built a single direction synchronization add-in
that works from desktop to the BlackBerry device.
Let’s get started
The first thing to do is to create an “ActiveX DLL” Project.
You can name it what you wish but remember that the
project name will be the name of the dll that gets deployed
and should describe your project. For this sample, let’s call it
Double Marshalling
Microsoft® Visual Basic® was used to prevent double marshalling. Marshalling is a mechanism within .Net that has
been incorporated to support COM. Although it is very convenient to be able to use existing COM components, this
technique comes at a cost to performance.
Create a class in the project and name it “DataSync”.
Add “RIM DesktopApi 1.0 Type Library” into your project
references. You may not find this description within the selection but you are able to browse to it (click the browse button -- see Figure 1) by navigating to the folder where your
Desktop Manager is installed. From there, select Synchronize.dll.
A desktop add-in written in .Net would first incur marshalling when managed code tries to implement the RIM API.
After writing your code in C# or VB.Net, you would need to
convert the component to COM and register it so that the
BlackBerry Desktop Manager can see it. I strongly recommend the use of Visual Basic until the BlackBerry Desktop
Manager can take advantage of .Net infrastructure.
Now let’s see what this API looks like.
If you open the object browser (F2) and select DESKTOPAPILib, you should see something similar to Figure 2.
Notice how simple the interface is and how few objects there
are that you will need to learn.
Volume 2, Issue 2
BlackBerry Developer Journal
Figure 1
Figure 2
Volume 2, Issue 2
BlackBerry Developer Journal
If you have experience writing a C++ desktop add-in, then
the classes shown in Figure 2 should be familiar to you.
Readers who are just starting out need to be aware that the
project has to implement IRimExtension. Insert the following code in the declaration section of DataSync class:
Note that the Contact table is not a physical table. Rather, it
is virtual and is used as a means of communicating with the
BlackBerry device. You will need to implement the BlackBerry Synchronization API on the device. Refer to the
BlackBerry Application Developer Guide, Volume 2 for
more information. Since we are using the SyncDemo sample, this has been taken care of for us.
Option Explicit
Implements IRimExtension
Our sample application is designed to transfer data in one direction, from desktop to BlackBerry device. The next step is
to clear the device of the old contact data:
The first line is standard code that most Visual Basic Developers are familiar with. It forces you to declare your variables before using them. With the Implements keyword, VB
will automatically provide the events needed to implement
IRimExtension. Click on the top, left drop down selection to
see IRimExtension as one of the options. Select IRimExtension. On the top, right drop down, you will now see these
four events:
You need a Records object handle to add records and populate fields:
Set oRecords = oContact.LoadRecords
Set oRecord = oRecords.AddRecord
Set oFields = oRecord.fields
Called when a BlackBerry device user clicks on your
add-in within configure add-in
Now that you have object handles for a new record and
fields, it’s easy to add contact fields. There are only a couple
of lines of code to add the contact field. As a suggestion, it
would be best to write a subroutine to handle this to avoid repeating similar code, as shown below:
Called whenever an error occurs
Private Sub addField
(oFields As DESKTOPAPILib.IRimFields,
iFieldId As Integer, sData As String)
Dim oField As DESKTOPAPILib.IRimField
Dim ayWork() As Byte
Called when a user clicks on the details of your add-in
Called by the BlackBerry Desktop Manager when
synchronization occurs. This is where you insert most of
your code. Access to IRimUtility and
IRimDatabaseAccess is available on this event.
sData = sData & chr(0)
Set oField = oFields.addField
oField.Id = iFieldId
ayWork = StrConv(sData, vbFromUnicode)
oField.Value = ayWork
End Sub
Click each event on the dropdown and the IDE will automatically create a stub for you. Position your editor on the process stub then insert the following code.
To access a “database” on the BlackBerry device, use the
IRimDatabaseAccess parameter to read tables. As an example, use this sample code to access the “Contacts” table:
For the BlackBerry device Java application to properly receive the data, the string must be terminated by a null character, then converted to a byte array.
We can now insert the code to fill in the fields and add the
addField oFields, 1, "John" ‘First Name
addField oFields, 2, "Does" ‘Last Name
addField oFields, 3, "[email protected]" ‘Email
Congratulations! You have just created your first desktop
manager add-in in Visual Basic. As you can see, it is a very
straightforward and easy process. To extend this code and
achieve bi-directional synchronization, use the Record’s
Dirty flag, and add additional logic for the BlackBerry device and desktop code.
Set oTables = pRimDeviceAccess.Tables
'*** let's get the Contacts table from the
‘*** device on this list
For Each oTable In oTables
If oTable.Name = "Contacts" Then
Set oContact = oTable
Exit For
End If
Volume 2, Issue 2
You can improve the application by letting BlackBerry device users know the progress of the sync by casting
IRimUtility to IRimProgress such as this:
BlackBerry Developer Journal
Dim oTemp As Object
Allowing the BlackBerry Desktop Manager
to see the add-in
Set oTemp = pRimUtility
If TypeOf oTemp Is IRimProgress Then
Set oProgress = oTemp
End If
If you try running this sample for the first time and use Intellisync, you will notice that Intellisync does not recognize
your add-in. There is one more step needed to wrap this up.
Compile your add-in first and then set it to binary compatibility to the compiled dll (SyncSample.dll).
IRimProgress lets you update the progress dialog through
these two methods:
Set the title or the message. The constant will be
RIM_ProgressText_Title and RIM_ProgressText_Msg
Change the position of the progress bar
By setting binary compatibility, every succeeding compilation maintains the same class ID within the registry. You also
need to get this class ID to ensure that it implements IRimInterface within the registry. To do this, search for your
add-in in the registry. In this case, search for “SyncSample.dll”. Figure 3 is a snapshot of what it should look like.
This example has the following Class ID:
Create a registration file with the following information:
Figure 3
After running this registration file, your registry editor should pick up the change and look like Figure 4:
Figure 4
Volume 2, Issue 2
BlackBerry Developer Journal
A sample using an XML input file is listed below. Please
feel free to em ail me your comments/questions at
[email protected]
{DFCE97AB-25ED-4335-BB00-FE5863F41DED is the
class ID for IRimInterface. This registration file is needed
for deployment of your add-in. If you ever need to break the
compatibility, make sure that you update this file with the recent class ID of your add-in.
Author Biography
Finally, you need a description to display whenever a user
clicks on the "Configure Add-ins" on the BlackBerry Desktop Manager. You can provide it by implementing GetExtensionInfo. Sample source code is provided in "Source Code:
DataSync.cls" section. Again, you have to replace the class
ID with your add-in.
Dante Sarigumba is a multi-talented IT professional with
over 12 years of experience developing software on an array
of environments and for a number of industries.
Source Code: DataSync.cls
Option Explicit
Implements IRimExtension
Private Sub IRimExtension_Configure
(ByVal pRimUtility As DESKTOPAPILib.IRimUtility, ByVal HWND As Long)
'*** You can add code here if you want your user to display a screen allowing
'*** users to configure any parameters
End Sub
Private Sub IRimExtension_GetErrorString(ByVal errorCode As Long, errorMsg As String)
MsgBox "Encountered a problem during synchronization", vbCritical,
"SyncSample Data Synchronization"
End Sub
Private Sub IRimExtension_GetExtensionInfo(extensionInfo As String)
extensionInfo = "<?xml version=""1.0"" encoding=""UTF-8"" ?><extensioninfo version=""1.0.0"">"&_
vbCrLf & "<vendorname>Your company here</vendorname>" & _
vbCrLf & "<vendorversion>1.0</vendorversion>" & _
vbCrLf & "<path>C:\\BlackBerry\SyncSample</path>" & _
vbCrLf & "<description>Sample addin using VB 6.0</description><displayname>" & _
"Sample addin using VB 6.0</displayname>" & _
vbCrLf & "<clsid>{7BC5A21E-D252-4F36-9591-9656D3C76415}</clsid>" & _
vbCrLf & "<access><database>Contacts</database></access>" & _
vbCrLf & "</extensioninfo>"
End Sub
Private Sub IRimExtension_Process(ByVal pRimUtility As DESKTOPAPILib.IRimUtility,
ByVal pRimDeviceAccess As DESKTOPAPILib.IRimDatabaseAccess)
Dim oTemp
As Object
Dim oProgress
Dim oTables
Dim oTable
Dim oContact
Dim oRecords
Dim oRecord
Dim oFields
Dim oField
Dim oXML
As MSXML2.DOMDocument30
Dim oNodes
Dim oNode
Dim sPath
As String
Dim l
As Long
Dim lHigh
As Long
Volume 2, Issue 2
BlackBerry Developer Journal
On Error GoTo ErrorHandler
Set oXML = New MSXML2.DOMDocument30
oXML.Load App.Path & "\ContactList.xml"
Set oTemp = pRimUtility
If TypeOf oTemp Is IRimProgress Then
Set oProgress = oTemp
End If
oProgress.SetProgressDlgText RIM_ProgressText_Title, "Sample Data Syncronization"
oProgress.SetProgressDlgText RIM_ProgressText_Msg, "Start of data syncronization..."
If oXML.childNodes.length > 0 Then
'*** only do the sync if we got valid data
Set oTables = pRimDeviceAccess.Tables
'*** let's get the
For Each oTable In
If oTable.Name =
Set oContact =
Exit For
End If
application table from the device
"Contacts" Then
If oContact Is Nothing Then
MsgBox "Could not find the Contact database in the device", vbCritical
'*** let's clear the device of existing data
'*** let's set it up for updating
Set oRecords = oContact.LoadRecords(RIM_Mode_ReadWrite)
Set oNodes = oXML.selectNodes("//contact")
lHigh = oNodes.length - 1
If lHigh >= 0 Then
l = 0
oProgress.Notify RIM_Progress_Count, lHigh, 1
For Each oNode In oNodes
Set oRecord = oRecords.AddRecord
Set oFields = oRecord.fields
If Not oFields Is Nothing Then
addField oFields, FIELDTAG_FIRSTNAME, oNode.childNodes(0).Text
addField oFields, FIELDTAG_LASTNAME, oNode.childNodes(1).Text
addField oFields, FIELDTAG_EMAIL, oNode.childNodes(2).Text
End If
Set oField = Nothing
Set oRecord = Nothing
l = l + 1
oProgress.SetProgressDlgText RIM_ProgressText_Msg, "Uploading " & l & " of " & lHigh
oProgress.Notify RIM_Progress_Pos, l, 0
Volume 2, Issue 2
BlackBerry Developer Journal
oProgress.SetProgressDlgText RIM_ProgressText_Msg,
"please wait to wrap up the syncronization..."
End If
End If
End If
Exit Sub
MsgBox "Encountered an error during synchronization: (" & Err.Number & ") - " & Err.Description,
vbCritical, "Sample Data Synchronization"
End Sub
Private Sub addField(oFields As DESKTOPAPILib.IRimFields, iFieldId As Integer, sData As String)
Dim oField As DESKTOPAPILib.IRimField
Dim ayWork()
As Byte
sData = sData & Chr(0)
Set oField = oFields.addField
oField.Id = iFieldId
ayWork = StrConv(sData, vbFromUnicode)
oField.Value = ayWork
End Sub
Source Code: ContactList.xml
<contact first="Bob" last="Roberts">
<email>[email protected]</email>
<contact first="Alan" last="Alda">
<email>[email protected]</email>
<contact first="George" last="Castanza">
<email>[email protected]</email>
Volume 2, Issue 2
BlackBerry Developer Journal
.NET: A Simple C# Push Application
Anubhav Srivastava
How does the application work?
Push applications can be created using any development language that is able to initiate a network connection and perform an HTTP post. An HTTP post to the BlackBerry®
Mobile Data Service handles the delivery of pushed data to a
BlackBerry device.
When you run the application described in the next section
you will see the screen below.
The post is made up of a standard HTTP request header, a
few unique Browser Push headers and a stream of data.
Note: The web page does not have to be sent when performing a Browser Channel Delete Push
The following additional HTTP request headers are required
for a browser push to take place:
The “X-Rim-Push-Title” header contains the title that will
appear either on the Home screen of the BlackBerry device
for a Browser Channel Push, or in the subject of the message
for a Browser Message Push.
Figure 1
The “X-RIM-Push-Type” header holds the value that represents the type of push being sent. Possible values are:
Click the “Open” button to select a file that contains a list of
BlackBerry device users with their BlackBerry Enterprise
Server host, port and email/PIN. The following line shows
the format of a “User Information File”:
localhost 8080 2100000A
The “X- RIM-Push-Channel-ID” header contains the URL
of the page to be pushed to the device. This is not required
when performing a Browser Message or Browser Content
In this example, localhost is the name of the server that push
is being sent to, port 8080 is the web server listen port on
that server, and the PIN is set to 2100000A.
Note: The “User Information File” must be saved with an
extension of “.txt”
The “X-RIM-Push-UnRead-Icon-URL” and “X-RIM-PushRead-Icon-URL” are optional headers that specify the URL
of the icons to be used for a Browser Channel Push. If not
specified then the default Browser Channel Push icons are
used. These two headers are not required for Browser Message, Browser Content or Browser Channel Delete Push and
may be omitted
Select the push type to continue and then specify the URL
and the push name. If you want a read and unread icon to be
published, provide URLs. Otherwise, leave the settings
This article will show how to create an application to push a
URL to one or more BlackBerry device users. For further
information, please refer to “Push Me! Pushing web content
to BlackBerry” in Volume 2, Issue 1 of the BlackBerry
Developer Journal.
Volume 2, Issue 2
Note: Run the MDS Simulator before the BlackBerry device
simulator to see the following results.
BlackBerry Developer Journal
When the Send Push button is pushed, you should see the
following icon in your simulator screen.
Performs the push operation
The UI for the Bulk Push
Installation instructions and known
Figure 2
Let's get started
Download and unzip, and then
open BlackBerryBulkPush.sln. This is a solution file that
includes the setup project and the source project. When you
open this project you will see the screen in Figure 3.
Figure 3
The solution explorer shows six files in the BlackBerryBulkPush Project. The files have the following functions:
Used for configuration of logging
framework log4net
Icon file
File generated by VS .Net
The two relevant classes are PushDialog.cs and HttpPushWorker.cs. When the Send Push button is pressed, it invokes
the button1_Click event in PushDialog.cs. Let’s review the
button1_Click code to see what happens:
private void button1_Click(object sender, System.EventArgs e)
int pos,start;
string BESAddress,BESPort,Email,url;
string fDelimiter= " ";
//verifying information is filled correctly
} else {
this.PushStatusBar.Text = "Missing Required Fields";
//checking for correct file (.txt extension)
if((txtFileName.Text).Substring((txtFileName.Text).IndexOf(".",0)+1,3) != "txt")
MessageBox.Show("Please enter a file with extension .txt");
//checking if file exists
if (!File.Exists(txtFileName.Text))
MessageBox.Show(this,"Incorrect file name");
return ;
//verifying url
PushStatusBar.Text = "Requesting Page Data";
HttpPushWorker pusher = new HttpPushWorker(ref PushStatusBar,ref url);
Volume 2, Issue 2
BlackBerry Developer Journal
if ( url == "Wrong" )
PushStatusBar.Text = "Push Failed, bad URL";
// create reader & open file
TextReader sr = new StreamReader(txtFileName.Text);
//reading contents into string variable
string fContent = sr.ReadLine();
/*looping thrugh the reader and parsing the
BES address,port and email from the file*/
while (fContent != null)
//looking for " "
//pushing pos and start variable to parse Address
//setting start position for port
//looking for " "
//using pos and start variable to parse Port
//setting start
//using length and start to parse email
//logging the parsed infomation
log.Info("Sending: " + BESAddress + " " + BESPort + " " + Email);
//Verifying the parsed information
if (verifyFile(BESAddress,BESPort,Email))
//calling the push method to perform push
"http://"+UnreadIconURLTextBox.Text, Email);
MessageBox.Show("Error:The file does not have proper formatting");
//reading line
fContent= sr.ReadLine();
catch(Exception t)
log.Info("Exception: "+ t.Message,t);
//closing stream reader
Volume 2, Issue 2
BlackBerry Developer Journal
The method above declares variables and performs field,
file, and URL verification and validation. It then passes the
Status Bar and the URL by reference to an instance of HttpPushWorker class. A text reader is then created to read
through the user file.
The httpPush method in the HttpPushWorker class is then
called to push the web page to the user. Each user information is read and then the URL is pushed. Once all lines have
been read from the user file the reader will close the file.
How the httpPush method performs the push
The httpPush method within the HttpPushWorker.cs
class first reads in the source data and then adds it to the push
connection. The method will also add all necessary HTTP
headers that the BlackBerry Browser uses to identify this
connection as an HTTP push.
Address (or IP) of the
BlackBerry Enterprise
Server/BlackBerry Mobile
Data Service
Port BlackBerry Mobile
Data Service listens on for
incoming connections
Index of the push type
Title to use for the push
URL of the source page
URL of the read icon to use
(for channel push)
URL of the unread icon to
use (for channel push)
PIN or Email address of the
BlackBerry device user to
push to
public void httpPush(string BESAddress, string BESWebserverListenPort, int typeIndex,
string pushTitle, string url, string readIconURL, string unreadIconURL, string pushPin)
string pushPort = "7874";
string pushType = PUSH_TYPES[typeIndex];
status.Text = "Sending Push";
//Create the push URL for MDS this is of the format
string httpURL = "http://"+BESAddress+":"+BESWebserverListenPort
+ "/push?DESTINATION=" + pushPin+"&PORT=" + pushPort + "&REQUESTURI=/";
//make the connection
//we'll put this whole thing in a try/catch block for some basic error handling.
HttpWebRequest HttpWReq = (HttpWebRequest)WebRequest.Create(httpURL);
HttpWReq.Method = ("POST");
//add the headers nessecary for the push
HttpWReq.Headers.Add("X-RIM-Push-Title", pushTitle);
if (pushType.Equals("Browser-Channel") || pushType.Equals("Browser-Channel-Delete"))
HttpWReq.Headers.Add("X-RIM-Push-Channel-ID", url);
if (pushType.Equals("Browser-Channel"))
HttpWReq.Headers.Add("X-RIM-Push-Read-Icon-URL", readIconURL);
//add some of the headers from the source page
int headerCount = headers.Count;
Volume 2, Issue 2
BlackBerry Developer Journal
for (int i = 0; i<headerCount;++i)
Console.Out.WriteLine("Adding Header = "+headers.GetKey(i));
if (headers.GetKey(i).ToLower().Equals("content-type"))
HttpWReq.ContentType = headers.Get(i);
HttpWReq.ContentLength = data.Length;
//Getting Request stream to write data to it
Stream requestStream = HttpWReq.GetRequestStream();
//Write the data from the source
//get the response (this should be HTTP 200)
HttpWebResponse HttpWRes = (HttpWebResponse)HttpWReq.GetResponse();
//Update status on the Status Bar wich Is passed by reference from PushDialog.cs
if (HttpWRes.StatusCode == HttpStatusCode.OK)
status.Text = "Pushed";
} else {
status.Text = "Push Failed, bad response";
log.Info("Failed to Push");
//Close the streams
status.Text = "Closing Streams";
status.Text = "Success with "+ timesFailed + " Failures";
catch(System.Exception e)
log.Error("Push Failed "+ e.Message,e);
status.Text = "Push Failed, could not send";
Author Biography:
In the method above, the variable PUSH_TYPES is a String
array with the following structure
Anubhav Srivastava (Ash) is currently in his last semester of
Computer Engineering at the University of Waterloo and has
been programming in .NET for 3 years. His experience with
a wide range of technologies and databases has inspired him
to help people integrate technologies to simplify tasks and
make businesses more efficient. Ash is also a columnist for
ASPAlliance [] and ASPToday
[]. His curiosity with wireless and RIM
push technology has led him to integrate .NET programming
with BlackBerry ‘push’ technology. In his free time he
serves as the councillor for the engineering faculty on University of Waterloo Federation of Students. Other interests
include swimming and meditation. You can reach him at [email protected]
public static string[] PUSH_TYPES
= new string[]{
PUSH_TYPES is declared in the HttpPushWorker class.
After variable declaration, a URL is created that allows the
application to perform the HTTP Post necessary to push the
page to the BlackBerry Mobile Data Service and the BlackBerry device. Once the URL is created and the connection
to the BlackBerry Mobile Data Service is established, specific headers are added to the request.
A request stream is then obtained to write source data (web
page) to the destination. When the data has been written to
the stream, the response from the HTTP request is checked
for status 200. The response is used to inform the user about
the status of the push. The status is displayed on the status
bar in PushDialog.cs.
Volume 2, Issue 2
BlackBerry Developer Journal
.NET: Pushing Microsoft Excel, Access or
SQL Server Data Using Multiple Interfaces
Anubhav Srivastava
This article will describe how to push data from Microsoft®
Excel, Microsoft Access and Microsoft SQL Server to
BlackBerry devices. It builds on the article, “.NET: A Simple C# Push Application” and will demonstrate how to push
Emergency Contact List (ECL) data to BlackBerry devices,
and how to push ECL to BlackBerry devices by using three
different interfaces depending on need:
ECL Service Application
This is like a Windows® Service, which performs a
push at a regular interval to BlackBerry devices.
ECL Command Line application
A command line application that performs a push once
to BlackBerry devices.
Client Catcher
Client catcher is used when the server encodes the contact
data into a non-standard format then sends it to a custom application that must be installed on the user's BlackBerry device. When the catcher receives a pushed message, it stores
the encoded data locally using the BlackBerry persistence
framework. The user interface component of the BlackBerry
device displays its locally stored copy of the contact list in a
collapsible tree form.
Open the Application Loader file “ECLv2\Device\bin\ECLContactList.alx” with your BlackBerry Desktop Manager
software and follow the procedure for installing the program
on your USB connected device. Once installed, the catcher
will run in the background. Alternatively, if using the simulator, open the workspace:
ECL GUI Application
A Graphical User Interface (GUI) application that
performs a push once to BlackBerry devices.
Each of these interfaces depend on the ECL Logic Engine
(ECLLogic.dll) to process the inputs and perform the push.
... in the BlackBerry Java Development Environment (JDE)
and press F5 to launch the BlackBerry device simulator.
Make sure that the MDS Simulator is also running.
We will take all of the push logic described in the previous
article, put it in a Dynamic Link Library (DLL) file, and then
use these interfaces to gather information from the user and
pass it to the DLL so it can do the work for us.
Customizing the Example
There are two push types that can be performed using the
Browser application as detailed below:
There are two kinds of customizations that are easily made to
this example:
Browser Channel Push
Browser channel push is used where the server encodes the
contact data in an HTML page and pushes the page to the
BlackBerry Browser. When the BlackBerry Browser receives a Channel Push, it stores the pushed content in its
cache and adds an icon to the main ribbon that acts as a
bookmark to that page. In this form, the program on the
handheld is the BlackBerry Browser, so there is no ECL-specific code that needs to be installed on the device.
It is important to understand how the server program reads
data from the Excel workbook to make this demonstration
work with different spreadsheet formats.
The server is “hard coded” to understand the arrangement of
cells found in XYZ Company's spreadsheet/database table. It
scans the worksheet from top to bottom, searching for rows
that contain data in the first column but not in the second.
Such rows are interpreted as group headings. Other rows are
interpreted as people within the most recently started group.
The data from all used cells in a person's row become the
line items that make up the person's record when it is displayed on the device.
Arrange to have a copy of the “ECLv2/Server/content” folder published as a web resource. You will need to make it possible for a BlackBerry device to fetch a URL such as
"" to obtain the data from “content\ecl_unread_icon.gif”. You can set this property in the
GUI and in Settings.config for the Service and Command
Line Application.
When the server program is processing a person's row and
encounters a used cell, it applies the formatting rule for the
appropriate column when generating that field's line item.
Note that the spreadsheet heading row is ignored. Thus, as
long as the new format is similar enough to the old, you can
adapt the server to read a differently formatted spreadsheet
by adjusting these properties.
For example:
[WebContextRoot]/ecl.html -->
<add key="WebContextRoot"
value="http://localhost/ecl/content" />
Volume 2, Issue 2
Making it read a different spreadsheet/database format
Changing how the list gets displayed on the BlackBerry
BlackBerry Developer Journal
The server software must be changed to read a drastically
different format. All the logic for parsing spreadsheets is in
“DataReader.cs”. This component accesses the spreadsheet
using the row/column interface provided by OLEDB. While
the server issues SQL commands over OLEDB, it is not using a relational database paradigm; rather, it is using the
scanning algorithm described earlier.
Note that there are fairly high degrees of coupling between
“ECLv2\Device\src\” and “ECLv2\Server\src
\CustomAppPusher.cs” since these classes jointly define the
application's over-the-air transmission format.
Another straightforward customization would be to modify
how the contact list gets displayed on the device. This can be
done in Settings.config file or GUI.
The GUI Application has one class, PushDialog.cs. The
main function is used to validate UI values and send them to
Open the following workspace in the BlackBerry JDE to alter the BlackBerry Handheld Software:
The Command Line Application also has one class, CommandLine.cs. The main function is used to validate UI values and send them to ECLLogic.
Now that we have an understanding of the architecture, let’s
review the code.
The Windows Service Application has two classes:
After you have made the desired changes, you can run the result in the simulator. You must sign your compiled application to deploy on a real handheld because it uses RIM's
persistence and networking APIs.
1. ECLService.cs
2. ProjectInstaller.cs
The main function of ECLService is used to validate UI values then sends them to ECLLogic.
This demo includes a pre-signed build in “ECLv2\Device
\bin\ECLContactList.cod” that can be installed without
The ProjectInstaller.cs class handles the installation of a service.
You should be able to make changes you need to the
look-and-feel of the device app by only minor edits to the
code in “ECLv2\Device\src\”.
These classes are used to get inputs and locations of data
sources and pass them on to ECLLogic, which has all the
Push Logic.
“ECLv2\Device\src\” is a fairly generic push listener, while “ECLv2\Device\src\” handles lower-level data management.
Now let us see how ECL Logic works.
<< extends >>
Here is what happens:
public struct ECLConfiguration
//File containing user information
//(Server Port Email/Pin)
public String recipientFile;
//Push Destination(Channel/Catcher)
public String PushTo;
//has a value 0 (Browser-Channel)
//or 1 (Browser-Channel-Delete)
Step 1
The interface class gets information from the user and then
pass it to ECLLogic.cs. The ECLLogic.cs class has a struct
in which the value is passed. The struct is called ECLConfiguration and can be seen below. This structure is used to send
Connection information. It has twelve variables.
Volume 2, Issue 2
BlackBerry Developer Journal
Step 3
public int PushType;
//This can be Access,Excel,MSSQL
public String ConnectionType;
//Database name,used in case of MS SQL
public String Database;
//File name(.xls or .mdb) or Server Name
//(used in MSSQL)
public String File_Server_Name;
//Worksheet Name(Used in Excel)
//or Table name (used in Access or MSSQL)
public String Sheet_Table_Name;
//The format in which data is displayed
//on the handheld
public String[] ColumnFormat;
//The location where the html file should
//stored after it has been formed
public String fileStoreLoc;
//The http:\\ URL where the read and
// unread icon files are
public String WebRoot;
//The name to be displayed as Channel Title
//on the handheld
public String ChannelName;
//The Source of the input(GUI/Console/Service)
public String Source;
If the push type is Browser-Channel then it calls DataReader.cs to access the data. While data is being accessed, it is also translated into HTML/comma delimited format by calling
methods of the Pusher.cs class. All data sources have different connection strings whose configuration information is
passed along with the ECLConfiguration struct from the interface classes.
//if Push Type is Browser-Channel
// Open the data source from which we
// will read in contact data.
dataReader = new DataReader();
("Opening Data Source for retreiving data");
//Fetch the group names
log.Info("Getting list of group names");
System.Collections.ArrayList groupDescription
= dataReader.GroupList(config);
// Assemble the data of all contacts (from all
// groups) that we will push to handhelds.
log.Info("Getting user contact information");
for (int i=0; i<groupDescription.Count; i++)
// Define the current group.
// Add all its members.
groupContactList = dataReader.
for (int j=0;j<groupContactList.Count;j++)
System.String[] dataFields =
// Log the message we just built
log.Info("Finished building the push
message with contacts in " +
groupDescription.Count + " groups. " );
Step 2
ECLLogic.cs receives the structure and then creates an instance of BrowserChannelPusher.cs or CustomAppPusher.cs. It then checks if the push type is Browser-Channel/
Browser-Channel Delete.
Pusher pusher = null;
if (config.PushTo == "Channel")
log.Info("Push To: Channel");
// Construct a pusher that sends to a
// browser channel.
pusher = new BrowserChannelPusher();
else if (config.PushTo == "Catcher")
log.Info("Push To: Custom Catcher");
// Construct a pusher that sends to a
// custom catcher.
pusher = new CustomAppPusher();
It then parses the recipient’s list file to get user information
and stores it in ArrayList.
ArrayList recipientEmails =
Volume 2, Issue 2
BlackBerry Developer Journal
Step 4
//Sends the message
After the data has been extracted and translated, all that is required is to push the data to the BlackBerry device user. To
accomplish this, loop the recipients list to send data.
// Push the message we just built to
// all recipients.
for (int i = 0; i < recipientEmails.Count; i++)
SenderInfo curRecipient
= (SenderInfo) recipientEmails[i];
The sendToHandheld method sets up the URL and the HTTP
connection and sends the data to the BlackBerry device.
Author Biography:
Anubhav Srivastava (Ash) is currently in his last semester of Computer Engineering at the University of Waterloo and has
been programming in .NET for 3 years. His experience with a wide range of technologies and databases has inspired him to
help people integrate technologies to simplify tasks and make businesses more efficient. Ash is also a columnist for ASPAlliance [] and ASPToday []. His curiosity with wireless and BlackBerry ‘push’ technology has led him to integrate .NET programming with RIM push technology. In his free time he serves as the councillor for
the engineering faculty on University of Waterloo Federation of Students. Other interests include swimming and meditation.
You can reach him at [email protected]
Volume 2, Issue 2
BlackBerry Developer Journal
.NET : Building Mobile Web Forms for
BlackBerry Devices
Anubhav Srivastava
In this article I will show how to build a simple travel request
form using ASP .NET that sends form data to specific users
as email.
//perform validation
if(txtMailTo.Text=="" || txtFrom.Text=="")
("Please fill in to and from fields");
//If the code is validated then take all
//the input values and form an HTML message
MailMessage m=new MailMessage();
//Get input values from the form
m.To= txtMailTo.Text;
m.Subject="Travel Request";
m.Body= "Name : "+TextBox1.Text +"<br>"+
"Department : "+ TextBox2.Text +"<br>"+
"Cost Center and GL : " +
TextBox3.Text +"<br>"+
"Manager : "+ Textbox4.Text +"<br>"+
"Name of VP to Authorize : " +
Textbox5.Text +"<br>"+
"Destination : "+ Textbox6.Text +"<br>"+
"Date and Time of Departure : " +
Textbox7.Text +"<br>"+
"Additional remarks :"+ Textbox18.Text ;
//Send the message
//Redirect the user to another page saying
// message was sent successfully
Let’s get started
Open Microsoft Visual Studio® .NET and start a new
project of type “ASP .NET Mobile Application”. In
Form1.aspx, create an interface as shown below.
Post the page to your web server, access it from your BlackBerry device, enter some test data and then press the submit
button to send an email to the user in HTML format. This application can also be extended to send form data to a database instead of an email.
Author Biography:
Anubhav Srivastava (Ash) is currently in his last semester of Computer
Engineering at the University of Waterloo and has been programming in
.NET for 3 years. His experience with a wide range of technologies and
databases has inspired him to help people integrate technologies to simplify
tasks and make businesses more efficient. Ash is also a columnist for
ASPAlliance [] and ASPToday
[]. His curiosity with wireless and RIM push technology
has led him to integrate .NET programming with BlackBerry ‘push’
technology. In his free time he serves as the councillor for the engineering
faculty on University of Waterloo Federation of Students. Other interests
include swimming and meditation. You can reach him at
[email protected]
Double click on “Submit” and then enter in the following
using System.Web.Mail;
private void Command1_Click
(object sender, System.EventArgs e)
Volume 2, Issue 2
BlackBerry Developer Journal
BlackBerry Graphical User Interface Part 1
Mark Sohm, Research In Motion
The Screen class (net.rim.device.api.ui.Screen) is the starting point for the UI. Only one screen is displayed on a
BlackBerry device at any given time. Screens are displayed
on the device by pushing and popping them from the display
stack. The screen at the top of the display stack is the one
shown to the user. A screen can only exist once in the display stack, but can be pushed, or popped from, the display
stack at any time. Common subclasses of the Screen class
are contained in the net.rim.device.api.ui.container package.
A graphical user interface manages the relationship between
the application and its user. It is important to provide as
much information as possible in an easy to read manner using available screen space. An application that is easy to use
lets a user perform tasks in an efficient manner, whereas a
poor design can easily frustrate a user and prevent that person from using the application. A graphical user interface
should feel intuitive and familiar to a user. The BlackBerry
APIs can help developers by providing many common
screen elements for use in an application.
The Manager class (net.rim.device.api.ui.Manager) manages
the layout and interaction between field objects added to it.
A Manager is responsible for the location and layout of its
fields, as well as scrolling and focus change. A screen is required to have at least one manager to manage its fields,
even if the manager has been provided by the default constructor. Common sub-classes of Manager are located in the
net.rim.device.api.ui.container package.
The BlackBerry graphical user interface (GUI) is a three level hierarchical structure in its most basic form:
The Field class provides key functionality for all field components. A field represents a region contained by a manager
that is used to display output or handle input. The content
will vary depending on the field type and any restrictions
placed on the field. The net.rim.device.api.ui.component
package contains a library of prebuilt UI components and
controls for constructing BlackBerry applications.
A BlackBerry application requires at least one screen to display information. There are various extensions of the Screen
class available in the BlackBerry API set.
A screen that contains a single VerticalFieldManager as
its delegate manager.
Volume 2, Issue 2
Extends FullScreen and adds some additional functionality common to many BlackBerry device applications.
MainScreen also allows for a title area at the top of the
screen followed by a SeparatorField. The main area of
BlackBerry Developer Journal
the screen is scrollable because this screen contains a
VerticalFieldManager as its delegate manager that is
inherited from FullScreen. MainScreen also contains an
implementation of the makeMenu method to handle
menu creation.
theScreen.add(new LabelField("Hello there.");
A screen can be updated from outside of the main event
thread by calling the invokeLater() or invokeAndWait()
methods respectively. Use invokeLater() to change screens
when possible. This adds the screen change to the application’s event queue to be executed. The invokeAndWait()
method will force the code to be executed right away, halting
other processing. invokeAndWait() can be used when screen
updates must occur in a timely fashion, such as when performing an animation. invokeAndWait() should not be held
to perform lengthy operations.
The add method above can be run from the main event
thread. An IllegalStateException will be thrown if a thread
other than the main event thread attempts to execute this line
of code. The solution is to place the screen change in the
screen’s event queue or obtain the event lock.
A screen that provides dialog or status screen features.
A screen that provides the behaviour of a dialog box that
is used to present information to a user and accept input.
The alert, ask, inform and doModal methods of the Dialog class will display the Dialog and block (wait) for
user input. The show method of the Dialog class does
not block, therefore program execution will continue
after the Dialog has been displayed.
Calling invokeLater() repeatedly in rapid succession may
cause the event queue to overflow and result in an exception.
These methods should only be used when necessary and only
for the least amount of time to update the screen. Calculations should be performed outside of these methods. Code on
the event thread should not block or execute for long periods
of time because the system will not dispatch messages and
the event queue could overflow causing an exception to be
A screen that provides the features of a dialog but does
not accept user input or block. The status screen is
designed to display that an action that has taken place.
Status screens are set to display for a fixed time or until
the user presses the trackwheel, escape key or space
One of the most commonly used screen classes for a BlackBerry application is MainScreen which provides functionality to easily add a title and menu functions. The following
code sample demonstrates use of these methods.
The following code illustrates the use of invokeLater()
(new Runnable() {
public void run()
//Add a new LabelField to the screen.
theScreen.add(new LabelField
("Hello there.");
//Instantiate MainScreen
MainScreen theScreen = new MainScreen();
//Instantiate a LabelField
LabelField theTitle = new LabelField
("My application!");
//Set the title of theScreen
//Call the screen’s invalidate method to
//force the screen to redraw itself.
//Note that invalidate can be called
//at the screen, manager or field level,
//which means you can inform the
//BlackBerry to only redraw the area that
//has changed.
//Instantiate a MenuItem
MenuItem clickMe = new MenuItem
("Click Me!", 40, 40)
//The run command will be called when the user
//clicks on the MenuItem
public void run()
Dialog.alert("You clicked me!");
The next level beneath Screen in the BlackBerry UI heirarchy is the Manager class. Managers are responsible for vertical and/or horizontal scrolling, and the positioning and
layout of fields. Fields are added to managers which will
place it in an appropriate area on the BlackBerry device’s
screen. The BlackBerry API contains a set of managers that
extend from the Manager class and provide a layout mechanism for common screen designs.
//Add clickMe to theScreen
//Push the screen onto the display stack.
A screen that has been pushed to the top of the stack is under
the control of the main event thread. This means that only
the event thread is able to make changes to the screen. An
example of this could be adding a new LabelField to the
Volume 2, Issue 2
BlackBerry Developer Journal
LabelField leftTitle = new LabelField("Name");
Lays out fields from left to right in a single row. This
manager can provide horizontal scrolling for fields that
do not fit on the BlackBerry device screen as well as
vertical scrolling for fields that are taller than the screen.
LabelField rightTitle = new LabelField("Age");
//Determine half of the screen width.
width = Graphics.getScreenWidth() / 2;
Lays out fields in a single vertical column. This manager can provide vertical scrolling for fields that do not
fit on the BlackBerry device screen as well as horizontal
scrolling for fields that are wider than screen.
//Get the default font.
Font font = Font.getDefault();
//Determine the size of a space in the
//default font.
spaceSize = font.getAdvance(' ');
Lays out fields in a horizontal then vertical flow. Fields
are positioned from left to right, and any fields that do
not fit within the allotted horizontal space are placed on
the following line, starting from the left. The FlowFieldManager also supports horizontal and vertical scrolling.
//Build up a string that contains enough spaces
//that it fills half of the screen. This will be
//used to set the column width.
for(count = 0;count <= width;count += spaceSize)
sBuffer.append(' ');
Handles an icon, a message, and a special area which
can hold a list of user-specified custom fields. A VerticalFieldManager is used to layout the fields in the user
area. It lays out its icon in the top left corner, and its
message label in the top left corner.
//Add spacers to move to the next line and set
//the column width.
leftColumn.add(new LabelField
rightColumn.add(new LabelField
Managers are an extension of the Field class and can contain
other managers. This is known as nesting. Nesting can be
used to create enhanced layout styles such as a column or table layout. The following is a sample that designed to divide
a BlackBerry device screen into two even columns:
//Add some data to the screen.
//Populate and add the name and age fields.
for (count = 0; count < 5; count++)
displayNames[count] = new LabelField
displayAges[count] = new LabelField
//Create an instance of MainScreen.
MainScreen theScreen = new MainScreen();
//Create a HorizontalFieldManager to hold the
//two VerticalFieldManagers.
HorizontalFieldManager backGround =
new HorizontalFieldManager();
VerticalFieldManager leftColumn =
new VerticalFieldManager();
VerticalFieldManager rightColumn =
new VerticalFieldManager();
//Add the name LabelField to the left column.
//Add the age LabelField to the right column.
//The data to be displayed.
String[] names = {
int ages[] = {36, 34, 10, 8, 3};
//Add the two vertical columns to the
//horizontal field manager.
//Add the horizontal field manager to
//the screen.
//Arrays of fields to display the names
//and ages.
LabelField displayNames[] = new LabelField[5];
LabelField displayAges[] = new LabelField[5];
int count, width, spaceSize;
StringBuffer sBuffer = new StringBuffer();
//Add the column titles.
Volume 2, Issue 2
BlackBerry Developer Journal
The output of the sample code above will appear as two columns of text as shown below:
for (int i = 0; i < numberOfFields; i++)
//Get the field.
field = (CustomField)getField(i);
//Obtain the custom x and y coordinates for
//the field and set the position for
//the field.
setPositionChild(field, field.getXCoord(),
//Layout the field.
layoutChild(field, width, height);
//Set the manager's extent
setExtent(width, height);
public int getPreferredWidth()
//This manager is designed to utilize the
//entire screen width.
return Graphics.getScreenWidth();
public int getPreferredHeight()
//This manager is designed to utilize the
//entire screen height.
return Graphics.getScreenHeight();
A field represents a region contained by a manager. All
fields are derived from the base Field class. The BlackBerry
API contains many specialized fields that have been detailed
The Manager class can be extended to allow custom behaviour. This lets you position fields in a unique manner, or add
a graphical effect to the screens in your application. The following is an example of a custom manager that works with a
custom field that will be discussed later in this article. The
custom field allows you to set its x and y coordinates used to
position the field in the manager. The custom manager below makes use of these x and y coordinates to determine
where to draw the field.
A field that uses a supplied set of string patterns to scan
through simple text and pick out 'active' regions. These
active regions are identified with underlining and are
designed to supply additional menu items if a user clicks
on them. This field supports use of the device’s AutoText dictionary and abides by any AutoText replacment
rules. Meaning, when a word is entered that is in the
AutoText database for the current locale, this field
replaces it, including any effects of macro expansion.
Pressing backspace when the cursor is on the most
recent autotext expansion reverses all effects of the
AutoText substitution.
public class CustomManager extends Manager
public CustomManager()
//Disable scrolling in this manager.
A field that uses a supplied set of string patterns to scan
through a simple text string and pick out 'active' regions.
These active regions are identified with underlining and
will supply additional menu items if the user clicks on
them. This field also supports the formatting of a RichTextField.
//Override sublayout.
protected void sublayout
(int width, int height) {
CustomField field;
//Get the total number of fields within
//this manager.
//Note that this manager only supports the
//CustomField described within this article.
int numberOfFields = getFieldCount();
Volume 2, Issue 2
This field supports the use of the AutoText dictionary
on the device and will abide by any AutoText replace-
BlackBerry Developer Journal
ment rules. Meaning, when a word is entered that is in
the autotext database for the current locale, this field
replaces it, including any effects of macro expansion.
Pressing backspace when the cursor is on the most
recent autotext expansion reverses all effects of the
autotext substitution.
A field of no size that can provide specialized focus
An extension of ChoiceField that supports the selection
of a range of numbers. It is recommended to keep the
number of values in this list to less than 20.
An editable text field that can contain a label. The label
will appear to the left of the editable area. BasicEditField does not support any text formatting options.
A field that will display a bitmap.
An extension of the ChoiceField that supports a list of
objects. All contained objects must support the
toString() method.
An extension of ListField that displays a list of objects.
All contained objects must support the toString()
A clickable button that can contain a text label.
This field consists of a text label and a checkbox. The
checkbox appears to the right of the text label.
An extension of an EditField where entered data is displayed as a mask of asterisks (*) equal to the number of
characters entered.
This field consists of a text label and a choice selector/dropdown list. The choice selector will expand to
display a list of choices when clicked on or when the
“Change Option” menu item is selected. Using the space
bar or holding the Alt key while scrolling the trackwheel
can also change choices. Text in the drop down list will
be truncated if it does not fit within the available width.
ChoiceField is an abstract class and cannot be instantiated directly.
This field consists of a text label and a radio-button control. The radio-button control appears to the right of a
text label. These fields can be grouped using a
RadioButtonGroup where only one field may be
selected at a time.
Displays a text label followed by a formatted date value.
A read-only text field to show text in a variety of fonts
and formatting styles (bold, italics, underlined, etc.).
A field that displays a horizontal line across its width.
An extension of BasicEditField. EditField also allows a
user to enter special characters entered by holding a key
while rolling the trackwheel. This is common for locales
that utilize characters with accents.
A field that will display a tree structure.
A field must be added to a manager to be shown to a user.
This is done by calling the add method of a manager, passing
it the field you wish to add. Fields may only be added to one
manager at a time but can be removed and re-added during
their lifespan. The following sample code illustrates adding a
LabelField to a VerticalFieldManager.
An extension of EditField. EmailAddressField is
designed to only allow characters to be entered that are
valid for an email address.
LabelField myField =
new LabelField("Hello world!");
VerticalFieldManager myManager =
new VerticalFieldManager();
A horizontal bar that can be used for either numerical
selection or as a progress indicator.
A label of unformatted text.
The Field class can also be extended to allow custom behaviour. This may be screen placement, visual changes or other
forms of custom functionality. The following is a sample
class that extends the Field class. It works with the sample
CustomManager class shown earlier in the Manager section
of this article. This field creates a non-focusable circle that
can be placed anywhere on the screen. It adds additional
methods to get and set the x and y coordinates of where the
field will be shown in the manager.
Displays rows of selectable items. Lists will support
prefix searching by default where pressing a character
selects the next item starting with the character. ListFields must register a ListFieldCallback object to handle
repaint tasks. When this field must display a particular
item in its list, it invokes the appropriate methods on the
registered callback object.
Volume 2, Issue 2
BlackBerry Developer Journal
yCoord = yVal;
public class CustomField extends Field
implements DrawStyle
private int fieldWidth, fieldHeight,
xCoord, yCoord;
//Get the y coordinate of the field.
public int getYCoord()
return yCoord;
//Retrieves the preferred width of the button.
public int getPreferredWidth()
return fieldWidth;
//Retrieves the preferred height of
//the button.
public int getPreferredHeight()
return fieldHeight;
//Lays out this field's contents.
//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.
public void layout(int width, int height)
//Repaints the button.
//The field's manager invokes this method
//during the repainting process to instruct
//this field to repaint itself.
public void paint(Graphics graphics)
//Draw a circle the size of the field.
graphics.fillArc(fieldWidth / 2, 0,
fieldWidth, fieldHeight, 0, 360);
public CustomField(int xVal, int yVal)
//Create a non focusable field.
//Set the x and y coordinates.
xCoord = xVal;
yCoord = yVal;
//Set the field to be one quarter the screen
//width and height.
fieldHeight = Graphics.getScreenHeight()/4;
fieldWidth = Graphics.getScreenWidth()/4;
//Set the x coordinate of the field.
public void setXCoord(int xVal)
//If the x coordinate is different the the
//current x coordinate
//set the x coordinate to the new value and
//call the invalidate method of this field.
//Calling invalidate will force the field
//to be repainted.
if (xVal != xCoord)
xCoord = xVal;
//Get the x coordinate of the field.
public int getXCoord()
return xCoord;
//Set the y coordinate of the field.
public void setYCorrd(int yVal)
//If the y coordinate is different the
//current y coordinate then set the y
//coordinate to the new value and call the
//invalidate method of this field.
//Calling invalidate will force the field
//to be repainted.
if (yVal != yCoord)
By making use of screens, managers and fields, you will be
able to create an application with a familiar look and feel.
Extending any of these classes will allow you to add a custom look or function to your application as shown in the
CustomManager and CustomField samples. Making use of
the graphics class methods and drawing directly to a screen,
manager or field can achieve even further customization.
Stay tuned for part two of The BlackBerry Graphical User
Interface in the next issue to learn about the power of the
graphics class!
Please email your comments, suggestions and editorial submissions to [email protected]
Volume 2, Issue 2
BlackBerry Developer Journal
Logging Your Calls with the Phone API
Rohit Gupta, BlackBerry Solutions Group, Research In Motion
Sample Time!
Blackberry® Java Development Environment version 4.0
provides several new APIs, one of them being With the addition of this API, advanced
tools are provided to manipulate phone data and phone features. The Phone Logs API in particular has proven useful
for firms using time billing.
Figure 1 shows the generic call log found on all BlackBerry
devices. The only information shown are numbers of calls
dialed or received. Figure 2 shows the log of both numbers
created by using the Phone Log API.
The Phone Logs API provides functionality to extract a great
deal of information regarding phone activities on a BlackBerry wireless device.
Note: To add notes on a call, press the track wheel while on
the call and select notes. Once finished typing your note,
press the track wheel again and select hide notes. Please see
Figure 3 and 4 for visualization.
The three main benefits of the Phone Log API are:
Application integration
Customizing of User Interface
Every time this application is invoked it will hold the current
values of the call. This is because the phone thread receives a
new instance of the phone log when the application is invoked. (See the second line in the function run () under the
Phonethread class.)
3. Redundant backup for all calls
Firms that bill by the second need to have accurate billing
data. The Phone Log API can be used within a third-party
application on the BlackBerry device to provide exact information regarding any call when integrated with a billing system. For example, if a simple expense report requires the
amount of time spent on the phone per call, this API could be
used to provide that information and display it within the expense report.
There can be a need for customization due to information required by the BlackBerry device user. The Phone Log API
allows developers to customize their options in regards to
log data. These options include date of the call, length of the
call, notes made on the call, number of the call, setting ID to
a number, call status, and more.
Figure 1
Note: For a listing of all the functions found in this API
please refer to “API Spotlight: BlackBerry Apps Phone
Home” in Volume 2, Issue 1 of The BlackBerry Developer
Redundant backups are made by having the log data copied
to another application on the BlackBerry device. The application can also be configured to send this data to a server
process at regular intervals where it can be processed or
stored. This ensures that critical call notes will not be lost
and that all numbers will be saved in more than one location.
Figure 2
Volume 2, Issue 2
BlackBerry Developer Journal
Figure 3
Figure 4
Sample Code
* This sample illustrates logging phone calls or keeping a record of them using the phonelogs API.
* This sample logs all calls except missed calls.
class Phone_Log extends UiApplication{
*an instance of MainScreen, to add display content and set display options on the device
MainScreen _screen = new MainScreen();
* instance of Phonethread(used in the background to retrieve data)
Phonethread _phone;
Date _date;
* Instance of PhoneLogs API, used for filtering through the log
PhoneLogs _logs;
* will define the total talk time
int _total = 0;
* Will hold the string value of the date variable
SimpleDateFormat _formatedDate = new SimpleDateFormat(DateFormat.DATE_DEFAULT);
* main function that starts the event thread
public static void main(String arg[])
Phone_Log application = new Phone_Log();
//create a new instance of the application
//and start the application on the event thread
* Class constructor
* Sets the application title, starts a separate phone thread,
* and pushes the screen on the device
public Phone_Log(){
_screen.setTitle("Phone Log");
Volume 2, Issue 2
BlackBerry Developer Journal
_screen.add(new RichTextField("Activities on your Phone"));
_screen.add(new SeparatorField());
_phone = new Phonethread();
* Private class that extends thread.
* It will run in the background, and not affect the performance of the device.
private final class Phonethread extends Thread{
* Class constructor, invokes super
public Phonethread(){
* Run method that will receive a copy of the phone log and work through it to collect data.<p>
* It will then display the log in chronological order. The items that will be displayed are:
* the date of a call; the number of the call; the duration of the call in seconds;
* and if there were any notes. Uses the screen variable to display items on the device.<p>
* The log will only be taken from the normal folder, which contains all calls except
* the missed. For a log of missed calls please use missed folder.
public void run(){
_date=new Date();
//using normal folder because this is where all call logs are stored
//except the ones that are missed.
for(int i=0;i<(_logs.numberOfCalls(_logs.FOLDER_NORMAL_CALLS));i++){
//extracting the date from the log
_date=_logs.callAt(i, _logs.FOLDER_NORMAL_CALLS).getDate();
PhoneCallLog callLog=(PhoneCallLog)_logs.callAt(i, _logs.FOLDER_NORMAL_CALLS);
String number=callLog.getParticipant().getNumber();
String data=_formatedDate.formatLocal(_date.getTime());
//seeing if a call is received or dialed and outputting the correct information
if(callLog.getType() == callLog.TYPE_RECEIVED_CALL){
_screen.add(new RichTextField("You received a call from: "+number));
_screen.add(new RichTextField("it was received on: "+data));
if(callLog.getType() == callLog.TYPE_PLACED_CALL){
_screen.add(new RichTextField("The number you dialed was: "+number));
_screen.add(new RichTextField("it was made on: "+data));
//adding the duration of the call and any notes that were made
_screen.add(new RichTextField("It lasted for: "+ callLog.getDuration() + " secs"));
_screen.add(new RichTextField(""));
_screen.add(new RichTextField("These are your notes: " +callLog.getNotes()));
_screen.add(new SeparatorField());
//end for
_screen.add(new RichTextField("Total time spent on the phone: "+_total+" secs"));
} //end run
}//end phonethread
}//end Phone_Log
Volume 2, Issue 2
BlackBerry Developer Journal
The functions used to navigate through a phone log are
callAt() and getInstance(). callAt() will return a CallLog
object. Use that object to extract data and/or set data. getInstance() is important because it is designed to always return
the current values stored in a Phone Log.
EditField phonefield =
new EditField("Please enter a # ");
String number = phonefield.getText();
String log_number =
Extract the data here, everything inside
the current FOR loop would go here.
The classes PhoneCallLog (which extends CallLog) and
PhoneCallLogID return data structures from a call record.
PhoneCallLogID, and deals with data regarding the phone
number. This class contains getNumber(), getName(), setName() and more.
PhoneCallLog will produce the rest of the data like getDate(), getNotes(), getStatus() and setNotes(). It is important
to use all classes in this API to build an appropriate phone
log application.
Note: There is no function in the API that matches a telephone number with the records in the log. You must traverse
through the callAt (int index, long folderID), function like it
has been done in the sample.
In this sample, all call activities for all calls were displayed.
If you need to display information for only a select range of
calls, you can either:
Given a telephone number in string format, do string
equals with callLog.getParticipant().getNumber(), in a
nested IF statement. Use the same format as found in
this sample to display information. For example, use the
same FOR loop found in the sample under the run()
method, and modify it by inserting the following code
before invoking any other methods.
Enter the index number of the call to find information
using callAt() function. For example:
I wrote this article as an overview of the capabilities of this
API, and created the sample code to show the ease of development. As noted above, this new API is likely to benefit
any organization that wants to develop a more streamlined,
independent or bill-as-you-go phone log system.
int j = index_number;
callAt(j, logs.FOLDER_NORMAL_CALLS).get...
After gaining focus to a certain call, the application can
“get” any data pertaining to it.
Please email your comments, suggestions and editorial submissions to [email protected]
Volume 2, Issue 2
BlackBerry Developer Journal
BlackBerry Application Control
Mike Kirkup, Research In Motion
With the introduction of Application Control in BlackBerry® Handheld Software version 3.8 and version 4.0, it is important for developers to be aware of what Application
Control does and its impact on an application.
Application Control is designed to provide an IT Administrator with the ability to establish what capabilities an application should have when executing on a specific BlackBerry
device. It is important to note that Application Control can
only be effective when the BlackBerry device is connected
to the BlackBerry Enterprise Server within an enterprise setting.
For example, Application Control would allow the IT Administrator to ensure that a game loaded onto a device is not
allowed to access the Phone API. This article will list the different areas that are currently covered by Application Control, what method call in that API will invoke the
Application Control check and how application developers
should modify their code to properly handle these checks.
In the case where the IT Administrator or BlackBerry device
user have denied the application access to one of the protected areas, the associated method will throw a ControlledAccessException. In the case of class level checks, it will throw
a ClassDefNotFoundError. The ClassDefNotFoundError occurs in Java™ when an exception is thrown from a static
constructor. Your application will need to handle both of
these types of errors depending on what APIs you attempt to
Application Control currently covers the following areas:
Methods and APIs:
External Connections
An external connection is defined as one that would not
be able to retrieve information from inside the firewall.
Common examples of an external connection would be
Direct TCP and WAP.
Methods and APIs:
Local Connections (USB or Serial Port)
A local connection is defined as one that involves one of
the local ports on the device such as the USB or Serial
Methods and APIs:
Interprocess Communication
Handheld KeyStore
Interprocess communication refers to allowing an application to access methods or APIs that would provide an
application with the ability to share information with
another process application on the BlackBerry device.
The Handheld KeyStore is defined as part of the
net.rim.device.api.crypto.keystore API. This policy is
designed to determine whether applications are allowed
to access the keystore. The keystore contains certificates, public keys and private keys for the user.
Methods and APIs:
Methods and APIs:
Bluetooth® Serial Port Profile
Internal Connections
On BlackBerry devices that support Bluetooth there is
an API which provides the Serial Port Profile (SPP) for
An internal connection is defined as one that would be
able to retrieve information inside the firewall. The most
notable example of an internal connection would be a
connection via the BlackBerry Mobile Data Service,
which is typically located behind the firewall.
Methods and APIs:
Volume 2, Issue 2
BlackBerry Developer Journal
Email API Access
Event Injector API
The email API net.rim.blackberry.api.mail allows
applications to access mail stored on the device.
The Event Injector API net.rim.device.api.system.Event
Injector allows applications to inject events such as key
events and trackwheel events into the system in order to
simulate a BlackBerry device user initiating these
Methods and APIs:
Methods and APIs:
PIM API Access
Browser Filters API
The PIM APIs provide applications with the ability to
access PIM information (Contacts, Tasks, and Events)
on the device:
• net.rim.blackberry.api.pdap
javax. microedition.pim
The Browser Filters API
allows application developers to register fully qualified
domain names to have their application invoke when the
browser requests content from that domain name. The
application can then add, remove or otherwise modify
content before passing it up to the browser.
Methods and APIs:
Methods and APIs:
Phone API Access
The Phone API and the
Invoke API net.rim.blackberry.api.invoke provides the
application developer with unique capabilities such as
invoking the phone application or retrieving the phone
logs on the device.
Methods and APIs:
Volume 2, Issue 2
BlackBerry Developer Journal
cHTML In Depth
Jennifer Emery, Research In Motion
cHTML (Compact HyperText MarkUp Language) is designed for small portable devices such as the BlackBerry®
device, phones and other PDAs (Personal Digital Assistants). It is derived from a subset of HTML 2.0, 3.2 and 4.0
specifications. Development using cHTML is becoming
more essential in today’s expanding wireless market.
Immediately following DOCTYPE, the opening:
Almost all portable devices will have some form of hardware
restrictions. These restrictions can be any or all of the following items: memory, CPU, little or no secondary storage,
display size and color, single character font or restricted input methods, to name a few. cHTML takes into account
these restrictions when developing sites for portable devices.
... should follow. Per the cHTML specification, the version
attribute can also be included within the opening <html> tag.
This attribute declares the type of page that will be displayed. For cHTML, the version would be:
... and closing HTML tag:
<html version="C-HTML 1.0">
The overall design of cHTML is based on four principles:
Based on the current HTML recommendations.
“Lite Specifications.” cHTML pages are viewed on a
limited memory and lower power CPU devices.
Viewed on small monochrome or color display screens.
Note: The following code samples must include the cHTML
header, and must be wrapped between the HTML tags.
Like basic HTML or xHTML web pages, cHTML pages are
divided into two main sections:
Easily operated by end-users. cHTML is designed to
provide the end-users with basic operation.
The features listed below are excluded from the cHTML
<head>Header Section</head>
Images - .jpeg / ImageMaps
Contains information about the document such as title, style
and meta information. The tags <base>, <title> and <meta>
are supported. These tags must be placed between the opening <head> and closing </head> tags.
Multiple character fonts and styles
Background color and images
<base />
Style Sheets
Several benefits of using cHTML are:
Defines a base URL for all links (including images) on the
particular page.
Allows mobile devices to view web pages.
For example:
cHTML retains the advantages of HTML and may solve
restriction problems that mobile devices may have.
<title>cHTML Page</title>
<base href= />
<img src="Send.gif" />
HTML authoring tools can reference cHTML
This article focuses on cHTML development for the BlackBerry device while delving into the cHTML specifications.
The Basic Structure
A cHTML page should begin with the definition of the document type. The DOCTYPE tells the browser which page
specification to use and specifies any rules that may apply to
the page.
The Send.gif image is located in the subfolder called Images.
There is only one DOCTYPE for cHTML which is defined
Defines a title for the page that is displayed in the title bar on
the browser window.
<title>Page Title</title>
HTML 1.0 Draft//EN">
Volume 2, Issue 2
BlackBerry Developer Journal
<meta />
<blockquote>Blockquote text</blockquote>
Provides meta information about the page. Newer versions
of the BlackBerry Browser contain limited support for meta
tags, however only one of the three valid http-equiv types
(refresh, expires and cache-control) are supported by the
cHTML specification:
The BlackBerry Browser version 4.0 or later is designed to
indent the enclosed text by one full-width space. Earlier versions of the BlackBerry Browser will not render the indentation.
Code Sample:
<blockquote>This is the start of the blockquote,
which defines the start of a long
This is used to refresh the page at specified intervals, and can
be used to redirect one page to another. For example:
<meta http-equiv="refresh" content="2; url =
http://localhost:8080/BlackBerry/index.html" />
BlackBerry Browser Output:
<body>Body Section</body>
Contains page contents, such as text and images. The body
tag contains numerous attributes that can customize how the
page is displayed. Note that the cHTML specification does
not include support for these attributes.
The cHTML skeleton structure so far:
HTML 1.0 Draft//EN">
<title>CHTML Page</title>
<meta /><!-- Meta tags would appear here -->
<pre> Preformatted text, fixed-font </pre>
The <pre> tag may show the enclosed text with the following characteristics:
BlackBerry Browser Output:
leave white space intact
render text with a fixed-pitch font
disable automatic word wrap
must not disable bidirectional processing.
<center>pre Element</center><br />
This is preformatted text
Line # 2
Line # 3
Line # 4
BlackBerry Browser Output:
Note: Any text enclosed with the <!-- - -> tag is defined as a
comment. Comments are used to describe the source code
and are ignored by the browser.
Text Formatting - Supported Style Tags
The BlackBerry Browser has the ability to recognize a variety of style tags, such as <b>bold text</b>, and <u>Underline Text</u>. The cHTML specification limits which style
tags are supported.
Volume 2, Issue 2
BlackBerry Developer Journal
Defining a header
BlackBerry Browser Output:
Header tags are used to emphasize text on a page. There are
six sets of tags, <h1></h1> through to <h6></h6>. <h1> is
the largest header and <h6> is the smallest. An align attribute can be added to align the enclosed text, either left,
center or to the right.
Code Sample:
<h1>Header # 1</h1>
<h2 align="right">Header # 2</h2>
<h3>Header # 3</h3>
<h4>Header # 4</h4>
<h5>Header # 5</h5>
<h6>Header # 6</h6>
<div>A division or section within the
BlackBerry Browser Output:
The div tag is a way to add structure to the contents of the
page. It includes an align attribute that is used to horizontally
align the contents. The possible values for align are left, center or right. Vertical alignment is ignored by the BlackBerry
Browser application.
Code Sample:
<div align="left">This is div, left
<br />
<div align="center">This is div, center
<div align="right">This is div, right
<br />
Text Layout
The cHTML language supports tags that align, list and display page contents in a customized way. The following tags
illustrate all supported layout tags.
<br />
Inserts a single line break
BlackBerry Browser Output:
In previous versions of the BlackBerry Browser (3.7 and earlier), multiple <br /> tags in a row will be ignored. The
BlackBerry Browser version 4.0 or later is designed to execute and render multiple <br /> tags correctly.
An align attribute can be added to a tag to determine where
the next line will start. Note that the BlackBerry Browser
will ignore the align attribute if included in the tag.
<center>Center enclosed text</center>
<center>Center Element</center>
Volume 2, Issue 2
BlackBerry Developer Journal
The following code sample shows each alignment value.
<hr />
Insert a horizontal rule
Draws a horizontal line. The <hr /> tag incorporates several
formatting attributes as shown in the following table:
BlackBerry Browser Output:
Aligns the rule on the page.
The default value is center.
Determines the height of the rule.
The default value is 1.
Determines the width of the rule.
The default value is 100%.
When specified, the rule is rendered as a solid
color rather than a traditional 2-color
align="center">P Element</p>
align="left">Left Align</p>
align="center">Center Align</p>
align="right">Right Align</p>
Note: Older versions of the BlackBerry device(versions 3.7
or earlier) may not render the <p> align properly.
Code Sample:
<center>hr Element</center><br />
Line # 1
Line # 2
<hr size="10" width="50" align="center">
Line # 3
<hr size="10" noshade>
Layout - Lists
There are numerous methods within the cHTML specifications for providing a list structure. Each type of list will differ slightly from a visual perspective when the page is
rendered but are all used to organize page contents.
BlackBerry Browser Output:
The first style is a simple ordered or unordered list. The
items in an ordered list appear in a numbered sequence. In an
un-ordered list, the items are prefixed with a bullet. In other
web languages, such as HTML or xHTML, the type of bullet
can be defined. However, the cHTML specification does not
permit this.
The following code samples illustrate these styles:
Ordered List:
<li>Item # 1
<li>Item # 2
<li>Item # 3
<p>New paragraph of text</p>
Unordered List:
The paragraph tag must be properly closed, as some browser
applications will ignore empty tags. Paragraphs can be
aligned to the left, center or right:
<li>Option # 1
<li>Option # 2
<li>Option # 3
<p align="left">
<p align="center">
<p align="right">
The BlackBerry Browser supports horizontal alignment of
text, and ignores vertical alignment.
Volume 2, Issue 2
BlackBerry Developer Journal
BlackBerry Browser Output:
BlackBerry Browser Output:
The <li> tag defines a list item. Lists can be nested inside
each other, creating a multi-tier list. The following code
sample illustrates nested lists:
The start and end of a definition list.
The start and end of the term within a
definition list.
<li>Item # 1
<li>Item # 2
<li>Item # 3
The start and end of the description of a
term in a definition list.
# 1
# 2
# 3
A third list type is a directory list. A directory list is created
using the <dir></dir> tag, where each item in the list is prefixed with the <li> element.
For example:
<li>Item # 1
<li>Item # 2
<li>Item # 3
# 4
# 5
BlackBerry Browser Output:
The second list style is a definition list which consists of two
Code Sample:
A device that computes, especially a
programmable electronic machine that
performs high-speed mathematical or
logical operations or that assembles,
stores, correlates, or otherwise
processes information.
The last type of list is designed for single column menu lists.
A menu list is defined by using the <menu></menu> tags
along with using the <li> tag to list each individual menu
For example:
Volume 2, Issue 2
BlackBerry Developer Journal
The BlackBerry Browser supports the following link
BlackBerry Browser Output:
The syntax for a mailto link is as follows:
<a href="mailto:[email protected]">
Email [email protected] for Application
Development Support</a>
Special Characters
cHTML supports a variety of special characters. These characters can range from symbols to spaces or dashes. For example, below is a very small subset of these characters:
The BlackBerry Browser can recognize wbmp (monochrome
wireless bitmap), gif, tif, jpeg, and png image formats. When
using a BlackBerry Mobile Data Service, this service will
convert gif images to png format as png images have a higher compression ratio and support alpha channels. Jpeg images are used on color screen BlackBerry devices only.
Code Sample:
Copyright - &copy; or &#169; <br />
Quotation Mark - " or &quot; or &#34; <br />
Ampersand - & or &amp; or &#38; <br />
Registered Trademark - &reg; or &#174; <br />
Less-Than - < or &lt; or &#60; <br />
Greater-Than - > or &gt; or &#62; <br />
The following tables lists all attributes associated with the
<img> tag:
BlackBerry Browser Output:
The source (link/URL) of the image.
Aligns images horizontally or vertically on
the page. Acceptable values are left, right, top,
middle and bottom. The BlackBerry Browser
aligns images to the left by default and ignores
center alignment. In addition the BlackBerry
Browser ignores vertical alignment.
Short image description. The enclosed text
will display if the image is unavailable or if
the user has disabled display of images on the
BlackBerry Browser.
For a complete list of all special characters, please see the
following Developer’s Knowledge Base article:
Specifies the image width.
Ignored by the BlackBerry Browser.
Specifies the image height.
Ignored by the BlackBerry Browser.
Specifies white space to the left and right
sides of the image.
Ignored by the BlackBerry Browser.
Specifies white space to the top and bottom of
the image.
Ignored by the BlackBerry Browser.
Defines a border.
Ignored by the BlackBerry Browser.
Navigation is an important element in any web page and is
created through links. Links are defined by the use the anchor (<a> and </a>) tag, where the enclosed text appears underlined to represent a hyperlink. The attributes “name” and
“href” are the only attributes supported in cHTML.
Volume 2, Issue 2
BlackBerry Developer Journal
The cHTML specification does not include support for image maps (i.e. usemap/area tags).
BlackBerry Browser Output:
Adding a form to any web page enhances functionality and
user interaction. Data from the form fields is collected when
the “Submit” button is selected. The name and associated
values are gathered and submitted to the specified location.
cHTML provides support for basic forms, which is also supported by the BlackBerry Browser.
The syntax supported by the BlackBerry Browser is:
Any option that includes the checked attribute will automatically be displayed as selected when the page loads.
<form action="" method="">
Attribute: name
A request form attribute to set the submission URL.
The check box group name. Required attribute.
Attribute: value
The HTTP method used to submit data to the URL
specified in the action attribute. The method is set to
either POST or GET, and is set to GET by default. GET
submits the form contents within the URL, where POST
submits contents in the body of the request.
Specifies the value of the check box. This value is sent
to the server when the form is submitted. Required
type: hidden
The cHTML specification also includes the “enctype” attribute for the opening <form> tag, which defines the mime
type used to encode the contents of the form. Note that the
BlackBerry Browser will ignore this attribute.
Defines a hidden element on a form. This item will be included when the form is processed but is not displayed in the
browser window.
The <input> tag is used to define a field on a form:
<input type="" name="" value="">
<input type="hidden" name="HiddenField"
value="HiddenValue" />
There are several different types of input fields, however the
default (if not specified) is “text”. The following describes
each type of input in detail:
type: password
type: checkbox
Creates a password input field. The characters entered are
masked with an asterisk (*).
Defines a checkbox control.
<input type="password" name="UserPassword"
size="10" maxlength="5" />
<input type="checkbox" name="CheckBox"
value="1" checked />Check Box # 1<br />
<input type="checkbox" name="CheckBox"
value="2" />Check Box # 2<br />
<input type="checkbox" name="CheckBox"
value="3" />Check Box # 3<br />
<input type="checkbox" name="CheckBox"
value="4" checked />Check Box # 4<br />
The “size” attribute is used to set the size of the field
that is displayed.
The “maxlength” attribute is used to limit the number of
characters that can be entered.
type: radio
Defines a radio control where only one option can be selected at a time.
<input type="radio"
value="1" />Radio
<input type="radio"
value="2" />Radio
Volume 2, Issue 2
# 1<br />
# 2<br />
BlackBerry Developer Journal
<input type="radio" name="RadioControl"
value="3" checked />Radio # 3<br />
Note: The input type “img” and “file” are not supported by
the cHTML specification nor the BlackBerry Brower
BlackBerry Browser Output:
Another input method that can be added to the form is a
selection list (or drop-down list). This is created through a
<select> tag, which can be set to single-selection or
multiple-selection. The select is set to single-selection by
default, where the first item is automatically selected (unless
specified differently). To create a multiple-selection drop
down list, you must specify the attribute “multiple” in the
opening select tag. A select list contains one or more
<option> tags to define items in the drop-down list. Each
<option> tag appears between the opening and closing select
Example: Single Select List
type: reset
<select name="SingleSelectList">
<option selected>Option # 1</option>
<option>Option # 2</option>
<option>Option # 3</option>
<option>Option # 4</option>
Displays a Reset button. When selected, all form fields are
restored to their original values.
<input name="ResetButton" type="reset" />
When an <option> tag contains the “selected” attribute, it
displays the item as selected when the page loads. In addition, this item will also be displayed first in the list.
type: submit
BlackBerry Browser Output:
Defines a Submit button. When selected, the contents of the
form are submitted to the provided URL with the action attribute of the form element.
<input name="SubmitContents" type="submit" />
type: text
Defines a text input field.
BlackBerry Browser Output:
Enter Information:<br />
<input type="text" name="TextField"
size="10" maxlength="20" />
BlackBerry Browser Output:
Example: Multiple Select List
<select name="MultipleSelectList"
multiple size="1">
<option value="Option1" >Option # 1</option>
<option value="Option2">Option # 2</option>
<option value="Option3" selected>
Volume 2, Issue 2
BlackBerry Developer Journal
The last type of field that can be added on a form is
“textarea.” A textarea field is a multi-line text area, defined
by the <textarea> tag. You can specify the number rows and
columns visible in the text area within this tag.
Option # 3</option>
<option value="Option4">Option # 4</option>
BlackBerry Browser Output:
The following example defines a textarea that spans 10 rows
and 15 columns:
<label>Text Area:</label><br />
<textarea name="TextArea1" rows="10"
BlackBerry Browser Output:
BlackBerry Browser Output:
For additional web development information for the BlackBerry Browser, please visit the Developer’s section of
An additional attribute called “size” can be added into the
opening <select> tag. This attribute determines the number
of visible items in the drop down list. If this attribute is not
specified, all items are shown in the drop down list when selected by default. For example, if the size attribute is specified and set to “2”, two items will be displayed when the
drop down list is selected.
... or visit the World Wide Web Consortium:
Please email your comments, suggestions and editorial submissions to [email protected]
Volume 2, Issue 2
BlackBerry Developer Journal
Pimp My Object:
Creating a TextBox Field
Michael Clewley, Editor
Java lets developers take an existing element, use its current
pieces, and build something unique to the developer’s needs
that is based on the original element. This column will focus
on doing just that. Like Doctor Frankenstein, we will take
elements from objects and combine them into something that
has a life of its own.
The default constructor performs a few small tasks here.
When an instance of the TextBoxField is first created, the
width and height of the field itself is passed. Another key
component is to call the super instance of the VerticalFieldManager and pass it the Manager.NO_VERTICAL_
SCROLL flag. This keeps the edit field in place and provides
the desired scrolling effect.
When designing and laying out a screen for a BlackBerry
device application, you must keep in mind what the needs of
the user are and how to make it user friendly yet esthetically
pleasing at the same time. Combining all three aspects of
screen design into a flowing piece of art can be difficult at
times. From one developer to another, I suggest that you
shouldn’t sell yourself short because creating an attractive
but useful screen is a work of art. Yes, a Picasso you are!
public TextBoxField(int width, int height) {
managerWidth = width;
managerHeight = height;
The next part of the constructor is to create two elements that
will be added to the VerticalFieldManager, and then create
another VerticalFieldManager that allows vertical scroll. We
will create the edit field after the manager has been created.
A small modification is required for the edit field to override
the paint() method and invalidate() the manager each time
the field has to repaint itself. This helps keep the border
around the field clean when scrolling occurs. Lastly, add the
edit field to the vertical field manager, and add the vertical
field manager to the primary vertical field manager.
Did you ever notice that an edit field just doesn’t always
work from an esthetic point of view? Text entry that involves
more than one line can cause all elements on the screen to
shift. Perhaps you just want your edit field to have a nice
border around it. In this issue we will focus on creating a
TextBox field in an attempt to address similar issues.
For this article I have defined a TextBox field to have the
following attributes:
VerticalFieldManager vfm =
new VerticalFieldManager
fixed width and height
surrounded by a border
editField = new EditField(){
public void paint(Graphics g) {
multiple lines of text do not increase the size of the edit
field or cause the screen, or objects on the screen, to
shift or scroll
the field will scroll if it contains multiple lines of text
Now that we have a definition, let’s look at how to accomplish this feat. We will create a TextBoxField class so that
the object can be reused time and time again without modification or recoding.
One of the first things that may seem odd is that we are
extending a VerticalFieldManager and not an edit field. The
manager is going to be responsible for the fixed width and
height of the field, and will also help with the scrolling
Now override the paint() method of the vertical field manager to provide the border around the field itself. Here we are
just drawing a simple rectangle around the field based on the
width and height that you provided when the object was
instantiated. Of course if you wanted to really get crazy,
more content could be added here that really lets out the Picasso in you. Always remember that at some point you need
to call super.paint()!
public class TextBoxField extends
VerticalFieldManager {
//define some variables to be used
//in the class
private int managerWidth;
private int managerHeight;
private EditField editField;
Volume 2, Issue 2
public void paint(Graphics g) {
g.drawRect(0, 0, getWidth(), getHeight());
BlackBerry Developer Journal
Overriding the vertical field manager’s sublayout allows the
fixed properties of the field to be maintained. We start with
two simple checks to ensure that the width and height are not
zero. If so then use the values that have been passed into sublayout by the system. Call super.sublayout() once the boundaries have been established. This is a needed step to ensure
that your field is created successfully. After super.sublayout
has been called we need to force the extent of the manager.
This step gives the fixed height of the field where the call to
super.sublayout() provides the fixed width.
That’s it! The TextBoxField has now been coded. All that’s
left is to add it to your application and instantiate it. Let’s
take a look at the end result.
public void sublayout(int width, int height) {
if (managerWidth == 0) {
managerWidth = width;
if (managerHeight == 0) {
managerHeight = height;
super.sublayout(managerWidth, managerHeight);
The last step is to provide methods that allow you, as a
developer, to set or read the text of the field. Because the
TextBoxField class is extending a manager and not an edit
field, these methods are not inherited. These methods will
access the edit field that was created in the constructor.
public String getText() {
return editField.getText();
public void setText(String text) {
Please email your comments, suggestions and editorial submissions to [email protected]
Volume 2, Issue 2
BlackBerry Developer Journal
This document is provided for informational, non-commercial or personal use only and must not be produced, reproduced, published, modified, broadcast, posted or distributed in any form or medium whatsoever, in whole or in part. Any such production, reproduction, publishing, modification, broadcast, posting or distribution is a violation of Research In Motion Limited's exclusive copyright. Use for any other purpose is expressly prohibited by law,
and may result in severe civil and criminal penalties. Violators will be prosecuted to the maximum extent possible.
No Research In Motion Limited or BlackBerry logo, graphic, sound or image may be produced, reproduced, published, modified, broadcast, posted or
distributed unless expressly permitted in writing by Research In Motion Limited.
© 2005 Research In Motion Limited. All Rights Reserved. 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
BlackBerry are registered with the U.S. Patent and Trademark Office and may be pending or registered in other countries.
Adobe and PageMaker are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States and/or other countries.
The Bluetooth word mark is owned by Bluetooth SIG, Inc. and any use of such marks by Research In Motion Limited is under license. Microsoft,
Visual Basic, Visual Studio and Windows are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other
countries. Sun Microsystems, Java, JavaScript, Java ME, J2SE, JVM, and Java EE are trademarks or registered trademarks of Sun Microsystems,
Inc. in the United States and other countries. All other brands, product names, company names, trademarks and service marks are the properties of
their respective owners.
The BlackBerry 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.
This document is provided “as is” and Research In Motion Limited and its affiliated companies (“RIM”) assume no responsibility for any typographical, technical or other inaccuracies in this document. RIM reserves the right to periodically change information that is contained in this document;
however, RIM makes no commitment to provide any such changes, updates, enhancements or other additions to this document to you in a timely
This document might contain references to third party sources of information, hardware or software, products or services and/or third party web sites
(collectively the “Third-Party Information”). RIM does not control, and is not responsible for any Third-Party Information, including, without limitation the content, accuracy, copyright compliance, compatibility, performance, trustworthiness, legality, decency, links, or any other aspect of
Third-Party Information. The inclusion of Third-Party Information in this document does not imply endorsement by RIM of the Third Party Information or the third party in any way. Installation and use of Third Party Information with RIM's products and services may require one or more patent,
trademark or copyright licenses in order to avoid infringement of the intellectual property rights of others. Any dealings with Third Party Information, including, without limitation, compliance with applicable licenses and terms and conditions, are solely between you and the third party. You are
solely responsible for determining whether such third party licenses are required and are responsible for acquiring any such licenses relating to Third
Party Information. To the extent that such intellectual property licenses may be required, RIM expressly recommends that you do not install or use
Third Party Information until all such applicable licenses have been acquired by you or on your behalf. Your use of Third Party Information shall be
governed by and subject to you agreeing to the terms of the Third Party Information licenses. Any Third Party Information that is provided with
RIM's products and services is provided “as is”. RIM makes no representation, warranty or guarantee whatsoever in relation to the Third Party Information and RIM assumes no liability whatsoever in relation to the Third Party Information even if RIM has been advised of the possibility of such
damages or can anticipate such damages.
Certain features outlined in this document require a minimum version of BlackBerry Enterprise Server software, BlackBerry Desktop Software,
BlackBerry Handheld Software and/or BlackBerry or RIM software and may require additional development or third party products and/or services
for access to corporate applications.
RIM does not claim ownership of the materials you provide to RIM in any way. By providing or submitting your material you warrant and represent
that you own or otherwise control all of the rights to your material as described in this section including, without limitation, all the rights necessary
for you to provide or submit the material. However, with the exception of your personal information, by providing or submitting any such materials,
you agree to grant to RIM, and any necessary sublicensees, a perpetual, irrevocable, non-exclusive, worldwide, royalty-free license to use your submitted materials in connection with the operation of the BlackBerry Developer Journal and/or its business, including, without limitation, the rights
to: produce, reproduce, publish, modify, post, distribute, broadcast, transmit, publicly display, publicly perform, translate and reformat any portion,
in whole or in part, of your submitted material. No compensation will be paid with respect to the use by RIM or any necessary sublicensee of your
submitted material, as provided herein. RIM is under no obligation to post or use any material you may provide or submit and RIM may remove any
such material at any time in its sole discretion. Notwithstanding the foregoing, any suggestions, improvements or modifications to RIM products and
services (“Enhancements”) made by you or anyone acting on your behalf, including your employees, will be the property of RIM without any further
consideration to you, whether or not such Enhancements are incorporated into RIM products and services.
By submitting personal information to RIM, you consent to the collection, use, and disclosure of your personal information by RIM for the purposes
of RIM’s internal use and for use in relation to the BlackBerry Developer Journal , all in accordance with RIM’s privacy policy, which may be
viewed at
Volume 2, Issue 2
BlackBerry Developer Journal
Was this manual useful for you? yes no
Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Download PDF