os blackberry pdf

33
Create BlackBerry applications with open source tools, Part 1: Laying the groundwork Skill Level: Intermediate Frank Ableson Author 19 Aug 2008 There is perhaps no bigger market-transformational technology than the cell phone. And within that classification of devices, perhaps none more recognizable than the BlackBerry from Research In Motion (RIM). Most people think it is just for business e-mail, but there is untapped potential in that addictive device. Despite being a popular platform, third-party applications are still needed for the BlackBerry platform. There is no better way to bring those applications to fruition than to enable the help from the open source community. Follow along as this tutorial lays the groundwork for an open source data-collection application, upon which an accessible and easy-to-use data-collection service is built. Section 1. Before you start This tutorial is for open source and Java™ technology developers interested in BlackBerry application development in the context of a mobile data-collection application. The example application demonstrates a simple data-collection application leveraging the freely available BlackBerry development tools. Mobile development experience is helpful, but not required. Java programming skills are required for BlackBerry applications, but are not an explicit requirement for this tutorial. Likewise, PHP and MySQL are employed on the back end, so familiarity with those platforms is helpful, but, again, not a requirement. About this tutorial So why are we concerned about writing applications for BlackBerry? One of the Laying the groundwork © Copyright IBM Corporation 2008. All rights reserved. Page 1 of 33

Upload: yesaya79

Post on 31-Mar-2015

292 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Os Blackberry PDF

Create BlackBerry applications with open sourcetools, Part 1: Laying the groundworkSkill Level: Intermediate

Frank AblesonAuthor

19 Aug 2008

There is perhaps no bigger market-transformational technology than the cell phone.And within that classification of devices, perhaps none more recognizable than theBlackBerry from Research In Motion (RIM). Most people think it is just for businesse-mail, but there is untapped potential in that addictive device. Despite being apopular platform, third-party applications are still needed for the BlackBerry platform.There is no better way to bring those applications to fruition than to enable the helpfrom the open source community. Follow along as this tutorial lays the groundworkfor an open source data-collection application, upon which an accessible andeasy-to-use data-collection service is built.

Section 1. Before you start

This tutorial is for open source and Java™ technology developers interested inBlackBerry application development in the context of a mobile data-collectionapplication. The example application demonstrates a simple data-collectionapplication leveraging the freely available BlackBerry development tools. Mobiledevelopment experience is helpful, but not required. Java programming skills arerequired for BlackBerry applications, but are not an explicit requirement for thistutorial. Likewise, PHP and MySQL are employed on the back end, so familiarity withthose platforms is helpful, but, again, not a requirement.

About this tutorial

So why are we concerned about writing applications for BlackBerry? One of the

Laying the groundwork© Copyright IBM Corporation 2008. All rights reserved. Page 1 of 33

Page 2: Os Blackberry PDF

challenges of open source software is that it is often seen with only a single face —Linux® — and that is often hidden on a server buried in a data center. However, oneof the biggest secrets in the market is that the most popular and powerful mobileplatform uses an open source programming language: the Java programminglanguage. That's right, an open source language powers the applications in theBlackBerry devices used every day.

BlackBerry applications represent an interesting convergence of usage profile andcapability. The prototypical user of a BlackBerry is a professional who uses aBlackBerry for work. BlackBerry devices allow people to be more available andreal-time because BlackBerry is the current leader in mobile e-mail use. But theBlackBerry platform offers more than just e-mail. Built upon a J2ME foundation, RIMhas extended the Java environment to provide powerful and desirable featuresenabling useful and fun applications for business and entertainment alike. As newmobile platforms come on the scene, the measuring stick is BlackBerry. If otherplatforms compare themselves to BlackBerry, there is motivation enough to explorethe capabilities of this market-moving platform.

This tutorial introduces BlackBerry application development within the context of themobile data-collection application space. It provides an introduction to BlackBerrydevelopment with a quick introduction to the platform, a tour of the BlackBerrydevelopment tools, and construction of a complete data-collection application.Complete source code is available for the BlackBerry application and the server-sidecomponents used in the sample application in the Download section. This tutorial isorganized into the following sections:

• BlackBerry platform basics

• BlackBerry application development with JDE

• Data-collection applications with BlackBerry

• Transaction processing on the server side

• Next steps

System requirements

This tutorial demonstrates a few open source technologies and stitches themtogether to form a prototype for an open source mobile data-collection platform. Youneed all of them to perform the steps in this tutorial. Our primary focus is developingapplications for the BlackBerry platform, so those pieces are the primaryrequirement. You can leverage a publicly available Web site for server-sidetransactions if building out the server side is not of interest to you. Here's the full list:

BlackBerry Java Development Environment

developerWorks® ibm.com/developerWorks

Laying the groundworkPage 2 of 33 © Copyright IBM Corporation 2008. All rights reserved.

Page 3: Os Blackberry PDF

This tutorial employs V4.0.2 of the JDE, although a later version is available.

PHPPHP may be downloaded from PHP.net. The latest stable release is V4.4.9.

MySQLThe latest stable release is V5.0.

IBM Tutorial on BlackBerry Data Collection ApplicationsAccess the author's site hosting the server-side transactions.

Sample code highlights

In this tutorial, a generic data-collection application is constructed for the BlackBerry.It has the uninspiring name of bb_ibm_demo. But don't let the name fool you. Whenthe concepts presented are absorbed, a whole host of useful applications await. Fullsource code is available in the Download section. Source-code snippets include:

bb_ibm_demo constructorThis is the primary class of the BlackBerry application.

main() method in bb_ibm_demo of the BlackBerry applicationThis is the public static void method for the application (the entry point of theBlackBerry application).

bb_ibm_screen constructorThis is the actual user interface (UI) shown to the user on the BlackBerry. Thismethod demonstrates the creation of the UI elements.

fieldChanged()This is the method that handles button presses in the UI screen on theBlackBerry.

ProcessTransactionThis method communicates from the BlackBerry to a server over the Internetusing HTTP.

index.phpThis is the home page of our sample server application. From here, you canlaunch a search for previously uploaded transactions.

db.phpManages connection to MySQL database.

export.phpProvides an export to CSV file of uploaded transactions.

ibm.com/developerWorks developerWorks®

Laying the groundwork© Copyright IBM Corporation 2008. All rights reserved. Page 3 of 33

Page 4: Os Blackberry PDF

manage.phpManages uploaded transactions. Add to this file for your own functionality.

showtransactions.phpDisplays any transactions loaded for a specific identifier.

posttransaction.phpThis server routine works hand in hand with ProcessTransaction on theBlackBerry to record data collected in the field.

utils.phpThis file contains helper functions for managing transactions on the server.

db.sqlThis script contains the data-definition language (DDL) to create the transactiontable used on the server.

Section 2. Blackberry basics and the JDE

Before jumping into the installation of the BlackBerry JDE and building anapplication, let's introduce the major components of the BlackBerry platform. Oncesome of the fundamentals are presented, we'll examine the JDE.

Meet the BlackBerry

Historically, BlackBerry has always been a messaging platform. Early versions ofRIM's devices were glorified two-way pagers. Expanding from that humble — andimportant — beginning, today's BlackBerry is an integrated telephone, text, e-mail,and rich application environment, including media and GPS capabilities on newerdevices. Unlike other modern devices that boast sexy touch screens andfeature-packed hardware, the BlackBerry is a capable and tactile device, ideal forthe power business user and the power text-messaging user.

Network communications options

All communications between a BlackBerry device and the Internet take place bygoing through RIM's data centers. Communication between the device and RIM isdone using a secure protocol. If you have a BlackBerry, you will run under one of afew different scenarios:

developerWorks® ibm.com/developerWorks

Laying the groundworkPage 4 of 33 © Copyright IBM Corporation 2008. All rights reserved.

Page 5: Os Blackberry PDF

BlackBerry Enterprise Server (BES)Corporate networks employ a BES as a means to manage mobile users'devices and connect the devices to corporate e-mail servers. Communicationvia RIM's network and an instance of a BES is fully secure; there is noplain-text portion of this communication over the Internet.

BlackBerry Internet Service (BIS)This is the service most consumers and small-business users employ, as it hasthe cheapest licensing costs and no additional hardware requirements beyonda BlackBerry device. BIS works by configuring your e-mail account(s) on RIM'sWeb site and auto-magically, your e-mail shows up on your BlackBerry.Communication between RIM and your device is secure, but the connectionbetween RIM and your e-mail server may or may not be secure, depending onthe kind of e-mail provider you use.

Desktop Redirector for OutlookThe redirector connects RIM's data center with a local Microsoft® Outlook®session running on a local computer. In this scenario, the Outlook programmust stay logged in at all times in order for e-mail to flow to the BlackBerrydevice. This is not an ideal scenario for the truly mobile user who has a laptop,rather than a desktop computer. If the laptop is packed in a bag with you on thetrain, there is no mobile e-mail.

Running under a BES environment provides the most control and options forapplications and IT policy enforcement. For example, an IT administrator canprevent users from reaching certain Internet sites, thereby restricting device use tobusiness only. In addition, certain "push"-application capabilities are enabled with aBES. The topics in this tutorial are universally applicable regardless of theenvironment a particular BlackBerry operates under. The only assumption made isthat a data plan allowing Internet access is permitted. Of course, if you have aBlackBerry restricted with respect to what Internet sites may be visited, you mayhave to convince your IT administrator to open up access to the sample application'sserver.

Device characteristics

There are a few physical characteristics of a BlackBerry device worth mentioning:

QWERTY keyboardBlackBerry devices have long been distinguishable by their full QWERTYkeyboard — a must-have for text-intensive mobile users. The tactile buttonsare good also for keyboard shortcuts — a feature sorely lacking on devices thatdo not have physical buttons.

Track wheel

ibm.com/developerWorks developerWorks®

Laying the groundwork© Copyright IBM Corporation 2008. All rights reserved. Page 5 of 33

Page 6: Os Blackberry PDF

The track wheel is essentially a "jog dial" on the side of your BlackBerry. Thetrack wheel is used for navigating the UI because BlackBerry devices do notfeature a touch screen. The track wheel is "selectable," meaning it can bedepressed to make a selection in the GUI. Pressing the track wheel isanalogous to "clicking" the mouse on a desktop computer. Holding the Altbutton on the keypad modifies the behavior of the track wheel within the UI.Newer devices have a track ball, which acts similarly to the track wheel.

Escape buttonThis button acts as a back button, moving the user back one step in thenavigation.

Ribbon vs. non-Ribbon applicationsThe application icons on the main screen are referred to as the Ribbon.Custom applications, like the one constructed in this tutorial, reside inside theApplications folder in the Ribbon.

Bluetooth communicationsIn addition to the standard Bluetooth hands-free ear piece, many BlackBerrydevices support the Bluetooth serial-port profile. This allows sophisticatedapplications to be written for a BlackBerry. Ideas include communicating with aGPS receiver, printing, or loading firmware into an embedded device, such asan appliance or vending machine.

Figure 1 highlights some of these physical characteristics.

Figure 1. BlackBerry device

developerWorks® ibm.com/developerWorks

Laying the groundworkPage 6 of 33 © Copyright IBM Corporation 2008. All rights reserved.

Page 7: Os Blackberry PDF

Now let's examine BlackBerry application development.

BlackBerry JDE

ibm.com/developerWorks developerWorks®

Laying the groundwork© Copyright IBM Corporation 2008. All rights reserved. Page 7 of 33

Page 8: Os Blackberry PDF

From a software perspective, BlackBerry devices are Java-enabled and provide anexcellent platform for application development. Unlike some J2ME-capable phones,where running an application feels like jumping to the other side of the phone in a"dual-boot" fashion, application launch on the BlackBerry has a natural andintegrated feel. In fact, integration is so tight that third-party applications can evenadd custom menus to many of the core BlackBerry applications. Having a solidunderstanding of the Java language is helpful for building BlackBerry applications.

This tutorial focuses on using the BlackBerry JDE. There are a number of versionsof the JDE available for download from the RIM Web site. These distinct versionscorrespond to software revisions found on BlackBerry hardware. For example, usingan older version of the JDE can be a good idea when the application is aiming towork on as many devices as possible, including older devices, which may have amore-limited feature set. This might look like writing an application that does notrequire a camera or true GPS services. Taking a least-common denominator can bea good idea when building a commercial application because the more devicescapable of running the application the more opportunity exists for product sales.

What is included?

The available development environment download packages from RIM consist ofmore than simply a graphical code editor and compilation tools. Resources from RIMinclude:

Graphical code editorThis looks similar to other programming environments offering applicationproject management, code editing, code compiling, and debugging.

Device simulatorsThese enable the code, compile, and debug cycle to take place directly on thedevelopment computer. This is a great advantage over testing solely on thereal device. Good coding practices suggest that testing takes place on thedevice before release of a product. However, using the simulator is a greattime-saver during the development phase. Using simulators can also be animportant part of the application-support process because a user may report ananomaly that only occurs on a particular device. For example, one application Iwrote worked fine on most devices, but the 8700c demonstrated quirkybehavior. Using the simulator, I was able to isolate the problem and find asolution. It's a good idea to periodically test your application on the latestdevice simulators as they become available. This is a cheaper alternative topurchasing every new device that hits the market. The simulator is also aconvenient mechanism for documenting an application — grabbingscreensshots is simple.

API reference

developerWorks® ibm.com/developerWorks

Laying the groundworkPage 8 of 33 © Copyright IBM Corporation 2008. All rights reserved.

Page 9: Os Blackberry PDF

A convenient and detailed API reference is included in the JDE download.

MDS simulatorThis software simulates the communication traffic between a real BlackBerryand the RIM network. Without the MDS simulator running, the BlackBerrydevice simulator is unable to communicate with hosts on the Internet.

E-mail simulatorThe JDE also includes an e-mail simulator. Because so much of the operationof a BlackBerry is e-mail-related, it's a good idea to make use of the e-mailsimulator. This permits applications to test e-mail-related functionality.

From a code perspective, BlackBerry applications leverage J2ME classes, as well asspecially extended Application Programming Interfaces (APIs). These APIs havesome overlap with the J2ME packages. However, the BlackBerry-provided classesare of great interest due to the powerful access they provide to a BlackBerry.

If your objective here is to follow along by building the sample application, pleasetake a moment now to install a version of the BlackBerry JDE. The Systemrequirements section includes a link to the JDE download page on RIM's Web site.

Section 3. A BlackBerry application

The best way to learn is by doing, so let's jump right in and build a BlackBerrydata-collection application. Each major element of the tutorial sample application isexamined, including the relevant source-code snippets.

The BlackBerry Application class

This tutorial creates a single application, which will be built up in parts throughout thetutorial. The first code snippet to review is found in bb_ibm_demo.java. You candownload the complete source code for this tutorial from the Download section.

Like any basic Java application, an application requires an entry point, namely main.Portions of the source file bb_ibm_demo.java are included below.

Listing 1. main method of the bb_ibm_demo.java file

//// bb_ibm_demo.java//

ibm.com/developerWorks developerWorks®

Laying the groundwork© Copyright IBM Corporation 2008. All rights reserved. Page 9 of 33

Page 10: Os Blackberry PDF

// MSI Services, Inc.// Frank Ableson// 973.448.0070// [email protected]// code free to use for any purpose,commercial or otherwise

package com.msi.ibm;

// required importsimport net.rim.device.api.ui.*;

// our application classclass bb_ibm_demo extends UiApplication{

// application entry pointpublic static void main(String[] args){

// create an instance of our appbb_ibm_demo theApp = new

bb_ibm_demo();

// "run" the apptheApp.enterEventDispatcher();

}

// app constructorpublic bb_ibm_demo(){

// create an instance of the mainscreen of our application

bb_ibm_screen screen = newbb_ibm_screen();

// make the screen visiblepushScreen(screen);

}}

The main method creates a new instance of the class named bb_ibm_demo. Thisclass is an extension of the UiApplication class. UiApplication is found in thenet.rim.device.api.ui package. The UiApplication class is a base classfor all BlackBerry applications that have a UI.

The constructor of the bb_ibm_demo class creates an instance of thebb_ibm_screen class. This class is defined and implemented inbb_ibm_screen.java. Once the screen is created, it is passed to the pushScreen()method. This essentially brings the screen into view on the device.

The screen

The example application has a very basic UI. The bb_ibm_screen class extendsthe MainScreen class, which is a class provided by RIM that implements featurescommon to BlackBerry applications. In addition, this class implements the Java

developerWorks® ibm.com/developerWorks

Laying the groundworkPage 10 of 33 © Copyright IBM Corporation 2008. All rights reserved.

Page 11: Os Blackberry PDF

Interface FieldChangeListener. This allows the class to react to user input in theUI elements. This topic is explained in greater detail in an upcoming section ondetecting a button press.

The core UI for the sample application is created in the constructor of the classbb_ibm_screen. Before looking at the code for the creation of the UI elements,let's look at the declaration of the UI elements that are members of our class.

Listing 2. Declaration of UI elements

// private members - these represent the "controls"private BasicEditField identifierfield = null;private BasicEditField datafield = null;private ButtonField submitbutton = null;private LabelField statusfield = null;

Each variable represents a UI element. There are two fields where text may beentered. These are the BasicEditField members. The ButtonField is used toinitiate a transaction. The LabelField provides a read-only display of what ishappening in the application. Let's look at the code that creates the UI for the tutorialsample application (see Listing 3). The constructor invokes the super-classconstructor with a call to super(). The title of the screen is set, and a method iscalled to create the UI. The UI is broken out to a separate method.

Listing 3. Creating the UI for the sample application

// constructorpublic bb_ibm_screen(){

// invoke the constructor of the super class (MainScreen)super();// give our application window a titlesetTitle("BB IBM Demo App");// create user interface componentscreateui();

}

The layout

Looking closer at the createui method, note that each of the fields is created witha specific method call (see Listing 4). For example, the BasicEditField classpresents a label, along with an entry field with a specific default value, maximumlength, and a style. For a list of the available styles, examine the Field andEditField class definitions in the API Javadoc. A ButtonField is used to submitthe transaction. A LabelField is also created to provide status information. Onceeach of these elements is instantiated, the add method is used to include the UIcomponent on the screen. One of the very nice features of BlackBerry screens is

ibm.com/developerWorks developerWorks®

Laying the groundwork© Copyright IBM Corporation 2008. All rights reserved. Page 11 of 33

Page 12: Os Blackberry PDF

that vertical scrolling occurs automatically without the need for complicated scrollingcode. For data-collection applications that require a fair amount of screen realestate, this is a welcome feature.

Listing 4. The creatui() method

private void createui(){

try{// create a field for entering the "identifier" of our transactionidentifierfield = new BasicEditField("Identifier: ","",50, EditField.NO_NEWLINE );// add this field to the screenadd(identifierfield);// create a field for the data of our transactiondatafield = new BasicEditField("Data: ","",100, EditField.NO_NEWLINE );// add this field to the screenadd(datafield);// create a button to submit out transactionsubmitbutton = new ButtonField("Submit Transaction",ButtonField.CONSUME_CLICK);// tell this button who handles changes (selection)submitbutton.setChangeListener(this);// add this button to the screenadd(submitbutton);// add a status labelstatusfield = new LabelField("Please enter transaction data.");// add label to screenadd(statusfield);}catch (Exception e){

System.out.println("Failed to create user interface components");}

}

Now that the UI has been created, it's time to look at the detection of events.Keeping in line with the Java architecture powering the BlackBerry platform, eventdetection is implemented through the use of one or more event-listener interfaces.

Detecting button press

There are a number of event listeners available in the BlackBerry environment. Thelistener of interest to this sample application is the FieldChangeListenerinterface. This interface provides a means for detecting changes in fields, includingbuttons. To make use of a FieldChangeListener, three requirements must bemet. The first is the implementation of the interface's method fieldChanged().The method is actually quite simple, requiring only two arguments — the moreimportant being the first, which represents the field that has changed in somemanner.

Listing 5. fieldChanged() method

public void fieldChanged(Field field, int Context);

developerWorks® ibm.com/developerWorks

Laying the groundworkPage 12 of 33 © Copyright IBM Corporation 2008. All rights reserved.

Page 13: Os Blackberry PDF

The second required step is to install the listener with a call tosetChangeListener(), as shown in the code snippet above. Without this methodinvocation, changes to the field are not processed.

The third requirement is that the argument passed to setChangeListener mustbe a class that contains the fieldChanged method. Another way of stating this isthat the class implements the FieldChangeListener interface. In this case, thetutorial sample application's UI class (bb_ibm_screen) implementsFieldChangeListener: class bb_ibm_screen extends MainScreen, whichimplements FieldChangeListener.

Let's examine the fieldChanged method, as shown in Listing 6.

Listing 6. The fieldChanged method

// this method implements the FieldChangedListener Interface// it is used to detect when the button is selected// after validating that the input data is correct, it attempts to submit a

// transaction to the serverpublic void fieldChanged(Field f, int context){

// which field was changedif (f == submitbutton){

// check fields....String id = identifierfield.getText();String data = datafield.getText();

if (id.trim().length() == 0 || data.trim().length() == 0){Dialog.alert("Please fill in all fields.");identifierfield.setFocus();return;}

// ok, looks like we have some good dataif (bb_ibm_transaction.ProcessTransaction(id,data) == true){// transaction was submitted successfully, let's reset the GUI for easy

// entry to another \fieldidentifierfield.setText("");datafield.setText("");\identifierfield.setFocus();statusfield.setText("Transaction Sent.");

// if you preferred to just close this application after submission,// uncomment out the following line//onClose();

}

}}

The method checks to see if the field passed to the method is the Submit button. Ifso, the implementation proceeds to verify the input data. In this example, the codesimply checks that the fields are not empty. In a more stringent application, thesevalues might be validated against a local store of known identifiers or other inputcriteria. Assuming the data passes the simple validation test, the transaction isprocessed with a call to the ProcessTransaction method of thebb_ibm_transaction class, which is reviewed in the next section.

ibm.com/developerWorks developerWorks®

Laying the groundwork© Copyright IBM Corporation 2008. All rights reserved. Page 13 of 33

Page 14: Os Blackberry PDF

Section 4. Data-collection applications with BlackBerry

Just what is a data-collection application anyway? Many applications fit into thiscategory; they are all around us. Every time we sign for a package or take a pictureof a house we are considering renting, we're collecting data. Oftentimes, theseapplications are associated with a "vertical," such as healthcare or logistics. Nomatter the industry; there are some design patterns and practices that are importantwhen collecting information with a mobile device. The next section talks about whatto do with the data once it has been collected, including a working Java method forprocessing a transaction.

What makes a good data-collection application

There are a handful of techniques that contribute to a good data-collectionapplication. Sometimes devices go out of range, but are still capable of collectingdata. An example of this is a Bluetooth-enabled piece of equipment that is in aremote location. The field-service technician carrying a BlackBerry may not have acellular signal, but can still interact with the equipment by way of a local Bluetoothdata connection. In this case, it is important that the user have the option to store(queue) data locally for transmission at a later time when back in range. Anotherexample of local storage is for reference data used to validate data-entry fields bymobile users. During an inventory-cycle count, a reference list of items to countwould be reasonable to store on the device without having a network connection.

There are, however, times when local storage is not necessary or warranted. Forexample, an application may require an Internet connection to a server providingimportant information relevant to the user at the time, such as the proximity of otherusers in the network. An example of this would be a networking applicationconcerned with the availability of specific people or resources. Market data isanother example where real-time data is important. We don't want to purchase porkbellies at a higher price than the market, for example.

Building the capability to store data locally is an important aspect of mobiledata-collection applications. However, the techniques for storing data locally on theBlackBerry are beyond the scope of this tutorial. That said, the tutorial sampleapplication does, in fact, collect data and needs to have something to do with it oncecollected. To do this, let's examine the ProcessTransaction method in thebb_ibm_transaction class, implemented in the file bb_ibm_transaction.java.

Listing 7. The ProcessTransaction method

developerWorks® ibm.com/developerWorks

Laying the groundworkPage 14 of 33 © Copyright IBM Corporation 2008. All rights reserved.

Page 15: Os Blackberry PDF

// this method interacts with the serverpublic static boolean ProcessTransaction(String id,String data){

// default to non-success return codeboolean ret = false;

// some variables necessary for HTTP communicationInputStream inputStream = null;HttpConnection httpConnection = null;

// because many of the steps can throw an exception, wrap this method// in a try/catch block

try{

StringBuffer returnStringBuffer = new StringBuffer();String returnString = new String();

String desiredEncoding = "ISO-8859-1";

URLEncodedPostData params = new URLEncodedPostData(URLEncodedPostData.DEFAULT_CHARSET, true);

params.append("identifier", id);params.append("data", data);

String url = "http://ibm.msi-wireless.com/posttransaction.php?"+ params.toString();

System.out.println(url);//Connecting to ServerhttpConnection = (HttpConnection)Connector.open(url);inputStream = httpConnection.openDataInputStream();

if(httpConnection.getResponseCode() == HttpConnection.HTTP_OK){int ch;//Process Response// check header field for a specific encodingString \

contenttype = httpConnection.getHeaderField("Content-Type");if (contenttype != null){contenttype = contenttype.toUpperCase(); \if (contenttype.indexOf("UTF-8") != -1) { desiredEncoding = "UTF-8"; }}

// get an inputstreamreader to handle utf-8 dataInputStreamReader \isr = new InputStreamReader(inputStream,desiredEncoding);while ((ch = isr.read()) != -1) { returnStringBuffer.append((char) ch);} \

inputStream.close();httpConnection.close();inputStream = null;\httpConnection = null;returnString = returnStringBuffer.toString();

// examine return stringif (returnString.indexOf("SUCCESS") \!= -1){ ret = true;}return ret;

}inputStream.close();httpConnection.close();inputStream = null;httpConnection = null;//Bad Transaction.return ret;

}catch (Exception e){

System.out.println("Error occurred in ProcessTransaction(" + id + ","+ data + ")\n" + e.toString());

return ret;}finally{

try{if (inputStream != null) inputStream.close();if \

ibm.com/developerWorks developerWorks®

Laying the groundwork© Copyright IBM Corporation 2008. All rights reserved. Page 15 of 33

Page 16: Os Blackberry PDF

(httpConnection != null) httpConnection.close();}catch (Exception ee){}

}}

The ProcessTransaction method demonstrates a number of useful techniquesfor communicating with a Web server. It establishes a connection and submits aURLEncoded query to a specific URL. The URLEncodedPostData takes care offormatting data as if the data were generated by a "Form Field" in a desktopbrowser. Note the code that examines the content type and sets up anInputStreamReader to process the data. Without this step, any data beyond themost basic of text can come across in unexpected and undesired ways. Thisfunction returns True if the Web server returns the string SUCCESS.

Building the application

Now that the relevant code snippets have been reviewed, let's jump back to theBlackBerry development environment to build the application. After loading thesample code, the BlackBerry JDE should look similar to Figure 2.

Figure 2. The BlackBerry JDE with the sample code loaded

developerWorks® ibm.com/developerWorks

Laying the groundworkPage 16 of 33 © Copyright IBM Corporation 2008. All rights reserved.

Page 17: Os Blackberry PDF

To build the application, press the F7 key. To see the output of the build process,select the Output option under the View menu or use Alt+2 (while holding the Altkey, press the number 2).

Assuming there are no errors in the code and the application has been built withouterrors, it's time to run the application in the BlackBerry simulator. The first step totake is to make sure that the MDS simulator is running. The MDS simulator allowsthe BlackBerry simulator to connect to the network, including the Internet. The MDSsimulator can be started automatically if preferred. To make changes like when theMDS simulator is started (automatically or manually) and other BlackBerry simulator

ibm.com/developerWorks developerWorks®

Laying the groundwork© Copyright IBM Corporation 2008. All rights reserved. Page 17 of 33

Page 18: Os Blackberry PDF

options, use the Preferences option in the Edit menu in the BlackBerry JDE editor,as shown below.

Figure 3. Preferences option in the BlackBerry JDE editor

Hitting F5 will start the BlackBerry simulator. The tutorial sample application will notstart right away. It must be started by navigating to the application's icon on thehome-page application Ribbon and selecting the tutorial sample application: bb_ibm.The arrow keys on the computer simulate the track wheel, the Enter key simulatespressing the track wheel, and the escape key emulates the BlackBerry escapebutton.

Now that the BlackBerry side of this tutorial has been discussed, let's look at theimportant server-side, where data is stored and managed.

developerWorks® ibm.com/developerWorks

Laying the groundworkPage 18 of 33 © Copyright IBM Corporation 2008. All rights reserved.

Page 19: Os Blackberry PDF

Section 5. Transaction processing on the server

Without a place to store and manage collected data, the BlackBerry applicationwould be of limited value. While a mobile data-collection application may store dataonly on the mobile device. In most cases, a successful mobile data-collectionapplication will have a server-side component to complement the mobiledata-collection software.

Data storage

To store data on the server, the tutorial sample application leverages the verypopular open source MySQL database. A single application database table isemployed: tbl_transactions. This table stores data sent by the BlackBerryapplication. Other management steps, including exporting and purging data leveragethis same database table. The Data Definition Language for this table is found inListing 8.

Listing 8. Data Definition Language for tbl_transactions table

CREATE TABLE'db_ibmmsiwireless'.'tbl_transactions' ('tid' INT UNSIGNED NOT NULL AUTO_INCREMENTCOMMENT 'unique id','usercode' VARCHAR( 50 ) CHARACTER SET asciiCOLLATE ascii_general_ci

NOT NULL COMMENT 'which user','datum' LONGTEXT CHARACTER SET ascii COLLATEascii_general_ci

NOT NULL COMMENT 'data from tran','stampx' DATETIME NOT NULL COMMENT 'whentransaction occurred',PRIMARY KEY ( 'tid' ) ,INDEX ( 'usercode' , 'stampx' )) ENGINE = MYISAM CHARACTER SET asciiCOLLATE ascii_general_ci

Having a database table does not solve the challenge of storing data completely.What is needed is a transaction to accept the incoming data, validate the data, asnecessary, and store the transaction. There are a number of options available here.The application requires a Remote Procedure Call (RPC) of some kind. Withoutgetting caught up in the various philosophical discussions of which RPC method isbetter, the tutorial is taking a simplistic approach of using URL encoded form data fortransaction submission. In order to not get distracted with other (important)technologies, let's keep things simple.

An advantage of using a form-based data approach is that testing the server side

ibm.com/developerWorks developerWorks®

Laying the groundwork© Copyright IBM Corporation 2008. All rights reserved. Page 19 of 33

Page 20: Os Blackberry PDF

can be done with a simply constructed form — no costly or complex tools arerequired.

Transaction processing

The transaction on the server side is implemented in another open sourcetechnology: PHP. PHP is employed because of its ease of use, its rich functionality,and its open source licensing model. Like many programming environments,breaking functionality out to separate modules or classes is a good programmingstyle, fostering ease of maintenance and readability. Let's examine the PHPenvironment that implements the tutorial sample application's server side.

Listing 9. PHP transaction for the server side

db.php<?php$mysql_db = "db_ibmmsiwireless";$mysql_user = "username";$mysql_pass = "password";$mysql_link = mysql_connect("dbservername", $mysql_user, $mysql_pass);mysql_select_db($mysql_db, $mysql_link);?>

The db.php page contains database-related connectivity information. This file isincluded by any pages that interact with the database. Note that the use of adatabase platform other than MySQL would result in the db.php file contents beingchanged to reflect the alternate database environment.

Listing 10. Database details

posttransaction.php<?phprequire('db.php');require('utils.php');putTransaction($_GET['identifier'],$_GET['data'])?>

The post-transaction.php page is very simple — it references the database settingsfound in db.php and loads the routines found in utils.php, which will be reviewedshortly.

Once the two require statements are processed to load the database and utilityroutines, respectively, this server-side script passes two data elements to a functionnamed putTransaction. Note the syntax of $_GET[]. This demonstrates themeans to access form data sent to the page from the BlackBerry (or a testing form).Note that if data were to be sent using POST, rather than GET, it would be accessedusing the $_POST[] syntax.

developerWorks® ibm.com/developerWorks

Laying the groundworkPage 20 of 33 © Copyright IBM Corporation 2008. All rights reserved.

Page 21: Os Blackberry PDF

Let's look at the putTransaction function, which is found in the file utils.php.

Listing 11. putTransaction function

function putTransaction($id,$datum){global $mysql_link;

$sql = "insert tbl_transactions (usercode,datum,stampx) values ('$id','$datum',NOW())";//print($sql);$result = mysql_query($sql,$mysql_link);if ($result == 1){

print("SUCCESS");}else{

print("FAILED");}}

The putTransaction method receives two arguments: an identifier and the datato be stored, or $id and $datum, respectively. The function generates a simpleSQL insert statement to populate a new row into the tbl_transactions table. Notethe use of the MySQL function of NOW(). This allows a database-generatedtimestamp to be provided on every transaction recorded. This can be a useful tool indata-collection applications to know when a transaction was received.

Additionally, a production transaction should include a provision to guard against anSQL injection attack. This step is omitted for the sake of clarity.

If the database operation is successful, this method returns the string SUCCESS,otherwise the string FAILED. Note that this function uses the PHP print function,which means that this string is sent back directly to the client, which in the case ofthis tutorial sample application, is the BlackBerry application presented earlier. In thestrictest sense, this is a shortcut. Functions found in utils.php should ideally returnvalues to their callers, which would then make the decision on what to communicateback to the client. In the interest of simplicity, all of the functions return valuesdirectly to the client.

Congratulations! The transaction that started on the BlackBerry is now safely storedin a relational database on the server. Now that the data has been stored, let's lookat what can be done with it.

Managing the data

Additional functions in the utils.php enable some other important features of a datacollection application. The getTransactions() function is invoked from theshowtransactions.php page. This allows a simple query across all stored

ibm.com/developerWorks developerWorks®

Laying the groundwork© Copyright IBM Corporation 2008. All rights reserved. Page 21 of 33

Page 22: Os Blackberry PDF

transactions and displays the results in the browser.

Listing 12. getTransactions() function is invoked from showtransactions.php

// In file showtransactions.php:

<?require('db.php');require('utils.php');require('header.php');?><html><head><title>MSI Wireless Transactions</title></head><body><h3>Transaction List for <? print('['.$_POST['identifier'].']')

?>.</h3><hr /><? getTransactions($_POST['identifier']) ?><br><a href="/">Try again</a><br><? require('footer.php'); ?></body></html>

// In file utils.php:

function getTransactions($id){global $mysql_link;$result = mysql_query("SELECT * from tbl_transactions where \usercode = '$id' order by tid", $mysql_link);if(mysql_num_rows($result)){

print("<table border=1><tr><td>Transaction#</td><td>Data</td><td>Time Stamp</td></tr>");

while($row = mysql_fetch_row($result)){

print("<tr><td>$row[0]</td><td>$row[2]</td><td>$row[3]</td></tr>");

}print("</table>");print("<a target='_blank' href='export.php?id=$id'>Export Your

Transactions</a>");print("<br>");print("<br>");print("<a href='manage.php?id=$id&action=remove'>Delete Your

Transactions</a>");print("<br>");

}else{

print("There are no transactions available.");}

}

The file showtransactions.php is essentially a form processor for the input formfound in index.php, with relevant portions show below.

Listing 13. Abbreviated showtransactions.php file

developerWorks® ibm.com/developerWorks

Laying the groundworkPage 22 of 33 © Copyright IBM Corporation 2008. All rights reserved.

Page 23: Os Blackberry PDF

<?require ('header.php'); ?>//<form method="POST" action="showtransactions.php">Your identifier:&nbsp;<input name="identifier" maxlength="50"><input type=submit value="Look Up My Transactions"></form><br>//<? require('footer.php'); ?></body></html>

Full transaction sequence

The following screenshots walk through the use of the tutorial sample application,starting with the BlackBerry application and commencing with a search on the serverside to find the newly entered transactions. Entering a transaction on the BlackBerryis shown below.

Figure 4. Entering a transaction on the BlackBerry

ibm.com/developerWorks developerWorks®

Laying the groundwork© Copyright IBM Corporation 2008. All rights reserved. Page 23 of 33

Page 24: Os Blackberry PDF

developerWorks® ibm.com/developerWorks

Laying the groundworkPage 24 of 33 © Copyright IBM Corporation 2008. All rights reserved.

Page 25: Os Blackberry PDF

Figure 5 shows the server side accepting a query for this transaction type. Note thatthe input form has the string IBM DEMO. You can enter any value you like for thisfield. This field corresponds to the identifier or ID field in the database table andcode snippets previously introduced.

Figure 5. The server side accepting a query for the transaction shown inFigure 4

The showtransactions.php page calls the getTransactions function, passing inthe query value, which in this case is IBM DEMO. Any transactions found intbl_transactions matching that identifier are displayed in the resulting page, asshown below.

Figure 6. Displaying transactions in tbl_transactions table matchingIBM_DEMO

ibm.com/developerWorks developerWorks®

Laying the groundwork© Copyright IBM Corporation 2008. All rights reserved. Page 25 of 33

Page 26: Os Blackberry PDF

Data integration

An important feature of a data-collection system is the ability to export collected datafor subsequent use in destination-management systems, such as a logisticspackage or perhaps a billing system. For example, this tutorial sample applicationcould be adapted for use by a utility company to collect meter data from the field.The identifier would be the meter number and the data the KWH reading from themeter.

The server side implements a simplistic export function that brings the selecteddata into a Microsoft Excel®-readable comma-separated value (CSV) file. Theserver-side code that implements this function is found in export.php.

Listing 14. export function from export.php file

<?phpheader("Content-Type: application/vns.ms-excel");header('Cache-Control: maxage=10');header('Pragma: public');header('Content-Disposition: attachment; filename="'.$_GET['id'].

'_transactions.csv"');require('db.php');require('utils.php');$out = fopen('php://output', 'w');getTransactionsToCSV($out,$_GET['id']);fclose($out);

developerWorks® ibm.com/developerWorks

Laying the groundworkPage 26 of 33 © Copyright IBM Corporation 2008. All rights reserved.

Page 27: Os Blackberry PDF

?>

The getTransactionsToCSV function, found in utils.php, is shown below.

Listing 15. The getTransactionsToCSV function

function getTransactionsToCSV($out,$id){global $mysql_link;$result = mysql_query("SELECT tid,datum,stampx from \tbl_transactions where usercode = '$id' order by tid", $mysql_link);if(mysql_num_rows($result)){

fputcsv($out,array("Transaction #","Data","Timestamp"));while($row = mysql_fetch_array($result,MYSQL_NUM)){

fputcsv($out,$row);}

}}

This server-side functionality is freely available for you to use for testing out yourBlackBerry data-collection applications (see System requirements).

Section 6. Next steps

There are a few topics yet to be addressed before this tutorial can be complete. Thistutorial sample application is missing one crucial step required for runningapplications on a real BlackBerry. Additionally, there are two nice-to-have features inany mobile data-collection application that need to be addressed. And the topic ofopen source licensing is touched upon before wrapping up.

Controlled APIs

First, let's discuss the required step for loading an application on a real BlackBerry.There are a number of classes in the BlackBerry API that require code signing.These classes are referred to as Controlled APIs. This means that RIM views theuse of these classes as sensitive and, therefore, requires that you sign theapplication with a RIM-supplied developer key. This allows RIM to identify the authorof an application. Why is this important? Let's say someone authors an applicationthat sends out spam or otherwise is a misbehaving citizen. The step of requiring asignature makes the developer think twice before releasing such an application.Additionally, RIM can revoke a developer key if necessary, thereby hampering therogue developer's ability to release these kinds of applications. Of course, building

ibm.com/developerWorks developerWorks®

Laying the groundwork© Copyright IBM Corporation 2008. All rights reserved. Page 27 of 33

Page 28: Os Blackberry PDF

rogue applications is not the intent here. However it is important to discuss becausethis step is require before loading an application to a real device. Unfortunately, thisstep is not free, but the fee ($20 USD) is not excessive.

To obtain a developer key, you must apply at RIM's Web site. See Resources for thedeveloper key registration URL.

Once a developer key is installed in the JDE, signing the application isstraightforward.

Signing the application

After successfully building the application, select the Request Signatures optionbeneath the Build menu.

Figure 7. Selecting the Request Signatures option

When the Signature Tool screen launches, each code module is listed, along with aCategory field indicating whether the particular module requires signing. Enter theprivate-key password established when the developer key was established toproceed with the signing operation.

Figure 8. Entering the private key password

developerWorks® ibm.com/developerWorks

Laying the groundworkPage 28 of 33 © Copyright IBM Corporation 2008. All rights reserved.

Page 29: Os Blackberry PDF

Once the signing step is complete, the Status column will indicate that the moduleshave been signed.

Figure 9. Status column indicates modules have been signed

At this point, the application is ready to be installed on the device. Applications maybe installed via a BlackBerry Enterprise Server, the BlackBerry Desktop Manager, orusing an Over The Air method. For more information about loading an application ona real device, see Resources.

Error handling

Error handling is omitted from this tutorial for the sake of brevity and clarity. Ofcourse, any production-ready code should have a healthy dose of error handling andinstructions for the user of the application in the event that something goes awry.

ibm.com/developerWorks developerWorks®

Laying the groundwork© Copyright IBM Corporation 2008. All rights reserved. Page 29 of 33

Page 30: Os Blackberry PDF

Queuing

This topic was touched upon briefly, but it warrants further mention. There arescenarios where an application will need to queue data. The reasons may involvedata requirements of gathering data in batches and submitting them with summaryinformation — a physical-inventory application, for example. Alternatively, there maybe connectivity issues where transactions cannot be sent immediately uponcollection. While this topic was not expressly implemented in the tutorial sampleapplication, queuing strategy should not be overlooked in a real-world data-collectionapplication.

Open source licensing

Taking an idea from concept to a licensed open source application is no small feat.This tutorial sample is a good starting point for a more comprehensivedata-collection platform, but there is more work to be done. One next step could beadding location-based information (GPS data, for example) or perhaps bolting on aBluetooth-capable barcode scanner for gathering inventory data in the field.Regardless of the next technical feature to add to this application, the choosing of anappropriate open source license needs to be addressed. The pros and cons of anopen source license selection is beyond the scope of this tutorial, but it needs somethought for any serious open source product. The reference section contains a linkto a site that aggregates a number of open source licenses. If you are serious aboutbuilding an open source application, put some thought into choosing an appropriatelicense for your BlackBerry application.

Section 7. Summary

This tutorial has introduced the BlackBerry platform and demonstrated developingmobile data-collection applications with open source technologies, including Java,PHP, and MySQL. The basics of BlackBerry UI and communications wereintroduced, along with a simple, yet powerful server side implemented in opensource staples PHP and MySQL. Leveraging these open source technologies opensup a world of software creativity far exceeding custom ringtones and text messaging.One might even say that the market for open source BlackBerry applications withJava is ripe for the picking.

developerWorks® ibm.com/developerWorks

Laying the groundworkPage 30 of 33 © Copyright IBM Corporation 2008. All rights reserved.

Page 31: Os Blackberry PDF

Downloads

Description Name Size Downloadmethod

Java code os-blackberry-code.zip 17KB HTTP

PHP and SQL code os-blackberry-serverside.zip 4KB HTTP

Information about download methods

ibm.com/developerWorks developerWorks®

Laying the groundwork© Copyright IBM Corporation 2008. All rights reserved. Page 31 of 33

Page 32: Os Blackberry PDF

Resources

Learn

• Be sure to read Part 2 and Part 3 of this series.

• BlackBerry Desktop Software: Research In Motion (RIM) offers a full range ofhelpful user and administrator information on BlackBerry Desktop Software,including more about installing software via the Desktop Manager.

• You'll find articles about every aspect of Java programming in thedeveloperWorks Java technology zone.

• OpenSource.org presents a catalog of the most popular open source licenses.

• PHP.net is the central resource for PHP developers.

• Check out the "Recommended PHP reading list."

• Browse all the PHP content on developerWorks.

• Expand your PHP skills by checking out IBM developerWorks' PHP projectresources.

• To listen to interesting interviews and discussions for software developers,check out developerWorks podcasts.

• Using a database with PHP? Check out the Zend Core for IBM, a seamless,out-of-the-box, easy-to-install PHP development and production environmentthat supports IBM DB2 V9.

• Stay current with developerWorks' Technical events and webcasts.

• Check out upcoming conferences, trade shows, webcasts, and other Eventsaround the world that are of interest to IBM open source developers.

• Visit the developerWorks Open source zone for extensive how-to information,tools, and project updates to help you develop with open source technologiesand use them with IBM's products.

• Watch and learn about IBM and open source technologies and productfunctions with the no-cost developerWorks On demand demos.

Get products and technologies

• Get PHP. The latest, stable release is V4.4.9.

• Get MySQL. The latest stable version is 5.0.

• Tutorial application's free hosted service.

• Get the BlackBerry Java Development Environment.

developerWorks® ibm.com/developerWorks

Laying the groundworkPage 32 of 33 © Copyright IBM Corporation 2008. All rights reserved.

Page 33: Os Blackberry PDF

• BlackBerry Code Signing Keys Order Form: Visit this site to obtain a developerkey to access Controlled APIs within the BlackBerry environment.

• Innovate your next open source development project with IBM trial software,available for download or on DVD.

• Download IBM product evaluation versions, and get your hands on applicationdevelopment tools and middleware products from DB2®, Lotus®, Rational®,Tivoli®, and WebSphere®.

Discuss

• Participate in developerWorks blogs and get involved in the developerWorkscommunity.

• Participate in the developerWorks PHP Forum: Developing PHP applicationswith IBM Information Management products (DB2, IDS).

About the author

Frank AblesonAfter his college basketball career came to an end without a multiyear contract toplay for the L.A. Lakers, Frank Ableson shifted his focus to computer softwaredesign. He enjoys solving complex problems, particularly in the areas ofcommunications and hardware interfacing. When not working, he can be foundspending time with his wife Nikki and their children. You can reach Frank [email protected].

ibm.com/developerWorks developerWorks®

Laying the groundwork© Copyright IBM Corporation 2008. All rights reserved. Page 33 of 33