Java Reference
In-Depth Information
The WeatherFetcher class implements Runnable , because the actual connection occurs
in a separate thread. This permits the MIDlet to perform the network communication
without blocking the user interface—a feature expected by today's users. Given a location
and an instance of the application to notify when the network operation is complete, the
class creates a new thread, connects to the remote server, posts the location to the server,
and obtains the results. This work is started in the class constructor, which sets aside the
provided location and reference to the application's user interface before starting a new
thread using the newly created instance of this class. The WeatherFetcher class requires a
reference to the MIDlet that uses it; the class notifies the MIDlet when the update has
occurred by invoking the MIDlet's update method. Listing 12-11 shows this change to the
WeatherWidget MIDlet, and I'll discuss this change more in a bit.
The user interface can cancel the operation at any time; this can occur if you pick a
different location while the WeatherFetcher and its thread are blocked awaiting a response
from the network. To do this, the user interface invokes the cancel method; it simply
asserts a cancellation flag, which the WeatherFetcher tests before updating the user inter-
face. In fact, cancel doesn't actually cancel the HTTP connection, because there's really
no good way to do this; instead, it permits the HTTP connection to complete and cancels
updating the user interface.
The run method actually performs the work necessary to obtain a weather forecast
for a specific location; this code should be familiar to you by now. The WeatherConnection
class assumes the remote web server has accepted the desired location as a name-value
pair encoded as a form argument; this is typical for simple web servers that also provide
content for web forms. Consequently, the first thing that run does is create a name-value
pair and store the result in vars ; the syntax of this pair is appropriate for any web server
responding to a form, and looks like this:
location=Berkeley,CA
This step must URL-encode the argument string; some characters such as a space
character ( "" ) cannot be transmitted as they are, but instead are represented as a single
percent symbol ( % ) followed by the two-digit hexadecimal ASCII code of the character.
Thus, a space character ( "" ) would be represented as the string %20 . While the example
passes only a single named value location , it could just as easily pass multiple values;
these would be concatenated using an ampersand ( & ), like this:
city=Berkeley&state=CA
Typically, however, if you're building an application to exchange structured data with
a web server, you'll probably encode that structured data using XML—a subject I save for
Chapter 13.
 
Search WWH ::




Custom Search