One of the first things I wanted to get right once I got my BlackBerry development environment setup using the BlackBerry JDE, was to be able consume a .NET web service or any other web service for that matter. Unfortunately there doesn’t seem to be any support for web services in the BlackBerry APIs. I found a couple of different methods of consuming web services, but they either seem too difficult to implement or a steep price tag was attached. So I ended up doing it by using the Java ME Platform SDK 3.0. Anyway let’s get started.
Firstly you’ll need to build a simple .NET (SOAP) web service that has two methods. One to retrieve the server’s hostname and the other returns the current date and time on the server. I won’t go into detail on the steps required to develop this service as it’s pretty basic if you’re familiar with .NET. This is what the service code looks like:
<br />
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Diagnostics;
namespace SampleNetService
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{
[WebMethod]
public string GetHostname()
{
return Environment.MachineName;
}
[WebMethod]
public string GetServerDateTime()
{
return string.Format("Server Time: {0}", DateTime.Now.ToString());
}
}
}
The URL to the service on my machine is http://localhost/SampleNetService/Service.asmx.
I you’ve ever consumed a web service using a .NET client application, you’ll know that you normally just add a web reference on the project and Visual Studio automatically generates the stub classes which you can use on the client application i.e. the web service proxy. The first approach I came across is to use the KSoap libraries, but the implementation code looks incredibly verbose and it doesn’t look like there is anyway to generate the classes. Instead you pretty much have to code everything yourself (specifying the parameters, URL, method names etc.) and the libraries just handle the communication for you. If you’re interested in this approach you can have a look this tutorial on the subject:
- BlackBerry and .NET Web Service Tutorial – Part 1
- BlackBerry and .NET Web Service Tutorial – Part 2
- BlackBerry and .NET Web Service Tutorial – Part 3
I did find what seems to be a great API for generating stubs and consuming web services called WSClient++, which you can download from http://wsclient.neurospeech.com/. Unfortunately it’s a little too expensive for my liking. They have a demo version, but they limit you on accessing only two web services per project and being able to call (generate stubs for) only two web service methods.
So instead I opted for using the Java ME Platform SDK 3.0 to generate the stubs. It’s surprisingly easy and it just works. Firstly, download and install it from http://www.oracle.com/technetwork/java/javame/downloads/sdk30-jsp-139759.html. You can of course achieve the same result using the the Java Wireless Toolkit 2.5.2 which is the predecessor to the Java ME Platform SDK, which can be downloaded from http://www.oracle.com/technetwork/java/download-135801.html. If you’re interested in the nitty-gritty behind J2ME web services and consuming them, then have a look at this article http://developers.sun.com/mobility/apis/articles/wsa/.
Once you’ve gotten it in installed, navigate to the bin folder of your installation directory. On my machine it’s C:\Java_ME_platform_SDK_3.0\bin. The command line tool we’re going to use is wscompile.exe. To run the tool you’ll need to create a small config file which you’ll pass as an argument to wscompile.exe. So in this directory create a config.xml with the following contents:
<?xml version="1.0" encoding="UTF-8"?> <configuration xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/config"> <wsdl location="http://10.120.6.24/SampleNetService/Service.asmx?wsdl" packageName="rpcdemo" /> </configuration>
In the wsdl element you’ll need to set the location to the URL of your web service including the ?wsdl suffix (which generates the wsdl file), as well as the packageName attribute. Also notice that in the URL I replaced localhost with the address of my machine hosting the web service. The reason being that the generated stubs will contain the URL which the device application will be pointed to. Therefore using localhost in the client application will result in it not being able to access the URL. You could obviously use the hostname of your machine instead of the IP address, provided that it will be able to resolve it. The package name corresponds to the package which will contain the generated stub classes.
Now from command prompt, navigate to the above directory and run the following command:
wscompile.exe -gen -cldc1.1 config.xml
After having run the command you should find a subdirectory in the bin directory named after the package name you specified in the config file. In my case it’s rpcdemo. If you get an error that it cannot parse the config file it’s because for whatever reason the tool does not recognize UTF-8 encoding. If you then in command prompt enter the following command to see the contents of the config.xml file, you’ll probably notice that there are some strange characters preceding the first line in the file:
type config.xml
To fix the issue, make sure that you create the config.xml file using a regular text editor as opposed to an XML editor.
Now let’s develop the BlackBerry application. Open the BlackBerry JDE and create a new workspace. Then create a new project in the workspace. We’ll now need to create a class extending MainScreen on which we’ll place two labels to display the info retrieved from the web service as well a button which initiates and performs the web service calls. We also need a class that extends UiApplication, which will push (display) the screen with the controls onto the screen stack. Separate packages aren’t strictly necessary, but in my example I create two separate packages to store these two classes in i.e. core (for the UiApplication) and ui (for the screen). So for each of the above two classes, right click the project and select Create new File in Project and append a subdirectory name to the path corresponding to the package you want created i.e. core or ui. The java files I’ve created for the screen and UiApplication are GetServerDateScreen.java (ui package) and NetServiceBBConsumerApp.java (core package) respectively.
Open the NetServiceBBConsumerApp.java, clear the code in it and paste the following code:
</p>
/*
* NetServiceBBConsumerApp.java
*
* © <your company here>, <year>
* Confidential and proprietary.
*/
package core;
import net.rim.device.api.ui.*;
import ui.*;
/**
*
*/
public class NetServiceBBConsumerApp extends UiApplication
{
public static void main(String[] args)
{
NetServiceBBConsumerApp app = new NetServiceBBConsumerApp();
app.enterEventDispatcher();
}
NetServiceBBConsumerApp()
{
}
public void activate()
{
if(getScreenCount() == 0)
{
//This is the first time the activate method has been called by the event dispatcher i.e. the app has just started up.
this.pushScreen(new ui.GetServerDateScreen());
}
else
{
//The application has just been reactivated e.g. the user might have switched to a different application deactivating this one and then switched back to this application.
updateDisplay();
}
}
}
In the application’s entry method, main(String[] args), we create a new NetServiceBBConsumerApp which extends UiApplication. We then override the application’s activate function. This method gets called either when the application gets started or when perhaps a user navigates away from our application (by opening another application or taking a phone call) and then returns to our application. In this function we then check whether the application has just been launched (no screens exist on the stack yet) or whether the application has just been reactivated after another app has been closed (screens already exist on the stack). If this is a fresh start up of the appliation we create a new GetServerDateScreen (which contains our controls/fields) and push it onto the screen stack. If you’ve ever done .NET Compact Framework development or Windows Forms, you can think if this class as the Program class containing the main method that starts up the main form. Also notice that we’re importing the ui package at the top. Otherwise if this is a reactivation, we just call updateDisplay() which will refresh the device’s display for all the screens in the application.
In the GetServerDateScreen.java file, clear the code in it and paste the following code:
package ui;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import rpcdemo.*;
public class GetServerDateScreen extends MainScreen
{
LabelField lblServerHostname = new LabelField("", LabelField.FIELD_LEFT);
LabelField lblServerDate = new LabelField("", LabelField.FIELD_LEFT);
ButtonField btnGetServerInfo = new ButtonField("Get Server Info", ButtonField.CONSUME_CLICK)
{
protected boolean navigationClick(int status, int time)
{
GetServerInfo();
return true;
}
}
public GetServerDateScreen()
{
setTitle("Current Server Date");
add(lblServerHostname);
add(lblServerDate);
add(btnGetServerInfo);
}
public boolean onClose()
{
System.exit(0);
return true;
}
public void GetServerInfo()
{
try
{
ServiceSoap_Stub service = new ServiceSoap_Stub();
String serverHostname = service.getHostname();
String serverDateTime = service.getServerDateTime();
lblServerHostname.setText(serverHostname); lblServerDate.setText(serverDateTime);
}
catch(Exception e)
{
Dialog.alert(e.getMessage());
}
}
}
Here we basically create the two labels and a button on which we override its navigationClick method. This method gets called when the button gets clicked. So we handle this event by calling the GetServerInfo method which simply instantiates the ServiceSoap_Stub class that we generated earlier and calls the appropriate web service methods to retrieve the server’s hostname and date. Thereafter we display the results on the two labels. On this screen’s constructor we add the controls/fields to the screen.
The generated web service stub classes need to be imported into the project before we can build it. Copy the rpcdemo directory from C:\Java_ME_platform_SDK_3.0\bin to the your project’s directory. To import them, right click the project and select Add File to Project. Navigate to the project’s rpcdemo subdirectory and select all the java files in it. In this example there should be six of them. The project’s file structure should look as follows:
If you open the ServiceSoap_Stub class, in its constructor you’ll notice the URL you specified in the config file. So if the location of the service ever changes this is where you can change the URL before rebuilding the mobile application. One very important thing to remember is that an application will by default try to connect to via MDS. So although you might find that it can connect to the web service on an emulator, it will fail to connect once deployed on the device if the device is not connected to the MDS. Therefore, you need to specify in your code whether to use MDS, a straight GPRS connection via your service provider or a connection via WiFi. You do this by appending a connection string to the end of your web service URL in the ServiceSoap_Stub’s constructor. For example to force a WiFi connection you would append “;interface=wifi”. For a straight GPRS connection, you would append “;deviceside=true”. Here’s a method you can include in your code that generates and appends the correct connection string to your URL depending on whether an MDS or WiFi connection is available, otherwise a straight GPRS connection.
// Determines what connection type to use and returns the necessary string to use it.
// @return A string with the connection info
public static String getConnectionString(String connectionString)
{
// This code is based on the connection code developed by Mike Nelson of AccelGolf.
// http://blog.accelgolf.com/2009/05/22/blackberry-cross-carrier-and-cross-network-http-connection
// Simulator behavior is controlled by the USE_MDS_IN_SIMULATOR variable.
if(DeviceInfo.isSimulator())
{
//Dialog.alert("Device is a simulator and USE_MDS_IN_SIMULATOR is false");
connectionString += ";deviceside=true";
}
// Wifi is the preferred transmission method
else if( (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) && RadioInfo.areWAFsSupported(RadioInfo.WAF_WLAN))
{
//Dialog.alert("Device is connected via Wifi.");
connectionString += ";interface=wifi";
}
// Is the carrier network the only way to connect?
else if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT)
{
//Dialog.alert("Carrier coverage.");
String carrierUid = getCarrierBIBSUid();
if(carrierUid == null)
{
// Has carrier coverage, but not BIBS. So use the carrier's TCP network
//Dialog.alert("No Uid");
connectionString += ";deviceside=true";
}
else
{
// otherwise, use the Uid to construct a valid carrier BIBS request
//Dialog.alert("uid is: " + carrierUid);
connectionString += ";deviceside=false;connectionUID="+carrierUid + ";ConnectionType=mds-public";
}
}
// Check for an MDS connection instead (BlackBerry Enterprise Server)
else if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS)
{
//Dialog.alert("MDS coverage found");
connectionString += ";deviceside=false";
}
// If there is no connection available abort to avoid bugging the user unnecssarily.
else if(CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE)
{
//Dialog.alert("There is no available connection.");
}
// In theory, all bases are covered so this shouldn't be reachable.
else
{
//Dialog.alert("no other options found, assuming device.");
connectionString += ";deviceside=true";
}
return connectionString;
}
// Looks through the phone's service book for a carrier provided BIBS network
// @return The uid used to connect to that network.
private static String getCarrierBIBSUid()
{
ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for(currentRecord = 0; currentRecord < records.length; currentRecord++)
{
if(records[currentRecord].getCid().toLowerCase().equals("ippp"))
{
if(records[currentRecord].getName().toLowerCase().indexOf("bibs") >= 0)
{
return records[currentRecord].getUid();
}
}
}
return null;
}
Once you’ve built the project, using a command prompt window navigate to the project’s folder and there should find a new COD file. This is the BlackBerry executable that needs to be deployed to the device. To deploy, run the following command after connecting the device via a USB to the machine:
javaloader -usb load NetServiceBBConsumer.cod
On the device you need to set the permissions for the application by clicking Menu > Options > Applications, selecting the application and making sure every field is set to allow.
Next we need to configure the device to connect to the WiFi, test the connectivity with your machine and web service and lastly test the application.
WiFi:
- Enable WiFi on the device by clicking Menu -> Manage Connections and checking the WiFi checkbox.
- In the same pop up menu select Wi-Fi Options.
- To connect to a specific WiFi AP (Access Point), click Menu > New and then Scan For Networks.
- Select your WiFi network/AP and enter all the relevant wireless settings for your AP i.e. security type, key etc. and then click Connect.
Test the connectivity to the server (your development machine) and web service:
- Click Menu > Manage Connections > Wi-Fi Options > Menu > Wi-Fi Tools
- Select Wi-Fi Diagnostics from above available tools menu to ensure you’re connected to the correct WiFi network and view your IP Address.
- From your machine try pinging your device with the above IP address.
- From the device select the Ping tool from the above tools menu and enter the IP Address of your machine followed by clicking Menu > Send Ping.
- To go a step further you can establish whether the device can access the service, by opening the device’s internet browser.
- Once inside the browser, in the top right hand corner you should see a WiFi icon. Otherwise if any other icon such as EDGE is displayed you won’t be able to access any resource on the WiFi network. Unfortunately as we all know a BlackBerry phone is a merely a phone, not an iPhone, therefore it’s not smart enough to choose the least expensive network automatically. To switch to WiFi for browsing, in your browser, click Menu > Options > General Properties and from the Default Browser drop down select Hotspot Browser followed by clicking Menu > Save Options. Then click the Broser Configuration menu item and from the Browser drop down ensure that Hotspot Browser is selected and then save the options by clicking Menu > Save Options.
- Lastly in your browser, enter the URL of your web service in the address bar and hit enter on the device’s keyboard.
Test the application:
- Click Menu > Downloads and select the application you’ve just built and deployed.
- Once it starts up, click the Get Server Info button and it should now hit the service and shortly after display the server’s hostname and date on the two labels.
That’s pretty much it. You can also download the source code from here: http://www.mediafire.com/?g3hnbhwrd2k3s5e

Hi, thanks for the excellent tutorial.
I was wondering, did you experience any problems connecting to the service on your device? My application works as expected in the simulator, however when I try it via Wifi the service call just hangs. I’ve gone through the diagnostics you suggested, I can ping my computer as well as view the service from within the Blackberry browser. My particular devices (Storm and Bold) don’t have SIM cards installed, and so are only using Wifi.
Any help much appreciated, otherwise many thanks for getting me this far
Marc
Posted by Marc | June 20, 2011, 8:33 amHi Marc,
Yes I actually did have a the same issue. The problem is the device tries to connect via MDS to the web service. If your device is connected to MDS, which in turn can access your web service it will connect, otherwise not. So you have to implement your own connection management to force the application to use either MDS, straight over WiFi and bypass MDS or straight over your service provider’s GPRS connection. You do this by appending a connection string to your web service URL. Just remember to configure your APN settings correctly if you’re going to use a straight GPRS connection.
Have a look at my post again, I’ve modified it to include the code that determines what connection is available and forces that connection (e.g. WiFi) over MDS. I got that code from someone else on the net.
Hope that helps.
Cheers,
Paul
Posted by Paul Kolozsvari | June 20, 2011, 11:16 amHi, i get this error:
error: package javax.xml.soap does not exist
Posted by willem | September 22, 2011, 1:55 pmI understand this article and thank you for your assitance. However, my issue is that I am trying to use this webservice to send as well as receive information. I have the BB Ui with edit fields already established. My question is how to send the info within the edit fields to the webservice. Thank you inadvanced.
Posted by David | November 28, 2011, 8:22 amGlad it worked for you. I normally use text fields, but you can get the text that the user types into the edit fields by calling the edit field’s “getText()” method.
If you’re developing from the BlackBerry JDE, you can have a look at the documentation which lists all the classes and their methods with their descriptions, by clicking Help -> API Reference, then searching for a class and then the method.
To send data back to your web service you’re obviously going to need to add parameters to your web methods. I generally create classes on the web service that wrap all the data I want to receive/send
from/to the mobile app. When you run the wscompile, it will generate any stub (proxy) Java classes that are needed for you to talk with the web service.
Hope that helps.
Posted by Paul Kolozsvari | November 28, 2011, 8:42 amIs there a tutorial for creating the actual webservice. Thank you.
Posted by David | December 19, 2011, 11:54 pmYou can have a look at this video: http://www.asp.net/web-forms/videos/how-do-i/how-do-i-create-and-call-a-simple-web-service-in-aspnet
or go through this tutorial: http://www.codeproject.com/KB/webservices/myservice.aspx
Posted by Paul Kolozsvari | December 20, 2011, 8:25 amThank you that helped. Is there any video that shows more on how to setup sql database access from within the webservice? He touched on it briefly but gave no examples.
Posted by David | December 21, 2011, 3:15 amThere’s various ways of accessing a database, but personally I prefer using LINQ to SQL. Have a look at these videos: http://windowsclient.net/learn/videos_linq.aspx
… or go through these articles: http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx and http://weblogs.asp.net/scottgu/archive/2007/05/29/linq-to-sql-part-2-defining-our-data-model-classes.aspx
Also if you want to make your life easier once you get to grips with LINQ to SQL you can maybe try out http://whatpaulhaslearnt.wordpress.com/2010/10/09/a-generic-linq-the-sql-classes-data-context-wrapper-to-dynamically-funnel-entities-the-underlying-data-source/
Posted by Paul Kolozsvari | December 21, 2011, 9:33 amThank you again. So i am able to incorporate LINQ commands into my blackberry client? I feel like Im on knowledge overload and I dont know if I’m learning what I need to. Do you think we can chat if you have a moment?
dyoungjr10@gmail.com
Posted by David Young | December 21, 2011, 10:35 amNo. The LINQ you’ll have to write in your web service. So your web service will be responsible for querying your database and returning results to the device. I’ve sent you a mail with more details.
Posted by Paul Kolozsvari | December 21, 2011, 1:29 pmThanks for providing this code it really helped me alot. I really struggled for internet type availabilty check to my project , this site solved my problem
Posted by prashanti | February 2, 2012, 8:01 amGlad it helped you out
Posted by Paul Kolozsvari | February 2, 2012, 8:30 am