Java Reference
In-Depth Information
catch(Exception e) { return; };
xmlBytes = xml.getBytes();
bis = new ByteArrayInputStream(xmlBytes);
try {
parser.parse(bis,handler);
}
catch(Exception e){}
finally {
try {
bis.close();
}
catch(Exception e) {}
}
}
}
The
fromXml
method creates an initial
LocationParserHandler
, linking it to the
current
Location
instance. Under the hood, the platform can provide different imple-
mentations of SAX parsers, so it's important to use the
SAXParserFactory
to get an
instance of the parser; you do this by creating an instance of the factory and then
invoking that instance's
newSAXParser
method. The parser takes its data in the form of
an
InputStream
; converting the incoming XML to a byte array and using that with the
ByteArrayInputStream
class provides the input stream necessary for the parser's
parse
method. That's all there is to it!
All of this code assumes a RESTful web service that provides an XML document with
weather data given a location; Listing 13-10 shows a version of
WeatherFetcher
that does
just this, building on what you learned from the previous chapter.
Listing 13-10.
A RESTful Implementation of WeatherFetcher
package com.apress.rischpater.weatherwidget;
import java.io.*;
import javax.microedition.io.*;
public class WeatherFetcher implements Runnable {
private static String url = "http://www.noplace.com/location/";
private Location location;
private boolean cancelled;
private WeatherWidget app;