1Creating user interfaces.............................................................................................................................................................7
Create a screen.......................................................................................................................................................................8
How the BlackBerry JVM manages screens........................................................................................................................8
Provide screen navigation when using a MainScreen.......................................................................................................8
Manage a drawing area.........................................................................................................................................................9
Touch screen orientation and direction.......................................................................................................................................10
Retrieve the orientation of the touch screen......................................................................................................................10
Restrict the touch screen direction......................................................................................................................................11
Receive notification when a drawable area of the touch screen changes......................................................................11
Receive notification when the orientation of the touch screen changes........................................................................11
Working with the accelerometer of a BlackBerry device............................................................................................................12
Types of accelerometer data.................................................................................................................................................12
Retrieve accelerometer data at specific intervals...............................................................................................................13
Query the accelerometer when the application is in the foreground..............................................................................13
Query the accelerometer when the application is in the background.............................................................................14
Store accelerometer readings in a buffer............................................................................................................................14
Retrieve accelerometer readings from a buffer..................................................................................................................15
Get the time a reading was taken from the accelerometer..............................................................................................15
Add a UI component to a screen..........................................................................................................................................15
Create a dialog box................................................................................................................................................................16
Creat a bitmap........................................................................................................................................................................16
Create a button.......................................................................................................................................................................16
Create a list.............................................................................................................................................................................16
Create an alphanumeric drop-down list..............................................................................................................................16
Create a text list that can be filtered...................................................................................................................................17
Create a check box.................................................................................................................................................................19
Create a radio button.............................................................................................................................................................19
Create a date field..................................................................................................................................................................19
Create a text field...................................................................................................................................................................20
Create a read-only text field that allows formatting..........................................................................................................20
Create an editable text field that has no formatting and accepts filters.........................................................................20
Create an editable text field that allows special characters.............................................................................................20
Create a password field.........................................................................................................................................................20
Create a text field for AutoText.............................................................................................................................................20
Create a progress bar field....................................................................................................................................................21
Create a text label..................................................................................................................................................................21
Create a list from which users can select multiple items..................................................................................................21
Create a field to display a parent and child relationship between items........................................................................22
Add a UI component to a screen..........................................................................................................................................23
Create a custom field.............................................................................................................................................................23
Create a menu item................................................................................................................................................................27
Adding menu items to a BlackBerry device application....................................................................................................28
Register a menu item.............................................................................................................................................................28
Create a layout manager.......................................................................................................................................................29
Align a field to a line of text..................................................................................................................................................30
Respond to UI navigation events.........................................................................................................................................30
Determine the type of input method...................................................................................................................................30
Respond to BlackBerry device user interaction..................................................................................................................31
Types of touch screen events................................................................................................................................................31
Respond to touch screen events...........................................................................................................................................33
Keyboard on a BlackBerry device with a touch screen...............................................................................................................40
Change the state of the keyboard on a BlackBerry device with a touch screen.............................................................40
Display the keyboard on a BlackBerry device with a touch screen..................................................................................40
Hide the keyboard on a BlackBerry device with a touch screen.......................................................................................41
Listen for a spell check event................................................................................................................................................43
Data management..........................................................................................................................................................................45
Support for APIs to store data to persistent memory.................................................................................................................45
Data management..........................................................................................................................................................................45
Access to memory...........................................................................................................................................................................45
Persistent data storage..................................................................................................................................................................46
Create a persistent data store...............................................................................................................................................46
Store persistent data..............................................................................................................................................................46
MIDP record storage......................................................................................................................................................................48
Create an MIDP record store................................................................................................................................................48
Add a record to a record store..............................................................................................................................................48
Retrieve a record from a record store..................................................................................................................................48
Retrieve all records from a record store...............................................................................................................................48
Retrieve a collection from persistent storage.....................................................................................................................49
Create a collection listener to notify the system when a collection changes.................................................................50
Remove a collection listener that notifies the system when a collection changes........................................................50
Notify the system when a collection changes....................................................................................................................51
Retrieve the runtime store.....................................................................................................................................................51
Add an object in the runtime store......................................................................................................................................52
Replace an object in the runtime store................................................................................................................................52
Retrieve a registered runtime object....................................................................................................................................52
Retrieve an unregistered runtime object.............................................................................................................................53
Using the BlackBerry Enterprise Server as an intranet gateway......................................................................................54
Using the wireless service provider's Internet gateway....................................................................................................54
Retrieve the wireless network name....................................................................................................................................54
Use HTTP authentication......................................................................................................................................................55
Use an HTTPS connection.....................................................................................................................................................56
Use a socket connection........................................................................................................................................................57
Use a datagram connection..................................................................................................................................................58
Use a USB or serial port connection....................................................................................................................................60
Use a Bluetooth serial port connection...............................................................................................................................61
Retrieve the wireless access families that a BlackBerry device supports........................................................................63
Determine if a BlackBerry device supports multiple wireless access families................................................................63
Determine the wireless access family transceivers that are turned on...........................................................................63
Turn on the transceiver for a wireless access family..........................................................................................................63
Turn off the transceiver for a wireless access family..........................................................................................................63
Check if the Wi-Fi transceiver is turned on.........................................................................................................................63
Check if the Wi-Fi transceiver is connected to a wireless access point...........................................................................63
Retrieve the status of the wireless access point or the active Wi-Fi profile....................................................................64
Open a Wi-Fi socket connection...........................................................................................................................................64
Open a Wi-Fi HTTP connection............................................................................................................................................64
Open a Wi-Fi HTTPS connection..........................................................................................................................................65
Retrieve information about a BlackBerry Java Application...............................................................................................66
Communicate with another BlackBerry Java Applications................................................................................................66
Determine the services that are available to a BlackBerry Java Application..................................................................67
Access control messages...............................................................................................................................................................68
Displaying a message for an operation that requires user permission............................................................................68
Display an application control message to a user..............................................................................................................69
5 Using custom messages and folders in the message list......................................................................................................70
Creating a module for background processes.............................................................................................................................70
Creating a module for the UI.........................................................................................................................................................70
Create the module for background processes.............................................................................................................................70
Start the module for background processes or the module for the UI.....................................................................................71
Create an icon for a custom message..........................................................................................................................................71
Create a custom folder in the message list..................................................................................................................................72
Send a notification when a custom folder changes....................................................................................................................73
Create an indicator for the number of messages in a custom folder.......................................................................................74
Hide an indicator for a custom folder...........................................................................................................................................74
Remove an indicator for a custom folder.....................................................................................................................................74
6 Applications for push content...................................................................................................................................................76
Types of push applications.............................................................................................................................................................76
Types of push requests...................................................................................................................................................................76
Files required for localization........................................................................................................................................................78
Manage localization files for a suite of BlackBerry device applications...................................................................................79
8 Controlling access to APIs and application data....................................................................................................................81
Check if a code signature is required...........................................................................................................................................81
Java APIs with controlled access...................................................................................................................................................81
Register to use controlled APIs.....................................................................................................................................................82
Restrictions on code signatures....................................................................................................................................................82
Request a code signature...............................................................................................................................................................83
Register a signature key using a proxy server.............................................................................................................................83
Sign an application using a proxy server.....................................................................................................................................84
View the signature status for an application...............................................................................................................................84
Using keys to protect APIs and data............................................................................................................................................84
Protect APIs using code signing keys...........................................................................................................................................85
Protect runtime store data using code signing keys..................................................................................................................85
Protect persistent data using code signing keys.........................................................................................................................86
9 Testing a BlackBerry device application..................................................................................................................................87
Testing applications on a BlackBerry Smartphone Simulator...................................................................................................87
Testing applications on a BlackBerry device...............................................................................................................................87
Testing applications using the compiled .cod files.....................................................................................................................87
Install and remove a .cod file for testing.............................................................................................................................88
Save a .cod file from a device to a computer......................................................................................................................88
Retrieve information about a .cod file..................................................................................................................................88
10 Packaging and distributing a BlackBerry Java Application..................................................................................................90
Preverify a BlackBerry device application....................................................................................................................................90
Application distribution over the wireless network.....................................................................................................................90
Distributing BlackBerry Java Applications over the wireless network......................................................................................90
Modifying information for a MIDlet suite............................................................................................................................91
Correct the .cod file sizes listed in a .jad file.......................................................................................................................92
Create .jad files that reference multiple .cod files.............................................................................................................92
Distributing BlackBerry device applications with the BlackBerry Desktop Software.............................................................93
Elements in BlackBerry device application .alx file............................................................................................................93
Properties of BlackBerry device application .jad files........................................................................................................98
Application distribution through a computer connection..........................................................................................................99
Distribute an application from a computer.........................................................................................................................99
Distribute an application from a web page.........................................................................................................................99
Distribute an application for testing....................................................................................................................................99
Distributing an application from a computer..............................................................................................................................99
Create an application loader file...................................................................................................................................................99
Install a BlackBerry device application on a specific device...................................................................................................... 100
Specifing supported versions of the BlackBerry Device Software............................................................................................ 100
12 Provide feedback......................................................................................................................................................................... 104
The main structure for a BlackBerry® device user interface is the Screen object. A BlackBerry Java® Application may display
more than one screen at a time, but only one screen in a BlackBerry Java Application is active at one time.
The user interface APIs initialize simple Screen objects. Once you create a screen, you can add fields and a menu to the screen
and display it to the BlackBerry device user by pushing it on to the UI stack. The menu object has associated menu items that
are runnable objects, which perform a specific task when the BlackBerry device user selects one of the items. For example, menu
items may invoke the necessary code to establish a network connection, commit a data object to memory or close the BlackBerry
Java Application. For a more sophisticated custom BlackBerry Java Application, you can customize the BlackBerry device user
interface and implement new field types, as required. You can also add custom navigation and trackwheel behavior.
The Screen class does not implement disambiguation, which is required for complex input methods, such as international
keyboards. For seamless integration of the different input methods, extend Field or one of its subclasses. Do not use
Screen objects for typing text.
For knowledge base articles about displaying and working with screens, visit the BlackBerry Developer Zone at
www.blackberry.com/developers .
Screen classes
ClassDescription
Screen
FullScreen
MainScreen
Use the Screen class to define a manager to lay out UI components on the screen
and to define a specific type of screen using the styles that the constants on the
Field superclass define.
By default, a FullScreen class contains a single vertical field manager. Use a
FullScreen class to provide an empty screen that you can add UI components
to in a standard vertical layout. For another layout style, such as horizontal or
diagonal, use a Screen class and add a Manager to it.
The MainScreen class provides features that are common to standard
BlackBerry® Java® Applications. Use a MainScreen object for the first screen
of your BlackBerry Java Application to maintain consistency with other BlackBerry
Java Applications. The MainScreen class provides the following UI components:
•default position of a screen title, with a SeparatorField after the title
7
Development Guide
ClassDescription
•main scrollable section contained in a VerticalFieldManager
•default menu with a Close menu item
•default close action when the BlackBerry device user clicks the Close menu
item or presses the Escape key
Screens
Create a screen
1.Import the following classes:
net.rim.device.api.ui.Screen
•
net.rim.device.api.ui.container.FullScreen
•
net.rim.device.api.ui.container.MainScreen
•
2.Extend the Screen class or one of its subclasses, FullScreen or MainScreen.
How the BlackBerry JVM manages screens
The BlackBerry® Java® Virtual Machine maintains Screen objects in a display stack, which is an ordered set of Screen
objects. The screen at the top of the stack is the active screen that the BlackBerry device user sees. When a displays a screen, it
pushes the screen to the top of the stack. When a BlackBerry Java Application closes a screen, it removes the screen off the top
of the stack and displays the next screen on the stack, redrawing it as necessary. Each screen can appear only once in the display
stack. The BlackBerry JVM throws a runtime exception if a Screen that the BlackBerry Java Application pushes to the stack
already exists. A BlackBerry Java Application must remove screens from the display stack when the BlackBerry device user finishes
interacting with them so that the BlackBerry Java Application uses memory efficiently. Use only a few modal screens at one time,
because each screen uses a separate thread.
Provide screen navigation when using a MainScreen
Creating a MainScreen object provides default navigation to your BlackBerry® device application. Avoid using buttons or
other UI elements that take up space on the screen.
8
Development Guide
Screens
MainScreen mScreen = new MainScreen(DEFAULT_MENU | DEFAULT_CLOSE);
Manage a drawing area
The Graphics object represents the entire drawing surface that is available to the BlackBerry® device application. To limit
this area, divide it into XYRect objects. Each XYPoint represents a point on the screen, which is composed of an X coordinate and a Y co-ordinate.
1.Import the following classes:
net.rim.device.api.ui.Graphics
•
net.rim.device.api.ui.XYRect
•
net.rim.device.api.ui.XYPoint
•
2.Create an instance of an XYPoint object and an XYRect object.
XYPoint bottomRight = new XYPoint(50, 50);
XYRect rectangle = new XYRect(topLeft, bottomRight);
XYPoint topLeft = new XYPoint(10, 10);
3.Invoke Graphics.pushContext() to make drawing calls that specify that the region origin should not adjust the
drawing offset. In the following code sample, we create two XYPoint objects to represent the top left and bottom right
points of a rectangle. We then create a rectangular clipping region by creating an XYRect object using the XYPoint
objects. We invoke Graphics.pushContext() to push the rectangular clipping region to the context stack. We
invoke Graphics.drawRect() to draw a rectangle and invoke Graphics.fillRect() to fill a rectangle. We
invoke Graphics.popContext() to pop the current context off of the context stack.
XYPoint bottomRight = new XYPoint(50, 50);
XYPoint topLeft = new XYPoint(10, 10);
XYRect rectangle = new XYRect(topLeft, bottomRight);
4.Invoke pushRegion() and specify that the region origin should adjust the drawing offset. In the following code sample,
we invoke Graphics.drawRect() to draw a rectangle and invoke Graphics.fillRect() to fill a rectangle.
We invoke Graphics.popContext() to pop the current context off of the context stack.
8.Invoke translate(). The XYRect is translated from its origin of (1, 1) to an origin of (20, 20). After translation, the
bottom portion of the XYRect object extends past the bounds of the graphics context and clips it.
XYRect rectangle = new XYRect(1, 1, 100, 100);
XYPoint newLocation = new XYPoint(20, 20);
rectangle.translate(newLocation);
Touch screen orientation and direction
Touch screen orientation and direction
You can specify the orientation and direction of the Screen in a BlackBerry® device application.
Orientation refers to the Screen aspect ratio, relative to the ground, where the left, right, top, bottom, front, or back of the
device are furthest from the ground.
Direction refers to the top of the drawing area of the screen, relative to the location of the BlackBerry logo. If you change the
direction that a Screen supports, the change takes effect the next time the Screen orientation of the device changes.
A Screen for a BlackBerry device application can have the following directions and orientations:
Direction
•DIRECTION_NORTH - the top of the drawable area is the screen side closest to the BlackBerry logo
•DIRECTION_WEST - the top of the drawable area is to the left of the logo
•DIRECTION_EAST - the top of the drawable area is to the right of the logo
•DIRECTION_SOUTH - the top of the drawable area is the screen side farthest from the BlackBerry logo
Orientation
•DIRECTION_LANDSCAPE - the top of the drawable area is the screen side farthest from the BlackBerry logo
•DIRECTION_PORTRAIT - the screen is display in protrait view
Retrieve the orientation of the touch screen
1.Import the net.rim.device.api.system.Display class.
net.rim.device.api.ui.UiEngineInstance.setAcceptableDirections(byte flags)
and pass the argument for the direction of the Screen.
_ue.setAcceptableDirections(Display.DIRECTION_WEST);
Receive notification when a drawable area of the touch screen changes
1.Import the javax.microedition.lcdui.Canvas class.
2.Extend javax.microedition.lcdui.Canvas.
3.Override Canvas.sizeChanged(int, int).
protected void sizeChanged(int w, int h) {
Dialog.alert("The size of the Canvas has changed);
}
}
Receive notification when the orientation of the touch screen changes
protected void sublayout(int width, int height) {
int x = 0;
int y = 0;
Field field;
int numberOfFields = getFieldCount();
for (int i=0; i<numberOfFields; ++i) {
field = getField(i);
layoutChild(field, width, height);
setPositionChild(field, x, y);
field.setPosition(x,y);
11
Development Guide
x += field.getPreferredWidth();
y += field.getPreferredHeight();
}
setExtent(width,height);
}
Working with the accelerometer of a BlackBerry device
Working with the accelerometer of a BlackBerry device
On a BlackBerry® device with an accelerometer, you can create a BlackBerry device application that listens for accelerometer
events and retrieves data about the orientation of the BlackBerry device.
The BlackBerry OS converts accelerometer readings into orientation coordinates such as TOP_UP, FACE_UP, and
LEFT_UP. The BlackBerry OS may also rotate the screen in response to accelerometer readings.
Querying the accelerometer consumes battery power. Connections to the accelerometer should not be kept open for long periods
of time.
Types of accelerometer data
A BlackBerry® device application can retrieve data from the accelerometer.
Data typeDescription
orientationThe orientation of the BlackBerry device with respect to the ground.
accelerationThe acceleration of the rotation of the BlackBerry device.
For more information about types of data from the accelerometer, see the API reference for the BlackBerry® Java® Development
Environment
Accelerometer
The BlackBerry® Storm device includes an acclerometer that senses the orientation and acceleration of the device. When a
BlackBerry device user moves the device, the accelerometer senses the movement in 3-D space along the x, y, and z axis. A
BlackBerry device user can change the orientation of the device which can change the display direction of a screen for a BlackBerry
device application between portrait and landscape.
The Accelerometer APIs in the net.rim.device.api.system package let a BlackBerry device application respond to
the orientation and acceleration of a BlackBerry device. For example, you can manipulate a game application to change the
direction and speed of a moving object on the screen as a BlackBerry device user moves and rotates the BlackBerry device at
different speeds.
12
Development Guide
Working with the accelerometer of a BlackBerry device
Retrieve accelerometer data at specific intervals
If a BlackBerry® device application opens a channel to the accelerometer when the application is in the foreground, when the
application is in the background, the channel pauses and the accelerometer is not queried. If a BlackBerry device application
invokes AccelerometerSensor.Channel.getLastAccelerationData(short[]) at close intervals or
when the BlackBerry device is not in motion, the method might return duplicate values.
2.Create a configuration for a channel to the accelerometer.
AccelerometerChannelConfig channelConfig = new AccelerometerChannelConfig
( AccelerometerChannelConfig.TYPE_RAW );
3.Invoke AccelerometerChannelConfig.setSamplesCount(), to specify the number of acceleration
readings to store in the buffer. Each element in the buffer contains acceleration readings for the X, Y, and Z axes and data
on when the reading took place.
channelConfig.setSamplesCount( 500 );
14
Development Guide
4.Invoke AccelerometerSensor.openChannel() to open a channel to the accelerometer.
3.Invoke AccelerometerData.getNewBatchLength(), to get the number of readings retrieved since the last
query.
int newBatchSize = accData.getNewBatchLength();
4.Invoke AccelerometerData.getXAccHistory(), AccelerometerData.getYAccHistory(),
and AccelerometerData.getZAccHistory(), to retrieve accelerometer data from the buffer for each axis.
You can create an application that uses the KeywordFilterField class, included in the
net.rim.device.api.ui.component package, to provide a UI field that consists of a single text input field and a
list of selectable elements. A word that a BlackBerry® device user enters into the text input field filters the elements in the list.
For more information about using the KeywordFilterField class, see the KeywordFilterFieldDemo sample, included
with the BlackBerry® Java® Development Environment version 4.3.1.
8.Set a label for the input field of the KeywordFilterFIeld.
_keywordField.setLabel("Search: ");
9.Create the main screen of the application and add a KeywordFilterField to the main screen.
17
Development Guide
UI components
KeywordFilterDemoScreen screen = new KeywordFilterDemoScreen
(this,_keywordField);
screen.add(_keywordField.getKeywordField());
screen.add(_keywordField);
pushScreen(screen);
10. To create a method that populates and returns a vector of Country objects containing data from text file, In the method
signature, specify Vector as the return type.
public Vector getDataFromFile()
{
11.Create and store a reference to a new Vector object.
Vector countries = new Vector();
13. Read CRLF delimited lines from the input stream.
LineReader lineReader = new LineReader(stream);
14. Read data from the input stream one line at a time until you reach the end of file flag. Each line is parsed to extract data
that is used to construct Country objects.
for(;;)
{ //Obtain a line of text from the text file
String line = new String(lineReader.readLine());
//If we are not at the end of the file, parse the line of text
if(!line.equals("EOF"))
{int space1 = line.indexOf(" ");
String country = line.substring(0,space1);
int space2 = line.indexOf(" ",space1+1);
String population = line.substring(space1
+1,space2);
String capital = line.substring(space2+1,line.length());
// Create a new Country object.
countries.addElement(new Country
(country,population,capital));
}
else
{
break;
}
} // end the for loop
return countries;
}
15. To add a keyword to the list of selectable text items, invoke SortedReadableList.doAdd(element).
16. To update the list of selectable text items, invoke KeywordFilterField.updateList().
_keywordField.updateList();
17. To obtain the key word that a BlackBerry device user typed into the KeywordFilterField, invoke
KeywordFilterField.getKeyword().
String userTypedWord = _keywordField.getKeyword();
UI components
Create a check box
1.Import the net.rim.device.api.ui.component.CheckboxField class.
2.Create an instance of a CheckboxField.
CheckboxField myCheckbox = new CheckboxField("First checkbox", true);
Create a radio button
1.Import the following classes:
net.rim.device.api.ui.component.RadioButtonGroup
•
net.rim.device.api.ui.component.RadioButtonField
•
2.Create an instance of a RadioButtonGroup.
RadioButtonGroup rbGroup = new RadioButtonGroup();
3.Create an instance of a RadioButtonField for each option you want to make available to the BlackBerry® device
user.
RadioButtonField rbField2 = new RadioButtonField("Second field");
4.Invoke RadioButtonGroup.add() to add the RadioButtonFields to the RadioButtonGroup and
make sure the BlackBerry device user can select only one option at a time.
rbGroup.add(rbField);
rbGroup.add(rbField2);
Create a date field
1.Import the net.rim.device.api.ui.component.DateField class.
2.Create an instance of a DateField, providing the value returned by System.currentTimeMillis() as a
parameter to return the current time.
DateField dateField = new DateField("Date: ",System.currentTimeMillis(),
DateField.DATE_TIME);
19
Development Guide
Create a text field
Create a read-only text field that allows formatting
1.Import the net.rim.device.api.ui.component.RichTextField class.
2.Create an instance of a RichTextField.
RichTextField rich = new RichTextField("RichTextField");
Create an editable text field that has no formatting and accepts filters
1.Import the following classes:
net.rim.device.api.ui.component.BasicEditField
•
net.rim.device.api.ui.component.EditField
•
2.Create an instance of a BasicEditField.
BasicEditField bf = new BasicEditField("BasicEditField: ", "",
10, EditField.FILTER_UPPERCASE);
UI components
Create an editable text field that allows special characters
1.Import the net.rim.device.api.ui.component.EditField class.
2.Create an instance of an EditField.
EditField edit = new EditField("EditField: ", "", 10,
EditField.FILTER_DEFAULT);
Create a password field
1.Import the net.rim.device.api.ui.component.PasswordEditField class.
2.Create an instance of a PasswordEditField.
For example, the following instance uses a constructor that lets you provide a default initial value for the
PasswordEditField:
PasswordEditField pwd = new PasswordEditField("PasswordEditField: ", "");
Create a text field for AutoText
1.Import the following classes:
net.rim.device.api.ui.component.AutoTextEditField
•
net.rim.device.api.ui.autotext.AutoText
•
20
Development Guide
net.rim.device.api.ui.component.BasicEditField
•
2.Create an instance of an AutoTextEditField.
AutoTextEditField autoT = new AutoTextEditField("AutoTextEditField: ",
"");
Create a progress bar field
1.Import the net.rim.device.api.ui.component.GaugeField class.
2.Create an instance of a GaugeField.
GaugeField percentGauge = new GaugeField("Percent: ", 1, 100, 29,
GaugeField.PERCENT);
Create a text label
1.Import the net.rim.device.api.ui.component.LabelField class.
2.Create an instance of a LabelField to add a text label to a screen.
LabelField title = new LabelField("UI Component Sample",
LabelField.ELLIPSIS);
UI components
Create a list from which users can select multiple items
1.Import the following classes:
java.lang.String
•
net.rim.device.api.ui.component.ListField
•
net.rim.device.api.ui.container.MainScreen
•
2.Import the net.rim.device.api.ui.component.ListFieldCallback interface.
3.Create a class that implements the ListFieldCallback interface.
private class ListCallback implements
ListFieldCallback {
4.Create the items that you want to display in a ListField.
String fieldOne = new String("Mark Guo");
String fieldTwo = new String("Amy Krul");
5.Create an instance of a ListField.
ListField myList = new ListField(0,ListField.MULTI_SELECT);
21
Development Guide
UI components
6.Create an instance of a ListCallback.
ListCallback myCallback = new ListCallback();
7.Set the call back of the ListField to be the ListCallback.
myList.setCallback(myCallback);
8.Use the ListCallBack object to add items to the ListField.
myCallback.add(myList, fieldOne);
myCallback.add(myList, fieldTwo);
9.Add the ListField to the MainScreen.
mainScreen.add(myList);
Create a field to display a parent and child relationship between items
A TreeField contains parent and child nodes.
1.Import the following classes:
net.rim.device.api.ui.component.TreeField
•
java.lang.String
•
net.rim.device.api.ui.container.MainScreen
•
2.Import the net.rim.device.api.ui.component.TreeFieldCallback interface.
3.Implement the TreeFieldCallback interface.
4.Invoke TreeField.setExpanded() on the TreeField object to specify whether a folder is collapsible. In the
following code sample, we create a TreeField object and multiple child nodes to the TreeField object. We then
invoke TreeField.setExpanded() using node4 as a parameter to collapse the folder.
String fieldOne = new String("Main folder");
...
TreeCallback myCallback = new TreeCallback();
TreeField myTree = new TreeField(myCallback, Field.FOCUSABLE);
int node1 = myTree.addChildNode(0, fieldOne);
int node2 = myTree.addChildNode(0, fieldTwo);
int node3 = myTree.addChildNode(node2, fieldThree);
int node4 = myTree.addChildNode(node3, fieldFour);
...
int node10 = myTree.addChildNode(node1, fieldTen);
myTree.setExpanded(node4, false);
...
mainScreen.add(myTree);
22
Development Guide
5.To repaint a TreeField when a node changes, create a class that implements the TreeFieldCallback interface
and implement the TreeFieldCallback.drawTreeItem method. In the following code sample, the
TreeFieldCallback.drawTreeItem method uses the cookie for a tree node to draw a String in the location
of a node. The TreeFieldCallback.drawTreeItem method invokes Graphics.drawText() to draw
the String.
private class TreeCallback implements TreeFieldCallback {
public void drawTreeItem(TreeField _tree, Graphics g, int node, int y, int
width, int indent) {
String text = (String)_tree.getCookie(node);
g.drawText(text, indent, y);
}
}
UI components
Add a UI component to a screen
1.Import the following classes:
net.rim.device.api.ui.component.CheckboxField
•
net.rim.device.api.ui.container.MainScreen
•
2.Create an instance of a UI component.
CheckboxField myCheckbox = new CheckboxField("First checkbox", true);
3.Add the UI component to your extension of a Screen class.
mainScreen.add(myCheckbox);
Create a custom field
You can only add custom context menu items and custom layouts to a custom field.
1.Import the following classes:
net.rim.device.api.ui.Field
•
java.lang.String
•
net.rim.device.api.ui.Font
•
java.lang.Math
•
net.rim.device.api.ui.Graphics
•
2.Import the net.rim.device.api.ui.DrawStyle interface.
3.Extend the Field class, or one of its subclasses, implementing the DrawStyle interface to specify the characteristics
of the custom field and turn on drawing styles.
public class CustomButtonField extends Field implements DrawStyle {
public static final int RECTANGLE = 1;
public static final int TRIANGLE = 2;
public static final int OCTAGON = 3;
23
Development Guide
UI components
private String _label;
private int _shape;
private Font _font;
private int _labelHeight;
private int _labelWidth;
}
4.Implement constructors to define a label, shape, and style of the custom button.
public CustomButtonField(String label) {
this(label, RECTANGLE, 0);
}
public CustomButtonField(String label, int shape) {
this(label, shape, 0);
}
public CustomButtonField(String label, long style) {
this(label, RECTANGLE, style);
}
public CustomButtonField(String label, int shape, long style) {
super(style);
_label = label;
_shape = shape;
_font = getFont();
_labelHeight = _font.getHeight();
_labelWidth = _font.getAdvance(_label);
}
5.Implement layout() to specify the arrangement of field data. Perform the most complex calculations in layout()
instead of in paint(). The manager of the field invokes layout() to determine how the field arranges its contents in the
available space. In the following code sample, we invoke Math.min() to return the smaller of the specified width and
height and the preferred width and height of the field. We then invoke Field.setExtent(int,int) to set the
required dimensions for the field.
6.Implement getPreferredWidth(), using the relative dimensions of the field label to make sure that the label does
not exceed the dimensions of the component. In the following code sample, we use a switch block to determine the preferred
width based on the shape of the custom field. For each type of shape, we use an IF statement to compare dimensions and
determine the preferred width for the custom field.
24
Development Guide
UI components
public int getPreferredWidth() {
switch(_shape) {
case TRIANGLE:
if (_labelWidth < _labelHeight) {
return _labelHeight << 2;
} else {
return _labelWidth << 1;
}
case OCTAGON:
if (_labelWidth < _labelHeight) {
return _labelHeight + 4;
} else {
return _labelWidth + 8;
}
case RECTANGLE: default:
return _labelWidth + 8;
}
}
7.Implement getPreferredHeight(), using the relative dimensions of the field label to determine the preferred
height. In the following code sample, we use a switch block to determine the preferred height based on the shape of the
custom field. For each type of shape, we use an IF statement to compare dimensions and determine the preferred height
for the custom field.
public int getPreferredHeight() {
switch(_shape) {
case TRIANGLE:
if (_labelWidth < _labelHeight) {
return _labelHeight << 1;
} else {
return _labelWidth;
}
case RECTANGLE:
return _labelHeight + 4;
case OCTAGON:
return getPreferredWidth();
}
return 0;
}
8.Implement paint(). The manager of a field invokes paint() to redraw the field when an area of the field is marked
as invalid. In the following code sample, we use a switch block to repaint a custom field based on the shape of the custom
field. For a field that has a triangle or octagon shape, we use the width of the field to calculate the horizontal and vertical
position of a lines start point and end point. We then invoke graphics.drawLine() and use the start and end points
to draw the lines that define the custom field. For a field that has a rectangular shape, we invoke
graphics.drawRect() and use the width and height of the field to draw the custom field. We then invoke
graphics.drawText() and use the width of the field to draw a string of text to an area of the field
25
Development Guide
protected void paint(Graphics graphics) {
int textX, textY, textWidth;
int w = getWidth();
switch(_shape) {
case TRIANGLE:
int h = (w>>1);
int m = (w>>1)-1;
graphics.drawLine(0, h-1, m, 0);
graphics.drawLine(m, 0, w-1, h-1);
graphics.drawLine(0, h-1, w-1, h-1);
textWidth = Math.min(_labelWidth,h);
textX = (w - textWidth) >> 1;
textY = h >> 1;
break;
case OCTAGON:
int x = 5*w/17;
int x2 = w-x-1;
int x3 = w-1;
graphics.drawLine(0, x, 0, x2);
graphics.drawLine(x3, x, x3, x2);
graphics.drawLine(x, 0, x2, 0);
graphics.drawLine(x, x3, x2, x3);
graphics.drawLine(0, x, x, 0);
graphics.drawLine(0, x2, x, x3);
graphics.drawLine(x2, 0, x3, x);
graphics.drawLine(x2, x3, x3, x2);
textWidth = Math.min(_labelWidth, w - 6);
textX = (w-textWidth) >> 1;
textY = (w-_labelHeight) >> 1;
break;
case RECTANGLE: default:
graphics.drawRect(0, 0, w, getHeight());
textX = 4;
textY = 2;
textWidth = w - 6;
break;
}
graphics.drawText(_label, textX, textY, (int)( getStyle() &
DrawStyle.ELLIPSIS | DrawStyle.HALIGN_MASK ), textWidth );
}
9.Implement the Field set() and get() methods. In the following code sample, we implement the
Field.getLabel(), Field. getShape(), Field. setLabel(String label), and
Field. setShape(int shape) methods to return the instance variables of the custom field.
UI components
26
Development Guide
UI components
public String getLabel() {
return _label;
}
public int getShape() {
return _shape;
}
public void setLabel(String label) {
_label = label;
_labelWidth = _font.getAdvance(_label);
updateLayout();
}
public void setShape(int shape) {
_shape = shape;
}
2.Import the javax.microedition.pim.Contact interface.
3.Extend the abstract ApplicationMenuItem class to define a menu item.
public class SampleMenuItem extends ApplicationMenuItem { ... }
4.Invoke ApplicationMenuItem() to specify the position of the menu item in the menu. A higher number means
that the menu item appears lower in the menu.
SampleMenuItem() {
super(20);
}
5.Implement toString() to specify the menu item text. In the following code sample, we implement toString() to
display the text "Open the Contacts Demo application" in the menu of the BlackBerry® device application.
public String toString() {
return "Open the Contacts Demo application";
}
6.Implement run() to specify the behaviour of the menu item. In the following code sample, if a BlackBerry device user
clicks the text "Open the Contacts Demo application" in the menu of the BlackBerry device application, if a Contact
exists, we allow an application called ContactsDemo to receive events by invoking
ContactsDemo.enterEventDispatcher().
public Object run(Object context) {
Contact c = (Contact)context; // An error occurs if this does not work.
if ( c != null ) {
27
Development Guide
new ContactsDemo().enterEventDispatcher();
} else {
throw new IllegalStateException( "Context is null, expected a Contact
instance");
}
return null;
}
Adding menu items to a BlackBerry device application
You can use the Application Menu Item API, in the net.rim.blackberry.api.menuitem package to add menu
items to a BlackBerry® device application. You can use the ApplicationMenuItemRepository class to add or remove
menu items from a BlackBerry device application.