Implementation
You can download the source code here. We'll look at some specific details about the code, but you can freely alter the code and use it any way you want. The kXML parser is not included in the source code package, so you have to download it yourself from the Web site.
NewsReaderMIDlet, which is the main class of the application, is quite straightforward. It introduces two commands (Exit and Back), sets the command listeners, uses HTTPConnectionWrapper to get and parse the XML document, and then displays the menu containing the headlines. When a certain headline is selected (by the user), the whole text of the headline is shown with HeadlideDetail.
Listing 3 shows the fetch() method, which uses HttpConnection to fetch the XML document. Then it parses the XML document and creates a new list.
Listing 3 Fetching the XML Document
public List fetch(){ HttpConnection con = null; InputStream is = null; String xml = new String(); OutputStream out = null; try { con = (HttpConnection)Connector.open(this.url, Connector.READ_WRITE); con.setRequestMethod(HttpConnection.GET); is = con.openInputStream(); // Read the XML file from the ByteArrayOutputStream bas = new ByteArrayOutputStream(); int ch; while ((ch = is.read()) != -1) { bas.write(ch); } // Parsing the xml xml = bas.toString(); parseNews(xml); // Creating the menu list = new List("XML News", List.IMPLICIT); int i=0; for (Enumeration e = v.elements() ; e.hasMoreElements() ; i++) { list.append((String)(e.nextElement()), null); } int rCode = con.getResponseCode(); String rMesg = con.getResponseMessage(); } catch (Exception e) { System.out.println("Exception " +e.getMessage()); } finally { try { if (null!=out) out.close(); if (null!= is) is.close(); con.close(); } catch (Exception ex) { System.out.println("Exception while closing connection."); } } return list; }