Device programming with MIDP, Part
3 - JavaWorld
July 2001
Tutorial Details:
Device programming with MIDP, Part 3
Device programming with MIDP, Part 3
By: By Michael Cymerman
Use MIDP's communication APIs to interact with external systems
n the first two parts of this three-part series, I examined the features and functionality of the Mobile Information Device Profile (MIDP) APIs as they relate to operations and information stored on the device itself. In this final part, I'll focus on the interaction of a networked device with the network at large.
Read the whole "Device Programming with MIDP" series:
Part 1. Build devices with MIDP APIs and J2ME across multiple wireless platforms
Part 2. Use these user-interface and data-store components to create MIDP-based applications
Part 3. Use the communication APIs to interact with external systems
Networked devices can use numerous protocols to communicate with each other. In this article, I'll focus on the HttpConnection interface that you can use to access information stored on a Web server. Preceding the article's example, I will discuss the interactions of the javax.microedition.io interfaces and classes. The example will concentrate on the interaction between a MIDP device and a JSP-based system.
Connection hierarchy
All interfaces in the javax.microedition.io package are based on the Connection interface. Other connection interfaces inherit the method contained in Connection and define methods used for accessing relevant variables and actions of that Connection type. I will discuss the more common interfaces in this article; the other interfaces are left to the reader for investigation.
HTTPConnection explained
The HttpConnection interface provides other methods on top of the Connection interface to enable HTTP interaction. Here is a list of some of those useful methods:
String getHeaderField(int index)
String getHeaderField(String name)
long getHeaderFieldDate(String name, long def)
int getHeaderFieldInt(String name, int def)
String getHeaderFieldKey(int n)
String getHost()
long getLastModified()
int getPort()
String getProtocol()
String getQuery()
String getRef()
String getRequestMethod()
String getRequestProperty(String key)
int getResponseCode()
String getResponseMessage()
String getURL()
void setRequestMethod(String method)
void setRequestProperty(String key, String value)
These methods let you access the HTTP fields just as you would in a servlet-based system.
The other interfaces are well documented in the API specification. Those interfaces will contain methods for sending datagram packets and streaming data to and from the device using a variety of protocols. I will not examine those in detail because while they differ in exact method signature, they are obtained in an identical fashion.
The Connector object
How does the MIDP API figure out which interface to create and return to the calling class? The answer is that the proper Connector is returned based upon the value passed in the connection string.
The following connection string alerts the Connector object that the system is looking for an HttpConnection :
HttpConnection httpConn = Connector.open("http://www.itpath.com");
The MIDP Connector object parses through the connection string and determines that it is a URL for accessing a Webpage. An implementation of the HttpConnection interface is returned to the calling class.
Other connection protocols need different connection strings. Consult Table 1 for a listing of the connection strings for various protocols:
Table 1. Connection strings for various protocols
Protocol
Connection String
Http
http://www.yahoo.com
Stream-based Socket
Socket://localhost:6160
Datagram-based Socket - listening
datagram://:6160
Datagram-based Socket - sending
datagram://121.232.121.232:6160
Serial Port
comm.:0;baudrate=5000
File
file://helloWorld.txt
Example: Tying it all together
The following example is intended to tie the concepts discussed in this article to those in the rest of the series. In this example, the MIDlet accesses information stored on a remote system. That information is returned in the form of an XML message to the MIDlet. By parsing that XML, the MIDlet then constructs a user interface based upon the data.
The user interface consists of a question posed to the user. The response causes a request to be made to the server to add data to the survey. The updated data is then returned to the user.
This article provides a detailed example with code that you can download in the Resources section to further explore the basic usage and syntax of the J2ME Connection APIs.
VoterMidlet
The VoterMidlet class is the only MIDlet in this example. Upon loading, it creates an instance of the VoteResults object:
public class VoterMidlet extends MIDlet implements ScreenCallback
{
private Display _display;
// midlet has three screens
private VoteResults voteResults = new VoteResults( (ScreenCallback) this);
public VoterMidlet()
{
_display = Display.getDisplay(this);
_display.setCurrent(voteResults);
}
public void exit()
{
try
{
this.destroyApp(true);
} catch (MIDletStateChangeException e)
{}
}
...
}
ScreenCallback
As shown above, the VoterMidlet implements the ScreenCallback interface. This interface masks certain events from the UI classes that may need a reference to the MIDlet. The ScreenCallback interface contains a single method public void exit() , which the UI screen uses to alert the MIDlet that the user has pressed the "Exit" button.
By coding to the ScreenCallback interface, the other MIDlet methods are hidden from the UI screen developers. This is important because some MIDlet methods have a damaging effect on the program if used incorrectly.
VoteResults
The VoteResults class is a user interface class that displays the voting results to the user. To keep the example simple, this class implements two of the Model-View-Controller classes: View and Controller .
The Constructor takes the ScreenCallback interface as its only argument from the MIDlet. As described above, that interface gives the Screen the ability to call back to the MIDlet for certain methods.
The Constructor initializes the object and creates the user interface for the example. Here are the lines of particular interest:
VoteSummary voteSummary = ResourceUtility.getVoteSummary();
initialize(voteSummary);
Those lines are responsible for the initial communication between the MIDlet and the JSP page that simulates a real-world system. The ResourceUtility accesses a URL via the HTTP parameter and retrieves information from the JSP. It uses that information to create a VoteSummary object. This interface will be further examined as we proceed with the example.
The initialize() method is then called to create the UI display consisting of two StringItems displaying the prior voting results, and a ChoiceGroup containing all the possible votes and the number of votes for that category:
public void initialize(VoteSummary voteSummary)
{
append( getNumVotesString( voteSummary.getNumVotes() )) ;
append( getAvgVoteString( voteSummary.getAvgVote() ));
append( showVoteResults( voteSummary.getVotes() ));
}
Upon user input to the display, the commandAction() method is executed. That method accepts input from the device. If the command entered is equal to "Vote" , the currently selected item is retrieved from the ChoiceGroup . A Vote object is constructed and passed to the ResourceUtility.addEntry() method. That method passes information to the JSP, which then adds the new vote to the tally and returns an updated VoteSummary object. It then calls the update() method:
public void commandAction(Command c, Displayable s)
{
String command = c.getLabel();
if ( command.equals("Exit") )
{
_screenCallback.exit();
}
else if ( command.equals("Vote") )
{
// get the selected item
int selectedIndex = _voteResults.getSelectedIndex();
Vote newVote = new Vote(""+ selectedIndex, null, null);
VoteSummary voteSummary = ResourceUtility.addEntry( newVote);
update( voteSummary );
}
}
VoteSummary
The VoteSummary object contains information about the current voting status. It keeps track of the total number of votes, the average vote, and also maintains a Vector of the votes themselves (rolled-up for each choice):
public VoteSummary(String numVotes, String avgVote, Vector votes)
{
_numVotes = numVotes;
_avgVote = avgVote;
_votes = votes;
}
Based upon the XML passed from the JSP to the MIDlet, the VoteSummary object is created.
ResourceUtility
The ResourceUtility class obtains the XML from the remote server. It uses an HttpConnection to request the XML from the JSP and then interfaces with the XMLUtil to convert the XML into a VoteSummary object:
public static VoteSummary getVoteSummary()
{
String xml = loadVoteResults();
return convertXMLToVoteSummary( xml);
}
The getVoteSummary() method shown above accesses this object. The method in turn calls the loadVoteResults() and convertXMLToVoteSummary() methods. The loadVoteResults() method, shown below, wraps the backendComms() method that is also used for adding votes to the backend system:
public static String loadVoteResults()
{
return backendComms(LOAD_URL, "");
}
private static String backendComms(String requestURL, String requeststring)
{
HttpConnection httpConnection = null;
DataInputStream dataInputStream = null;
StringBuffer messagebuffer = new StringBuffer();
String requestString = requestURL + requeststring;
Try
{
// Open an HTTP connection with the Web server
httpConnection = (HttpConnection)
Connector.open(requestString, Connector.READ_WRITE);
// Set the request method to GET
httpConnection.setRequestMethod(HttpConnection.GET);
// Retrieve the response back from the servlet
dataInputStream =
new DataInputStream(httpConnection.openInputStream());
int inputChar;
// Check the Content-Length first
long contentLength = httpConnection.getLength();
if(contentLength!=-1)
{
for(int i = 0;I{
if
Read
Tutorial at: Click here to view the tutorial
Rate Tutorial: Device programming with MIDP, Part
3 - JavaWorld
July 2001
View Tutorial: Device programming with MIDP, Part
3 - JavaWorld
July 2001
Related
Tutorials:
Track wireless sessions with J2ME/MIDP
Track wireless sessions with J2ME/MIDP |
Master J2ME for live data
delivery
Master J2ME for live data
delivery |
J2SE 1.4
breathes new life into the CORBA community, Part
1
J2SE 1.4
breathes new life into the CORBA community, Part
1 |
Best tools for
mobile application development
Best tools for
mobile application development |
J2ME devices:
Real-world performance
J2ME devices:
Real-world performance |
Big designs for
small devices
Big designs for
small devices |
Picture
this
Picture
this |
Maybe the future UI design of choice
Maybe the future UI design of choice |
Java and GIS, Part 2: Mobile LBS
Java and GIS, Mobile LBS
Using LBS
First, let\'s make sure that we understand what an LBS application is. Typically, an LBS application is trying to answer the question \"Where am I?\" and then do something with that information. There are a number |
J2ME app development on the 6600
J2ME app development on the 6600
Introduction
When you first look at the Nokia 6600, the first reaction is very predictable. wow! It is truely a good looking phone. A stunner. Let's find out if there's more to this phone than just good looks. |
Getting Started With the Mobile 3D Graphics API for J2ME
This tutorial introduces the Mobile 3D Graphics API for J2ME, JSR 184. The article presents an overview, potential application areas, the differences between JSR 184 and two related APIs, the classes in the new optional package, the programming model, the |
The SATSA Developer's Guide
Describes how to use the SATSA APIs in MIDP applications. It includes lucid explanations and example code that illustrate how to communicate with a smart card and how to use cryptographic services. It is based on the SATSA Reference Implementation 1.0. |
Game Canvas Basics
Introduces the MIDP 2.0 GameCanvas class and the game loop concept. Required reading for all aspiring "first person shooter" developers. |
Understanding MIDP System Threads
Describes the multi-threaded aspects of the J2ME application environment. Understanding the interactions between systems threads, user-interface and application threads will help in avoiding MIDlet deadlock. |
Develop MIDlets using the J2ME MIDP Development for NetBeans IDE 4.0
This release integrates with the J2ME Wireless Toolkit 2.2 to create a powerful environment for developing MIDP 2.0 applications. |
What are the defined J2ME system property names?
A compilation of J2ME properties sorted by JSR. Learn the names, test for optional packages or retrieve platform specific configuration values. |
Definition of Bioinformatics
Definition of Bioinformatics
Definition of Bioinformatics
About Bioinformatics
In February 2001, the human genome was finally deciphered! In other words, scientists have succeeded in reading the chain of more than 3 billion base pairs that |
Pure Java SSH Tool for J2ME
JSch is the pure Java SSH2 implementation developed by JCraft under revised BSD license. It has been already widely adopted by several open source projects, including Eclipse, Apache Ant, etc., |
Easy Emulation With New NetBeans Mobility Pack 4.0
With the click of a button, switch back and forth between different emulation environments while developing one set of code. It's never been this easy to take advantage of Java technology's cross-platform capabilities. |
Getting Started With the PIM APIs
This article provides a code-intensive introductory tutorial to Personal information management (PIM) APIs, JSR 75. |
|
|
|